Exemplo n.º 1
0
/**
* Disapprove Post/Topic
*/
function disapprove_post($post_id_list, $mode)
{
    global $db, $template, $user, $config;
    global $phpEx, $phpbb_root_path;
    if (!($forum_id = check_ids($post_id_list, POSTS_TABLE, 'post_id', 'm_approve'))) {
        trigger_error('NOT_AUTHORIZED');
    }
    $redirect = request_var('redirect', build_url(array('t', 'mode')) . '&mode=unapproved_topics');
    $reason = request_var('reason', '', true);
    $reason_id = request_var('reason_id', 0);
    $success_msg = $additional_msg = '';
    $s_hidden_fields = build_hidden_fields(array('i' => 'queue', 'mode' => $mode, 'post_id_list' => $post_id_list, 'f' => $forum_id, 'action' => 'disapprove', 'redirect' => $redirect));
    $notify_poster = isset($_REQUEST['notify_poster']) ? true : false;
    $disapprove_reason = '';
    if ($reason_id) {
        $sql = 'SELECT reason_title, reason_description
			FROM ' . REPORTS_REASONS_TABLE . "\n\t\t\tWHERE reason_id = {$reason_id}";
        $result = $db->sql_query($sql);
        $row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if (!$row || !$reason && $row['reason_title'] == 'other') {
            $additional_msg = $user->lang['NO_REASON_DISAPPROVAL'];
            unset($_POST['confirm']);
        } else {
            // If the reason is defined within the language file, we will use the localized version, else just use the database entry...
            $disapprove_reason = $row['reason_title'] != 'other' ? isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])]) ? $user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])] : $row['reason_description'] : '';
            $disapprove_reason .= $reason ? "\n\n" . $reason : '';
        }
    }
    if (confirm_box(true)) {
        $post_info = get_post_data($post_id_list, 'm_approve');
        // If Topic -> forum_topics_real -= 1
        // If Post -> topic_replies_real -= 1
        $forum_topics_real = 0;
        $topic_replies_real_sql = $post_disapprove_sql = $topic_id_list = array();
        foreach ($post_info as $post_id => $post_data) {
            $topic_id_list[$post_data['topic_id']] = 1;
            // Topic or Post. ;)
            if ($post_data['topic_first_post_id'] == $post_id && $post_data['topic_last_post_id'] == $post_id) {
                if ($post_data['forum_id']) {
                    $forum_topics_real++;
                }
            } else {
                if (!isset($topic_replies_real_sql[$post_data['topic_id']])) {
                    $topic_replies_real_sql[$post_data['topic_id']] = 1;
                } else {
                    $topic_replies_real_sql[$post_data['topic_id']]++;
                }
            }
            $post_disapprove_sql[] = $post_id;
        }
        if ($forum_topics_real) {
            $sql = 'UPDATE ' . FORUMS_TABLE . "\n\t\t\t\tSET forum_topics_real = forum_topics_real - {$forum_topics_real}\n\t\t\t\tWHERE forum_id = {$forum_id}";
            $db->sql_query($sql);
        }
        if (sizeof($topic_replies_real_sql)) {
            foreach ($topic_replies_real_sql as $topic_id => $num_replies) {
                $sql = 'UPDATE ' . TOPICS_TABLE . "\n\t\t\t\t\tSET topic_replies_real = topic_replies_real - {$num_replies}\n\t\t\t\t\tWHERE topic_id = {$topic_id}";
                $db->sql_query($sql);
            }
        }
        if (sizeof($post_disapprove_sql)) {
            if (!function_exists('delete_posts')) {
                include_once $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts
            delete_posts('post_id', $post_disapprove_sql);
        }
        unset($post_disapprove_sql, $topic_replies_real_sql);
        update_post_information('topic', array_keys($topic_id_list));
        update_post_information('forum', $forum_id);
        unset($topic_id_list);
        $messenger = new messenger();
        // Notify Poster?
        if ($notify_poster) {
            $email_sig = str_replace('<br />', "\n", "-- \n" . $config['board_email_sig']);
            foreach ($post_info as $post_id => $post_data) {
                if ($post_data['poster_id'] == ANONYMOUS) {
                    continue;
                }
                $email_template = $post_data['post_id'] == $post_data['topic_first_post_id'] && $post_data['post_id'] == $post_data['topic_last_post_id'] ? 'topic_disapproved' : 'post_disapproved';
                $messenger->template($email_template, $post_data['user_lang']);
                $messenger->replyto($config['board_email']);
                $messenger->to($post_data['user_email'], $post_data['username']);
                $messenger->im($post_data['user_jabber'], $post_data['username']);
                $messenger->assign_vars(array('EMAIL_SIG' => $email_sig, 'SITENAME' => $config['sitename'], 'USERNAME' => html_entity_decode($post_data['username']), 'REASON' => html_entity_decode($disapprove_reason), 'POST_SUBJECT' => html_entity_decode(censor_text($post_data['post_subject'])), 'TOPIC_TITLE' => html_entity_decode(censor_text($post_data['topic_title']))));
                $messenger->send($post_data['user_notify_type']);
                $messenger->reset();
            }
            $messenger->save_queue();
        }
        unset($post_info, $disapprove_reason);
        if ($forum_topics_real) {
            $success_msg = $forum_topics_real == 1 ? 'TOPIC_DISAPPROVED_SUCCESS' : 'TOPICS_DISAPPROVED_SUCCESS';
        } else {
            $success_msg = sizeof($post_id_list) == 1 ? 'POST_DISAPPROVED_SUCCESS' : 'POSTS_DISAPPROVED_SUCCESS';
        }
    } else {
        include_once $phpbb_root_path . 'includes/functions_display.' . $phpEx;
        display_reasons($reason_id);
        $template->assign_vars(array('S_NOTIFY_POSTER' => true, 'S_APPROVE' => false, 'REASON' => $reason, 'ADDITIONAL_MSG' => $additional_msg));
        confirm_box(false, 'DISAPPROVE_POST' . (sizeof($post_id_list) == 1 ? '' : 'S'), $s_hidden_fields, 'mcp_approve.html');
    }
    $redirect = request_var('redirect', "index.{$phpEx}");
    $redirect = reapply_sid($redirect);
    if (!$success_msg) {
        redirect($redirect);
    } else {
        meta_refresh(3, $redirect);
        trigger_error($user->lang[$success_msg] . '<br /><br />' . sprintf($user->lang['RETURN_PAGE'], "<a href=\"{$redirect}\">", '</a>'));
    }
}
Exemplo n.º 2
0
    function main($id, $mode)
    {
        global $config, $db, $user, $auth, $template;
        global $phpbb_root_path, $phpbb_admin_path, $phpEx;
        global $phpbb_dispatcher, $request;
        global $phpbb_container, $phpbb_log;
        $user->add_lang(array('posting', 'ucp', 'acp/users'));
        $this->tpl_name = 'acp_users';
        $error = array();
        $username = $request->variable('username', '', true);
        $user_id = $request->variable('u', 0);
        $action = $request->variable('action', '');
        // Get referer to redirect user to the appropriate page after delete action
        $redirect = $request->variable('redirect', '');
        $redirect_tag = "redirect={$redirect}";
        $redirect_url = append_sid("{$phpbb_admin_path}index.{$phpEx}", "i={$redirect}");
        $submit = isset($_POST['update']) && !isset($_POST['cancel']) ? true : false;
        $form_name = 'acp_users';
        add_form_key($form_name);
        // Whois (special case)
        if ($action == 'whois') {
            if (!function_exists('user_get_id_name')) {
                include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
            }
            $this->page_title = 'WHOIS';
            $this->tpl_name = 'simple_body';
            $user_ip = phpbb_ip_normalise($request->variable('user_ip', ''));
            $domain = gethostbyaddr($user_ip);
            $ipwhois = user_ipwhois($user_ip);
            $template->assign_vars(array('MESSAGE_TITLE' => sprintf($user->lang['IP_WHOIS_FOR'], $domain), 'MESSAGE_TEXT' => nl2br($ipwhois)));
            return;
        }
        // Show user selection mask
        if (!$username && !$user_id) {
            $this->page_title = 'SELECT_USER';
            $template->assign_vars(array('U_ACTION' => $this->u_action, 'ANONYMOUS_USER_ID' => ANONYMOUS, 'S_SELECT_USER' => true, 'U_FIND_USERNAME' => append_sid("{$phpbb_root_path}memberlist.{$phpEx}", 'mode=searchuser&amp;form=select_user&amp;field=username&amp;select_single=true')));
            return;
        }
        if (!$user_id) {
            $sql = 'SELECT user_id
				FROM ' . USERS_TABLE . "\n\t\t\t\tWHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'";
            $result = $db->sql_query($sql);
            $user_id = (int) $db->sql_fetchfield('user_id');
            $db->sql_freeresult($result);
            if (!$user_id) {
                trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action), E_USER_WARNING);
            }
        }
        // Generate content for all modes
        $sql = 'SELECT u.*, s.*
			FROM ' . USERS_TABLE . ' u
				LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
			WHERE u.user_id = ' . $user_id . '
			ORDER BY s.session_time DESC';
        $result = $db->sql_query_limit($sql, 1);
        $user_row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if (!$user_row) {
            trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action), E_USER_WARNING);
        }
        // Generate overall "header" for user admin
        $s_form_options = '';
        // Build modes dropdown list
        $sql = 'SELECT module_mode, module_auth
			FROM ' . MODULES_TABLE . "\n\t\t\tWHERE module_basename = 'acp_users'\n\t\t\t\tAND module_enabled = 1\n\t\t\t\tAND module_class = 'acp'\n\t\t\tORDER BY left_id, module_mode";
        $result = $db->sql_query($sql);
        $dropdown_modes = array();
        while ($row = $db->sql_fetchrow($result)) {
            if (!$this->p_master->module_auth_self($row['module_auth'])) {
                continue;
            }
            $dropdown_modes[$row['module_mode']] = true;
        }
        $db->sql_freeresult($result);
        foreach ($dropdown_modes as $module_mode => $null) {
            $selected = $mode == $module_mode ? ' selected="selected"' : '';
            $s_form_options .= '<option value="' . $module_mode . '"' . $selected . '>' . $user->lang['ACP_USER_' . strtoupper($module_mode)] . '</option>';
        }
        $template->assign_vars(array('U_BACK' => empty($redirect) ? $this->u_action : $redirect_url, 'U_MODE_SELECT' => append_sid("{$phpbb_admin_path}index.{$phpEx}", "i={$id}&amp;u={$user_id}"), 'U_ACTION' => $this->u_action . '&amp;u=' . $user_id . (empty($redirect) ? '' : '&amp;' . $redirect_tag), 'S_FORM_OPTIONS' => $s_form_options, 'MANAGED_USERNAME' => $user_row['username']));
        // Prevent normal users/admins change/view founders if they are not a founder by themselves
        if ($user->data['user_type'] != USER_FOUNDER && $user_row['user_type'] == USER_FOUNDER) {
            trigger_error($user->lang['NOT_MANAGE_FOUNDER'] . adm_back_link($this->u_action), E_USER_WARNING);
        }
        $this->page_title = $user_row['username'] . ' :: ' . $user->lang('ACP_USER_' . strtoupper($mode));
        switch ($mode) {
            case 'overview':
                if (!function_exists('user_get_id_name')) {
                    include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
                }
                $user->add_lang('acp/ban');
                $delete = $request->variable('delete', 0);
                $delete_type = $request->variable('delete_type', '');
                $ip = $request->variable('ip', 'ip');
                /**
                 * Run code at beginning of ACP users overview
                 *
                 * @event core.acp_users_overview_before
                 * @var	array   user_row    Current user data
                 * @var	string  mode        Active module
                 * @var	string  action      Module that should be run
                 * @var	bool    submit      Do we display the form only
                 *                          or did the user press submit
                 * @var	array   error       Array holding error messages
                 * @since 3.1.3-RC1
                 */
                $vars = array('user_row', 'mode', 'action', 'submit', 'error');
                extract($phpbb_dispatcher->trigger_event('core.acp_users_overview_before', compact($vars)));
                if ($submit) {
                    if ($delete) {
                        if (!$auth->acl_get('a_userdel')) {
                            send_status_line(403, 'Forbidden');
                            trigger_error($user->lang['NO_AUTH_OPERATION'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                        // Check if the user wants to remove himself or the guest user account
                        if ($user_id == ANONYMOUS) {
                            trigger_error($user->lang['CANNOT_REMOVE_ANONYMOUS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                        // Founders can not be deleted.
                        if ($user_row['user_type'] == USER_FOUNDER) {
                            trigger_error($user->lang['CANNOT_REMOVE_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                        if ($user_id == $user->data['user_id']) {
                            trigger_error($user->lang['CANNOT_REMOVE_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                        if ($delete_type) {
                            if (confirm_box(true)) {
                                user_delete($delete_type, $user_id, $user_row['username']);
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DELETED', false, array($user_row['username']));
                                trigger_error($user->lang['USER_DELETED'] . adm_back_link(empty($redirect) ? $this->u_action : $redirect_url));
                            } else {
                                $delete_confirm_hidden_fields = array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true, 'delete' => 1, 'delete_type' => $delete_type);
                                // Checks if the redirection page is specified
                                if (!empty($redirect)) {
                                    $delete_confirm_hidden_fields['redirect'] = $redirect;
                                }
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields($delete_confirm_hidden_fields));
                            }
                        } else {
                            trigger_error($user->lang['NO_MODE'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                    }
                    // Handle quicktool actions
                    switch ($action) {
                        case 'banuser':
                        case 'banemail':
                        case 'banip':
                            if ($user_id == $user->data['user_id']) {
                                trigger_error($user->lang['CANNOT_BAN_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_id == ANONYMOUS) {
                                trigger_error($user->lang['CANNOT_BAN_ANONYMOUS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_row['user_type'] == USER_FOUNDER) {
                                trigger_error($user->lang['CANNOT_BAN_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            $ban = array();
                            switch ($action) {
                                case 'banuser':
                                    $ban[] = $user_row['username'];
                                    $reason = 'USER_ADMIN_BAN_NAME_REASON';
                                    break;
                                case 'banemail':
                                    $ban[] = $user_row['user_email'];
                                    $reason = 'USER_ADMIN_BAN_EMAIL_REASON';
                                    break;
                                case 'banip':
                                    $ban[] = $user_row['user_ip'];
                                    $sql = 'SELECT DISTINCT poster_ip
										FROM ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\tWHERE poster_id = {$user_id}";
                                    $result = $db->sql_query($sql);
                                    while ($row = $db->sql_fetchrow($result)) {
                                        $ban[] = $row['poster_ip'];
                                    }
                                    $db->sql_freeresult($result);
                                    $reason = 'USER_ADMIN_BAN_IP_REASON';
                                    break;
                            }
                            $ban_reason = $request->variable('ban_reason', $user->lang[$reason], true);
                            $ban_give_reason = $request->variable('ban_give_reason', '', true);
                            // Log not used at the moment, we simply utilize the ban function.
                            $result = user_ban(substr($action, 3), $ban, 0, 0, 0, $ban_reason, $ban_give_reason);
                            trigger_error(($result === false ? $user->lang['BAN_ALREADY_ENTERED'] : $user->lang['BAN_SUCCESSFUL']) . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'reactivate':
                            if ($user_id == $user->data['user_id']) {
                                trigger_error($user->lang['CANNOT_FORCE_REACT_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_row['user_type'] == USER_FOUNDER) {
                                trigger_error($user->lang['CANNOT_FORCE_REACT_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_row['user_type'] == USER_IGNORE) {
                                trigger_error($user->lang['CANNOT_FORCE_REACT_BOT'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($config['email_enable']) {
                                if (!class_exists('messenger')) {
                                    include $phpbb_root_path . 'includes/functions_messenger.' . $phpEx;
                                }
                                $server_url = generate_board_url();
                                $user_actkey = gen_rand_string(mt_rand(6, 10));
                                $email_template = $user_row['user_type'] == USER_NORMAL ? 'user_reactivate_account' : 'user_resend_inactive';
                                if ($user_row['user_type'] == USER_NORMAL) {
                                    user_active_flip('deactivate', $user_id, INACTIVE_REMIND);
                                    $sql = 'UPDATE ' . USERS_TABLE . "\n\t\t\t\t\t\t\t\t\t\tSET user_actkey = '" . $db->sql_escape($user_actkey) . "'\n\t\t\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                                    $db->sql_query($sql);
                                } else {
                                    // Grabbing the last confirm key - we only send a reminder
                                    $sql = 'SELECT user_actkey
										FROM ' . USERS_TABLE . '
										WHERE user_id = ' . $user_id;
                                    $result = $db->sql_query($sql);
                                    $user_actkey = (string) $db->sql_fetchfield('user_actkey');
                                    $db->sql_freeresult($result);
                                }
                                $messenger = new messenger(false);
                                $messenger->template($email_template, $user_row['user_lang']);
                                $messenger->set_addresses($user_row);
                                $messenger->anti_abuse_headers($config, $user);
                                $messenger->assign_vars(array('WELCOME_MSG' => htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])), 'USERNAME' => htmlspecialchars_decode($user_row['username']), 'U_ACTIVATE' => "{$server_url}/ucp.{$phpEx}?mode=activate&u={$user_row['user_id']}&k={$user_actkey}"));
                                $messenger->send(NOTIFY_EMAIL);
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_REACTIVATE', false, array($user_row['username']));
                                $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_REACTIVATE_USER', false, array('reportee_id' => $user_id));
                                trigger_error($user->lang['FORCE_REACTIVATION_SUCCESS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            }
                            break;
                        case 'active':
                            if ($user_id == $user->data['user_id']) {
                                // It is only deactivation since the user is already activated (else he would not have reached this page)
                                trigger_error($user->lang['CANNOT_DEACTIVATE_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_row['user_type'] == USER_FOUNDER) {
                                trigger_error($user->lang['CANNOT_DEACTIVATE_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($user_row['user_type'] == USER_IGNORE) {
                                trigger_error($user->lang['CANNOT_DEACTIVATE_BOT'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            user_active_flip('flip', $user_id);
                            if ($user_row['user_type'] == USER_INACTIVE) {
                                if ($config['require_activation'] == USER_ACTIVATION_ADMIN) {
                                    /* @var $phpbb_notifications \phpbb\notification\manager */
                                    $phpbb_notifications = $phpbb_container->get('notification_manager');
                                    $phpbb_notifications->delete_notifications('notification.type.admin_activate_user', $user_row['user_id']);
                                    if (!class_exists('messenger')) {
                                        include $phpbb_root_path . 'includes/functions_messenger.' . $phpEx;
                                    }
                                    $messenger = new messenger(false);
                                    $messenger->template('admin_welcome_activated', $user_row['user_lang']);
                                    $messenger->set_addresses($user_row);
                                    $messenger->anti_abuse_headers($config, $user);
                                    $messenger->assign_vars(array('USERNAME' => htmlspecialchars_decode($user_row['username'])));
                                    $messenger->send(NOTIFY_EMAIL);
                                }
                            }
                            $message = $user_row['user_type'] == USER_INACTIVE ? 'USER_ADMIN_ACTIVATED' : 'USER_ADMIN_DEACTIVED';
                            $log = $user_row['user_type'] == USER_INACTIVE ? 'LOG_USER_ACTIVE' : 'LOG_USER_INACTIVE';
                            $phpbb_log->add('admin', $user->data['user_id'], $user->ip, $log, false, array($user_row['username']));
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, $log . '_USER', false, array('reportee_id' => $user_id));
                            trigger_error($user->lang[$message] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delsig':
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            $sql_ary = array('user_sig' => '', 'user_sig_bbcode_uid' => '', 'user_sig_bbcode_bitfield' => '');
                            $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_SIG', false, array($user_row['username']));
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_SIG_USER', false, array('reportee_id' => $user_id));
                            trigger_error($user->lang['USER_ADMIN_SIG_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delavatar':
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            // Delete old avatar if present
                            /* @var $phpbb_avatar_manager \phpbb\avatar\manager */
                            $phpbb_avatar_manager = $phpbb_container->get('avatar.manager');
                            $phpbb_avatar_manager->handle_avatar_delete($db, $user, $phpbb_avatar_manager->clean_row($user_row, 'user'), USERS_TABLE, 'user_');
                            $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_AVATAR', false, array($user_row['username']));
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_AVATAR_USER', false, array('reportee_id' => $user_id));
                            trigger_error($user->lang['USER_ADMIN_AVATAR_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delposts':
                            if (confirm_box(true)) {
                                // Delete posts, attachments, etc.
                                delete_posts('poster_id', $user_id);
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_POSTS', false, array($user_row['username']));
                                trigger_error($user->lang['USER_POSTS_DELETED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        case 'delattach':
                            if (confirm_box(true)) {
                                /** @var \phpbb\attachment\manager $attachment_manager */
                                $attachment_manager = $phpbb_container->get('attachment.manager');
                                $attachment_manager->delete('user', $user_id);
                                unset($attachment_manager);
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_ATTACH', false, array($user_row['username']));
                                trigger_error($user->lang['USER_ATTACHMENTS_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        case 'deloutbox':
                            if (confirm_box(true)) {
                                $msg_ids = array();
                                $lang = 'EMPTY';
                                $sql = 'SELECT msg_id
									FROM ' . PRIVMSGS_TO_TABLE . "\n\t\t\t\t\t\t\t\t\tWHERE author_id = {$user_id}\n\t\t\t\t\t\t\t\t\t\tAND folder_id = " . PRIVMSGS_OUTBOX;
                                $result = $db->sql_query($sql);
                                if ($row = $db->sql_fetchrow($result)) {
                                    if (!function_exists('delete_pm')) {
                                        include $phpbb_root_path . 'includes/functions_privmsgs.' . $phpEx;
                                    }
                                    do {
                                        $msg_ids[] = (int) $row['msg_id'];
                                    } while ($row = $db->sql_fetchrow($result));
                                    $db->sql_freeresult($result);
                                    delete_pm($user_id, $msg_ids, PRIVMSGS_OUTBOX);
                                    $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_DEL_OUTBOX', false, array($user_row['username']));
                                    $lang = 'EMPTIED';
                                }
                                $db->sql_freeresult($result);
                                trigger_error($user->lang['USER_OUTBOX_' . $lang] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        case 'moveposts':
                            if (!check_form_key($form_name)) {
                                trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            $user->add_lang('acp/forums');
                            $new_forum_id = $request->variable('new_f', 0);
                            if (!$new_forum_id) {
                                $this->page_title = 'USER_ADMIN_MOVE_POSTS';
                                $template->assign_vars(array('S_SELECT_FORUM' => true, 'U_ACTION' => $this->u_action . "&amp;action={$action}&amp;u={$user_id}", 'U_BACK' => $this->u_action . "&amp;u={$user_id}", 'S_FORUM_OPTIONS' => make_forum_select(false, false, false, true)));
                                return;
                            }
                            // Is the new forum postable to?
                            $sql = 'SELECT forum_name, forum_type
								FROM ' . FORUMS_TABLE . "\n\t\t\t\t\t\t\t\tWHERE forum_id = {$new_forum_id}";
                            $result = $db->sql_query($sql);
                            $forum_info = $db->sql_fetchrow($result);
                            $db->sql_freeresult($result);
                            if (!$forum_info) {
                                trigger_error($user->lang['NO_FORUM'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($forum_info['forum_type'] != FORUM_POST) {
                                trigger_error($user->lang['MOVE_POSTS_NO_POSTABLE_FORUM'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            // Two stage?
                            // Move topics comprising only posts from this user
                            $topic_id_ary = $move_topic_ary = $move_post_ary = $new_topic_id_ary = array();
                            $forum_id_ary = array($new_forum_id);
                            $sql = 'SELECT topic_id, post_visibility, COUNT(post_id) AS total_posts
								FROM ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\t\t\t\t\t\tAND forum_id <> {$new_forum_id}\n\t\t\t\t\t\t\t\tGROUP BY topic_id, post_visibility";
                            $result = $db->sql_query($sql);
                            while ($row = $db->sql_fetchrow($result)) {
                                $topic_id_ary[$row['topic_id']][$row['post_visibility']] = $row['total_posts'];
                            }
                            $db->sql_freeresult($result);
                            if (sizeof($topic_id_ary)) {
                                $sql = 'SELECT topic_id, forum_id, topic_title, topic_posts_approved, topic_posts_unapproved, topic_posts_softdeleted, topic_attachment
									FROM ' . TOPICS_TABLE . '
									WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if ($topic_id_ary[$row['topic_id']][ITEM_APPROVED] == $row['topic_posts_approved'] && $topic_id_ary[$row['topic_id']][ITEM_UNAPPROVED] == $row['topic_posts_unapproved'] && $topic_id_ary[$row['topic_id']][ITEM_REAPPROVE] == $row['topic_posts_unapproved'] && $topic_id_ary[$row['topic_id']][ITEM_DELETED] == $row['topic_posts_softdeleted']) {
                                        $move_topic_ary[] = $row['topic_id'];
                                    } else {
                                        $move_post_ary[$row['topic_id']]['title'] = $row['topic_title'];
                                        $move_post_ary[$row['topic_id']]['attach'] = $row['topic_attachment'] ? 1 : 0;
                                    }
                                    $forum_id_ary[] = $row['forum_id'];
                                }
                                $db->sql_freeresult($result);
                            }
                            // Entire topic comprises posts by this user, move these topics
                            if (sizeof($move_topic_ary)) {
                                move_topics($move_topic_ary, $new_forum_id, false);
                            }
                            if (sizeof($move_post_ary)) {
                                // Create new topic
                                // Update post_ids, report_ids, attachment_ids
                                foreach ($move_post_ary as $topic_id => $post_ary) {
                                    // Create new topic
                                    $sql = 'INSERT INTO ' . TOPICS_TABLE . ' ' . $db->sql_build_array('INSERT', array('topic_poster' => $user_id, 'topic_time' => time(), 'forum_id' => $new_forum_id, 'icon_id' => 0, 'topic_visibility' => ITEM_APPROVED, 'topic_title' => $post_ary['title'], 'topic_first_poster_name' => $user_row['username'], 'topic_type' => POST_NORMAL, 'topic_time_limit' => 0, 'topic_attachment' => $post_ary['attach']));
                                    $db->sql_query($sql);
                                    $new_topic_id = $db->sql_nextid();
                                    // Move posts
                                    $sql = 'UPDATE ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\tSET forum_id = {$new_forum_id}, topic_id = {$new_topic_id}\n\t\t\t\t\t\t\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\t\t\t\t\t\t\tAND poster_id = {$user_id}";
                                    $db->sql_query($sql);
                                    if ($post_ary['attach']) {
                                        $sql = 'UPDATE ' . ATTACHMENTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\t\tSET topic_id = {$new_topic_id}\n\t\t\t\t\t\t\t\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\t\t\t\t\t\t\t\tAND poster_id = {$user_id}";
                                        $db->sql_query($sql);
                                    }
                                    $new_topic_id_ary[] = $new_topic_id;
                                }
                            }
                            $forum_id_ary = array_unique($forum_id_ary);
                            $topic_id_ary = array_unique(array_merge(array_keys($topic_id_ary), $new_topic_id_ary));
                            if (sizeof($topic_id_ary)) {
                                sync('topic_reported', 'topic_id', $topic_id_ary);
                                sync('topic', 'topic_id', $topic_id_ary);
                            }
                            if (sizeof($forum_id_ary)) {
                                sync('forum', 'forum_id', $forum_id_ary, false, true);
                            }
                            $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_MOVE_POSTS', false, array($user_row['username'], $forum_info['forum_name']));
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_MOVE_POSTS_USER', false, array('reportee_id' => $user_id, $forum_info['forum_name']));
                            trigger_error($user->lang['USER_POSTS_MOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'leave_nr':
                            if (confirm_box(true)) {
                                remove_newly_registered($user_id, $user_row);
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_REMOVED_NR', false, array($user_row['username']));
                                trigger_error($user->lang['USER_LIFTED_NR'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        default:
                            /**
                             * Run custom quicktool code
                             *
                             * @event core.acp_users_overview_run_quicktool
                             * @var	array	user_row	Current user data
                             * @var	string	action		Quick tool that should be run
                             * @since 3.1.0-a1
                             */
                            $vars = array('action', 'user_row');
                            extract($phpbb_dispatcher->trigger_event('core.acp_users_overview_run_quicktool', compact($vars)));
                            break;
                    }
                    // Handle registration info updates
                    $data = array('username' => $request->variable('user', $user_row['username'], true), 'user_founder' => $request->variable('user_founder', $user_row['user_type'] == USER_FOUNDER ? 1 : 0), 'email' => strtolower($request->variable('user_email', $user_row['user_email'])), 'new_password' => $request->variable('new_password', '', true), 'password_confirm' => $request->variable('password_confirm', '', true));
                    // Validation data - we do not check the password complexity setting here
                    $check_ary = array('new_password' => array(array('string', true, $config['min_pass_chars'], $config['max_pass_chars']), array('password')), 'password_confirm' => array('string', true, $config['min_pass_chars'], $config['max_pass_chars']));
                    // Check username if altered
                    if ($data['username'] != $user_row['username']) {
                        $check_ary += array('username' => array(array('string', false, $config['min_name_chars'], $config['max_name_chars']), array('username', $user_row['username'])));
                    }
                    // Check email if altered
                    if ($data['email'] != $user_row['user_email']) {
                        $check_ary += array('email' => array(array('string', false, 6, 60), array('user_email', $user_row['user_email'])));
                    }
                    $error = validate_data($data, $check_ary);
                    if ($data['new_password'] && $data['password_confirm'] != $data['new_password']) {
                        $error[] = 'NEW_PASSWORD_ERROR';
                    }
                    if (!check_form_key($form_name)) {
                        $error[] = 'FORM_INVALID';
                    }
                    // Instantiate passwords manager
                    /* @var $passwords_manager \phpbb\passwords\manager */
                    $passwords_manager = $phpbb_container->get('passwords.manager');
                    // Which updates do we need to do?
                    $update_username = $user_row['username'] != $data['username'] ? $data['username'] : false;
                    $update_password = $data['new_password'] && !$passwords_manager->check($data['new_password'], $user_row['user_password']);
                    $update_email = $data['email'] != $user_row['user_email'] ? $data['email'] : false;
                    if (!sizeof($error)) {
                        $sql_ary = array();
                        if ($user_row['user_type'] != USER_FOUNDER || $user->data['user_type'] == USER_FOUNDER) {
                            // Only allow founders updating the founder status...
                            if ($user->data['user_type'] == USER_FOUNDER) {
                                // Setting a normal member to be a founder
                                if ($data['user_founder'] && $user_row['user_type'] != USER_FOUNDER) {
                                    // Make sure the user is not setting an Inactive or ignored user to be a founder
                                    if ($user_row['user_type'] == USER_IGNORE) {
                                        trigger_error($user->lang['CANNOT_SET_FOUNDER_IGNORED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                                    }
                                    if ($user_row['user_type'] == USER_INACTIVE) {
                                        trigger_error($user->lang['CANNOT_SET_FOUNDER_INACTIVE'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                                    }
                                    $sql_ary['user_type'] = USER_FOUNDER;
                                } else {
                                    if (!$data['user_founder'] && $user_row['user_type'] == USER_FOUNDER) {
                                        // Check if at least one founder is present
                                        $sql = 'SELECT user_id
										FROM ' . USERS_TABLE . '
										WHERE user_type = ' . USER_FOUNDER . '
											AND user_id <> ' . $user_id;
                                        $result = $db->sql_query_limit($sql, 1);
                                        $row = $db->sql_fetchrow($result);
                                        $db->sql_freeresult($result);
                                        if ($row) {
                                            $sql_ary['user_type'] = USER_NORMAL;
                                        } else {
                                            trigger_error($user->lang['AT_LEAST_ONE_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                                        }
                                    }
                                }
                            }
                        }
                        /**
                         * Modify user data before we update it
                         *
                         * @event core.acp_users_overview_modify_data
                         * @var	array	user_row	Current user data
                         * @var	array	data		Submitted user data
                         * @var	array	sql_ary		User data we udpate
                         * @since 3.1.0-a1
                         */
                        $vars = array('user_row', 'data', 'sql_ary');
                        extract($phpbb_dispatcher->trigger_event('core.acp_users_overview_modify_data', compact($vars)));
                        if ($update_username !== false) {
                            $sql_ary['username'] = $update_username;
                            $sql_ary['username_clean'] = utf8_clean_string($update_username);
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_UPDATE_NAME', false, array('reportee_id' => $user_id, $user_row['username'], $update_username));
                        }
                        if ($update_email !== false) {
                            $sql_ary += array('user_email' => $update_email, 'user_email_hash' => phpbb_email_hash($update_email));
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_UPDATE_EMAIL', false, array('reportee_id' => $user_id, $user_row['username'], $user_row['user_email'], $update_email));
                        }
                        if ($update_password) {
                            $sql_ary += array('user_password' => $passwords_manager->hash($data['new_password']), 'user_passchg' => time());
                            $user->reset_login_keys($user_id);
                            $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_NEW_PASSWORD', false, array('reportee_id' => $user_id, $user_row['username']));
                        }
                        if (sizeof($sql_ary)) {
                            $sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE user_id = ' . $user_id;
                            $db->sql_query($sql);
                        }
                        if ($update_username) {
                            user_update_name($user_row['username'], $update_username);
                        }
                        // Let the users permissions being updated
                        $auth->acl_clear_prefetch($user_id);
                        $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_USER_UPDATE', false, array($data['username']));
                        trigger_error($user->lang['USER_OVERVIEW_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = array_map(array($user, 'lang'), $error);
                }
                if ($user_id == $user->data['user_id']) {
                    $quick_tool_ary = array('delsig' => 'DEL_SIG', 'delavatar' => 'DEL_AVATAR', 'moveposts' => 'MOVE_POSTS', 'delposts' => 'DEL_POSTS', 'delattach' => 'DEL_ATTACH', 'deloutbox' => 'DEL_OUTBOX');
                    if ($user_row['user_new']) {
                        $quick_tool_ary['leave_nr'] = 'LEAVE_NR';
                    }
                } else {
                    $quick_tool_ary = array();
                    if ($user_row['user_type'] != USER_FOUNDER) {
                        $quick_tool_ary += array('banuser' => 'BAN_USER', 'banemail' => 'BAN_EMAIL', 'banip' => 'BAN_IP');
                    }
                    if ($user_row['user_type'] != USER_FOUNDER && $user_row['user_type'] != USER_IGNORE) {
                        $quick_tool_ary += array('active' => $user_row['user_type'] == USER_INACTIVE ? 'ACTIVATE' : 'DEACTIVATE');
                    }
                    $quick_tool_ary += array('delsig' => 'DEL_SIG', 'delavatar' => 'DEL_AVATAR', 'moveposts' => 'MOVE_POSTS', 'delposts' => 'DEL_POSTS', 'delattach' => 'DEL_ATTACH', 'deloutbox' => 'DEL_OUTBOX');
                    if ($config['email_enable'] && ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_INACTIVE)) {
                        $quick_tool_ary['reactivate'] = 'FORCE';
                    }
                    if ($user_row['user_new']) {
                        $quick_tool_ary['leave_nr'] = 'LEAVE_NR';
                    }
                }
                if ($config['load_onlinetrack']) {
                    $sql = 'SELECT MAX(session_time) AS session_time, MIN(session_viewonline) AS session_viewonline
						FROM ' . SESSIONS_TABLE . "\n\t\t\t\t\t\tWHERE session_user_id = {$user_id}";
                    $result = $db->sql_query($sql);
                    $row = $db->sql_fetchrow($result);
                    $db->sql_freeresult($result);
                    $user_row['session_time'] = isset($row['session_time']) ? $row['session_time'] : 0;
                    $user_row['session_viewonline'] = isset($row['session_viewonline']) ? $row['session_viewonline'] : 0;
                    unset($row);
                }
                /**
                 * Add additional quick tool options and overwrite user data
                 *
                 * @event core.acp_users_display_overview
                 * @var	array	user_row			Array with user data
                 * @var	array	quick_tool_ary		Ouick tool options
                 * @since 3.1.0-a1
                 */
                $vars = array('user_row', 'quick_tool_ary');
                extract($phpbb_dispatcher->trigger_event('core.acp_users_display_overview', compact($vars)));
                $s_action_options = '<option class="sep" value="">' . $user->lang['SELECT_OPTION'] . '</option>';
                foreach ($quick_tool_ary as $value => $lang) {
                    $s_action_options .= '<option value="' . $value . '">' . $user->lang['USER_ADMIN_' . $lang] . '</option>';
                }
                $last_active = !empty($user_row['session_time']) ? $user_row['session_time'] : $user_row['user_lastvisit'];
                $inactive_reason = '';
                if ($user_row['user_type'] == USER_INACTIVE) {
                    $inactive_reason = $user->lang['INACTIVE_REASON_UNKNOWN'];
                    switch ($user_row['user_inactive_reason']) {
                        case INACTIVE_REGISTER:
                            $inactive_reason = $user->lang['INACTIVE_REASON_REGISTER'];
                            break;
                        case INACTIVE_PROFILE:
                            $inactive_reason = $user->lang['INACTIVE_REASON_PROFILE'];
                            break;
                        case INACTIVE_MANUAL:
                            $inactive_reason = $user->lang['INACTIVE_REASON_MANUAL'];
                            break;
                        case INACTIVE_REMIND:
                            $inactive_reason = $user->lang['INACTIVE_REASON_REMIND'];
                            break;
                    }
                }
                // Posts in Queue
                $sql = 'SELECT COUNT(post_id) as posts_in_queue
					FROM ' . POSTS_TABLE . '
					WHERE poster_id = ' . $user_id . '
						AND ' . $db->sql_in_set('post_visibility', array(ITEM_UNAPPROVED, ITEM_REAPPROVE));
                $result = $db->sql_query($sql);
                $user_row['posts_in_queue'] = (int) $db->sql_fetchfield('posts_in_queue');
                $db->sql_freeresult($result);
                $sql = 'SELECT post_id
					FROM ' . POSTS_TABLE . '
					WHERE poster_id = ' . $user_id;
                $result = $db->sql_query_limit($sql, 1);
                $user_row['user_has_posts'] = (bool) $db->sql_fetchfield('post_id');
                $db->sql_freeresult($result);
                $template->assign_vars(array('L_NAME_CHARS_EXPLAIN' => $user->lang($config['allow_name_chars'] . '_EXPLAIN', $user->lang('CHARACTERS', (int) $config['min_name_chars']), $user->lang('CHARACTERS', (int) $config['max_name_chars'])), 'L_CHANGE_PASSWORD_EXPLAIN' => $user->lang($config['pass_complex'] . '_EXPLAIN', $user->lang('CHARACTERS', (int) $config['min_pass_chars']), $user->lang('CHARACTERS', (int) $config['max_pass_chars'])), 'L_POSTS_IN_QUEUE' => $user->lang('NUM_POSTS_IN_QUEUE', $user_row['posts_in_queue']), 'S_FOUNDER' => $user->data['user_type'] == USER_FOUNDER ? true : false, 'S_OVERVIEW' => true, 'S_USER_IP' => $user_row['user_ip'] ? true : false, 'S_USER_FOUNDER' => $user_row['user_type'] == USER_FOUNDER ? true : false, 'S_ACTION_OPTIONS' => $s_action_options, 'S_OWN_ACCOUNT' => $user_id == $user->data['user_id'] ? true : false, 'S_USER_INACTIVE' => $user_row['user_type'] == USER_INACTIVE ? true : false, 'U_SHOW_IP' => $this->u_action . "&amp;u={$user_id}&amp;ip=" . ($ip == 'ip' ? 'hostname' : 'ip'), 'U_WHOIS' => $this->u_action . "&amp;action=whois&amp;user_ip={$user_row['user_ip']}", 'U_MCP_QUEUE' => $auth->acl_getf_global('m_approve') ? append_sid("{$phpbb_root_path}mcp.{$phpEx}", 'i=queue', true, $user->session_id) : '', 'U_SEARCH_USER' => $config['load_search'] && $auth->acl_get('u_search') ? append_sid("{$phpbb_root_path}search.{$phpEx}", "author_id={$user_row['user_id']}&amp;sr=posts") : '', 'U_SWITCH_PERMISSIONS' => $auth->acl_get('a_switchperm') && $user->data['user_id'] != $user_row['user_id'] ? append_sid("{$phpbb_root_path}ucp.{$phpEx}", "mode=switch_perm&amp;u={$user_row['user_id']}&amp;hash=" . generate_link_hash('switchperm')) : '', 'POSTS_IN_QUEUE' => $user_row['posts_in_queue'], 'USER' => $user_row['username'], 'USER_REGISTERED' => $user->format_date($user_row['user_regdate']), 'REGISTERED_IP' => $ip == 'hostname' ? gethostbyaddr($user_row['user_ip']) : $user_row['user_ip'], 'USER_LASTACTIVE' => $last_active ? $user->format_date($last_active) : ' - ', 'USER_EMAIL' => $user_row['user_email'], 'USER_WARNINGS' => $user_row['user_warnings'], 'USER_POSTS' => $user_row['user_posts'], 'USER_HAS_POSTS' => $user_row['user_has_posts'], 'USER_INACTIVE_REASON' => $inactive_reason));
                break;
            case 'feedback':
                $user->add_lang('mcp');
                // Set up general vars
                $start = $request->variable('start', 0);
                $deletemark = isset($_POST['delmarked']) ? true : false;
                $deleteall = isset($_POST['delall']) ? true : false;
                $marked = $request->variable('mark', array(0));
                $message = $request->variable('message', '', true);
                /* @var $pagination \phpbb\pagination */
                $pagination = $phpbb_container->get('pagination');
                // Sort keys
                $sort_days = $request->variable('st', 0);
                $sort_key = $request->variable('sk', 't');
                $sort_dir = $request->variable('sd', 'd');
                // Delete entries if requested and able
                if (($deletemark || $deleteall) && $auth->acl_get('a_clearlogs')) {
                    if (!check_form_key($form_name)) {
                        trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    $where_sql = '';
                    if ($deletemark && $marked) {
                        $sql_in = array();
                        foreach ($marked as $mark) {
                            $sql_in[] = $mark;
                        }
                        $where_sql = ' AND ' . $db->sql_in_set('log_id', $sql_in);
                        unset($sql_in);
                    }
                    if ($where_sql || $deleteall) {
                        $sql = 'DELETE FROM ' . LOG_TABLE . '
							WHERE log_type = ' . LOG_USERS . "\n\t\t\t\t\t\t\tAND reportee_id = {$user_id}\n\t\t\t\t\t\t\t{$where_sql}";
                        $db->sql_query($sql);
                        $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_CLEAR_USER', false, array($user_row['username']));
                    }
                }
                if ($submit && $message) {
                    if (!check_form_key($form_name)) {
                        trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_USER_FEEDBACK', false, array($user_row['username']));
                    $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_USER_FEEDBACK', false, array('forum_id' => 0, 'topic_id' => 0, $user_row['username']));
                    $phpbb_log->add('user', $user->data['user_id'], $user->ip, 'LOG_USER_GENERAL', false, array('reportee_id' => $user_id, $message));
                    trigger_error($user->lang['USER_FEEDBACK_ADDED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                }
                // Sorting
                $limit_days = array(0 => $user->lang['ALL_ENTRIES'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_text = array('u' => $user->lang['SORT_USERNAME'], 't' => $user->lang['SORT_DATE'], 'i' => $user->lang['SORT_IP'], 'o' => $user->lang['SORT_ACTION']);
                $sort_by_sql = array('u' => 'u.username_clean', 't' => 'l.log_time', 'i' => 'l.log_ip', 'o' => 'l.log_operation');
                $s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
                gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
                // Define where and sort sql for use in displaying logs
                $sql_where = $sort_days ? time() - $sort_days * 86400 : 0;
                $sql_sort = $sort_by_sql[$sort_key] . ' ' . ($sort_dir == 'd' ? 'DESC' : 'ASC');
                // Grab log data
                $log_data = array();
                $log_count = 0;
                $start = view_log('user', $log_data, $log_count, $config['topics_per_page'], $start, 0, 0, $user_id, $sql_where, $sql_sort);
                $base_url = $this->u_action . "&amp;u={$user_id}&amp;{$u_sort_param}";
                $pagination->generate_template_pagination($base_url, 'pagination', 'start', $log_count, $config['topics_per_page'], $start);
                $template->assign_vars(array('S_FEEDBACK' => true, 'S_LIMIT_DAYS' => $s_limit_days, 'S_SORT_KEY' => $s_sort_key, 'S_SORT_DIR' => $s_sort_dir, 'S_CLEARLOGS' => $auth->acl_get('a_clearlogs')));
                foreach ($log_data as $row) {
                    $template->assign_block_vars('log', array('USERNAME' => $row['username_full'], 'IP' => $row['ip'], 'DATE' => $user->format_date($row['time']), 'ACTION' => nl2br($row['action']), 'ID' => $row['id']));
                }
                break;
            case 'warnings':
                $user->add_lang('mcp');
                // Set up general vars
                $deletemark = isset($_POST['delmarked']) ? true : false;
                $deleteall = isset($_POST['delall']) ? true : false;
                $confirm = isset($_POST['confirm']) ? true : false;
                $marked = $request->variable('mark', array(0));
                // Delete entries if requested and able
                if ($deletemark || $deleteall || $confirm) {
                    if (confirm_box(true)) {
                        $where_sql = '';
                        $deletemark = $request->variable('delmarked', 0);
                        $deleteall = $request->variable('delall', 0);
                        if ($deletemark && $marked) {
                            $where_sql = ' AND ' . $db->sql_in_set('warning_id', array_values($marked));
                        }
                        if ($where_sql || $deleteall) {
                            $sql = 'DELETE FROM ' . WARNINGS_TABLE . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}\n\t\t\t\t\t\t\t\t\t{$where_sql}";
                            $db->sql_query($sql);
                            if ($deleteall) {
                                $log_warnings = $deleted_warnings = 0;
                            } else {
                                $num_warnings = (int) $db->sql_affectedrows();
                                $deleted_warnings = ' user_warnings - ' . $num_warnings;
                                $log_warnings = $num_warnings > 2 ? 2 : $num_warnings;
                            }
                            $sql = 'UPDATE ' . USERS_TABLE . "\n\t\t\t\t\t\t\t\tSET user_warnings = {$deleted_warnings}\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            if ($log_warnings) {
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_WARNINGS_DELETED', false, array($user_row['username'], $num_warnings));
                            } else {
                                $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_WARNINGS_DELETED_ALL', false, array($user_row['username']));
                            }
                        }
                    } else {
                        $s_hidden_fields = array('i' => $id, 'mode' => $mode, 'u' => $user_id, 'mark' => $marked);
                        if (isset($_POST['delmarked'])) {
                            $s_hidden_fields['delmarked'] = 1;
                        }
                        if (isset($_POST['delall'])) {
                            $s_hidden_fields['delall'] = 1;
                        }
                        if (isset($_POST['delall']) || isset($_POST['delmarked']) && sizeof($marked)) {
                            confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields($s_hidden_fields));
                        }
                    }
                }
                $sql = 'SELECT w.warning_id, w.warning_time, w.post_id, l.log_operation, l.log_data, l.user_id AS mod_user_id, m.username AS mod_username, m.user_colour AS mod_user_colour
					FROM ' . WARNINGS_TABLE . ' w
					LEFT JOIN ' . LOG_TABLE . ' l
						ON (w.log_id = l.log_id)
					LEFT JOIN ' . USERS_TABLE . ' m
						ON (l.user_id = m.user_id)
					WHERE w.user_id = ' . $user_id . '
					ORDER BY w.warning_time DESC';
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    if (!$row['log_operation']) {
                        // We do not have a log-entry anymore, so there is no data available
                        $row['action'] = $user->lang['USER_WARNING_LOG_DELETED'];
                    } else {
                        $row['action'] = isset($user->lang[$row['log_operation']]) ? $user->lang[$row['log_operation']] : '{' . ucfirst(str_replace('_', ' ', $row['log_operation'])) . '}';
                        if (!empty($row['log_data'])) {
                            $log_data_ary = @unserialize($row['log_data']);
                            $log_data_ary = $log_data_ary === false ? array() : $log_data_ary;
                            if (isset($user->lang[$row['log_operation']])) {
                                // Check if there are more occurrences of % than arguments, if there are we fill out the arguments array
                                // It doesn't matter if we add more arguments than placeholders
                                if (substr_count($row['action'], '%') - sizeof($log_data_ary) > 0) {
                                    $log_data_ary = array_merge($log_data_ary, array_fill(0, substr_count($row['action'], '%') - sizeof($log_data_ary), ''));
                                }
                                $row['action'] = vsprintf($row['action'], $log_data_ary);
                                $row['action'] = bbcode_nl2br(censor_text($row['action']));
                            } else {
                                if (!empty($log_data_ary)) {
                                    $row['action'] .= '<br />' . implode('', $log_data_ary);
                                }
                            }
                        }
                    }
                    $template->assign_block_vars('warn', array('ID' => $row['warning_id'], 'USERNAME' => $row['log_operation'] ? get_username_string('full', $row['mod_user_id'], $row['mod_username'], $row['mod_user_colour']) : '-', 'ACTION' => make_clickable($row['action']), 'DATE' => $user->format_date($row['warning_time'])));
                }
                $db->sql_freeresult($result);
                $template->assign_vars(array('S_WARNINGS' => true));
                break;
            case 'profile':
                if (!function_exists('user_get_id_name')) {
                    include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
                }
                /* @var $cp \phpbb\profilefields\manager */
                $cp = $phpbb_container->get('profilefields.manager');
                $cp_data = $cp_error = array();
                $sql = 'SELECT lang_id
					FROM ' . LANG_TABLE . "\n\t\t\t\t\tWHERE lang_iso = '" . $db->sql_escape($user->data['user_lang']) . "'";
                $result = $db->sql_query($sql);
                $row = $db->sql_fetchrow($result);
                $db->sql_freeresult($result);
                $user_row['iso_lang_id'] = $row['lang_id'];
                $data = array('jabber' => $request->variable('jabber', $user_row['user_jabber'], true), 'bday_day' => 0, 'bday_month' => 0, 'bday_year' => 0);
                if ($user_row['user_birthday']) {
                    list($data['bday_day'], $data['bday_month'], $data['bday_year']) = explode('-', $user_row['user_birthday']);
                }
                $data['bday_day'] = $request->variable('bday_day', $data['bday_day']);
                $data['bday_month'] = $request->variable('bday_month', $data['bday_month']);
                $data['bday_year'] = $request->variable('bday_year', $data['bday_year']);
                $data['user_birthday'] = sprintf('%2d-%2d-%4d', $data['bday_day'], $data['bday_month'], $data['bday_year']);
                /**
                 * Modify user data on editing profile in ACP
                 *
                 * @event core.acp_users_modify_profile
                 * @var	array	data		Array with user profile data
                 * @var	bool	submit		Flag indicating if submit button has been pressed
                 * @var	int		user_id		The user id
                 * @var	array	user_row	Array with the full user data
                 * @since 3.1.4-RC1
                 */
                $vars = array('data', 'submit', 'user_id', 'user_row');
                extract($phpbb_dispatcher->trigger_event('core.acp_users_modify_profile', compact($vars)));
                if ($submit) {
                    $error = validate_data($data, array('jabber' => array(array('string', true, 5, 255), array('jabber')), 'bday_day' => array('num', true, 1, 31), 'bday_month' => array('num', true, 1, 12), 'bday_year' => array('num', true, 1901, gmdate('Y', time())), 'user_birthday' => array('date', true)));
                    // validate custom profile fields
                    $cp->submit_cp_field('profile', $user_row['iso_lang_id'], $cp_data, $cp_error);
                    if (sizeof($cp_error)) {
                        $error = array_merge($error, $cp_error);
                    }
                    if (!check_form_key($form_name)) {
                        $error[] = 'FORM_INVALID';
                    }
                    /**
                     * Validate profile data in ACP before submitting to the database
                     *
                     * @event core.acp_users_profile_validate
                     * @var	bool	submit		Flag indicating if submit button has been pressed
                     * @var	array	data		Array with user profile data
                     * @var	array	error		Array with the form errors
                     * @since 3.1.4-RC1
                     */
                    $vars = array('submit', 'data', 'error');
                    extract($phpbb_dispatcher->trigger_event('core.acp_users_profile_validate', compact($vars)));
                    if (!sizeof($error)) {
                        $sql_ary = array('user_jabber' => $data['jabber'], 'user_birthday' => $data['user_birthday']);
                        /**
                         * Modify profile data in ACP before submitting to the database
                         *
                         * @event core.acp_users_profile_modify_sql_ary
                         * @var	array	cp_data		Array with the user custom profile fields data
                         * @var	array	data		Array with user profile data
                         * @var	int		user_id		The user id
                         * @var	array	user_row	Array with the full user data
                         * @var	array	sql_ary		Array with sql data
                         * @since 3.1.4-RC1
                         */
                        $vars = array('cp_data', 'data', 'user_id', 'user_row', 'sql_ary');
                        extract($phpbb_dispatcher->trigger_event('core.acp_users_profile_modify_sql_ary', compact($vars)));
                        $sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                        $db->sql_query($sql);
                        // Update Custom Fields
                        $cp->update_profile_field_data($user_id, $cp_data);
                        trigger_error($user->lang['USER_PROFILE_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = array_map(array($user, 'lang'), $error);
                }
                $s_birthday_day_options = '<option value="0"' . (!$data['bday_day'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = 1; $i < 32; $i++) {
                    $selected = $i == $data['bday_day'] ? ' selected="selected"' : '';
                    $s_birthday_day_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                $s_birthday_month_options = '<option value="0"' . (!$data['bday_month'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = 1; $i < 13; $i++) {
                    $selected = $i == $data['bday_month'] ? ' selected="selected"' : '';
                    $s_birthday_month_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                $now = getdate();
                $s_birthday_year_options = '<option value="0"' . (!$data['bday_year'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = $now['year'] - 100; $i <= $now['year']; $i++) {
                    $selected = $i == $data['bday_year'] ? ' selected="selected"' : '';
                    $s_birthday_year_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                unset($now);
                $template->assign_vars(array('JABBER' => $data['jabber'], 'S_BIRTHDAY_DAY_OPTIONS' => $s_birthday_day_options, 'S_BIRTHDAY_MONTH_OPTIONS' => $s_birthday_month_options, 'S_BIRTHDAY_YEAR_OPTIONS' => $s_birthday_year_options, 'S_PROFILE' => true));
                // Get additional profile fields and assign them to the template block var 'profile_fields'
                $user->get_profile_fields($user_id);
                $cp->generate_profile_fields('profile', $user_row['iso_lang_id']);
                break;
            case 'prefs':
                if (!function_exists('user_get_id_name')) {
                    include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
                }
                $data = array('dateformat' => $request->variable('dateformat', $user_row['user_dateformat'], true), 'lang' => basename($request->variable('lang', $user_row['user_lang'])), 'tz' => $request->variable('tz', $user_row['user_timezone']), 'style' => $request->variable('style', $user_row['user_style']), 'viewemail' => $request->variable('viewemail', $user_row['user_allow_viewemail']), 'massemail' => $request->variable('massemail', $user_row['user_allow_massemail']), 'hideonline' => $request->variable('hideonline', !$user_row['user_allow_viewonline']), 'notifymethod' => $request->variable('notifymethod', $user_row['user_notify_type']), 'notifypm' => $request->variable('notifypm', $user_row['user_notify_pm']), 'allowpm' => $request->variable('allowpm', $user_row['user_allow_pm']), 'topic_sk' => $request->variable('topic_sk', $user_row['user_topic_sortby_type'] ? $user_row['user_topic_sortby_type'] : 't'), 'topic_sd' => $request->variable('topic_sd', $user_row['user_topic_sortby_dir'] ? $user_row['user_topic_sortby_dir'] : 'd'), 'topic_st' => $request->variable('topic_st', $user_row['user_topic_show_days'] ? $user_row['user_topic_show_days'] : 0), 'post_sk' => $request->variable('post_sk', $user_row['user_post_sortby_type'] ? $user_row['user_post_sortby_type'] : 't'), 'post_sd' => $request->variable('post_sd', $user_row['user_post_sortby_dir'] ? $user_row['user_post_sortby_dir'] : 'a'), 'post_st' => $request->variable('post_st', $user_row['user_post_show_days'] ? $user_row['user_post_show_days'] : 0), 'view_images' => $request->variable('view_images', $this->optionget($user_row, 'viewimg')), 'view_flash' => $request->variable('view_flash', $this->optionget($user_row, 'viewflash')), 'view_smilies' => $request->variable('view_smilies', $this->optionget($user_row, 'viewsmilies')), 'view_sigs' => $request->variable('view_sigs', $this->optionget($user_row, 'viewsigs')), 'view_avatars' => $request->variable('view_avatars', $this->optionget($user_row, 'viewavatars')), 'view_wordcensor' => $request->variable('view_wordcensor', $this->optionget($user_row, 'viewcensors')), 'bbcode' => $request->variable('bbcode', $this->optionget($user_row, 'bbcode')), 'smilies' => $request->variable('smilies', $this->optionget($user_row, 'smilies')), 'sig' => $request->variable('sig', $this->optionget($user_row, 'attachsig')), 'notify' => $request->variable('notify', $user_row['user_notify']));
                /**
                 * Modify users preferences data
                 *
                 * @event core.acp_users_prefs_modify_data
                 * @var	array	data			Array with users preferences data
                 * @var	array	user_row		Array with user data
                 * @since 3.1.0-b3
                 */
                $vars = array('data', 'user_row');
                extract($phpbb_dispatcher->trigger_event('core.acp_users_prefs_modify_data', compact($vars)));
                if ($submit) {
                    $error = validate_data($data, array('dateformat' => array('string', false, 1, 64), 'lang' => array('match', false, '#^[a-z_\\-]{2,}$#i'), 'tz' => array('timezone'), 'topic_sk' => array('string', false, 1, 1), 'topic_sd' => array('string', false, 1, 1), 'post_sk' => array('string', false, 1, 1), 'post_sd' => array('string', false, 1, 1)));
                    if (!check_form_key($form_name)) {
                        $error[] = 'FORM_INVALID';
                    }
                    if (!sizeof($error)) {
                        $this->optionset($user_row, 'viewimg', $data['view_images']);
                        $this->optionset($user_row, 'viewflash', $data['view_flash']);
                        $this->optionset($user_row, 'viewsmilies', $data['view_smilies']);
                        $this->optionset($user_row, 'viewsigs', $data['view_sigs']);
                        $this->optionset($user_row, 'viewavatars', $data['view_avatars']);
                        $this->optionset($user_row, 'viewcensors', $data['view_wordcensor']);
                        $this->optionset($user_row, 'bbcode', $data['bbcode']);
                        $this->optionset($user_row, 'smilies', $data['smilies']);
                        $this->optionset($user_row, 'attachsig', $data['sig']);
                        $sql_ary = array('user_options' => $user_row['user_options'], 'user_allow_pm' => $data['allowpm'], 'user_allow_viewemail' => $data['viewemail'], 'user_allow_massemail' => $data['massemail'], 'user_allow_viewonline' => !$data['hideonline'], 'user_notify_type' => $data['notifymethod'], 'user_notify_pm' => $data['notifypm'], 'user_dateformat' => $data['dateformat'], 'user_lang' => $data['lang'], 'user_timezone' => $data['tz'], 'user_style' => $data['style'], 'user_topic_sortby_type' => $data['topic_sk'], 'user_post_sortby_type' => $data['post_sk'], 'user_topic_sortby_dir' => $data['topic_sd'], 'user_post_sortby_dir' => $data['post_sd'], 'user_topic_show_days' => $data['topic_st'], 'user_post_show_days' => $data['post_st'], 'user_notify' => $data['notify']);
                        /**
                         * Modify SQL query before users preferences are updated
                         *
                         * @event core.acp_users_prefs_modify_sql
                         * @var	array	data			Array with users preferences data
                         * @var	array	user_row		Array with user data
                         * @var	array	sql_ary			SQL array with users preferences data to update
                         * @var	array	error			Array with errors data
                         * @since 3.1.0-b3
                         */
                        $vars = array('data', 'user_row', 'sql_ary', 'error');
                        extract($phpbb_dispatcher->trigger_event('core.acp_users_prefs_modify_sql', compact($vars)));
                        if (!sizeof($error)) {
                            $sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            // Check if user has an active session
                            if ($user_row['session_id']) {
                                // We'll update the session if user_allow_viewonline has changed and the user is a bot
                                // Or if it's a regular user and the admin set it to hide the session
                                if ($user_row['user_allow_viewonline'] != $sql_ary['user_allow_viewonline'] && $user_row['user_type'] == USER_IGNORE || $user_row['user_allow_viewonline'] && !$sql_ary['user_allow_viewonline']) {
                                    // We also need to check if the user has the permission to cloak.
                                    $user_auth = new \phpbb\auth\auth();
                                    $user_auth->acl($user_row);
                                    $session_sql_ary = array('session_viewonline' => $user_auth->acl_get('u_hideonline') ? $sql_ary['user_allow_viewonline'] : true);
                                    $sql = 'UPDATE ' . SESSIONS_TABLE . '
										SET ' . $db->sql_build_array('UPDATE', $session_sql_ary) . "\n\t\t\t\t\t\t\t\t\t\tWHERE session_user_id = {$user_id}";
                                    $db->sql_query($sql);
                                    unset($user_auth);
                                }
                            }
                            trigger_error($user->lang['USER_PREFS_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                        }
                    }
                    // Replace "error" strings with their real, localised form
                    $error = array_map(array($user, 'lang'), $error);
                }
                $dateformat_options = '';
                foreach ($user->lang['dateformats'] as $format => $null) {
                    $dateformat_options .= '<option value="' . $format . '"' . ($format == $data['dateformat'] ? ' selected="selected"' : '') . '>';
                    $dateformat_options .= $user->format_date(time(), $format, false) . (strpos($format, '|') !== false ? $user->lang['VARIANT_DATE_SEPARATOR'] . $user->format_date(time(), $format, true) : '');
                    $dateformat_options .= '</option>';
                }
                $s_custom = false;
                $dateformat_options .= '<option value="custom"';
                if (!isset($user->lang['dateformats'][$data['dateformat']])) {
                    $dateformat_options .= ' selected="selected"';
                    $s_custom = true;
                }
                $dateformat_options .= '>' . $user->lang['CUSTOM_DATEFORMAT'] . '</option>';
                $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
                // Topic ordering options
                $limit_topic_days = array(0 => $user->lang['ALL_TOPICS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_topic_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 'r' => $user->lang['REPLIES'], 's' => $user->lang['SUBJECT'], 'v' => $user->lang['VIEWS']);
                // Post ordering options
                $limit_post_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_post_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
                $_options = array('topic', 'post');
                foreach ($_options as $sort_option) {
                    ${'s_limit_' . $sort_option . '_days'} = '<select name="' . $sort_option . '_st">';
                    foreach (${'limit_' . $sort_option . '_days'} as $day => $text) {
                        $selected = $data[$sort_option . '_st'] == $day ? ' selected="selected"' : '';
                        ${'s_limit_' . $sort_option . '_days'} .= '<option value="' . $day . '"' . $selected . '>' . $text . '</option>';
                    }
                    ${'s_limit_' . $sort_option . '_days'} .= '</select>';
                    ${'s_sort_' . $sort_option . '_key'} = '<select name="' . $sort_option . '_sk">';
                    foreach (${'sort_by_' . $sort_option . '_text'} as $key => $text) {
                        $selected = $data[$sort_option . '_sk'] == $key ? ' selected="selected"' : '';
                        ${'s_sort_' . $sort_option . '_key'} .= '<option value="' . $key . '"' . $selected . '>' . $text . '</option>';
                    }
                    ${'s_sort_' . $sort_option . '_key'} .= '</select>';
                    ${'s_sort_' . $sort_option . '_dir'} = '<select name="' . $sort_option . '_sd">';
                    foreach ($sort_dir_text as $key => $value) {
                        $selected = $data[$sort_option . '_sd'] == $key ? ' selected="selected"' : '';
                        ${'s_sort_' . $sort_option . '_dir'} .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                    }
                    ${'s_sort_' . $sort_option . '_dir'} .= '</select>';
                }
                phpbb_timezone_select($template, $user, $data['tz'], true);
                $user_prefs_data = array('S_PREFS' => true, 'S_JABBER_DISABLED' => $config['jab_enable'] && $user_row['user_jabber'] && @extension_loaded('xml') ? false : true, 'VIEW_EMAIL' => $data['viewemail'], 'MASS_EMAIL' => $data['massemail'], 'ALLOW_PM' => $data['allowpm'], 'HIDE_ONLINE' => $data['hideonline'], 'NOTIFY_EMAIL' => $data['notifymethod'] == NOTIFY_EMAIL ? true : false, 'NOTIFY_IM' => $data['notifymethod'] == NOTIFY_IM ? true : false, 'NOTIFY_BOTH' => $data['notifymethod'] == NOTIFY_BOTH ? true : false, 'NOTIFY_PM' => $data['notifypm'], 'BBCODE' => $data['bbcode'], 'SMILIES' => $data['smilies'], 'ATTACH_SIG' => $data['sig'], 'NOTIFY' => $data['notify'], 'VIEW_IMAGES' => $data['view_images'], 'VIEW_FLASH' => $data['view_flash'], 'VIEW_SMILIES' => $data['view_smilies'], 'VIEW_SIGS' => $data['view_sigs'], 'VIEW_AVATARS' => $data['view_avatars'], 'VIEW_WORDCENSOR' => $data['view_wordcensor'], 'S_TOPIC_SORT_DAYS' => $s_limit_topic_days, 'S_TOPIC_SORT_KEY' => $s_sort_topic_key, 'S_TOPIC_SORT_DIR' => $s_sort_topic_dir, 'S_POST_SORT_DAYS' => $s_limit_post_days, 'S_POST_SORT_KEY' => $s_sort_post_key, 'S_POST_SORT_DIR' => $s_sort_post_dir, 'DATE_FORMAT' => $data['dateformat'], 'S_DATEFORMAT_OPTIONS' => $dateformat_options, 'S_CUSTOM_DATEFORMAT' => $s_custom, 'DEFAULT_DATEFORMAT' => $config['default_dateformat'], 'A_DEFAULT_DATEFORMAT' => addslashes($config['default_dateformat']), 'S_LANG_OPTIONS' => language_select($data['lang']), 'S_STYLE_OPTIONS' => style_select($data['style']));
                /**
                 * Modify users preferences data before assigning it to the template
                 *
                 * @event core.acp_users_prefs_modify_template_data
                 * @var	array	data				Array with users preferences data
                 * @var	array	user_row			Array with user data
                 * @var	array	user_prefs_data		Array with users preferences data to be assigned to the template
                 * @since 3.1.0-b3
                 */
                $vars = array('data', 'user_row', 'user_prefs_data');
                extract($phpbb_dispatcher->trigger_event('core.acp_users_prefs_modify_template_data', compact($vars)));
                $template->assign_vars($user_prefs_data);
                break;
            case 'avatar':
                $avatars_enabled = false;
                /** @var \phpbb\avatar\manager $phpbb_avatar_manager */
                $phpbb_avatar_manager = $phpbb_container->get('avatar.manager');
                if ($config['allow_avatar']) {
                    $avatar_drivers = $phpbb_avatar_manager->get_enabled_drivers();
                    // This is normalised data, without the user_ prefix
                    $avatar_data = \phpbb\avatar\manager::clean_row($user_row, 'user');
                    if ($submit) {
                        if (check_form_key($form_name)) {
                            $driver_name = $phpbb_avatar_manager->clean_driver_name($request->variable('avatar_driver', ''));
                            if (in_array($driver_name, $avatar_drivers) && !$request->is_set_post('avatar_delete')) {
                                $driver = $phpbb_avatar_manager->get_driver($driver_name);
                                $result = $driver->process_form($request, $template, $user, $avatar_data, $error);
                                if ($result && empty($error)) {
                                    // Success! Lets save the result in the database
                                    $result = array('user_avatar_type' => $driver_name, 'user_avatar' => $result['avatar'], 'user_avatar_width' => $result['avatar_width'], 'user_avatar_height' => $result['avatar_height']);
                                    $sql = 'UPDATE ' . USERS_TABLE . '
										SET ' . $db->sql_build_array('UPDATE', $result) . '
										WHERE user_id = ' . (int) $user_id;
                                    $db->sql_query($sql);
                                    trigger_error($user->lang['USER_AVATAR_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                                }
                            }
                        } else {
                            trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                    }
                    // Handle deletion of avatars
                    if ($request->is_set_post('avatar_delete')) {
                        if (!confirm_box(true)) {
                            confirm_box(false, $user->lang('CONFIRM_AVATAR_DELETE'), build_hidden_fields(array('avatar_delete' => true)));
                        } else {
                            $phpbb_avatar_manager->handle_avatar_delete($db, $user, $avatar_data, USERS_TABLE, 'user_');
                            trigger_error($user->lang['USER_AVATAR_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                        }
                    }
                    $selected_driver = $phpbb_avatar_manager->clean_driver_name($request->variable('avatar_driver', $user_row['user_avatar_type']));
                    // Assign min and max values before generating avatar driver html
                    $template->assign_vars(array('AVATAR_MIN_WIDTH' => $config['avatar_min_width'], 'AVATAR_MAX_WIDTH' => $config['avatar_max_width'], 'AVATAR_MIN_HEIGHT' => $config['avatar_min_height'], 'AVATAR_MAX_HEIGHT' => $config['avatar_max_height']));
                    foreach ($avatar_drivers as $current_driver) {
                        $driver = $phpbb_avatar_manager->get_driver($current_driver);
                        $avatars_enabled = true;
                        $template->set_filenames(array('avatar' => $driver->get_acp_template_name()));
                        if ($driver->prepare_form($request, $template, $user, $avatar_data, $error)) {
                            $driver_name = $phpbb_avatar_manager->prepare_driver_name($current_driver);
                            $driver_upper = strtoupper($driver_name);
                            $template->assign_block_vars('avatar_drivers', array('L_TITLE' => $user->lang($driver_upper . '_TITLE'), 'L_EXPLAIN' => $user->lang($driver_upper . '_EXPLAIN'), 'DRIVER' => $driver_name, 'SELECTED' => $current_driver == $selected_driver, 'OUTPUT' => $template->assign_display('avatar')));
                        }
                    }
                }
                // Avatar manager is not initialized if avatars are disabled
                if (isset($phpbb_avatar_manager)) {
                    // Replace "error" strings with their real, localised form
                    $error = $phpbb_avatar_manager->localize_errors($user, $error);
                }
                $avatar = phpbb_get_user_avatar($user_row, 'USER_AVATAR', true);
                $template->assign_vars(array('S_AVATAR' => true, 'ERROR' => !empty($error) ? implode('<br />', $error) : '', 'AVATAR' => empty($avatar) ? '<img src="' . $phpbb_admin_path . 'images/no_avatar.gif" alt="" />' : $avatar, 'S_FORM_ENCTYPE' => ' enctype="multipart/form-data"', 'L_AVATAR_EXPLAIN' => sprintf($user->lang['AVATAR_EXPLAIN'], $config['avatar_max_width'], $config['avatar_max_height'], $config['avatar_filesize'] / 1024), 'S_AVATARS_ENABLED' => $config['allow_avatar'] && $avatars_enabled));
                break;
            case 'rank':
                if ($submit) {
                    if (!check_form_key($form_name)) {
                        trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    $rank_id = $request->variable('user_rank', 0);
                    $sql = 'UPDATE ' . USERS_TABLE . "\n\t\t\t\t\t\tSET user_rank = {$rank_id}\n\t\t\t\t\t\tWHERE user_id = {$user_id}";
                    $db->sql_query($sql);
                    trigger_error($user->lang['USER_RANK_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                }
                $sql = 'SELECT *
					FROM ' . RANKS_TABLE . '
					WHERE rank_special = 1
					ORDER BY rank_title';
                $result = $db->sql_query($sql);
                $s_rank_options = '<option value="0"' . (!$user_row['user_rank'] ? ' selected="selected"' : '') . '>' . $user->lang['NO_SPECIAL_RANK'] . '</option>';
                while ($row = $db->sql_fetchrow($result)) {
                    $selected = $user_row['user_rank'] && $row['rank_id'] == $user_row['user_rank'] ? ' selected="selected"' : '';
                    $s_rank_options .= '<option value="' . $row['rank_id'] . '"' . $selected . '>' . $row['rank_title'] . '</option>';
                }
                $db->sql_freeresult($result);
                $template->assign_vars(array('S_RANK' => true, 'S_RANK_OPTIONS' => $s_rank_options));
                break;
            case 'sig':
                if (!function_exists('display_custom_bbcodes')) {
                    include $phpbb_root_path . 'includes/functions_display.' . $phpEx;
                }
                $enable_bbcode = $config['allow_sig_bbcode'] ? $this->optionget($user_row, 'sig_bbcode') : false;
                $enable_smilies = $config['allow_sig_smilies'] ? $this->optionget($user_row, 'sig_smilies') : false;
                $enable_urls = $config['allow_sig_links'] ? $this->optionget($user_row, 'sig_links') : false;
                $decoded_message = generate_text_for_edit($user_row['user_sig'], $user_row['user_sig_bbcode_uid'], $user_row['user_sig_bbcode_bitfield']);
                $signature = $request->variable('signature', $decoded_message['text'], true);
                $signature_preview = '';
                if ($submit || $request->is_set_post('preview')) {
                    $enable_bbcode = $config['allow_sig_bbcode'] ? !$request->variable('disable_bbcode', false) : false;
                    $enable_smilies = $config['allow_sig_smilies'] ? !$request->variable('disable_smilies', false) : false;
                    $enable_urls = $config['allow_sig_links'] ? !$request->variable('disable_magic_url', false) : false;
                    if (!check_form_key($form_name)) {
                        $error[] = 'FORM_INVALID';
                    }
                }
                $bbcode_uid = $bbcode_bitfield = $bbcode_flags = '';
                $warn_msg = generate_text_for_storage($signature, $bbcode_uid, $bbcode_bitfield, $bbcode_flags, $enable_bbcode, $enable_urls, $enable_smilies, $config['allow_sig_img'], $config['allow_sig_flash'], true, $config['allow_sig_links'], 'sig');
                if (sizeof($warn_msg)) {
                    $error += $warn_msg;
                }
                if (!$submit) {
                    // Parse it for displaying
                    $signature_preview = generate_text_for_display($signature, $bbcode_uid, $bbcode_bitfield, $bbcode_flags);
                } else {
                    if (!sizeof($error)) {
                        $this->optionset($user_row, 'sig_bbcode', $enable_bbcode);
                        $this->optionset($user_row, 'sig_smilies', $enable_smilies);
                        $this->optionset($user_row, 'sig_links', $enable_urls);
                        $sql_ary = array('user_sig' => $signature, 'user_options' => $user_row['user_options'], 'user_sig_bbcode_uid' => $bbcode_uid, 'user_sig_bbcode_bitfield' => $bbcode_bitfield);
                        $sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
							WHERE user_id = ' . $user_id;
                        $db->sql_query($sql);
                        trigger_error($user->lang['USER_SIG_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                }
                // Replace "error" strings with their real, localised form
                $error = array_map(array($user, 'lang'), $error);
                if ($request->is_set_post('preview')) {
                    $decoded_message = generate_text_for_edit($signature, $bbcode_uid, $bbcode_bitfield);
                }
                /** @var \phpbb\controller\helper $controller_helper */
                $controller_helper = $phpbb_container->get('controller.helper');
                $template->assign_vars(array('S_SIGNATURE' => true, 'SIGNATURE' => $decoded_message['text'], 'SIGNATURE_PREVIEW' => $signature_preview, 'S_BBCODE_CHECKED' => !$enable_bbcode ? ' checked="checked"' : '', 'S_SMILIES_CHECKED' => !$enable_smilies ? ' checked="checked"' : '', 'S_MAGIC_URL_CHECKED' => !$enable_urls ? ' checked="checked"' : '', 'BBCODE_STATUS' => $user->lang($config['allow_sig_bbcode'] ? 'BBCODE_IS_ON' : 'BBCODE_IS_OFF', '<a href="' . $controller_helper->route('phpbb_help_bbcode_controller') . '">', '</a>'), 'SMILIES_STATUS' => $config['allow_sig_smilies'] ? $user->lang['SMILIES_ARE_ON'] : $user->lang['SMILIES_ARE_OFF'], 'IMG_STATUS' => $config['allow_sig_img'] ? $user->lang['IMAGES_ARE_ON'] : $user->lang['IMAGES_ARE_OFF'], 'FLASH_STATUS' => $config['allow_sig_flash'] ? $user->lang['FLASH_IS_ON'] : $user->lang['FLASH_IS_OFF'], 'URL_STATUS' => $config['allow_sig_links'] ? $user->lang['URL_IS_ON'] : $user->lang['URL_IS_OFF'], 'L_SIGNATURE_EXPLAIN' => $user->lang('SIGNATURE_EXPLAIN', (int) $config['max_sig_chars']), 'S_BBCODE_ALLOWED' => $config['allow_sig_bbcode'], 'S_SMILIES_ALLOWED' => $config['allow_sig_smilies'], 'S_BBCODE_IMG' => $config['allow_sig_img'] ? true : false, 'S_BBCODE_FLASH' => $config['allow_sig_flash'] ? true : false, 'S_LINKS_ALLOWED' => $config['allow_sig_links'] ? true : false));
                // Assigning custom bbcodes
                display_custom_bbcodes();
                break;
            case 'attach':
                /* @var $pagination \phpbb\pagination */
                $pagination = $phpbb_container->get('pagination');
                $start = $request->variable('start', 0);
                $deletemark = isset($_POST['delmarked']) ? true : false;
                $marked = $request->variable('mark', array(0));
                // Sort keys
                $sort_key = $request->variable('sk', 'a');
                $sort_dir = $request->variable('sd', 'd');
                if ($deletemark && sizeof($marked)) {
                    $sql = 'SELECT attach_id
						FROM ' . ATTACHMENTS_TABLE . '
						WHERE poster_id = ' . $user_id . '
							AND is_orphan = 0
							AND ' . $db->sql_in_set('attach_id', $marked);
                    $result = $db->sql_query($sql);
                    $marked = array();
                    while ($row = $db->sql_fetchrow($result)) {
                        $marked[] = $row['attach_id'];
                    }
                    $db->sql_freeresult($result);
                }
                if ($deletemark && sizeof($marked)) {
                    if (confirm_box(true)) {
                        $sql = 'SELECT real_filename
							FROM ' . ATTACHMENTS_TABLE . '
							WHERE ' . $db->sql_in_set('attach_id', $marked);
                        $result = $db->sql_query($sql);
                        $log_attachments = array();
                        while ($row = $db->sql_fetchrow($result)) {
                            $log_attachments[] = $row['real_filename'];
                        }
                        $db->sql_freeresult($result);
                        /** @var \phpbb\attachment\manager $attachment_manager */
                        $attachment_manager = $phpbb_container->get('attachment.manager');
                        $attachment_manager->delete('attach', $marked);
                        unset($attachment_manager);
                        $message = sizeof($log_attachments) == 1 ? $user->lang['ATTACHMENT_DELETED'] : $user->lang['ATTACHMENTS_DELETED'];
                        $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_ATTACHMENTS_DELETED', false, array(implode($user->lang['COMMA_SEPARATOR'], $log_attachments)));
                        trigger_error($message . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    } else {
                        confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'delmarked' => true, 'mark' => $marked)));
                    }
                }
                $sk_text = array('a' => $user->lang['SORT_FILENAME'], 'c' => $user->lang['SORT_EXTENSION'], 'd' => $user->lang['SORT_SIZE'], 'e' => $user->lang['SORT_DOWNLOADS'], 'f' => $user->lang['SORT_POST_TIME'], 'g' => $user->lang['SORT_TOPIC_TITLE']);
                $sk_sql = array('a' => 'a.real_filename', 'c' => 'a.extension', 'd' => 'a.filesize', 'e' => 'a.download_count', 'f' => 'a.filetime', 'g' => 't.topic_title');
                $sd_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
                $s_sort_key = '';
                foreach ($sk_text as $key => $value) {
                    $selected = $sort_key == $key ? ' selected="selected"' : '';
                    $s_sort_key .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                }
                $s_sort_dir = '';
                foreach ($sd_text as $key => $value) {
                    $selected = $sort_dir == $key ? ' selected="selected"' : '';
                    $s_sort_dir .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                }
                if (!isset($sk_sql[$sort_key])) {
                    $sort_key = 'a';
                }
                $order_by = $sk_sql[$sort_key] . ' ' . ($sort_dir == 'a' ? 'ASC' : 'DESC');
                $sql = 'SELECT COUNT(attach_id) as num_attachments
					FROM ' . ATTACHMENTS_TABLE . "\n\t\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\t\t\tAND is_orphan = 0";
                $result = $db->sql_query_limit($sql, 1);
                $num_attachments = (int) $db->sql_fetchfield('num_attachments');
                $db->sql_freeresult($result);
                $sql = 'SELECT a.*, t.topic_title, p.message_subject as message_title
					FROM ' . ATTACHMENTS_TABLE . ' a
						LEFT JOIN ' . TOPICS_TABLE . ' t ON (a.topic_id = t.topic_id
							AND a.in_message = 0)
						LEFT JOIN ' . PRIVMSGS_TABLE . ' p ON (a.post_msg_id = p.msg_id
							AND a.in_message = 1)
					WHERE a.poster_id = ' . $user_id . "\n\t\t\t\t\t\tAND a.is_orphan = 0\n\t\t\t\t\tORDER BY {$order_by}";
                $result = $db->sql_query_limit($sql, $config['topics_per_page'], $start);
                while ($row = $db->sql_fetchrow($result)) {
                    if ($row['in_message']) {
                        $view_topic = append_sid("{$phpbb_root_path}ucp.{$phpEx}", "i=pm&amp;p={$row['post_msg_id']}");
                    } else {
                        $view_topic = append_sid("{$phpbb_root_path}viewtopic.{$phpEx}", "t={$row['topic_id']}&amp;p={$row['post_msg_id']}") . '#p' . $row['post_msg_id'];
                    }
                    $template->assign_block_vars('attach', array('REAL_FILENAME' => $row['real_filename'], 'COMMENT' => nl2br($row['attach_comment']), 'EXTENSION' => $row['extension'], 'SIZE' => get_formatted_filesize($row['filesize']), 'DOWNLOAD_COUNT' => $row['download_count'], 'POST_TIME' => $user->format_date($row['filetime']), 'TOPIC_TITLE' => $row['in_message'] ? $row['message_title'] : $row['topic_title'], 'ATTACH_ID' => $row['attach_id'], 'POST_ID' => $row['post_msg_id'], 'TOPIC_ID' => $row['topic_id'], 'S_IN_MESSAGE' => $row['in_message'], 'U_DOWNLOAD' => append_sid("{$phpbb_root_path}download/file.{$phpEx}", 'mode=view&amp;id=' . $row['attach_id']), 'U_VIEW_TOPIC' => $view_topic));
                }
                $db->sql_freeresult($result);
                $base_url = $this->u_action . "&amp;u={$user_id}&amp;sk={$sort_key}&amp;sd={$sort_dir}";
                $pagination->generate_template_pagination($base_url, 'pagination', 'start', $num_attachments, $config['topics_per_page'], $start);
                $template->assign_vars(array('S_ATTACHMENTS' => true, 'S_SORT_KEY' => $s_sort_key, 'S_SORT_DIR' => $s_sort_dir));
                break;
            case 'groups':
                if (!function_exists('group_user_attributes')) {
                    include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
                }
                $user->add_lang(array('groups', 'acp/groups'));
                $group_id = $request->variable('g', 0);
                if ($group_id) {
                    // Check the founder only entry for this group to make sure everything is well
                    $sql = 'SELECT group_founder_manage
						FROM ' . GROUPS_TABLE . '
						WHERE group_id = ' . $group_id;
                    $result = $db->sql_query($sql);
                    $founder_manage = (int) $db->sql_fetchfield('group_founder_manage');
                    $db->sql_freeresult($result);
                    if ($user->data['user_type'] != USER_FOUNDER && $founder_manage) {
                        trigger_error($user->lang['NOT_ALLOWED_MANAGE_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                }
                switch ($action) {
                    case 'demote':
                    case 'promote':
                    case 'default':
                        if (!$group_id) {
                            trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                        }
                        group_user_attributes($action, $group_id, $user_id);
                        if ($action == 'default') {
                            $user_row['group_id'] = $group_id;
                        }
                        break;
                    case 'delete':
                        if (confirm_box(true)) {
                            if (!$group_id) {
                                trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            if ($error = group_user_del($group_id, $user_id)) {
                                trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            $error = array();
                            // The delete action was successful - therefore update the user row...
                            $sql = 'SELECT u.*, s.*
								FROM ' . USERS_TABLE . ' u
									LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
								WHERE u.user_id = ' . $user_id . '
								ORDER BY s.session_time DESC';
                            $result = $db->sql_query_limit($sql, 1);
                            $user_row = $db->sql_fetchrow($result);
                            $db->sql_freeresult($result);
                        } else {
                            confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'g' => $group_id)));
                        }
                        break;
                    case 'approve':
                        if (confirm_box(true)) {
                            if (!$group_id) {
                                trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                            }
                            group_user_attributes($action, $group_id, $user_id);
                        } else {
                            confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'g' => $group_id)));
                        }
                        break;
                }
                // Add user to group?
                if ($submit) {
                    if (!check_form_key($form_name)) {
                        trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    if (!$group_id) {
                        trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    // Add user/s to group
                    if ($error = group_user_add($group_id, $user_id)) {
                        trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
                    }
                    $error = array();
                }
                /** @var \phpbb\group\helper $group_helper */
                $group_helper = $phpbb_container->get('group_helper');
                $sql = 'SELECT ug.*, g.*
					FROM ' . GROUPS_TABLE . ' g, ' . USER_GROUP_TABLE . " ug\n\t\t\t\t\tWHERE ug.user_id = {$user_id}\n\t\t\t\t\t\tAND g.group_id = ug.group_id\n\t\t\t\t\tORDER BY g.group_type DESC, ug.user_pending ASC, g.group_name";
                $result = $db->sql_query($sql);
                $i = 0;
                $group_data = $id_ary = array();
                while ($row = $db->sql_fetchrow($result)) {
                    $type = $row['group_type'] == GROUP_SPECIAL ? 'special' : ($row['user_pending'] ? 'pending' : 'normal');
                    $group_data[$type][$i]['group_id'] = $row['group_id'];
                    $group_data[$type][$i]['group_name'] = $row['group_name'];
                    $group_data[$type][$i]['group_leader'] = $row['group_leader'] ? 1 : 0;
                    $id_ary[] = $row['group_id'];
                    $i++;
                }
                $db->sql_freeresult($result);
                // Select box for other groups
                $sql = 'SELECT group_id, group_name, group_type, group_founder_manage
					FROM ' . GROUPS_TABLE . '
					' . (sizeof($id_ary) ? 'WHERE ' . $db->sql_in_set('group_id', $id_ary, true) : '') . '
					ORDER BY group_type DESC, group_name ASC';
                $result = $db->sql_query($sql);
                $s_group_options = '';
                while ($row = $db->sql_fetchrow($result)) {
                    if (!$config['coppa_enable'] && $row['group_name'] == 'REGISTERED_COPPA') {
                        continue;
                    }
                    // Do not display those groups not allowed to be managed
                    if ($user->data['user_type'] != USER_FOUNDER && $row['group_founder_manage']) {
                        continue;
                    }
                    $s_group_options .= '<option' . ($row['group_type'] == GROUP_SPECIAL ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '">' . $group_helper->get_name($row['group_name']) . '</option>';
                }
                $db->sql_freeresult($result);
                $current_type = '';
                foreach ($group_data as $group_type => $data_ary) {
                    if ($current_type != $group_type) {
                        $template->assign_block_vars('group', array('S_NEW_GROUP_TYPE' => true, 'GROUP_TYPE' => $user->lang['USER_GROUP_' . strtoupper($group_type)]));
                    }
                    foreach ($data_ary as $data) {
                        $template->assign_block_vars('group', array('U_EDIT_GROUP' => append_sid("{$phpbb_admin_path}index.{$phpEx}", "i=groups&amp;mode=manage&amp;action=edit&amp;u={$user_id}&amp;g={$data['group_id']}&amp;back_link=acp_users_groups"), 'U_DEFAULT' => $this->u_action . "&amp;action=default&amp;u={$user_id}&amp;g=" . $data['group_id'], 'U_DEMOTE_PROMOTE' => $this->u_action . '&amp;action=' . ($data['group_leader'] ? 'demote' : 'promote') . "&amp;u={$user_id}&amp;g=" . $data['group_id'], 'U_DELETE' => $this->u_action . "&amp;action=delete&amp;u={$user_id}&amp;g=" . $data['group_id'], 'U_APPROVE' => $group_type == 'pending' ? $this->u_action . "&amp;action=approve&amp;u={$user_id}&amp;g=" . $data['group_id'] : '', 'GROUP_NAME' => $group_type == 'special' ? $user->lang['G_' . $data['group_name']] : $data['group_name'], 'L_DEMOTE_PROMOTE' => $data['group_leader'] ? $user->lang['GROUP_DEMOTE'] : $user->lang['GROUP_PROMOTE'], 'S_IS_MEMBER' => $group_type != 'pending' ? true : false, 'S_NO_DEFAULT' => $user_row['group_id'] != $data['group_id'] ? true : false, 'S_SPECIAL_GROUP' => $group_type == 'special' ? true : false));
                    }
                }
                $template->assign_vars(array('S_GROUPS' => true, 'S_GROUP_OPTIONS' => $s_group_options));
                break;
            case 'perm':
                if (!class_exists('auth_admin')) {
                    include $phpbb_root_path . 'includes/acp/auth.' . $phpEx;
                }
                $auth_admin = new auth_admin();
                $user->add_lang('acp/permissions');
                add_permission_language();
                $forum_id = $request->variable('f', 0);
                // Global Permissions
                if (!$forum_id) {
                    // Select auth options
                    $sql = 'SELECT auth_option, is_local, is_global
						FROM ' . ACL_OPTIONS_TABLE . '
						WHERE auth_option ' . $db->sql_like_expression($db->get_any_char() . '_') . '
							AND is_global = 1
						ORDER BY auth_option';
                    $result = $db->sql_query($sql);
                    $hold_ary = array();
                    while ($row = $db->sql_fetchrow($result)) {
                        $hold_ary = $auth_admin->get_mask('view', $user_id, false, false, $row['auth_option'], 'global', ACL_NEVER);
                        $auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', false, false);
                    }
                    $db->sql_freeresult($result);
                    unset($hold_ary);
                } else {
                    $sql = 'SELECT auth_option, is_local, is_global
						FROM ' . ACL_OPTIONS_TABLE . "\n\t\t\t\t\t\tWHERE auth_option " . $db->sql_like_expression($db->get_any_char() . '_') . "\n\t\t\t\t\t\t\tAND is_local = 1\n\t\t\t\t\t\tORDER BY is_global DESC, auth_option";
                    $result = $db->sql_query($sql);
                    while ($row = $db->sql_fetchrow($result)) {
                        $hold_ary = $auth_admin->get_mask('view', $user_id, false, $forum_id, $row['auth_option'], 'local', ACL_NEVER);
                        $auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', true, false);
                    }
                    $db->sql_freeresult($result);
                }
                $s_forum_options = '<option value="0"' . (!$forum_id ? ' selected="selected"' : '') . '>' . $user->lang['VIEW_GLOBAL_PERMS'] . '</option>';
                $s_forum_options .= make_forum_select($forum_id, false, true, false, false, false);
                $template->assign_vars(array('S_PERMISSIONS' => true, 'S_GLOBAL' => !$forum_id ? true : false, 'S_FORUM_OPTIONS' => $s_forum_options, 'U_ACTION' => $this->u_action . '&amp;u=' . $user_id, 'U_USER_PERMISSIONS' => append_sid("{$phpbb_admin_path}index.{$phpEx}", 'i=permissions&amp;mode=setting_user_global&amp;user_id[]=' . $user_id), 'U_USER_FORUM_PERMISSIONS' => append_sid("{$phpbb_admin_path}index.{$phpEx}", 'i=permissions&amp;mode=setting_user_local&amp;user_id[]=' . $user_id)));
                break;
        }
        // Assign general variables
        $template->assign_vars(array('S_ERROR' => sizeof($error) ? true : false, 'ERROR_MSG' => sizeof($error) ? implode('<br />', $error) : ''));
    }
Exemplo n.º 3
0
 /**
  * Perform the right actions
  * @param Array $error An array that will be filled with error messages that might occure
  * @return void
  */
 function run_tool(&$error)
 {
     global $db, $user;
     $user->add_lang('ucp');
     if (!check_form_key('orphaned_posts')) {
         $error[] = 'FORM_INVALID';
         return;
     }
     $mode = request_var('mode', '');
     switch ($mode) {
         case 'empty_topics':
         case 'orphaned_shadows':
             $topic_ids = request_var('topics', array(0 => 0));
             if (!sizeof($topic_ids)) {
                 trigger_error('NO_TOPICS_SELECTED');
             }
             if (!function_exists('delete_topics')) {
                 include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
             }
             $return = delete_topics('topic_id', $topic_ids);
             trigger_error(sprintf($user->lang['TOPICS_DELETED'], $return['topics']));
             break;
         case 'forum_orphaned_posts':
             // No break
         // No break
         case 'orphaned_posts':
             if (isset($_POST['reassign'])) {
                 $post_map = request_var('posts', array(0 => 0));
                 foreach ($post_map as $post_id => $topic_id) {
                     if ($topic_id == 0) {
                         unset($post_map[$post_id]);
                     }
                 }
                 if (!sizeof($post_map)) {
                     trigger_error('NO_TOPIC_IDS');
                 }
                 // Make sure the specified topic IDs exist
                 $topic_ids = array_values($post_map);
                 $sql = 'SELECT topic_id, forum_id FROM ' . TOPICS_TABLE . ' WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
                 $result = $db->sql_query($sql);
                 $existing_topics = array();
                 while ($row = $db->sql_fetchrow($result)) {
                     $existing_topics[] = (int) $row['topic_id'];
                 }
                 $db->sql_freeresult($result);
                 $missing_topics = array_diff($topic_ids, $existing_topics);
                 if (sizeof($missing_topics)) {
                     trigger_error(sprintf($user->lang['NONEXISTENT_TOPIC_IDS'], implode(', ', $missing_topics)));
                 }
                 // Update the topics with their new IDs
                 foreach ($post_map as $post_id => $topic_id) {
                     $sql = 'SELECT forum_id FROM ' . TOPICS_TABLE . ' WHERE topic_id = ' . (int) $topic_id . '';
                     $result = $db->sql_query_limit($sql, 1);
                     $forum_id = (int) $db->sql_fetchfield('forum_id');
                     $db->sql_freeresult($result);
                     $sql = 'UPDATE ' . POSTS_TABLE . ' SET topic_id = ' . (int) $topic_id . ', forum_id = ' . (int) $forum_id . ' WHERE post_id = ' . (int) $post_id;
                     $db->sql_query($sql);
                 }
                 trigger_error(sprintf($user->lang['POSTS_REASSIGNED'], sizeof($post_map)));
             } else {
                 if (isset($_POST['delete'])) {
                     $post_ids = request_var('posts_del', array(0 => 0));
                     if (!sizeof($post_ids)) {
                         trigger_error('NO_POSTS_SELECTED');
                     }
                     if (!function_exists('delete_posts')) {
                         include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
                     }
                     $return = delete_posts('post_id', $post_ids);
                     trigger_error(sprintf($user->lang['POSTS_DELETED'], $return));
                 } else {
                     trigger_error('NO_MODE');
                 }
             }
             break;
         default:
             trigger_error('NO_MODE');
             break;
     }
 }
Exemplo n.º 4
0
/**
* Remove User
*/
function user_delete($mode, $user_id, $post_username = false)
{
    global $cache, $config, $db, $user, $auth;
    global $phpbb_root_path, $phpEx;
    $sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE user_id = ' . $user_id;
    $result = $db->sql_query($sql);
    $user_row = $db->sql_fetchrow($result);
    $db->sql_freeresult($result);
    if (!$user_row) {
        return false;
    }
    // Before we begin, we will remove the reports the user issued.
    $sql = 'SELECT r.post_id, p.topic_id
		FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
		WHERE r.user_id = ' . $user_id . '
			AND p.post_id = r.post_id';
    $result = $db->sql_query($sql);
    $report_posts = $report_topics = array();
    while ($row = $db->sql_fetchrow($result)) {
        $report_posts[] = $row['post_id'];
        $report_topics[] = $row['topic_id'];
    }
    $db->sql_freeresult($result);
    if (sizeof($report_posts)) {
        $report_posts = array_unique($report_posts);
        $report_topics = array_unique($report_topics);
        // Get a list of topics that still contain reported posts
        $sql = 'SELECT DISTINCT topic_id
			FROM ' . POSTS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
				AND post_reported = 1
				AND ' . $db->sql_in_set('post_id', $report_posts, true);
        $result = $db->sql_query($sql);
        $keep_report_topics = array();
        while ($row = $db->sql_fetchrow($result)) {
            $keep_report_topics[] = $row['topic_id'];
        }
        $db->sql_freeresult($result);
        if (sizeof($keep_report_topics)) {
            $report_topics = array_diff($report_topics, $keep_report_topics);
        }
        unset($keep_report_topics);
        // Now set the flags back
        $sql = 'UPDATE ' . POSTS_TABLE . '
			SET post_reported = 0
			WHERE ' . $db->sql_in_set('post_id', $report_posts);
        $db->sql_query($sql);
        if (sizeof($report_topics)) {
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_reported = 0
				WHERE ' . $db->sql_in_set('topic_id', $report_topics);
            $db->sql_query($sql);
        }
    }
    // Remove reports
    $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
    if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD) {
        avatar_delete('user', $user_row);
    }
    switch ($mode) {
        case 'retain':
            $db->sql_transaction('begin');
            if ($post_username === false) {
                $post_username = $user->lang['GUEST'];
            }
            // If the user is inactive and newly registered we assume no posts from this user being there...
            if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts']) {
            } else {
                $sql = 'UPDATE ' . FORUMS_TABLE . '
					SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''\n\t\t\t\t\tWHERE forum_last_poster_id = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET poster_id = ' . ANONYMOUS . ", post_username = '******'\n\t\t\t\t\tWHERE poster_id = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET post_edit_user = '******'UPDATE ' . TOPICS_TABLE . '
					SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''\n\t\t\t\t\tWHERE topic_poster = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''\n\t\t\t\t\tWHERE topic_last_poster_id = {$user_id}";
                $db->sql_query($sql);
                // Since we change every post by this author, we need to count this amount towards the anonymous user
                // Update the post count for the anonymous user
                if ($user_row['user_posts']) {
                    $sql = 'UPDATE ' . USERS_TABLE . '
						SET user_posts = user_posts + ' . $user_row['user_posts'] . '
						WHERE user_id = ' . ANONYMOUS;
                    $db->sql_query($sql);
                }
            }
            $db->sql_transaction('commit');
            break;
        case 'remove':
            if (!function_exists('delete_posts')) {
                include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
				FROM ' . POSTS_TABLE . "\n\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\tGROUP BY topic_id";
            $result = $db->sql_query($sql);
            $topic_id_ary = array();
            while ($row = $db->sql_fetchrow($result)) {
                $topic_id_ary[$row['topic_id']] = $row['total_posts'];
            }
            $db->sql_freeresult($result);
            if (sizeof($topic_id_ary)) {
                $sql = 'SELECT topic_id, topic_replies, topic_replies_real
					FROM ' . TOPICS_TABLE . '
					WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
                $result = $db->sql_query($sql);
                $del_topic_ary = array();
                while ($row = $db->sql_fetchrow($result)) {
                    if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']]) {
                        $del_topic_ary[] = $row['topic_id'];
                    }
                }
                $db->sql_freeresult($result);
                if (sizeof($del_topic_ary)) {
                    $sql = 'DELETE FROM ' . TOPICS_TABLE . '
						WHERE ' . $db->sql_in_set('topic_id', $del_topic_ary);
                    $db->sql_query($sql);
                }
            }
            // Delete posts, attachments, etc.
            delete_posts('poster_id', $user_id);
            break;
    }
    $db->sql_transaction('begin');
    $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE);
    foreach ($table_ary as $table) {
        $sql = "DELETE FROM {$table}\n\t\t\tWHERE user_id = {$user_id}";
        $db->sql_query($sql);
    }
    $cache->destroy('sql', MODERATOR_CACHE_TABLE);
    // Remove any undelivered mails...
    $sql = 'SELECT msg_id, user_id
		FROM ' . PRIVMSGS_TO_TABLE . '
		WHERE author_id = ' . $user_id . '
			AND folder_id = ' . PRIVMSGS_NO_BOX;
    $result = $db->sql_query($sql);
    $undelivered_msg = $undelivered_user = array();
    while ($row = $db->sql_fetchrow($result)) {
        $undelivered_msg[] = $row['msg_id'];
        $undelivered_user[$row['user_id']][] = true;
    }
    $db->sql_freeresult($result);
    if (sizeof($undelivered_msg)) {
        $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
			WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
        $db->sql_query($sql);
    }
    $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
		WHERE author_id = ' . $user_id . '
			AND folder_id = ' . PRIVMSGS_NO_BOX;
    $db->sql_query($sql);
    // Delete all to-information
    $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
		WHERE user_id = ' . $user_id;
    $db->sql_query($sql);
    // Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
    $sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
		SET author_id = ' . ANONYMOUS . '
		WHERE author_id = ' . $user_id;
    $db->sql_query($sql);
    $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
		SET author_id = ' . ANONYMOUS . '
		WHERE author_id = ' . $user_id;
    $db->sql_query($sql);
    foreach ($undelivered_user as $_user_id => $ary) {
        if ($_user_id == $user_id) {
            continue;
        }
        $sql = 'UPDATE ' . USERS_TABLE . '
			SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
				user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
			WHERE user_id = ' . $_user_id;
        $db->sql_query($sql);
    }
    $db->sql_transaction('commit');
    // Reset newest user info if appropriate
    if ($config['newest_user_id'] == $user_id) {
        update_last_username();
    }
    // Decrement number of users if this user is active
    if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE) {
        set_config('num_users', $config['num_users'] - 1, true);
    }
    //-- mod start : Garage ----------------------------------------------------------------------------------------------------
    //-- add
    if (!class_exists('garage_vehicle')) {
        include $phpbb_root_path . 'includes/mods/class_garage_vehicle.' . $phpEx;
    }
    $garage_vehicle = new garage_vehicle();
    $garage_vehicle->delete_user_vehicles($user_id);
    //-- mod finish : Garage ---------------------------------------------------------------------------------------------------
    return false;
}
Exemplo n.º 5
0
    function main($id, $mode)
    {
        global $config, $db, $user, $auth, $template, $cache;
        global $phpbb_root_path, $phpbb_admin_path, $phpEx, $table_prefix, $file_uploads;
        $user->add_lang(array('posting', 'ucp', 'acp/users'));
        $this->tpl_name = 'acp_users';
        $this->page_title = 'ACP_USER_' . strtoupper($mode);
        include $phpbb_root_path . 'includes/functions_user.' . $phpEx;
        include $phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx;
        $error = array();
        $username = request_var('username', '', true);
        $user_id = request_var('u', 0);
        $action = request_var('action', '');
        $submit = isset($_POST['update']) ? true : false;
        // Whois (special case)
        if ($action == 'whois') {
            $this->page_title = 'WHOIS';
            $this->tpl_name = 'simple_body';
            $user_ip = request_var('user_ip', '');
            $domain = gethostbyaddr($user_ip);
            $ipwhois = '';
            if ($ipwhois = user_ipwhois($user_ip)) {
                $ipwhois = preg_replace('#(\\s)([\\w\\-\\._\\+]+@[\\w\\-\\.]+)(\\s)#', '\\1<a href="mailto:\\2">\\2</a>\\3', $ipwhois);
                $ipwhois = preg_replace('#(\\s)(http:/{2}[^\\s]*)(\\s)#', '\\1<a href="\\2" target="_blank">\\2</a>\\3', $ipwhois);
            }
            $template->assign_vars(array('MESSAGE_TITLE' => sprintf($user->lang['IP_WHOIS_FOR'], $domain), 'MESSAGE_TEXT' => nl2br($ipwhois)));
            return;
        }
        // Show user selection mask
        if (!$username && !$user_id) {
            $this->page_title = 'SELECT_USER';
            $template->assign_vars(array('U_ACTION' => $this->u_action, 'ANONYMOUS_USER_ID' => ANONYMOUS, 'S_SELECT_USER' => true, 'U_FIND_USERNAME' => append_sid("{$phpbb_root_path}memberlist.{$phpEx}", 'mode=searchuser&amp;form=select_user&amp;field=username')));
            return;
        }
        if (!$user_id) {
            $sql = 'SELECT user_id
				FROM ' . USERS_TABLE . "\n\t\t\t\tWHERE username = '******'";
            $result = $db->sql_query($sql);
            $user_id = (int) $db->sql_fetchfield('user_id');
            $db->sql_freeresult($result);
            if (!$user_id) {
                trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action));
            }
        }
        // Generate content for all modes
        $sql = 'SELECT u.*, s.*
			FROM ' . USERS_TABLE . ' u
				LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
			WHERE u.user_id = ' . $user_id . '
			ORDER BY s.session_time DESC';
        $result = $db->sql_query($sql);
        $user_row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if (!$user_row) {
            trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action));
        }
        // Generate overall "header" for user admin
        $s_form_options = '';
        // Include info file...
        include_once $phpbb_root_path . 'includes/acp/info/acp_users.' . $phpEx;
        $forms_ary = acp_users_info::module();
        foreach ($forms_ary['modes'] as $value => $ary) {
            if (!$this->is_authed($ary['auth'])) {
                continue;
            }
            $selected = $mode == $value ? ' selected="selected"' : '';
            $s_form_options .= '<option value="' . $value . '"' . $selected . '>' . $user->lang['ACP_USER_' . strtoupper($value)] . '</option>';
        }
        $template->assign_vars(array('U_BACK' => $this->u_action, 'U_MODE_SELECT' => append_sid("{$phpbb_admin_path}index.{$phpEx}", "i={$id}&amp;u={$user_id}"), 'U_ACTION' => $this->u_action . '&amp;u=' . $user_id, 'S_FORM_OPTIONS' => $s_form_options));
        // Prevent normal users/admins change/view founders if they are not a founder by themselves
        if ($user->data['user_type'] != USER_FOUNDER && $user_row['user_type'] == USER_FOUNDER) {
            trigger_error($user->lang['NOT_MANAGE_FOUNDER'] . adm_back_link($this->u_action));
        }
        switch ($mode) {
            case 'overview':
                $delete = request_var('delete', 0);
                $delete_type = request_var('delete_type', '');
                $ip = request_var('ip', 'ip');
                if ($submit) {
                    // You can't delete the founder
                    if ($delete && $user_row['user_type'] != USER_FOUNDER) {
                        if (!$auth->acl_get('a_userdel')) {
                            trigger_error($user->lang['NO_ADMIN'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                        }
                        // Check if the user wants to remove himself or the guest user account
                        if ($user_id == ANONYMOUS) {
                            trigger_error($user->lang['CANNOT_REMOVE_ANONYMOUS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                        }
                        if ($user_id == $user->data['user_id']) {
                            trigger_error($user->lang['CANNOT_REMOVE_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                        }
                        if (confirm_box(true)) {
                            user_delete($delete_type, $user_id);
                            add_log('admin', 'LOG_USER_DELETED', $user_row['username']);
                            trigger_error($user->lang['USER_DELETED'] . adm_back_link($this->u_action));
                        } else {
                            confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true, 'delete' => 1, 'delete_type' => $delete_type)));
                        }
                    }
                    // Handle quicktool actions
                    switch ($action) {
                        case 'banuser':
                        case 'banemail':
                        case 'banip':
                            $ban = array();
                            switch ($action) {
                                case 'banuser':
                                    $ban[] = $user_row['username'];
                                    $reason = 'USER_ADMIN_BAN_NAME_REASON';
                                    $log = 'LOG_USER_BAN_USER';
                                    break;
                                case 'banemail':
                                    $ban[] = $user_row['user_email'];
                                    $reason = 'USER_ADMIN_BAN_EMAIL_REASON';
                                    $log = 'LOG_USER_BAN_EMAIL';
                                    break;
                                case 'banip':
                                    $ban[] = $user_row['user_ip'];
                                    $sql = 'SELECT DISTINCT poster_ip
										FROM ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\tWHERE poster_id = {$user_id}";
                                    $result = $db->sql_query($sql);
                                    while ($row = $db->sql_fetchrow($result)) {
                                        $ban[] = $row['poster_ip'];
                                    }
                                    $db->sql_freeresult($result);
                                    $reason = 'USER_ADMIN_BAN_IP_REASON';
                                    $log = 'LOG_USER_BAN_IP';
                                    break;
                            }
                            user_ban(substr($action, 3), $ban, 0, 0, 0, $user->lang[$reason]);
                            add_log('admin', $log, $user->lang[$reason]);
                            add_log('user', $user_id, $log, $user->lang[$reason]);
                            trigger_error($user->lang['BAN_SUCCESSFUL'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'reactivate':
                            if ($config['email_enable']) {
                                include_once $phpbb_root_path . 'includes/functions_messenger.' . $phpEx;
                                $server_url = generate_board_url();
                                $user_actkey = gen_rand_string(10);
                                $key_len = 54 - strlen($server_url);
                                $key_len = $key_len > 6 ? $key_len : 6;
                                $user_actkey = substr($user_actkey, 0, $key_len);
                                if ($user_row['user_type'] != USER_INACTIVE) {
                                    user_active_flip($user_id, $user_row['user_type'], $user_actkey, $user_row['username']);
                                }
                                $messenger = new messenger(false);
                                $messenger->template('user_resend_inactive', $user_row['user_lang']);
                                $messenger->replyto($config['board_contact']);
                                $messenger->to($user_row['user_email'], $user_row['username']);
                                $messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
                                $messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
                                $messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
                                $messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);
                                $messenger->assign_vars(array('SITENAME' => $config['sitename'], 'WELCOME_MSG' => sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename']), 'USERNAME' => html_entity_decode($user_row['username']), 'EMAIL_SIG' => str_replace('<br />', "\n", "-- \n" . $config['board_email_sig']), 'U_ACTIVATE' => "{$server_url}/ucp.{$phpEx}?mode=activate&u={$user_row['user_id']}&k={$user_actkey}"));
                                $messenger->send(NOTIFY_EMAIL);
                                add_log('admin', 'LOG_USER_REACTIVATE', $user_row['username']);
                                add_log('user', $user_id, 'LOG_USER_REACTIVATE_USER');
                                trigger_error($user->lang['FORCE_REACTIVATION_SUCCESS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            }
                            break;
                        case 'active':
                            user_active_flip($user_id, $user_row['user_type'], false, $user_row['username']);
                            $message = $user_row['user_type'] == USER_INACTIVE ? 'USER_ADMIN_ACTIVATED' : 'USER_ADMIN_DEACTIVED';
                            $log = $user_row['user_type'] == USER_INACTIVE ? 'LOG_USER_ACTIVE' : 'LOG_USER_INACTIVE';
                            add_log('user', $user_id, $log . '_USER');
                            if ($user_row['user_type'] == USER_INACTIVE) {
                                set_config('num_users', $config['num_users'] + 1, true);
                            } else {
                                set_config('num_users', $config['num_users'] - 1, true);
                            }
                            // Update latest username
                            update_last_username();
                            trigger_error($user->lang[$message] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delsig':
                            $sql_ary = array('user_sig' => '', 'user_sig_bbcode_uid' => '', 'user_sig_bbcode_bitfield' => 0);
                            $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            add_log('admin', 'LOG_USER_DEL_SIG', $user_row['username']);
                            add_log('user', $user_id, 'LOG_USER_DEL_SIG_USER');
                            trigger_error($user->lang['USER_ADMIN_SIG_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delavatar':
                            $sql_ary = array('user_avatar' => '', 'user_avatar_type' => 0, 'user_avatar_width' => 0, 'user_avatar_height' => 0);
                            $sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            // Delete old avatar if present
                            if ($user_row['user_avatar'] && $user_row['user_avatar_type'] != AVATAR_GALLERY) {
                                avatar_delete($user_row['user_avatar']);
                            }
                            add_log('admin', 'LOG_USER_DEL_AVATAR', $user_row['username']);
                            add_log('user', $user_id, 'LOG_USER_DEL_AVATAR_USER');
                            trigger_error($user->lang['USER_ADMIN_AVATAR_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                        case 'delposts':
                            if (confirm_box(true)) {
                                $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
									FROM ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\t\t\t\t\t\tGROUP BY topic_id";
                                $result = $db->sql_query($sql);
                                $topic_id_ary = array();
                                while ($row = $db->sql_fetchrow($result)) {
                                    $topic_id_ary[$row['topic_id']] = $row['total_posts'];
                                }
                                $db->sql_freeresult($result);
                                if (sizeof($topic_id_ary)) {
                                    $sql = 'SELECT topic_id, topic_replies, topic_replies_real
										FROM ' . TOPICS_TABLE . '
										WHERE topic_id IN (' . implode(', ', array_keys($topic_id_ary)) . ')';
                                    $result = $db->sql_query($sql);
                                    $del_topic_ary = array();
                                    while ($row = $db->sql_fetchrow($result)) {
                                        if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']]) {
                                            $del_topic_ary[] = $row['topic_id'];
                                        }
                                    }
                                    $db->sql_freeresult($result);
                                    if (sizeof($del_topic_ary)) {
                                        $sql = 'DELETE FROM ' . TOPICS_TABLE . '
											WHERE topic_id IN (' . implode(', ', $del_topic_ary) . ')';
                                        $db->sql_query($sql);
                                    }
                                }
                                // Delete posts, attachments, etc.
                                delete_posts('poster_id', $user_id);
                                add_log('admin', 'LOG_USER_DEL_POSTS', $user_row['username']);
                                trigger_error($user->lang['USER_POSTS_DELETED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        case 'delattach':
                            if (confirm_box(true)) {
                                delete_attachments('user', $user_id);
                                add_log('admin', 'LOG_USER_DEL_ATTACH', $user_row['username']);
                                trigger_error($user->lang['USER_ATTACHMENTS_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            } else {
                                confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'update' => true)));
                            }
                            break;
                        case 'moveposts':
                            $new_forum_id = request_var('new_f', 0);
                            if (!$new_forum_id) {
                                $this->page_title = 'USER_ADMIN_MOVE_POSTS';
                                $template->assign_vars(array('S_SELECT_FORUM' => true, 'U_ACTION' => $this->u_action . "&amp;action={$action}&amp;u={$user_id}", 'U_BACK' => $this->u_action . "&amp;u={$user_id}", 'S_FORUM_OPTIONS' => make_forum_select(false, false, false, true)));
                                return;
                            }
                            // Two stage?
                            // Move topics comprising only posts from this user
                            $topic_id_ary = $move_topic_ary = $move_post_ary = $new_topic_id_ary = array();
                            $forum_id_ary = array($new_forum_id);
                            $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
								FROM ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\t\t\t\t\t\tAND forum_id <> {$new_forum_id}\n\t\t\t\t\t\t\t\tGROUP BY topic_id";
                            $result = $db->sql_query($sql);
                            while ($row = $db->sql_fetchrow($result)) {
                                $topic_id_ary[$row['topic_id']] = $row['total_posts'];
                            }
                            $db->sql_freeresult($result);
                            if (sizeof($topic_id_ary)) {
                                $sql = 'SELECT topic_id, forum_id, topic_title, topic_replies, topic_replies_real
									FROM ' . TOPICS_TABLE . '
									WHERE topic_id IN (' . implode(', ', array_keys($topic_id_ary)) . ')';
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']]) {
                                        $move_topic_ary[] = $row['topic_id'];
                                    } else {
                                        $move_post_ary[$row['topic_id']]['title'] = $row['topic_title'];
                                        $move_post_ary[$row['topic_id']]['attach'] = $row['attach'] ? 1 : 0;
                                    }
                                    $forum_id_ary[] = $row['forum_id'];
                                }
                                $db->sql_freeresult($result);
                            }
                            // Entire topic comprises posts by this user, move these topics
                            if (sizeof($move_topic_ary)) {
                                move_topics($move_topic_ary, $new_forum_id, false);
                            }
                            if (sizeof($move_post_ary)) {
                                // Create new topic
                                // Update post_ids, report_ids, attachment_ids
                                foreach ($move_post_ary as $topic_id => $post_ary) {
                                    // Create new topic
                                    $sql = 'INSERT INTO ' . TOPICS_TABLE . ' ' . $db->sql_build_array('INSERT', array('topic_poster' => $user_id, 'topic_time' => time(), 'forum_id' => $new_forum_id, 'icon_id' => 0, 'topic_approved' => 1, 'topic_title' => $post_ary['title'], 'topic_first_poster_name' => $user_row['username'], 'topic_type' => POST_NORMAL, 'topic_time_limit' => 0, 'topic_attachment' => $post_ary['attach']));
                                    $db->sql_query($sql);
                                    $new_topic_id = $db->sql_nextid();
                                    // Move posts
                                    $sql = 'UPDATE ' . POSTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\tSET forum_id = {$new_forum_id}, topic_id = {$new_topic_id}\n\t\t\t\t\t\t\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\t\t\t\t\t\t\tAND poster_id = {$user_id}";
                                    $db->sql_query($sql);
                                    if ($post_ary['attach']) {
                                        $sql = 'UPDATE ' . ATTACHMENTS_TABLE . "\n\t\t\t\t\t\t\t\t\t\t\tSET topic_id = {$new_topic_id}\n\t\t\t\t\t\t\t\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\t\t\t\t\t\t\t\tAND poster_id = {$user_id}";
                                        $db->sql_query($sql);
                                    }
                                    $new_topic_id_ary[] = $new_topic_id;
                                }
                            }
                            $forum_id_ary = array_unique($forum_id_ary);
                            $topic_id_ary = array_unique(array_merge($topic_id_ary, $new_topic_id_ary));
                            if (sizeof($topic_id_ary)) {
                                sync('reported', 'topic_id', $topic_id_ary);
                                sync('topic', 'topic_id', $topic_id_ary);
                            }
                            if (sizeof($forum_id_ary)) {
                                sync('forum', 'forum_id', $forum_id_ary);
                            }
                            $sql = 'SELECT forum_name
								FROM ' . FORUMS_TABLE . "\n\t\t\t\t\t\t\t\tWHERE forum_id = {$new_forum_id}";
                            $result = $db->sql_query($sql, 3600);
                            $forum_info = $db->sql_fetchrow($result);
                            $db->sql_freeresult($result);
                            add_log('admin', 'LOG_USER_MOVE_POSTS', $user_row['username'], $forum_info['forum_name']);
                            add_log('user', $user_id, 'LOG_USER_MOVE_POSTS_USER', $forum_info['forum_name']);
                            trigger_error($user->lang['USER_POSTS_MOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            break;
                    }
                    $data = array();
                    // Handle registration info updates
                    $var_ary = array('user' => (string) $user_row['username'], 'user_founder' => (int) ($user_row['user_type'] == USER_FOUNDER ? 1 : 0), 'user_email' => (string) $user_row['user_email'], 'email_confirm' => (string) '', 'user_password' => (string) '', 'password_confirm' => (string) '', 'warnings' => (int) $user_row['user_warnings']);
                    // Get the data from the form. Use data from the database if no info is provided
                    foreach ($var_ary as $var => $default) {
                        $data[$var] = request_var($var, $default);
                    }
                    // We use user within the form to circumvent auto filling
                    $data['username'] = $data['user'];
                    unset($data['user']);
                    // Validation data
                    $var_ary = array('password_confirm' => array('string', true, $config['min_pass_chars'], $config['max_pass_chars']), 'user_password' => array('string', true, $config['min_pass_chars'], $config['max_pass_chars']), 'warnings' => array('num'));
                    // Check username if altered
                    if ($data['username'] != $user_row['username']) {
                        $var_ary += array('username' => array(array('string', false, $config['min_name_chars'], $config['max_name_chars']), array('username', $user_row['username'])));
                    }
                    // Check email if altered
                    if ($data['user_email'] != $user_row['user_email']) {
                        $var_ary += array('user_email' => array(array('string', false, 6, 60), array('email', $user_row['user_email'])), 'email_confirm' => array('string', true, 6, 60));
                    }
                    $error = validate_data($data, $var_ary);
                    if ($data['user_password'] && $data['password_confirm'] != $data['user_password']) {
                        $error[] = 'NEW_PASSWORD_ERROR';
                    }
                    if ($data['user_email'] != $user_row['user_email'] && $data['email_confirm'] != $data['user_email']) {
                        $error[] = 'NEW_EMAIL_ERROR';
                    }
                    // Which updates do we need to do?
                    $update_warning = $user_row['user_warnings'] != $data['warnings'] ? true : false;
                    $update_username = $user_row['username'] != $data['username'] ? $data['username'] : false;
                    $update_password = $data['user_password'] && $user_row['user_password'] != md5($data['user_password']) ? true : false;
                    $update_email = $data['user_email'] != $user_row['user_email'] ? $data['user_email'] : false;
                    if (!sizeof($error)) {
                        $sql_ary = array();
                        if ($user_row['user_type'] != USER_FOUNDER || $user->data['user_type'] == USER_FOUNDER) {
                            if ($update_warning) {
                                $sql_ary['user_warnings'] = $data['warnings'];
                            }
                            if ($user_row['user_type'] == USER_FOUNDER && !$data['user_founder'] || $user_row['user_type'] != USER_FOUNDER && $data['user_founder']) {
                                $sql_ary['user_type'] = $data['user_founder'] ? USER_FOUNDER : USER_NORMAL;
                            }
                        }
                        if ($update_username !== false) {
                            $sql_ary['username'] = $update_username;
                            add_log('user', $user_id, 'LOG_USER_UPDATE_NAME', $user_row['username'], $update_username);
                        }
                        if ($update_email !== false) {
                            $sql_ary += array('user_email' => $update_email, 'user_email_hash' => crc32(strtolower($update_email)) . strlen($update_email));
                            add_log('user', $user_id, 'LOG_USER_UPDATE_EMAIL', $user_row['username'], $user_row['user_email'], $update_email);
                        }
                        if ($update_password) {
                            $sql_ary += array('user_password' => md5($data['user_password']), 'user_passchg' => time());
                            $user->reset_login_keys($user_id);
                            add_log('user', $user_id, 'LOG_USER_NEW_PASSWORD', $user_row['username']);
                        }
                        if (sizeof($sql_ary)) {
                            $sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE user_id = ' . $user_id;
                            $db->sql_query($sql);
                        }
                        /**
                         * @todo adjust every data based in the number of user warnings
                         */
                        if ($update_warning) {
                        }
                        if ($update_username) {
                            user_update_name($user_row['username'], $update_username);
                        }
                        add_log('admin', 'LOG_USER_USER_UPDATE', $data['username']);
                        trigger_error($user->lang['USER_OVERVIEW_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
                }
                $user_char_ary = array('.*' => 'USERNAME_CHARS_ANY', '[\\w]+' => 'USERNAME_ALPHA_ONLY', '[\\w_\\+\\. \\-\\[\\]]+' => 'USERNAME_ALPHA_SPACERS');
                $quick_tool_ary = array('banuser' => 'BAN_USER', 'banemail' => 'BAN_EMAIL', 'banip' => 'BAN_IP', 'active' => $user_row['user_type'] == USER_INACTIVE ? 'ACTIVATE' : 'DEACTIVATE', 'delsig' => 'DEL_SIG', 'delavatar' => 'DEL_AVATAR', 'moveposts' => 'MOVE_POSTS', 'delposts' => 'DEL_POSTS', 'delattach' => 'DEL_ATTACH');
                if ($config['email_enable']) {
                    $quick_tool_ary['reactivate'] = 'FORCE';
                }
                $s_action_options = '<option class="sep" value="">' . $user->lang['SELECT_OPTION'] . '</option>';
                foreach ($quick_tool_ary as $value => $lang) {
                    $s_action_options .= '<option value="' . $value . '">' . $user->lang['USER_ADMIN_' . $lang] . '</option>';
                }
                $template->assign_vars(array('L_NAME_CHARS_EXPLAIN' => sprintf($user->lang[$user_char_ary[$config['allow_name_chars']] . '_EXPLAIN'], $config['min_name_chars'], $config['max_name_chars']), 'L_CHANGE_PASSWORD_EXPLAIN' => sprintf($user->lang['CHANGE_PASSWORD_EXPLAIN'], $config['min_pass_chars'], $config['max_pass_chars']), 'S_FOUNDER' => $user->data['user_type'] == USER_FOUNDER ? true : false, 'S_OVERVIEW' => true, 'S_USER_IP' => $user_row['user_ip'] ? true : false, 'S_USER_FOUNDER' => $user_row['user_type'] == USER_FOUNDER ? true : false, 'S_ACTION_OPTIONS' => $s_action_options, 'U_SHOW_IP' => $this->u_action . "&amp;u={$user_id}&amp;ip=" . ($ip == 'ip' ? 'hostname' : 'ip'), 'U_WHOIS' => $this->u_action . "&amp;action=whois&amp;user_ip={$user_row['user_ip']}", 'U_SWITCH_PERMISSIONS' => $auth->acl_get('a_switchperm') && $user->data['user_id'] != $user_row['user_id'] ? append_sid("{$phpbb_root_path}ucp.{$phpEx}", "mode=switch_perm&amp;u={$user_row['user_id']}") : '', 'USER' => $user_row['username'], 'USER_REGISTERED' => $user->format_date($user_row['user_regdate']), 'REGISTERED_IP' => $ip == 'hostname' ? gethostbyaddr($user_row['user_ip']) : $user_row['user_ip'], 'USER_LASTACTIVE' => $user_row['user_lastvisit'] ? $user->format_date($user_row['user_lastvisit']) : ' - ', 'USER_EMAIL' => $user_row['user_email'], 'USER_WARNINGS' => $user_row['user_warnings']));
                break;
            case 'feedback':
                $user->add_lang('mcp');
                // Set up general vars
                $start = request_var('start', 0);
                $deletemark = isset($_POST['delmarked']) ? true : false;
                $deleteall = isset($_POST['delall']) ? true : false;
                $marked = request_var('mark', array(0));
                $message = request_var('message', '', true);
                // Sort keys
                $sort_days = request_var('st', 0);
                $sort_key = request_var('sk', 't');
                $sort_dir = request_var('sd', 'd');
                // Delete entries if requested and able
                if (($deletemark || $deleteall) && $auth->acl_get('a_clearlogs')) {
                    $where_sql = '';
                    if ($deletemark && $marked) {
                        $sql_in = array();
                        foreach ($marked as $mark) {
                            $sql_in[] = $mark;
                        }
                        $where_sql = ' AND log_id IN (' . implode(', ', $sql_in) . ')';
                        unset($sql_in);
                    }
                    if ($where_sql || $deleteall) {
                        $sql = 'DELETE FROM ' . LOG_TABLE . '
							WHERE log_type = ' . LOG_USERS . "\n\t\t\t\t\t\t\t{$where_sql}";
                        $db->sql_query($sql);
                        add_log('admin', 'LOG_CLEAR_USER', $user_row['username']);
                    }
                }
                if ($submit && $message) {
                    add_log('admin', 'LOG_USER_FEEDBACK', $user_row['username']);
                    add_log('user', $user_id, 'LOG_USER_GENERAL', $message);
                    trigger_error($user->lang['USER_FEEDBACK_ADDED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                }
                // Sorting
                $limit_days = array(0 => $user->lang['ALL_ENTRIES'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_text = array('u' => $user->lang['SORT_USERNAME'], 't' => $user->lang['SORT_DATE'], 'i' => $user->lang['SORT_IP'], 'o' => $user->lang['SORT_ACTION']);
                $sort_by_sql = array('u' => 'l.user_id', 't' => 'l.log_time', 'i' => 'l.log_ip', 'o' => 'l.log_operation');
                $s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
                gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
                // Define where and sort sql for use in displaying logs
                $sql_where = $sort_days ? time() - $sort_days * 86400 : 0;
                $sql_sort = $sort_by_sql[$sort_key] . ' ' . ($sort_dir == 'd' ? 'DESC' : 'ASC');
                // Grab log data
                $log_data = array();
                $log_count = 0;
                view_log('user', $log_data, $log_count, $config['topics_per_page'], $start, 0, 0, $user_id, $sql_where, $sql_sort);
                $template->assign_vars(array('S_FEEDBACK' => true, 'S_ON_PAGE' => on_page($log_count, $config['topics_per_page'], $start), 'PAGINATION' => generate_pagination($this->u_action . "&amp;u={$user_id}&amp;{$u_sort_param}", $log_count, $config['topics_per_page'], $start, true), 'S_LIMIT_DAYS' => $s_limit_days, 'S_SORT_KEY' => $s_sort_key, 'S_SORT_DIR' => $s_sort_dir, 'S_CLEARLOGS' => $auth->acl_get('a_clearlogs')));
                foreach ($log_data as $row) {
                    $template->assign_block_vars('log', array('USERNAME' => $row['username'], 'IP' => $row['ip'], 'DATE' => $user->format_date($row['time']), 'ACTION' => nl2br($row['action']), 'ID' => $row['id']));
                }
                break;
            case 'profile':
                $cp = new custom_profile();
                $cp_data = $cp_error = array();
                $data = array();
                $sql = 'SELECT lang_id
					FROM ' . LANG_TABLE . "\n\t\t\t\t\tWHERE lang_iso = '" . $db->sql_escape($user_row['user_lang']) . "'";
                $result = $db->sql_query($sql);
                $row = $db->sql_fetchrow($result);
                $db->sql_freeresult($result);
                $user_row['iso_lang_id'] = $row['lang_id'];
                if ($submit) {
                    $var_ary = array('icq' => (string) '', 'aim' => (string) '', 'msn' => (string) '', 'yim' => (string) '', 'jabber' => (string) '', 'website' => (string) '', 'location' => (string) '', 'occupation' => (string) '', 'interests' => (string) '', 'bday_day' => 0, 'bday_month' => 0, 'bday_year' => 0);
                    foreach ($var_ary as $var => $default) {
                        $data[$var] = in_array($var, array('location', 'occupation', 'interests')) ? request_var($var, $default, true) : ($data[$var] = request_var($var, $default));
                    }
                    $var_ary = array('icq' => array(array('string', true, 3, 15), array('match', true, '#^[0-9]+$#i')), 'aim' => array('string', true, 3, 17), 'msn' => array('string', true, 5, 255), 'jabber' => array(array('string', true, 5, 255), array('match', true, '#^[a-z0-9\\.\\-_\\+]+?@(.*?\\.)*?[a-z0-9\\-_]+?\\.[a-z]{2,4}(/.*)?$#i')), 'yim' => array('string', true, 5, 255), 'website' => array(array('string', true, 12, 255), array('match', true, '#^http[s]?://(.*?\\.)*?[a-z0-9\\-]+\\.[a-z]{2,4}#i')), 'location' => array('string', true, 2, 255), 'occupation' => array('string', true, 2, 500), 'interests' => array('string', true, 2, 500), 'bday_day' => array('num', true, 1, 31), 'bday_month' => array('num', true, 1, 12), 'bday_year' => array('num', true, 1901, gmdate('Y', time())));
                    $error = validate_data($data, $var_ary);
                    // validate custom profile fields
                    $cp->submit_cp_field('profile', $user_row['iso_lang_id'], $cp_data, $cp_error);
                    if (sizeof($cp_error)) {
                        $error = array_merge($error, $cp_error);
                    }
                    if (!sizeof($error)) {
                        $sql_ary = array('user_icq' => $data['icq'], 'user_aim' => $data['aim'], 'user_msnm' => $data['msn'], 'user_yim' => $data['yim'], 'user_jabber' => $data['jabber'], 'user_website' => $data['website'], 'user_from' => $data['location'], 'user_occ' => $data['occupation'], 'user_interests' => $data['interests'], 'user_birthday' => sprintf('%2d-%2d-%4d', $data['bday_day'], $data['bday_month'], $data['bday_year']));
                        $sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                        $db->sql_query($sql);
                        // Update Custom Fields
                        if (sizeof($cp_data)) {
                            $sql = 'UPDATE ' . PROFILE_FIELDS_DATA_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $cp_data) . "\n\t\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                            $db->sql_query($sql);
                            if (!$db->sql_affectedrows()) {
                                $cp_data['user_id'] = (int) $user_id;
                                $db->return_on_error = true;
                                $sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' . $db->sql_build_array('INSERT', $cp_data);
                                $db->sql_query($sql);
                                $db->return_on_error = false;
                            }
                        }
                        trigger_error($user->lang['USER_PROFILE_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
                }
                if (!isset($data['bday_day'])) {
                    if ($user_row['user_birthday']) {
                        list($data['bday_day'], $data['bday_month'], $data['bday_year']) = explode('-', $user_row['user_birthday']);
                    } else {
                        $data['bday_day'] = $data['bday_month'] = $data['bday_year'] = 0;
                    }
                }
                $s_birthday_day_options = '<option value="0"' . (!$data['bday_day'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = 1; $i < 32; $i++) {
                    $selected = $i == $data['bday_day'] ? ' selected="selected"' : '';
                    $s_birthday_day_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                $s_birthday_month_options = '<option value="0"' . (!$data['bday_month'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = 1; $i < 13; $i++) {
                    $selected = $i == $data['bday_month'] ? ' selected="selected"' : '';
                    $s_birthday_month_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                $s_birthday_year_options = '';
                $now = getdate();
                $s_birthday_year_options = '<option value="0"' . (!$data['bday_year'] ? ' selected="selected"' : '') . '>--</option>';
                for ($i = $now['year'] - 100; $i < $now['year']; $i++) {
                    $selected = $i == $data['bday_year'] ? ' selected="selected"' : '';
                    $s_birthday_year_options .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
                }
                unset($now);
                $template->assign_vars(array('ICQ' => isset($data['icq']) ? $data['icq'] : $user_row['user_icq'], 'YIM' => isset($data['yim']) ? $data['yim'] : $user_row['user_yim'], 'AIM' => isset($data['aim']) ? $data['aim'] : $user_row['user_aim'], 'MSN' => isset($data['msn']) ? $data['msn'] : $user_row['user_msnm'], 'JABBER' => isset($data['jabber']) ? $data['jabber'] : $user_row['user_jabber'], 'WEBSITE' => isset($data['website']) ? $data['website'] : $user_row['user_website'], 'LOCATION' => isset($data['location']) ? $data['location'] : $user_row['user_from'], 'OCCUPATION' => isset($data['occupation']) ? $data['occupation'] : $user_row['user_occ'], 'INTERESTS' => isset($data['interests']) ? $data['interests'] : $user_row['user_interests'], 'S_BIRTHDAY_DAY_OPTIONS' => $s_birthday_day_options, 'S_BIRTHDAY_MONTH_OPTIONS' => $s_birthday_month_options, 'S_BIRTHDAY_YEAR_OPTIONS' => $s_birthday_year_options, 'S_PROFILE' => true));
                // Get additional profile fields and assign them to the template block var 'profile_fields'
                $user->get_profile_fields($user_id);
                $cp->generate_profile_fields('profile', $user_row['iso_lang_id']);
                break;
            case 'prefs':
                $data = array();
                if ($submit) {
                    $var_ary = array('dateformat' => (string) $config['default_dateformat'], 'lang' => (string) $config['default_lang'], 'tz' => (double) $config['board_timezone'], 'style' => (int) $config['default_style'], 'dst' => (bool) $config['board_dst'], 'viewemail' => false, 'massemail' => true, 'hideonline' => false, 'notifymethod' => 0, 'notifypm' => true, 'popuppm' => false, 'allowpm' => true, 'topic_sk' => (string) 't', 'topic_sd' => (string) 'd', 'topic_st' => 0, 'post_sk' => (string) 't', 'post_sd' => (string) 'a', 'post_st' => 0, 'view_images' => true, 'view_flash' => false, 'view_smilies' => true, 'view_sigs' => true, 'view_avatars' => true, 'view_wordcensor' => false, 'bbcode' => true, 'smilies' => true, 'sig' => true, 'notify' => false);
                    foreach ($var_ary as $var => $default) {
                        $data[$var] = request_var($var, $default);
                    }
                    $var_ary = array('dateformat' => array('string', false, 3, 30), 'lang' => array('match', false, '#^[a-z_]{2,}$#i'), 'tz' => array('num', false, -14, 14), 'topic_sk' => array('string', false, 1, 1), 'topic_sd' => array('string', false, 1, 1), 'post_sk' => array('string', false, 1, 1), 'post_sd' => array('string', false, 1, 1));
                    $error = validate_data($data, $var_ary);
                    if (!sizeof($error)) {
                        $this->optionset($user_row, 'popuppm', $data['popuppm']);
                        $this->optionset($user_row, 'viewimg', $data['view_images']);
                        $this->optionset($user_row, 'viewflash', $data['view_flash']);
                        $this->optionset($user_row, 'viewsmilies', $data['view_smilies']);
                        $this->optionset($user_row, 'viewsigs', $data['view_sigs']);
                        $this->optionset($user_row, 'viewavatars', $data['view_avatars']);
                        $this->optionset($user_row, 'viewcensors', $data['view_wordcensor']);
                        $this->optionset($user_row, 'bbcode', $data['bbcode']);
                        $this->optionset($user_row, 'smilies', $data['smilies']);
                        $this->optionset($user_row, 'attachsig', $data['sig']);
                        $sql_ary = array('user_options' => $user_row['user_options'], 'user_allow_pm' => $data['allowpm'], 'user_allow_viewemail' => $data['viewemail'], 'user_allow_massemail' => $data['massemail'], 'user_allow_viewonline' => !$data['hideonline'], 'user_notify_type' => $data['notifymethod'], 'user_notify_pm' => $data['notifypm'], 'user_dst' => $data['dst'], 'user_dateformat' => $data['dateformat'], 'user_lang' => $data['lang'], 'user_timezone' => $data['tz'], 'user_style' => $data['style'], 'user_topic_sortby_type' => $data['topic_sk'], 'user_post_sortby_type' => $data['post_sk'], 'user_topic_sortby_dir' => $data['topic_sd'], 'user_post_sortby_dir' => $data['post_sd'], 'user_topic_show_days' => $data['topic_st'], 'user_post_show_days' => $data['post_st'], 'user_notify' => $data['notify']);
                        $sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\tWHERE user_id = {$user_id}";
                        $db->sql_query($sql);
                        trigger_error($user->lang['USER_PREFS_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
                }
                $notify_method = isset($data['notifymethod']) ? $data['notifymethod'] : $user_row['user_notify_type'];
                $dateformat = isset($data['dateformat']) ? $data['dateformat'] : $user_row['user_dateformat'];
                $lang = isset($data['lang']) ? $data['lang'] : $user_row['user_lang'];
                $style = isset($data['style']) ? $data['style'] : $user_row['user_style'];
                $tz = isset($data['tz']) ? $data['tz'] : $user_row['user_timezone'];
                $dateformat_options = '';
                foreach ($user->lang['dateformats'] as $format => $null) {
                    $dateformat_options .= '<option value="' . $format . '"' . ($format == $dateformat ? ' selected="selected"' : '') . '>';
                    $dateformat_options .= $user->format_date(time(), $format, true) . (strpos($format, '|') !== false ? ' [' . $user->lang['RELATIVE_DAYS'] . ']' : '');
                    $dateformat_options .= '</option>';
                }
                $s_custom = false;
                $dateformat_options .= '<option value="custom"';
                if (!in_array($dateformat, array_keys($user->lang['dateformats']))) {
                    $dateformat_options .= ' selected="selected"';
                    $s_custom = true;
                }
                $dateformat_options .= '>' . $user->lang['CUSTOM_DATEFORMAT'] . '</option>';
                $topic_sk = isset($data['topic_sk']) ? $data['topic_sk'] : ($user_row['user_topic_sortby_type'] ? $user_row['user_topic_sortby_type'] : 't');
                $post_sk = isset($data['post_sk']) ? $data['post_sk'] : ($user_row['user_post_sortby_type'] ? $user_row['user_post_sortby_type'] : 't');
                $topic_sd = isset($data['topic_sd']) ? $data['topic_sd'] : ($user_row['user_topic_sortby_dir'] ? $user_row['user_topic_sortby_dir'] : 'd');
                $post_sd = isset($data['post_sd']) ? $data['post_sd'] : ($user_row['user_post_sortby_dir'] ? $user_row['user_post_sortby_dir'] : 'd');
                $topic_st = isset($data['topic_st']) ? $data['topic_st'] : ($user_row['user_topic_show_days'] ? $user_row['user_topic_show_days'] : 0);
                $post_st = isset($data['post_st']) ? $data['post_st'] : ($user_row['user_post_show_days'] ? $user_row['user_post_show_days'] : 0);
                $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
                // Topic ordering options
                $limit_topic_days = array(0 => $user->lang['ALL_TOPICS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_topic_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 'r' => $user->lang['REPLIES'], 's' => $user->lang['SUBJECT'], 'v' => $user->lang['VIEWS']);
                // Post ordering options
                $limit_post_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
                $sort_by_post_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
                $_options = array('topic', 'post');
                foreach ($_options as $sort_option) {
                    ${'s_limit_' . $sort_option . '_days'} = '<select name="' . $sort_option . '_st">';
                    foreach (${'limit_' . $sort_option . '_days'} as $day => $text) {
                        $selected = ${$sort_option . '_st'} == $day ? ' selected="selected"' : '';
                        ${'s_limit_' . $sort_option . '_days'} .= '<option value="' . $day . '"' . $selected . '>' . $text . '</option>';
                    }
                    ${'s_limit_' . $sort_option . '_days'} .= '</select>';
                    ${'s_sort_' . $sort_option . '_key'} = '<select name="' . $sort_option . '_sk">';
                    foreach (${'sort_by_' . $sort_option . '_text'} as $key => $text) {
                        $selected = ${$sort_option . '_sk'} == $key ? ' selected="selected"' : '';
                        ${'s_sort_' . $sort_option . '_key'} .= '<option value="' . $key . '"' . $selected . '>' . $text . '</option>';
                    }
                    ${'s_sort_' . $sort_option . '_key'} .= '</select>';
                    ${'s_sort_' . $sort_option . '_dir'} = '<select name="' . $sort_option . '_sd">';
                    foreach ($sort_dir_text as $key => $value) {
                        $selected = ${$sort_option . '_sd'} == $key ? ' selected="selected"' : '';
                        ${'s_sort_' . $sort_option . '_dir'} .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                    }
                    ${'s_sort_' . $sort_option . '_dir'} .= '</select>';
                }
                $template->assign_vars(array('S_PREFS' => true, 'S_JABBER_DISABLED' => $config['jab_enable'] && $user->data['user_jabber'] && @extension_loaded('xml') ? false : true, 'VIEW_EMAIL' => isset($data['viewemail']) ? $data['viewemail'] : $user_row['user_allow_viewemail'], 'MASS_EMAIL' => isset($data['massemail']) ? $data['massemail'] : $user_row['user_allow_massemail'], 'ALLOW_PM' => isset($data['allowpm']) ? $data['allowpm'] : $user_row['user_allow_pm'], 'HIDE_ONLINE' => isset($data['hideonline']) ? $data['hideonline'] : !$user_row['user_allow_viewonline'], 'NOTIFY_EMAIL' => $notify_method == NOTIFY_EMAIL ? true : false, 'NOTIFY_IM' => $notify_method == NOTIFY_IM ? true : false, 'NOTIFY_BOTH' => $notify_method == NOTIFY_BOTH ? true : false, 'NOTIFY_PM' => isset($data['notifypm']) ? $data['notifypm'] : $user_row['user_notify_pm'], 'POPUP_PM' => isset($data['popuppm']) ? $data['popuppm'] : $this->optionget($user_row, 'popuppm'), 'DST' => isset($data['dst']) ? $data['dst'] : $user_row['user_dst'], 'BBCODE' => isset($data['bbcode']) ? $data['bbcode'] : $this->optionget($user_row, 'bbcode'), 'SMILIES' => isset($data['smilies']) ? $data['smilies'] : $this->optionget($user_row, 'smilies'), 'ATTACH_SIG' => isset($data['sig']) ? $data['sig'] : $this->optionget($user_row, 'attachsig'), 'NOTIFY' => isset($data['notify']) ? $data['notify'] : $user_row['user_notify'], 'VIEW_IMAGES' => isset($data['view_images']) ? $data['view_images'] : $this->optionget($user_row, 'viewimg'), 'VIEW_FLASH' => isset($data['view_flash']) ? $data['view_flash'] : $this->optionget($user_row, 'viewflash'), 'VIEW_SMILIES' => isset($data['view_smilies']) ? $data['view_smilies'] : $this->optionget($user_row, 'viewsmilies'), 'VIEW_SIGS' => isset($data['view_sigs']) ? $data['view_sigs'] : $this->optionget($user_row, 'viewsigs'), 'VIEW_AVATARS' => isset($data['view_avatars']) ? $data['view_avatars'] : $this->optionget($user_row, 'viewavatars'), 'VIEW_WORDCENSOR' => isset($data['view_wordcensor']) ? $data['view_wordcensor'] : $this->optionget($user_row, 'viewcensors'), 'S_TOPIC_SORT_DAYS' => $s_limit_topic_days, 'S_TOPIC_SORT_KEY' => $s_sort_topic_key, 'S_TOPIC_SORT_DIR' => $s_sort_topic_dir, 'S_POST_SORT_DAYS' => $s_limit_post_days, 'S_POST_SORT_KEY' => $s_sort_post_key, 'S_POST_SORT_DIR' => $s_sort_post_dir, 'DATE_FORMAT' => $dateformat, 'S_DATEFORMAT_OPTIONS' => $dateformat_options, 'S_CUSTOM_DATEFORMAT' => $s_custom, 'DEFAULT_DATEFORMAT' => $config['default_dateformat'], 'A_DEFAULT_DATEFORMAT' => addslashes($config['default_dateformat']), 'S_LANG_OPTIONS' => language_select($lang), 'S_STYLE_OPTIONS' => style_select($style), 'S_TZ_OPTIONS' => tz_select($tz)));
                break;
            case 'avatar':
                $avatar_select = basename(request_var('avatar_select', ''));
                $category = basename(request_var('category', ''));
                $can_upload = file_exists($phpbb_root_path . $config['avatar_path']) && is_writeable($phpbb_root_path . $config['avatar_path']) && $file_uploads ? true : false;
                $data = array();
                if ($submit) {
                    $delete = request_var('delete', '');
                    $var_ary = array('uploadurl' => (string) '', 'remotelink' => (string) '', 'width' => (string) '', 'height' => (string) '');
                    foreach ($var_ary as $var => $default) {
                        $data[$var] = request_var($var, $default);
                    }
                    $var_ary = array('uploadurl' => array('string', true, 5, 255), 'remotelink' => array('string', true, 5, 255), 'width' => array('string', true, 1, 3), 'height' => array('string', true, 1, 3));
                    $error = validate_data($data, $var_ary);
                    if (!sizeof($error)) {
                        $data['user_id'] = $user_id;
                        if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload && $config['allow_avatar_upload']) {
                            list($type, $filename, $width, $height) = avatar_upload($data, $error);
                        } else {
                            if ($data['remotelink'] && $config['allow_avatar_remote']) {
                                list($type, $filename, $width, $height) = avatar_remote($data, $error);
                            } else {
                                if ($avatar_select && $config['allow_avatar_local']) {
                                    $type = AVATAR_GALLERY;
                                    $filename = $avatar_select;
                                    // check avatar gallery
                                    if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category)) {
                                        $type = $width = $height = 0;
                                        $filename = '';
                                    } else {
                                        list($width, $height) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . $filename);
                                        $filename = $category . '/' . $filename;
                                    }
                                } else {
                                    if ($delete) {
                                        $filename = '';
                                        $type = $width = $height = 0;
                                    } else {
                                        $data = array();
                                    }
                                }
                            }
                        }
                    }
                    if (!sizeof($error)) {
                        // Do we actually have any data to update?
                        if (sizeof($data)) {
                            $sql_ary = array('user_avatar' => $filename, 'user_avatar_type' => $type, 'user_avatar_width' => $width, 'user_avatar_height' => $height);
                            $sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE user_id = ' . $user_id;
                            $db->sql_query($sql);
                            // Delete old avatar if present
                            if ($user_row['user_avatar'] && $filename != $user_row['user_avatar'] && $user_row['user_avatar_type'] != AVATAR_GALLERY) {
                                avatar_delete($user_row['user_avatar']);
                            }
                        }
                        trigger_error($user->lang['USER_AVATAR_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
                }
                // Generate users avatar
                if ($user_row['user_avatar']) {
                    $avatar_img = '';
                    switch ($user_row['user_avatar_type']) {
                        case AVATAR_UPLOAD:
                            $avatar_img = $phpbb_root_path . $config['avatar_path'] . '/';
                            break;
                        case AVATAR_GALLERY:
                            $avatar_img = $phpbb_root_path . $config['avatar_gallery_path'] . '/';
                            break;
                    }
                    $avatar_img .= $user_row['user_avatar'];
                    $avatar_img = '<img src="' . $avatar_img . '" width="' . $user_row['user_avatar_width'] . '" height="' . $user_row['user_avatar_height'] . '" alt="" />';
                } else {
                    $avatar_img = '<img src="' . $phpbb_admin_path . 'images/no_avatar.gif" alt="" />';
                }
                $display_gallery = isset($_POST['display_gallery']) ? true : false;
                if ($config['allow_avatar_local'] && $display_gallery) {
                    avatar_gallery($category, $avatar_select, 4);
                }
                $template->assign_vars(array('S_AVATAR' => true, 'S_CAN_UPLOAD' => $can_upload && $config['allow_avatar_upload'] ? true : false, 'S_ALLOW_REMOTE' => $config['allow_avatar_remote'] ? true : false, 'S_DISPLAY_GALLERY' => $config['allow_avatar_local'] && !$display_gallery ? true : false, 'S_IN_GALLERY' => $config['allow_avatar_local'] && $display_gallery ? true : false, 'AVATAR_IMAGE' => $avatar_img, 'AVATAR_MAX_FILESIZE' => $config['avatar_filesize'], 'USER_AVATAR_WIDTH' => $user_row['user_avatar_width'], 'USER_AVATAR_HEIGHT' => $user_row['user_avatar_height'], 'L_AVATAR_EXPLAIN' => sprintf($user->lang['AVATAR_EXPLAIN'], $config['avatar_max_width'], $config['avatar_max_height'], round($config['avatar_filesize'] / 1024))));
                break;
            case 'rank':
                if ($submit) {
                    $rank_id = request_var('user_rank', 0);
                    $sql = 'UPDATE ' . USERS_TABLE . "\n\t\t\t\t\t\tSET user_rank = {$rank_id}\n\t\t\t\t\t\tWHERE user_id = {$user_id}";
                    $db->sql_query($sql);
                    trigger_error($user->lang['USER_RANK_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                }
                $sql = 'SELECT * 
					FROM ' . RANKS_TABLE . '
					WHERE rank_special = 1
					ORDER BY rank_title';
                $result = $db->sql_query($sql);
                $s_rank_options = '<option value="0"' . (!$user_row['user_rank'] ? ' selected="selected"' : '') . '>' . $user->lang['NO_SPECIAL_RANK'] . '</option>';
                while ($row = $db->sql_fetchrow($result)) {
                    $selected = $user_row['user_rank'] && $row['rank_id'] == $user_row['user_rank'] ? ' selected="selected"' : '';
                    $s_rank_options .= '<option value="' . $row['rank_id'] . '"' . $selected . '>' . $row['rank_title'] . '</option>';
                }
                $db->sql_freeresult($result);
                $template->assign_vars(array('S_RANK' => true, 'S_RANK_OPTIONS' => $s_rank_options));
                break;
            case 'sig':
                include_once $phpbb_root_path . 'includes/functions_posting.' . $phpEx;
                $enable_bbcode = $config['allow_sig_bbcode'] ? request_var('enable_bbcode', $this->optionget($user_row, 'bbcode')) : false;
                $enable_smilies = $config['allow_sig_smilies'] ? request_var('enable_smilies', $this->optionget($user_row, 'smilies')) : false;
                $enable_urls = request_var('enable_urls', true);
                $signature = request_var('signature', $user_row['user_sig'], true);
                $preview = isset($_POST['preview']) ? true : false;
                if ($submit || $preview) {
                    include_once $phpbb_root_path . 'includes/message_parser.' . $phpEx;
                    $message_parser = new parse_message($signature);
                    // Allowing Quote BBCode
                    $message_parser->parse($enable_bbcode, $enable_urls, $enable_smilies, $config['allow_sig_img'], $config['allow_sig_flash'], true, true, 'sig');
                    if (sizeof($message_parser->warn_msg)) {
                        $error[] = implode('<br />', $message_parser->warn_msg);
                    }
                    if (!sizeof($error) && $submit) {
                        $sql_ary = array('user_sig' => (string) $message_parser->message, 'user_sig_bbcode_uid' => (string) $message_parser->bbcode_uid, 'user_sig_bbcode_bitfield' => (int) $message_parser->bbcode_bitfield);
                        $sql = 'UPDATE ' . USERS_TABLE . ' 
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . ' 
							WHERE user_id = ' . $user_id;
                        $db->sql_query($sql);
                        trigger_error($user->lang['USER_SIG_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Replace "error" strings with their real, localised form
                    $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
                }
                $signature_preview = '';
                if ($preview) {
                    // Now parse it for displaying
                    $signature_preview = $message_parser->format_display($enable_bbcode, $enable_urls, $enable_smilies, false);
                    unset($message_parser);
                }
                decode_message($signature, $user_row['user_sig_bbcode_uid']);
                $template->assign_vars(array('S_SIGNATURE' => true, 'SIGNATURE' => $signature, 'SIGNATURE_PREVIEW' => $signature_preview, 'S_BBCODE_CHECKED' => !$enable_bbcode ? 'checked="checked"' : '', 'S_SMILIES_CHECKED' => !$enable_smilies ? 'checked="checked"' : '', 'S_MAGIC_URL_CHECKED' => !$enable_urls ? 'checked="checked"' : '', 'BBCODE_STATUS' => $config['allow_sig_bbcode'] ? sprintf($user->lang['BBCODE_IS_ON'], '<a href="' . append_sid("{$phpbb_root_path}faq.{$phpEx}", 'mode=bbcode') . '" onclick="target=\'_phpbbcode\';">', '</a>') : sprintf($user->lang['BBCODE_IS_OFF'], '<a href="' . append_sid("{$phpbb_root_path}faq.{$phpEx}", 'mode=bbcode') . '" onclick="target=\'_phpbbcode\';">', '</a>'), 'SMILIES_STATUS' => $config['allow_sig_smilies'] ? $user->lang['SMILIES_ARE_ON'] : $user->lang['SMILIES_ARE_OFF'], 'IMG_STATUS' => $config['allow_sig_img'] ? $user->lang['IMAGES_ARE_ON'] : $user->lang['IMAGES_ARE_OFF'], 'FLASH_STATUS' => $config['allow_sig_flash'] ? $user->lang['FLASH_IS_ON'] : $user->lang['FLASH_IS_OFF'], 'L_SIGNATURE_EXPLAIN' => sprintf($user->lang['SIGNATURE_EXPLAIN'], $config['max_sig_chars']), 'S_BBCODE_ALLOWED' => $config['allow_sig_bbcode'], 'S_SMILIES_ALLOWED' => $config['allow_sig_smilies']));
                break;
            case 'attach':
                $start = request_var('start', 0);
                $deletemark = isset($_POST['delmarked']) ? true : false;
                $marked = request_var('mark', array(0));
                // Sort keys
                $sort_key = request_var('sk', 'a');
                $sort_dir = request_var('sd', 'd');
                if ($deletemark && sizeof($marked)) {
                    if (confirm_box(true)) {
                        $sql = 'SELECT real_filename
							FROM ' . ATTACHMENTS_TABLE . '
							WHERE attach_id IN (' . implode(', ', $marked) . ')';
                        $result = $db->sql_query($sql);
                        $log_attachments = array();
                        while ($row = $db->sql_fetchrow($result)) {
                            $log_attachments[] = $row['real_filename'];
                        }
                        $db->sql_freeresult($result);
                        delete_attachments('attach', $marked);
                        $log = sizeof($log_attachments) == 1 ? 'ATTACHMENT_DELETED' : 'ATTACHMENTS_DELETED';
                        $message = sizeof($log_attachments) == 1 ? $user->lang['ATTACHMENT_DELETED'] : $user->lang['ATTACHMENTS_DELETED'];
                        add_log('admin', $log, implode(', ', $log_attachments));
                        trigger_error($message . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    } else {
                        confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'deletemark' => true, 'mark' => $marked)));
                    }
                }
                $sk_text = array('a' => $user->lang['SORT_FILENAME'], 'c' => $user->lang['SORT_EXTENSION'], 'd' => $user->lang['SORT_SIZE'], 'e' => $user->lang['SORT_DOWNLOADS'], 'f' => $user->lang['SORT_POST_TIME'], 'g' => $user->lang['SORT_TOPIC_TITLE']);
                $sk_sql = array('a' => 'a.real_filename', 'c' => 'a.extension', 'd' => 'a.filesize', 'e' => 'a.download_count', 'f' => 'a.filetime', 'g' => 't.topic_title');
                $sd_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
                $s_sort_key = '';
                foreach ($sk_text as $key => $value) {
                    $selected = $sort_key == $key ? ' selected="selected"' : '';
                    $s_sort_key .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                }
                $s_sort_dir = '';
                foreach ($sd_text as $key => $value) {
                    $selected = $sort_dir == $key ? ' selected="selected"' : '';
                    $s_sort_dir .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
                }
                $order_by = $sk_sql[$sort_key] . '  ' . ($sort_dir == 'a' ? 'ASC' : 'DESC');
                $sql = 'SELECT COUNT(attach_id) as num_attachments
					FROM ' . ATTACHMENTS_TABLE . "\n\t\t\t\t\tWHERE poster_id = {$user_id}";
                $result = $db->sql_query_limit($sql, 1);
                $num_attachments = (int) $db->sql_fetchfield('num_attachments');
                $db->sql_freeresult($result);
                $sql = 'SELECT a.*, t.topic_title, p.message_subject as message_title
					FROM ' . ATTACHMENTS_TABLE . ' a 
						LEFT JOIN ' . TOPICS_TABLE . ' t ON (a.topic_id = t.topic_id
							AND a.in_message = 0)
						LEFT JOIN ' . PRIVMSGS_TABLE . ' p ON (a.post_msg_id = p.msg_id
							AND a.in_message = 1)
					WHERE a.poster_id = ' . $user_id . "\n\t\t\t\t\tORDER BY {$order_by}";
                $result = $db->sql_query_limit($sql, $config['posts_per_page'], $start);
                while ($row = $db->sql_fetchrow($result)) {
                    if ($row['in_message']) {
                        $view_topic = append_sid("{$phpbb_root_path}ucp.{$phpEx}", "i=pm&amp;p={$row['post_msg_id']}");
                    } else {
                        $view_topic = append_sid("{$phpbb_root_path}viewtopic.{$phpEx}", "t={$row['topic_id']}&amp;p={$row['post_msg_id']}#{$row['post_msg_id']}");
                    }
                    $template->assign_block_vars('attach', array('REAL_FILENAME' => $row['real_filename'], 'COMMENT' => nl2br($row['comment']), 'EXTENSION' => $row['extension'], 'SIZE' => $row['filesize'] >= 1048576 ? ($row['filesize'] >> 20) . ' ' . $user->lang['MB'] : ($row['filesize'] >= 1024 ? ($row['filesize'] >> 10) . ' ' . $user->lang['KB'] : $row['filesize'] . ' ' . $user->lang['BYTES']), 'DOWNLOAD_COUNT' => $row['download_count'], 'POST_TIME' => $user->format_date($row['filetime']), 'TOPIC_TITLE' => $row['in_message'] ? $row['message_title'] : $row['topic_title'], 'ATTACH_ID' => $row['attach_id'], 'POST_ID' => $row['post_msg_id'], 'TOPIC_ID' => $row['topic_id'], 'S_IN_MESSAGE' => $row['in_message'], 'U_DOWNLOAD' => append_sid("{$phpbb_root_path}download.{$phpEx}", 'id=' . $row['attach_id']), 'U_VIEW_TOPIC' => $view_topic));
                }
                $db->sql_freeresult($result);
                $template->assign_vars(array('S_ATTACHMENTS' => true, 'S_ON_PAGE' => on_page($num_attachments, $config['topics_per_page'], $start), 'S_SORT_KEY' => $s_sort_key, 'S_SORT_DIR' => $s_sort_dir, 'PAGINATION' => generate_pagination($this->u_action . "&amp;sk={$sort_key}&amp;sd={$sort_dir}", $num_attachments, $config['topics_per_page'], $start, true)));
                break;
            case 'groups':
                $user->add_lang(array('groups', 'acp/groups'));
                $group_id = request_var('g', 0);
                switch ($action) {
                    case 'demote':
                    case 'promote':
                    case 'default':
                        group_user_attributes($action, $group_id, $user_id);
                        if ($action == 'default') {
                            $user_row['group_id'] = $group_id;
                        }
                        break;
                    case 'delete':
                        if (confirm_box(true)) {
                            if (!$group_id) {
                                trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            }
                            if ($error = group_user_del($group_id, $user_id)) {
                                trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                            }
                            $error = array();
                        } else {
                            confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array('u' => $user_id, 'i' => $id, 'mode' => $mode, 'action' => $action, 'g' => $group_id)));
                        }
                        break;
                }
                // Add user to group?
                if ($submit) {
                    if (!$group_id) {
                        trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    // Add user/s to group
                    if ($error = group_user_add($group_id, $user_id)) {
                        trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
                    }
                    $error = array();
                }
                $sql = 'SELECT ug.*, g.*
					FROM ' . GROUPS_TABLE . ' g, ' . USER_GROUP_TABLE . " ug\n\t\t\t\t\tWHERE ug.user_id = {$user_id}\n\t\t\t\t\t\tAND g.group_id = ug.group_id\n\t\t\t\t\tORDER BY g.group_type DESC, ug.user_pending ASC, g.group_name";
                $result = $db->sql_query($sql);
                $i = 0;
                $group_data = $id_ary = array();
                while ($row = $db->sql_fetchrow($result)) {
                    $type = $row['group_type'] == GROUP_SPECIAL ? 'special' : ($row['user_pending'] ? 'pending' : 'normal');
                    $group_data[$type][$i]['group_id'] = $row['group_id'];
                    $group_data[$type][$i]['group_name'] = $row['group_name'];
                    $group_data[$type][$i]['group_leader'] = $row['group_leader'] ? 1 : 0;
                    $id_ary[] = $row['group_id'];
                    $i++;
                }
                $db->sql_freeresult($result);
                // Select box for other groups
                $sql = 'SELECT group_id, group_name, group_type
					FROM ' . GROUPS_TABLE . '
					' . (sizeof($id_ary) ? 'WHERE group_id NOT IN (' . implode(', ', $id_ary) . ')' : '') . '
					ORDER BY group_type DESC, group_name ASC';
                $result = $db->sql_query($sql);
                $s_group_options = '';
                while ($row = $db->sql_fetchrow($result)) {
                    if ($config['coppa_hide_groups'] && in_array($row['group_name'], array('INACTIVE_COPPA', 'REGISTERED_COPPA'))) {
                        continue;
                    }
                    $s_group_options .= '<option' . ($row['group_type'] == GROUP_SPECIAL ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '">' . ($row['group_type'] == GROUP_SPECIAL ? $user->lang['G_' . $row['group_name']] : $row['group_name']) . '</option>';
                }
                $db->sql_freeresult($result);
                $current_type = '';
                foreach ($group_data as $group_type => $data_ary) {
                    if ($current_type != $group_type) {
                        $template->assign_block_vars('group', array('S_NEW_GROUP_TYPE' => true, 'GROUP_TYPE' => $user->lang['USER_GROUP_' . strtoupper($group_type)]));
                    }
                    foreach ($data_ary as $data) {
                        $template->assign_block_vars('group', array('U_EDIT_GROUP' => append_sid("{$phpbb_admin_path}index.{$phpEx}", "i=groups&amp;mode=manage&amp;action=edit&amp;u={$user_id}&amp;g={$data['group_id']}&amp;back_link=acp_users_groups"), 'U_DEFAULT' => $this->u_action . "&amp;action=default&amp;u={$user_id}&amp;g=" . $data['group_id'], 'U_DEMOTE_PROMOTE' => $this->u_action . '&amp;action=' . ($data['group_leader'] ? 'demote' : 'promote') . "&amp;u={$user_id}&amp;g=" . $data['group_id'], 'U_DELETE' => $this->u_action . "&amp;action=delete&amp;u={$user_id}&amp;g=" . $data['group_id'], 'GROUP_NAME' => $group_type == 'special' ? $user->lang['G_' . $data['group_name']] : $data['group_name'], 'L_DEMOTE_PROMOTE' => $data['group_leader'] ? $user->lang['GROUP_DEMOTE'] : $user->lang['GROUP_PROMOTE'], 'S_NO_DEFAULT' => $user_row['group_id'] != $data['group_id'] ? true : false, 'S_SPECIAL_GROUP' => $group_type == 'special' ? true : false));
                    }
                }
                $template->assign_vars(array('S_GROUPS' => true, 'S_GROUP_OPTIONS' => $s_group_options));
                break;
            case 'perm':
                include_once $phpbb_root_path . 'includes/acp/auth.' . $phpEx;
                $auth_admin = new auth_admin();
                $user->add_lang('acp/permissions');
                $user->add_lang('acp/permissions_phpbb');
                // Select auth options
                $sql = 'SELECT auth_option, is_local, is_global
					FROM ' . ACL_OPTIONS_TABLE . "\n\t\t\t\t\tWHERE auth_option LIKE '%\\_'\n\t\t\t\t\t\tAND is_global = 1\n\t\t\t\t\tORDER BY auth_option";
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $hold_ary = $auth_admin->get_mask('view', $user_id, false, false, $row['auth_option'], 'global', ACL_NO);
                    $auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', false, false);
                }
                $db->sql_freeresult($result);
                $sql = 'SELECT auth_option, is_local, is_global
					FROM ' . ACL_OPTIONS_TABLE . "\n\t\t\t\t\tWHERE auth_option LIKE '%\\_'\n\t\t\t\t\t\tAND is_local = 1\n\t\t\t\t\tORDER BY is_global DESC, auth_option";
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $hold_ary = $auth_admin->get_mask('view', $user_id, false, false, $row['auth_option'], 'local', ACL_NO);
                    $auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', true, false);
                }
                $db->sql_freeresult($result);
                $template->assign_vars(array('S_PERMISSIONS' => true, 'U_USER_PERMISSIONS' => append_sid("{$phpbb_admin_path}index.{$phpEx}", 'i=permissions&amp;mode=setting_user_global&amp;user_id[]=' . $user_id), 'U_USER_FORUM_PERMISSIONS' => append_sid("{$phpbb_admin_path}index.{$phpEx}", 'i=permissions&amp;mode=setting_user_local&amp;user_id[]=' . $user_id)));
                break;
        }
        // Assign general variables
        $template->assign_vars(array('S_ERROR' => sizeof($error) ? true : false, 'ERROR_MSG' => sizeof($error) ? implode('<br />', $error) : ''));
    }
Exemplo n.º 6
0
	function main($id, $mode)
	{
		global $config, $db, $user, $auth, $template, $cache;
		global $phpbb_root_path, $phpbb_admin_path, $phpEx, $table_prefix, $file_uploads;

		$user->add_lang(array('posting', 'ucp', 'acp/users'));
		$this->tpl_name = 'acp_users';
		$this->page_title = 'ACP_USER_' . strtoupper($mode);

		$error		= array();
		$username	= utf8_normalize_nfc(request_var('username', '', true));
		$user_id	= request_var('u', 0);
		$action		= request_var('action', '');

		$submit		= (isset($_POST['update']) && !isset($_POST['cancel'])) ? true : false;

		$form_name = 'acp_users';
		add_form_key($form_name);

		// Whois (special case)
		if ($action == 'whois')
		{
			include($phpbb_root_path . 'includes/functions_user.' . $phpEx);

			$this->page_title = 'WHOIS';
			$this->tpl_name = 'simple_body';

			$user_ip = request_var('user_ip', '');
			$domain = gethostbyaddr($user_ip);
			$ipwhois = user_ipwhois($user_ip);

			$template->assign_vars(array(
				'MESSAGE_TITLE'		=> sprintf($user->lang['IP_WHOIS_FOR'], $domain),
				'MESSAGE_TEXT'		=> nl2br($ipwhois))
			);

			return;
		}

		// Show user selection mask
		if (!$username && !$user_id)
		{
			$this->page_title = 'SELECT_USER';

			$template->assign_vars(array(
				'U_ACTION'			=> $this->u_action,
				'ANONYMOUS_USER_ID'	=> ANONYMOUS,

				'S_SELECT_USER'		=> true,
				'U_FIND_USERNAME'	=> append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=searchuser&amp;form=select_user&amp;field=username&amp;select_single=true'),
			));

			return;
		}

		if (!$user_id)
		{
			$sql = 'SELECT user_id
				FROM ' . USERS_TABLE . "
				WHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'";
			$result = $db->sql_query($sql);
			$user_id = (int) $db->sql_fetchfield('user_id');
			$db->sql_freeresult($result);

			if (!$user_id)
			{
				trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action), E_USER_WARNING);
			}
		}

		// Generate content for all modes
		$sql = 'SELECT u.*, s.*
			FROM ' . USERS_TABLE . ' u
				LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
			WHERE u.user_id = ' . $user_id . '
			ORDER BY s.session_time DESC';
		$result = $db->sql_query($sql);
		$user_row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		if (!$user_row)
		{
			trigger_error($user->lang['NO_USER'] . adm_back_link($this->u_action), E_USER_WARNING);
		}

		// Generate overall "header" for user admin
		$s_form_options = '';

		// Build modes dropdown list
		$sql = 'SELECT module_mode, module_auth
			FROM ' . MODULES_TABLE . "
			WHERE module_basename = 'users'
				AND module_enabled = 1
				AND module_class = 'acp'
			ORDER BY left_id, module_mode";
		$result = $db->sql_query($sql);

		$dropdown_modes = array();
		while ($row = $db->sql_fetchrow($result))
		{
			if (!$this->p_master->module_auth($row['module_auth']))
			{
				continue;
			}

			$dropdown_modes[$row['module_mode']] = true;
		}
		$db->sql_freeresult($result);

		foreach ($dropdown_modes as $module_mode => $null)
		{
			$selected = ($mode == $module_mode) ? ' selected="selected"' : '';
			$s_form_options .= '<option value="' . $module_mode . '"' . $selected . '>' . $user->lang['ACP_USER_' . strtoupper($module_mode)] . '</option>';
		}

		$template->assign_vars(array(
			'U_BACK'			=> $this->u_action,
			'U_MODE_SELECT'		=> append_sid("{$phpbb_admin_path}index.$phpEx", "i=$id&amp;u=$user_id"),
			'U_ACTION'			=> $this->u_action . '&amp;u=' . $user_id,
			'S_FORM_OPTIONS'	=> $s_form_options,
			'MANAGED_USERNAME'	=> $user_row['username'])
		);

		// Prevent normal users/admins change/view founders if they are not a founder by themselves
		if ($user->data['user_type'] != USER_FOUNDER && $user_row['user_type'] == USER_FOUNDER)
		{
			trigger_error($user->lang['NOT_MANAGE_FOUNDER'] . adm_back_link($this->u_action), E_USER_WARNING);
		}

		switch ($mode)
		{
			case 'overview':

				include($phpbb_root_path . 'includes/functions_user.' . $phpEx);

				$user->add_lang('acp/ban');

				$delete			= request_var('delete', 0);
				$delete_type	= request_var('delete_type', '');
				$ip				= request_var('ip', 'ip');

				if ($submit)
				{
					// You can't delete the founder
					if ($delete && $user_row['user_type'] != USER_FOUNDER)
					{
						if (!$auth->acl_get('a_userdel'))
						{
							trigger_error($user->lang['NO_AUTH_OPERATION'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
						}

						// Check if the user wants to remove himself or the guest user account
						if ($user_id == ANONYMOUS)
						{
							trigger_error($user->lang['CANNOT_REMOVE_ANONYMOUS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
						}

						if ($user_id == $user->data['user_id'])
						{
							trigger_error($user->lang['CANNOT_REMOVE_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
						}

						if (confirm_box(true))
						{
							user_delete($delete_type, $user_id, $user_row['username']);

							add_log('admin', 'LOG_USER_DELETED', $user_row['username']);
							trigger_error($user->lang['USER_DELETED'] . adm_back_link($this->u_action));
						}
						else
						{
							confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
								'u'				=> $user_id,
								'i'				=> $id,
								'mode'			=> $mode,
								'action'		=> $action,
								'update'		=> true,
								'delete'		=> 1,
								'delete_type'	=> $delete_type))
							);
						}
					}

					// Handle quicktool actions
					switch ($action)
					{
						case 'banuser':
						case 'banemail':
						case 'banip':

							if ($user_id == $user->data['user_id'])
							{
								trigger_error($user->lang['CANNOT_BAN_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($user_row['user_type'] == USER_FOUNDER)
							{
								trigger_error($user->lang['CANNOT_BAN_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							$ban = array();

							switch ($action)
							{
								case 'banuser':
									$ban[] = $user_row['username'];
									$reason = 'USER_ADMIN_BAN_NAME_REASON';
									$log = 'LOG_USER_BAN_USER';
								break;

								case 'banemail':
									$ban[] = $user_row['user_email'];
									$reason = 'USER_ADMIN_BAN_EMAIL_REASON';
									$log = 'LOG_USER_BAN_EMAIL';
								break;

								case 'banip':
									$ban[] = $user_row['user_ip'];

									$sql = 'SELECT DISTINCT poster_ip
										FROM ' . POSTS_TABLE . "
										WHERE poster_id = $user_id";
									$result = $db->sql_query($sql);

									while ($row = $db->sql_fetchrow($result))
									{
										$ban[] = $row['poster_ip'];
									}
									$db->sql_freeresult($result);

									$reason = 'USER_ADMIN_BAN_IP_REASON';
									$log = 'LOG_USER_BAN_IP';
								break;
							}

							$ban_reason = utf8_normalize_nfc(request_var('ban_reason', $user->lang[$reason], true));
							$ban_give_reason = utf8_normalize_nfc(request_var('ban_give_reason', '', true));

							// Log not used at the moment, we simply utilize the ban function.
							$result = user_ban(substr($action, 3), $ban, 0, 0, 0, $ban_reason, $ban_give_reason);

							trigger_error((($result === false) ? $user->lang['BAN_ALREADY_ENTERED'] : $user->lang['BAN_SUCCESSFUL']) . adm_back_link($this->u_action . '&amp;u=' . $user_id));

						break;

						case 'reactivate':

							if ($user_id == $user->data['user_id'])
							{
								trigger_error($user->lang['CANNOT_FORCE_REACT_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($user_row['user_type'] == USER_FOUNDER)
							{
								trigger_error($user->lang['CANNOT_FORCE_REACT_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($user_row['user_type'] == USER_IGNORE)
							{
								trigger_error($user->lang['CANNOT_FORCE_REACT_BOT'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($config['email_enable'])
							{
								include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);

								$server_url = generate_board_url();

								$user_actkey = gen_rand_string(10);
								$key_len = 54 - (strlen($server_url));
								$key_len = ($key_len > 6) ? $key_len : 6;
								$user_actkey = substr($user_actkey, 0, $key_len);
								$email_template = ($user_row['user_type'] == USER_NORMAL) ? 'user_reactivate_account' : 'user_resend_inactive';

								if ($user_row['user_type'] == USER_NORMAL)
								{
									user_active_flip('deactivate', $user_id, INACTIVE_REMIND);

									$sql = 'UPDATE ' . USERS_TABLE . "
										SET user_actkey = '" . $db->sql_escape($user_actkey) . "'
										WHERE user_id = $user_id";
									$db->sql_query($sql);
								}
								else
								{
									// Grabbing the last confirm key - we only send a reminder
									$sql = 'SELECT user_actkey
										FROM ' . USERS_TABLE . '
										WHERE user_id = ' . $user_id;
									$result = $db->sql_query($sql);
									$user_actkey = (string) $db->sql_fetchfield('user_actkey');
									$db->sql_freeresult($result);
								}

								$messenger = new messenger(false);

								$messenger->template($email_template, $user_row['user_lang']);

								$messenger->to($user_row['user_email'], $user_row['username']);

								$messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
								$messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
								$messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
								$messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);

								$messenger->assign_vars(array(
									'WELCOME_MSG'	=> htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])),
									'USERNAME'		=> htmlspecialchars_decode($user_row['username']),
									'U_ACTIVATE'	=> "$server_url/ucp.$phpEx?mode=activate&u={$user_row['user_id']}&k=$user_actkey")
								);

								$messenger->send(NOTIFY_EMAIL);

								add_log('admin', 'LOG_USER_REACTIVATE', $user_row['username']);
								add_log('user', $user_id, 'LOG_USER_REACTIVATE_USER');

								trigger_error($user->lang['FORCE_REACTIVATION_SUCCESS'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
							}

						break;

						case 'active':

							if ($user_id == $user->data['user_id'])
							{
								// It is only deactivation since the user is already activated (else he would not have reached this page)
								trigger_error($user->lang['CANNOT_DEACTIVATE_YOURSELF'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($user_row['user_type'] == USER_FOUNDER)
							{
								trigger_error($user->lang['CANNOT_DEACTIVATE_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($user_row['user_type'] == USER_IGNORE)
							{
								trigger_error($user->lang['CANNOT_DEACTIVATE_BOT'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							user_active_flip('flip', $user_id);

							$message = ($user_row['user_type'] == USER_INACTIVE) ? 'USER_ADMIN_ACTIVATED' : 'USER_ADMIN_DEACTIVED';
							$log = ($user_row['user_type'] == USER_INACTIVE) ? 'LOG_USER_ACTIVE' : 'LOG_USER_INACTIVE';

							add_log('admin', $log, $user_row['username']);
							add_log('user', $user_id, $log . '_USER');

							trigger_error($user->lang[$message] . adm_back_link($this->u_action . '&amp;u=' . $user_id));

						break;

						case 'delsig':

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							$sql_ary = array(
								'user_sig'					=> '',
								'user_sig_bbcode_uid'		=> '',
								'user_sig_bbcode_bitfield'	=> ''
							);

							$sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
								WHERE user_id = $user_id";
							$db->sql_query($sql);
						
							add_log('admin', 'LOG_USER_DEL_SIG', $user_row['username']);
							add_log('user', $user_id, 'LOG_USER_DEL_SIG_USER');

							trigger_error($user->lang['USER_ADMIN_SIG_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));

						break;

						case 'delavatar':

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							$sql_ary = array(
								'user_avatar'			=> '',
								'user_avatar_type'		=> 0,
								'user_avatar_width'		=> 0,
								'user_avatar_height'	=> 0,
							);

							$sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
								WHERE user_id = $user_id";
							$db->sql_query($sql);

							// Delete old avatar if present
							if ($user_row['user_avatar'] && $user_row['user_avatar_type'] != AVATAR_GALLERY)
							{
								avatar_delete('user', $user_row);
							}

							add_log('admin', 'LOG_USER_DEL_AVATAR', $user_row['username']);
							add_log('user', $user_id, 'LOG_USER_DEL_AVATAR_USER');

							trigger_error($user->lang['USER_ADMIN_AVATAR_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
						break;

						case 'delposts':

							if (confirm_box(true))
							{
								// Delete posts, attachments, etc.
								delete_posts('poster_id', $user_id);

								add_log('admin', 'LOG_USER_DEL_POSTS', $user_row['username']);
								trigger_error($user->lang['USER_POSTS_DELETED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
							}
							else
							{
								confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
									'u'				=> $user_id,
									'i'				=> $id,
									'mode'			=> $mode,
									'action'		=> $action,
									'update'		=> true))
								);
							}

						break;

						case 'delattach':

							if (confirm_box(true))
							{
								delete_attachments('user', $user_id);

								add_log('admin', 'LOG_USER_DEL_ATTACH', $user_row['username']);
								trigger_error($user->lang['USER_ATTACHMENTS_REMOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
							}
							else
							{
								confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
									'u'				=> $user_id,
									'i'				=> $id,
									'mode'			=> $mode,
									'action'		=> $action,
									'update'		=> true))
								);
							}
						
						break;
						
						case 'moveposts':

							if (!check_form_key($form_name))
							{
								trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							$user->add_lang('acp/forums');

							$new_forum_id = request_var('new_f', 0);

							if (!$new_forum_id)
							{
								$this->page_title = 'USER_ADMIN_MOVE_POSTS';

								$template->assign_vars(array(
									'S_SELECT_FORUM'		=> true,
									'U_ACTION'				=> $this->u_action . "&amp;action=$action&amp;u=$user_id",
									'U_BACK'				=> $this->u_action . "&amp;u=$user_id",
									'S_FORUM_OPTIONS'		=> make_forum_select(false, false, false, true))
								);

								return;
							}

							// Is the new forum postable to?
							$sql = 'SELECT forum_name, forum_type
								FROM ' . FORUMS_TABLE . "
								WHERE forum_id = $new_forum_id";
							$result = $db->sql_query($sql);
							$forum_info = $db->sql_fetchrow($result);
							$db->sql_freeresult($result);

							if (!$forum_info)
							{
								trigger_error($user->lang['NO_FORUM'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($forum_info['forum_type'] != FORUM_POST)
							{
								trigger_error($user->lang['MOVE_POSTS_NO_POSTABLE_FORUM'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							// Two stage?
							// Move topics comprising only posts from this user
							$topic_id_ary = $move_topic_ary = $move_post_ary = $new_topic_id_ary = array();
							$forum_id_ary = array($new_forum_id);

							$sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
								FROM ' . POSTS_TABLE . "
								WHERE poster_id = $user_id
									AND forum_id <> $new_forum_id
								GROUP BY topic_id";
							$result = $db->sql_query($sql);

							while ($row = $db->sql_fetchrow($result))
							{
								$topic_id_ary[$row['topic_id']] = $row['total_posts'];
							}
							$db->sql_freeresult($result);

							if (sizeof($topic_id_ary))
							{
								$sql = 'SELECT topic_id, forum_id, topic_title, topic_replies, topic_replies_real, topic_attachment
									FROM ' . TOPICS_TABLE . '
									WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
								$result = $db->sql_query($sql);

								while ($row = $db->sql_fetchrow($result))
								{
									if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
									{
										$move_topic_ary[] = $row['topic_id'];
									}
									else
									{
										$move_post_ary[$row['topic_id']]['title'] = $row['topic_title'];
										$move_post_ary[$row['topic_id']]['attach'] = ($row['topic_attachment']) ? 1 : 0;
									}

									$forum_id_ary[] = $row['forum_id'];
								}
								$db->sql_freeresult($result);
							}

							// Entire topic comprises posts by this user, move these topics
							if (sizeof($move_topic_ary))
							{
								move_topics($move_topic_ary, $new_forum_id, false);
							}

							if (sizeof($move_post_ary))
							{
								// Create new topic
								// Update post_ids, report_ids, attachment_ids
								foreach ($move_post_ary as $topic_id => $post_ary)
								{
									// Create new topic
									$sql = 'INSERT INTO ' . TOPICS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
										'topic_poster'				=> $user_id,
										'topic_time'				=> time(),
										'forum_id' 					=> $new_forum_id,
										'icon_id'					=> 0,
										'topic_approved'			=> 1,
										'topic_title' 				=> $post_ary['title'],
										'topic_first_poster_name'	=> $user_row['username'],
										'topic_type'				=> POST_NORMAL,
										'topic_time_limit'			=> 0,
										'topic_attachment'			=> $post_ary['attach'])
									);
									$db->sql_query($sql);

									$new_topic_id = $db->sql_nextid();

									// Move posts
									$sql = 'UPDATE ' . POSTS_TABLE . "
										SET forum_id = $new_forum_id, topic_id = $new_topic_id
										WHERE topic_id = $topic_id
											AND poster_id = $user_id";
									$db->sql_query($sql);

									if ($post_ary['attach'])
									{
										$sql = 'UPDATE ' . ATTACHMENTS_TABLE . "
											SET topic_id = $new_topic_id
											WHERE topic_id = $topic_id
												AND poster_id = $user_id";
										$db->sql_query($sql);
									}

									$new_topic_id_ary[] = $new_topic_id;
								}
							}

							$forum_id_ary = array_unique($forum_id_ary);
							$topic_id_ary = array_unique(array_merge($topic_id_ary, $new_topic_id_ary));

							if (sizeof($topic_id_ary))
							{
								sync('reported', 'topic_id', $topic_id_ary);
								sync('topic', 'topic_id', $topic_id_ary);
							}

							if (sizeof($forum_id_ary))
							{
								sync('forum', 'forum_id', $forum_id_ary, false, true);
							}


							add_log('admin', 'LOG_USER_MOVE_POSTS', $user_row['username'], $forum_info['forum_name']);
							add_log('user', $user_id, 'LOG_USER_MOVE_POSTS_USER', $forum_info['forum_name']);

							trigger_error($user->lang['USER_POSTS_MOVED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));

						break;
					}

					// Handle registration info updates
					$data = array(
						'username'			=> utf8_normalize_nfc(request_var('user', $user_row['username'], true)),
						'user_founder'		=> request_var('user_founder', ($user_row['user_type'] == USER_FOUNDER) ? 1 : 0),
						'email'				=> strtolower(request_var('user_email', $user_row['user_email'])),
						'email_confirm'		=> strtolower(request_var('email_confirm', '')),
						'new_password'		=> request_var('new_password', '', true),
						'password_confirm'	=> request_var('password_confirm', '', true),
					);

					// Validation data - we do not check the password complexity setting here
					$check_ary = array(
						'new_password'		=> array(
							array('string', true, $config['min_pass_chars'], $config['max_pass_chars']),
							array('password')),
						'password_confirm'	=> array('string', true, $config['min_pass_chars'], $config['max_pass_chars']),
					);

					// Check username if altered
					if ($data['username'] != $user_row['username'])
					{
						$check_ary += array(
							'username'			=> array(
								array('string', false, $config['min_name_chars'], $config['max_name_chars']),
								array('username', $user_row['username'])
							),
						);
					}

					// Check email if altered
					if ($data['email'] != $user_row['user_email'])
					{
						$check_ary += array(
							'email'				=> array(
								array('string', false, 6, 60),
								array('email', $user_row['user_email'])
							),
							'email_confirm'		=> array('string', true, 6, 60)
						);
					}

					$error = validate_data($data, $check_ary);

					if ($data['new_password'] && $data['password_confirm'] != $data['new_password'])
					{
						$error[] = 'NEW_PASSWORD_ERROR';
					}

					if ($data['email'] != $user_row['user_email'] && $data['email_confirm'] != $data['email'])
					{
						$error[] = 'NEW_EMAIL_ERROR';
					}

					if (!check_form_key($form_name))
					{
						$error[] = 'FORM_INVALID';
					}

					// Which updates do we need to do?
					$update_username = ($user_row['username'] != $data['username']) ? $data['username'] : false;
					$update_password = ($data['new_password'] && !phpbb_check_hash($user_row['user_password'], $data['new_password'])) ? true : false;
					$update_email = ($data['email'] != $user_row['user_email']) ? $data['email'] : false;

					if (!sizeof($error))
					{
						$sql_ary = array();

						if ($user_row['user_type'] != USER_FOUNDER || $user->data['user_type'] == USER_FOUNDER)
						{
							// Only allow founders updating the founder status...
							if ($user->data['user_type'] == USER_FOUNDER)
							{
								// Setting a normal member to be a founder
								if ($data['user_founder'] && $user_row['user_type'] != USER_FOUNDER)
								{
									// Make sure the user is not setting an Inactive or ignored user to be a founder
									if ($user_row['user_type'] == USER_IGNORE)
									{
										trigger_error($user->lang['CANNOT_SET_FOUNDER_IGNORED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
									}

									if ($user_row['user_type'] == USER_INACTIVE)
									{
										trigger_error($user->lang['CANNOT_SET_FOUNDER_INACTIVE'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
									}

									$sql_ary['user_type'] = USER_FOUNDER;
								}
								else if (!$data['user_founder'] && $user_row['user_type'] == USER_FOUNDER)
								{
									// Check if at least one founder is present
									$sql = 'SELECT user_id
										FROM ' . USERS_TABLE . '
										WHERE user_type = ' . USER_FOUNDER . '
											AND user_id <> ' . $user_id;
									$result = $db->sql_query_limit($sql, 1);
									$row = $db->sql_fetchrow($result);
									$db->sql_freeresult($result);

									if ($row)
									{
										$sql_ary['user_type'] = USER_NORMAL;
									}
									else
									{
										trigger_error($user->lang['AT_LEAST_ONE_FOUNDER'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
									}
								}
							}
						}

						if ($update_username !== false)
						{
							$sql_ary['username'] = $update_username;
							$sql_ary['username_clean'] = utf8_clean_string($update_username);

							add_log('user', $user_id, 'LOG_USER_UPDATE_NAME', $user_row['username'], $update_username);
						}

						if ($update_email !== false)
						{
							$sql_ary += array(
								'user_email'		=> $update_email,
								'user_email_hash'	=> crc32($update_email) . strlen($update_email)
							);

							add_log('user', $user_id, 'LOG_USER_UPDATE_EMAIL', $user_row['username'], $user_row['user_email'], $update_email);
						}

						if ($update_password)
						{
							$sql_ary += array(
								'user_password'		=> phpbb_hash($data['new_password']),
								'user_passchg'		=> time(),
								'user_pass_convert'	=> 0,
							);

							$user->reset_login_keys($user_id);
							add_log('user', $user_id, 'LOG_USER_NEW_PASSWORD', $user_row['username']);
						}

						if (sizeof($sql_ary))
						{
							$sql = 'UPDATE ' . USERS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE user_id = ' . $user_id;
							$db->sql_query($sql);
						}

						if ($update_username)
						{
							user_update_name($user_row['username'], $update_username);
						}

						// Let the users permissions being updated
						$auth->acl_clear_prefetch($user_id);

						add_log('admin', 'LOG_USER_USER_UPDATE', $data['username']);

						trigger_error($user->lang['USER_OVERVIEW_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
					}

					// Replace "error" strings with their real, localised form
					$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
				}

				if ($user_id == $user->data['user_id'])
				{
					$quick_tool_ary = array('delsig' => 'DEL_SIG', 'delavatar' => 'DEL_AVATAR', 'moveposts' => 'MOVE_POSTS', 'delposts' => 'DEL_POSTS', 'delattach' => 'DEL_ATTACH');
				}
				else
				{
					$quick_tool_ary = array();

					if ($user_row['user_type'] != USER_FOUNDER)
					{
						$quick_tool_ary += array('banuser' => 'BAN_USER', 'banemail' => 'BAN_EMAIL', 'banip' => 'BAN_IP');
					}

					if ($user_row['user_type'] != USER_FOUNDER && $user_row['user_type'] != USER_IGNORE)
					{
						$quick_tool_ary += array('active' => (($user_row['user_type'] == USER_INACTIVE) ? 'ACTIVATE' : 'DEACTIVATE'));
					}
					
					$quick_tool_ary += array('delsig' => 'DEL_SIG', 'delavatar' => 'DEL_AVATAR', 'moveposts' => 'MOVE_POSTS', 'delposts' => 'DEL_POSTS', 'delattach' => 'DEL_ATTACH');
					
					if ($config['email_enable'] && ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_INACTIVE))
					{
						$quick_tool_ary['reactivate'] = 'FORCE';
					}
				}

				$s_action_options = '<option class="sep" value="">' . $user->lang['SELECT_OPTION'] . '</option>';
				foreach ($quick_tool_ary as $value => $lang)
				{
					$s_action_options .= '<option value="' . $value . '">' . $user->lang['USER_ADMIN_' . $lang] . '</option>';
				}

				if ($config['load_onlinetrack'])
				{
					$sql = 'SELECT MAX(session_time) AS session_time, MIN(session_viewonline) AS session_viewonline
						FROM ' . SESSIONS_TABLE . "
						WHERE session_user_id = $user_id";
					$result = $db->sql_query($sql);
					$row = $db->sql_fetchrow($result);
					$db->sql_freeresult($result);

					$user_row['session_time'] = (isset($row['session_time'])) ? $row['session_time'] : 0;
					$user_row['session_viewonline'] = (isset($row['session_viewonline'])) ? $row['session_viewonline'] : 0;
					unset($row);
				}

				$last_visit = (!empty($user_row['session_time'])) ? $user_row['session_time'] : $user_row['user_lastvisit'];

				$inactive_reason = '';
				if ($user_row['user_type'] == USER_INACTIVE)
				{
					$inactive_reason = $user->lang['INACTIVE_REASON_UNKNOWN'];

					switch ($user_row['user_inactive_reason'])
					{
						case INACTIVE_REGISTER:
							$inactive_reason = $user->lang['INACTIVE_REASON_REGISTER'];
						break;

						case INACTIVE_PROFILE:
							$inactive_reason = $user->lang['INACTIVE_REASON_PROFILE'];
						break;

						case INACTIVE_MANUAL:
							$inactive_reason = $user->lang['INACTIVE_REASON_MANUAL'];
						break;

						case INACTIVE_REMIND:
							$inactive_reason = $user->lang['INACTIVE_REASON_REMIND'];
						break;
					}
				}

				$template->assign_vars(array(
					'L_NAME_CHARS_EXPLAIN'		=> sprintf($user->lang[$config['allow_name_chars'] . '_EXPLAIN'], $config['min_name_chars'], $config['max_name_chars']),
					'L_CHANGE_PASSWORD_EXPLAIN'	=> sprintf($user->lang[$config['pass_complex'] . '_EXPLAIN'], $config['min_pass_chars'], $config['max_pass_chars']),
					'S_FOUNDER'					=> ($user->data['user_type'] == USER_FOUNDER) ? true : false,

					'S_OVERVIEW'		=> true,
					'S_USER_IP'			=> ($user_row['user_ip']) ? true : false,
					'S_USER_FOUNDER'	=> ($user_row['user_type'] == USER_FOUNDER) ? true : false,
					'S_ACTION_OPTIONS'	=> $s_action_options,
					'S_OWN_ACCOUNT'		=> ($user_id == $user->data['user_id']) ? true : false,
					'S_USER_INACTIVE'	=> ($user_row['user_type'] == USER_INACTIVE) ? true : false,

					'U_SHOW_IP'		=> $this->u_action . "&amp;u=$user_id&amp;ip=" . (($ip == 'ip') ? 'hostname' : 'ip'),
					'U_WHOIS'		=> $this->u_action . "&amp;action=whois&amp;user_ip={$user_row['user_ip']}",

					'U_SWITCH_PERMISSIONS'	=> ($auth->acl_get('a_switchperm') && $user->data['user_id'] != $user_row['user_id']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", "mode=switch_perm&amp;u={$user_row['user_id']}") : '',

					'USER'				=> $user_row['username'],
					'USER_REGISTERED'	=> $user->format_date($user_row['user_regdate']),
					'REGISTERED_IP'		=> ($ip == 'hostname') ? gethostbyaddr($user_row['user_ip']) : $user_row['user_ip'],
					'USER_LASTACTIVE'	=> ($last_visit) ? $user->format_date($last_visit) : ' - ',
					'USER_EMAIL'		=> $user_row['user_email'],
					'USER_WARNINGS'		=> $user_row['user_warnings'],
					'USER_POSTS'		=> $user_row['user_posts'],
					'USER_INACTIVE_REASON'	=> $inactive_reason,
				));

			break;

			case 'feedback':

				$user->add_lang('mcp');
				
				// Set up general vars
				$start		= request_var('start', 0);
				$deletemark = (isset($_POST['delmarked'])) ? true : false;
				$deleteall	= (isset($_POST['delall'])) ? true : false;
				$marked		= request_var('mark', array(0));
				$message	= utf8_normalize_nfc(request_var('message', '', true));

				// Sort keys
				$sort_days	= request_var('st', 0);
				$sort_key	= request_var('sk', 't');
				$sort_dir	= request_var('sd', 'd');

				// Delete entries if requested and able
				if (($deletemark || $deleteall) && $auth->acl_get('a_clearlogs'))
				{
					if (!check_form_key($form_name))
					{
						trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					$where_sql = '';
					if ($deletemark && $marked)
					{
						$sql_in = array();
						foreach ($marked as $mark)
						{
							$sql_in[] = $mark;
						}
						$where_sql = ' AND ' . $db->sql_in_set('log_id', $sql_in);
						unset($sql_in);
					}

					if ($where_sql || $deleteall)
					{
						$sql = 'DELETE FROM ' . LOG_TABLE . '
							WHERE log_type = ' . LOG_USERS . "
							$where_sql";
						$db->sql_query($sql);

						add_log('admin', 'LOG_CLEAR_USER', $user_row['username']);
					}
				}

				if ($submit && $message)
				{
					if (!check_form_key($form_name))
					{
						trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					add_log('admin', 'LOG_USER_FEEDBACK', $user_row['username']);
					add_log('mod', 0, 0, 'LOG_USER_FEEDBACK', $user_row['username']);
					add_log('user', $user_id, 'LOG_USER_GENERAL', $message);

					trigger_error($user->lang['USER_FEEDBACK_ADDED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
				}
				
				// Sorting
				$limit_days = array(0 => $user->lang['ALL_ENTRIES'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
				$sort_by_text = array('u' => $user->lang['SORT_USERNAME'], 't' => $user->lang['SORT_DATE'], 'i' => $user->lang['SORT_IP'], 'o' => $user->lang['SORT_ACTION']);
				$sort_by_sql = array('u' => 'u.username_clean', 't' => 'l.log_time', 'i' => 'l.log_ip', 'o' => 'l.log_operation');

				$s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
				gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);

				// Define where and sort sql for use in displaying logs
				$sql_where = ($sort_days) ? (time() - ($sort_days * 86400)) : 0;
				$sql_sort = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');

				// Grab log data
				$log_data = array();
				$log_count = 0;
				view_log('user', $log_data, $log_count, $config['topics_per_page'], $start, 0, 0, $user_id, $sql_where, $sql_sort);

				$template->assign_vars(array(
					'S_FEEDBACK'	=> true,
					'S_ON_PAGE'		=> on_page($log_count, $config['topics_per_page'], $start),
					'PAGINATION'	=> generate_pagination($this->u_action . "&amp;u=$user_id&amp;$u_sort_param", $log_count, $config['topics_per_page'], $start, true),

					'S_LIMIT_DAYS'	=> $s_limit_days,
					'S_SORT_KEY'	=> $s_sort_key,
					'S_SORT_DIR'	=> $s_sort_dir,
					'S_CLEARLOGS'	=> $auth->acl_get('a_clearlogs'))
				);

				foreach ($log_data as $row)
				{
					$template->assign_block_vars('log', array(
						'USERNAME'		=> $row['username_full'],
						'IP'			=> $row['ip'],
						'DATE'			=> $user->format_date($row['time']),
						'ACTION'		=> nl2br($row['action']),
						'ID'			=> $row['id'])
					);
				}

			break;

			case 'profile':

				include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
				include($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);

				$cp = new custom_profile();

				$cp_data = $cp_error = array();

				$sql = 'SELECT lang_id
					FROM ' . LANG_TABLE . "
					WHERE lang_iso = '" . $db->sql_escape($user->data['user_lang']) . "'";
				$result = $db->sql_query($sql);
				$row = $db->sql_fetchrow($result);
				$db->sql_freeresult($result);

				$user_row['iso_lang_id'] = $row['lang_id'];

				$data = array(
					'icq'			=> request_var('icq', $user_row['user_icq']),
					'aim'			=> request_var('aim', $user_row['user_aim']),
					'msn'			=> request_var('msn', $user_row['user_msnm']),
					'yim'			=> request_var('yim', $user_row['user_yim']),
					'jabber'		=> utf8_normalize_nfc(request_var('jabber', $user_row['user_jabber'], true)),
					'website'		=> request_var('website', $user_row['user_website']),
					'location'		=> utf8_normalize_nfc(request_var('location', $user_row['user_from'], true)),
					'occupation'	=> utf8_normalize_nfc(request_var('occupation', $user_row['user_occ'], true)),
					'interests'		=> utf8_normalize_nfc(request_var('interests', $user_row['user_interests'], true)),
					'bday_day'		=> 0,
					'bday_month'	=> 0,
					'bday_year'		=> 0,
				);

				if ($user_row['user_birthday'])
				{
					list($data['bday_day'], $data['bday_month'], $data['bday_year']) = explode('-', $user_row['user_birthday']);
				}

				$data['bday_day'] = request_var('bday_day', $data['bday_day']);
				$data['bday_month'] = request_var('bday_month', $data['bday_month']);
				$data['bday_year'] = request_var('bday_year', $data['bday_year']);

				if ($submit)
				{
					$error = validate_data($data, array(
						'icq'			=> array(
							array('string', true, 3, 15),
							array('match', true, '#^[0-9]+$#i')),
						'aim'			=> array('string', true, 3, 255),
						'msn'			=> array('string', true, 5, 255),
						'jabber'		=> array(
							array('string', true, 5, 255),
							array('jabber')),
						'yim'			=> array('string', true, 5, 255),
						'website'		=> array(
							array('string', true, 12, 255),
							array('match', true, '#^http[s]?://(.*?\.)*?[a-z0-9\-]+\.[a-z]{2,4}#i')),
						'location'		=> array('string', true, 2, 255),
						'occupation'	=> array('string', true, 2, 500),
						'interests'		=> array('string', true, 2, 500),
						'bday_day'		=> array('num', true, 1, 31),
						'bday_month'	=> array('num', true, 1, 12),
						'bday_year'		=> array('num', true, 1901, gmdate('Y', time())),
					));

					// validate custom profile fields
					$cp->submit_cp_field('profile', $user_row['iso_lang_id'], $cp_data, $cp_error);

					if (sizeof($cp_error))
					{
						$error = array_merge($error, $cp_error);
					}
					if (!check_form_key($form_name))
					{
						$error[] = 'FORM_INVALID';
					}

					if (!sizeof($error))
					{
						$sql_ary = array(
							'user_icq'		=> $data['icq'],
							'user_aim'		=> $data['aim'],
							'user_msnm'		=> $data['msn'],
							'user_yim'		=> $data['yim'],
							'user_jabber'	=> $data['jabber'],
							'user_website'	=> $data['website'],
							'user_from'		=> $data['location'],
							'user_occ'		=> $data['occupation'],
							'user_interests'=> $data['interests'],
							'user_birthday'	=> sprintf('%2d-%2d-%4d', $data['bday_day'], $data['bday_month'], $data['bday_year']),
						);

						$sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
							WHERE user_id = $user_id";
						$db->sql_query($sql);

						// Update Custom Fields
						if (sizeof($cp_data))
						{
							switch ($db->sql_layer)
							{
								case 'oracle':
								case 'firebird':
								case 'postgres':
									$right_delim = $left_delim = '"';
								break;

								case 'sqlite':
								case 'mssql':
								case 'mssql_odbc':
									$right_delim = ']';
									$left_delim = '[';
								break;

								case 'mysql':
								case 'mysql4':
								case 'mysqli':
									$right_delim = $left_delim = '`';
								break;
							}

							foreach ($cp_data as $key => $value)
							{
								$cp_data[$left_delim . $key . $right_delim] = $value;
								unset($cp_data[$key]);
							}

							$sql = 'UPDATE ' . PROFILE_FIELDS_DATA_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $cp_data) . "
								WHERE user_id = $user_id";
							$db->sql_query($sql);

							if (!$db->sql_affectedrows())
							{
								$cp_data['user_id'] = (int) $user_id;

								$db->sql_return_on_error(true);

								$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' . $db->sql_build_array('INSERT', $cp_data);
								$db->sql_query($sql);

								$db->sql_return_on_error(false);
							}
						}

						trigger_error($user->lang['USER_PROFILE_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
					}

					// Replace "error" strings with their real, localised form
					$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
				}

				$s_birthday_day_options = '<option value="0"' . ((!$data['bday_day']) ? ' selected="selected"' : '') . '>--</option>';
				for ($i = 1; $i < 32; $i++)
				{
					$selected = ($i == $data['bday_day']) ? ' selected="selected"' : '';
					$s_birthday_day_options .= "<option value=\"$i\"$selected>$i</option>";
				}

				$s_birthday_month_options = '<option value="0"' . ((!$data['bday_month']) ? ' selected="selected"' : '') . '>--</option>';
				for ($i = 1; $i < 13; $i++)
				{
					$selected = ($i == $data['bday_month']) ? ' selected="selected"' : '';
					$s_birthday_month_options .= "<option value=\"$i\"$selected>$i</option>";
				}
				$s_birthday_year_options = '';

				$now = getdate();
				$s_birthday_year_options = '<option value="0"' . ((!$data['bday_year']) ? ' selected="selected"' : '') . '>--</option>';
				for ($i = $now['year'] - 100; $i < $now['year']; $i++)
				{
					$selected = ($i == $data['bday_year']) ? ' selected="selected"' : '';
					$s_birthday_year_options .= "<option value=\"$i\"$selected>$i</option>";
				}
				unset($now);

				$template->assign_vars(array(
					'ICQ'			=> $data['icq'],
					'YIM'			=> $data['yim'],
					'AIM'			=> $data['aim'],
					'MSN'			=> $data['msn'],
					'JABBER'		=> $data['jabber'],
					'WEBSITE'		=> $data['website'],
					'LOCATION'		=> $data['location'],
					'OCCUPATION'	=> $data['occupation'],
					'INTERESTS'		=> $data['interests'],

					'S_BIRTHDAY_DAY_OPTIONS'	=> $s_birthday_day_options,
					'S_BIRTHDAY_MONTH_OPTIONS'	=> $s_birthday_month_options,
					'S_BIRTHDAY_YEAR_OPTIONS'	=> $s_birthday_year_options,
						
					'S_PROFILE'		=> true)
				);

				// Get additional profile fields and assign them to the template block var 'profile_fields'
				$user->get_profile_fields($user_id);

				$cp->generate_profile_fields('profile', $user_row['iso_lang_id']);

			break;

			case 'prefs':

				include($phpbb_root_path . 'includes/functions_user.' . $phpEx);

				$data = array(
					'dateformat'		=> utf8_normalize_nfc(request_var('dateformat', $user_row['user_dateformat'], true)),
					'lang'				=> basename(request_var('lang', $user_row['user_lang'])),
					'tz'				=> request_var('tz', (float) $user_row['user_timezone']),
					'style'				=> request_var('style', $user_row['user_style']),
					'dst'				=> request_var('dst', $user_row['user_dst']),
					'viewemail'			=> request_var('viewemail', $user_row['user_allow_viewemail']),
					'massemail'			=> request_var('massemail', $user_row['user_allow_massemail']),
					'hideonline'		=> request_var('hideonline', !$user_row['user_allow_viewonline']),
					'notifymethod'		=> request_var('notifymethod', $user_row['user_notify_type']),
					'notifypm'			=> request_var('notifypm', $user_row['user_notify_pm']),
					'popuppm'			=> request_var('popuppm', $this->optionget($user_row, 'popuppm')),
					'allowpm'			=> request_var('allowpm', $user_row['user_allow_pm']),

					'topic_sk'			=> request_var('topic_sk', ($user_row['user_topic_sortby_type']) ? $user_row['user_topic_sortby_type'] : 't'),
					'topic_sd'			=> request_var('topic_sd', ($user_row['user_topic_sortby_dir']) ? $user_row['user_topic_sortby_dir'] : 'd'),
					'topic_st'			=> request_var('topic_st', ($user_row['user_topic_show_days']) ? $user_row['user_topic_show_days'] : 0),

					'post_sk'			=> request_var('post_sk', ($user_row['user_post_sortby_type']) ? $user_row['user_post_sortby_type'] : 't'),
					'post_sd'			=> request_var('post_sd', ($user_row['user_post_sortby_dir']) ? $user_row['user_post_sortby_dir'] : 'a'),
					'post_st'			=> request_var('post_st', ($user_row['user_post_show_days']) ? $user_row['user_post_show_days'] : 0),

					'view_images'		=> request_var('view_images', $this->optionget($user_row, 'viewimg')),
					'view_flash'		=> request_var('view_flash', $this->optionget($user_row, 'viewflash')),
					'view_smilies'		=> request_var('view_smilies', $this->optionget($user_row, 'viewsmilies')),
					'view_sigs'			=> request_var('view_sigs', $this->optionget($user_row, 'viewsigs')),
					'view_avatars'		=> request_var('view_avatars', $this->optionget($user_row, 'viewavatars')),
					'view_wordcensor'	=> request_var('view_wordcensor', $this->optionget($user_row, 'viewcensors')),

					'bbcode'	=> request_var('bbcode', $this->optionget($user_row, 'bbcode')),
					'smilies'	=> request_var('smilies', $this->optionget($user_row, 'smilies')),
					'sig'		=> request_var('sig', $this->optionget($user_row, 'attachsig')),
					'notify'	=> request_var('notify', $user_row['user_notify']),
				);

				if ($submit)
				{
					$error = validate_data($data, array(
						'dateformat'	=> array('string', false, 1, 30),
						'lang'			=> array('match', false, '#^[a-z_\-]{2,}$#i'),
						'tz'			=> array('num', false, -14, 14),

						'topic_sk'		=> array('string', false, 1, 1),
						'topic_sd'		=> array('string', false, 1, 1),
						'post_sk'		=> array('string', false, 1, 1),
						'post_sd'		=> array('string', false, 1, 1),
					));

					if (!check_form_key($form_name))
					{
						$error[] = 'FORM_INVALID';
					}

					if (!sizeof($error))
					{
						$this->optionset($user_row, 'popuppm', $data['popuppm']);
						$this->optionset($user_row, 'viewimg', $data['view_images']);
						$this->optionset($user_row, 'viewflash', $data['view_flash']);
						$this->optionset($user_row, 'viewsmilies', $data['view_smilies']);
						$this->optionset($user_row, 'viewsigs', $data['view_sigs']);
						$this->optionset($user_row, 'viewavatars', $data['view_avatars']);
						$this->optionset($user_row, 'viewcensors', $data['view_wordcensor']);
						$this->optionset($user_row, 'bbcode', $data['bbcode']);
						$this->optionset($user_row, 'smilies', $data['smilies']);
						$this->optionset($user_row, 'attachsig', $data['sig']);

						$sql_ary = array(
							'user_options'			=> $user_row['user_options'],

							'user_allow_pm'			=> $data['allowpm'],
							'user_allow_viewemail'	=> $data['viewemail'],
							'user_allow_massemail'	=> $data['massemail'],
							'user_allow_viewonline'	=> !$data['hideonline'],
							'user_notify_type'		=> $data['notifymethod'],
							'user_notify_pm'		=> $data['notifypm'],

							'user_dst'				=> $data['dst'],
							'user_dateformat'		=> $data['dateformat'],
							'user_lang'				=> $data['lang'],
							'user_timezone'			=> $data['tz'],
							'user_style'			=> $data['style'],

							'user_topic_sortby_type'	=> $data['topic_sk'],
							'user_post_sortby_type'		=> $data['post_sk'],
							'user_topic_sortby_dir'		=> $data['topic_sd'],
							'user_post_sortby_dir'		=> $data['post_sd'],

							'user_topic_show_days'	=> $data['topic_st'],
							'user_post_show_days'	=> $data['post_st'],

							'user_notify'	=> $data['notify'],
						);

						$sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
							WHERE user_id = $user_id";
						$db->sql_query($sql);

						trigger_error($user->lang['USER_PREFS_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
					}

					// Replace "error" strings with their real, localised form
					$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
				}

				$dateformat_options = '';
				foreach ($user->lang['dateformats'] as $format => $null)
				{
					$dateformat_options .= '<option value="' . $format . '"' . (($format == $data['dateformat']) ? ' selected="selected"' : '') . '>';
					$dateformat_options .= $user->format_date(time(), $format, false) . ((strpos($format, '|') !== false) ? $user->lang['VARIANT_DATE_SEPARATOR'] . $user->format_date(time(), $format, true) : '');
					$dateformat_options .= '</option>';
				}

				$s_custom = false;

				$dateformat_options .= '<option value="custom"';
				if (!in_array($data['dateformat'], array_keys($user->lang['dateformats'])))
				{
					$dateformat_options .= ' selected="selected"';
					$s_custom = true;
				}
				$dateformat_options .= '>' . $user->lang['CUSTOM_DATEFORMAT'] . '</option>';

				$sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);

				// Topic ordering options
				$limit_topic_days = array(0 => $user->lang['ALL_TOPICS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
				$sort_by_topic_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 'r' => $user->lang['REPLIES'], 's' => $user->lang['SUBJECT'], 'v' => $user->lang['VIEWS']);

				// Post ordering options
				$limit_post_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
				$sort_by_post_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);

				$_options = array('topic', 'post');
				foreach ($_options as $sort_option)
				{
					${'s_limit_' . $sort_option . '_days'} = '<select name="' . $sort_option . '_st">';
					foreach (${'limit_' . $sort_option . '_days'} as $day => $text)
					{
						$selected = ($data[$sort_option . '_st'] == $day) ? ' selected="selected"' : '';
						${'s_limit_' . $sort_option . '_days'} .= '<option value="' . $day . '"' . $selected . '>' . $text . '</option>';
					}
					${'s_limit_' . $sort_option . '_days'} .= '</select>';

					${'s_sort_' . $sort_option . '_key'} = '<select name="' . $sort_option . '_sk">';
					foreach (${'sort_by_' . $sort_option . '_text'} as $key => $text)
					{
						$selected = ($data[$sort_option . '_sk'] == $key) ? ' selected="selected"' : '';
						${'s_sort_' . $sort_option . '_key'} .= '<option value="' . $key . '"' . $selected . '>' . $text . '</option>';
					}
					${'s_sort_' . $sort_option . '_key'} .= '</select>';

					${'s_sort_' . $sort_option . '_dir'} = '<select name="' . $sort_option . '_sd">';
					foreach ($sort_dir_text as $key => $value)
					{
						$selected = ($data[$sort_option . '_sd'] == $key) ? ' selected="selected"' : '';
						${'s_sort_' . $sort_option . '_dir'} .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
					}
					${'s_sort_' . $sort_option . '_dir'} .= '</select>';
				}

				$template->assign_vars(array(
					'S_PREFS'			=> true,
					'S_JABBER_DISABLED'	=> ($config['jab_enable'] && $user_row['user_jabber'] && @extension_loaded('xml')) ? false : true,
					
					'VIEW_EMAIL'		=> $data['viewemail'],
					'MASS_EMAIL'		=> $data['massemail'],
					'ALLOW_PM'			=> $data['allowpm'],
					'HIDE_ONLINE'		=> $data['hideonline'],
					'NOTIFY_EMAIL'		=> ($data['notifymethod'] == NOTIFY_EMAIL) ? true : false,
					'NOTIFY_IM'			=> ($data['notifymethod'] == NOTIFY_IM) ? true : false,
					'NOTIFY_BOTH'		=> ($data['notifymethod'] == NOTIFY_BOTH) ? true : false,
					'NOTIFY_PM'			=> $data['notifypm'],
					'POPUP_PM'			=> $data['popuppm'],
					'DST'				=> $data['dst'],
					'BBCODE'			=> $data['bbcode'],
					'SMILIES'			=> $data['smilies'],
					'ATTACH_SIG'		=> $data['sig'],
					'NOTIFY'			=> $data['notify'],
					'VIEW_IMAGES'		=> $data['view_images'],
					'VIEW_FLASH'		=> $data['view_flash'],
					'VIEW_SMILIES'		=> $data['view_smilies'],
					'VIEW_SIGS'			=> $data['view_sigs'],
					'VIEW_AVATARS'		=> $data['view_avatars'],
					'VIEW_WORDCENSOR'	=> $data['view_wordcensor'],
					
					'S_TOPIC_SORT_DAYS'		=> $s_limit_topic_days,
					'S_TOPIC_SORT_KEY'		=> $s_sort_topic_key,
					'S_TOPIC_SORT_DIR'		=> $s_sort_topic_dir,
					'S_POST_SORT_DAYS'		=> $s_limit_post_days,
					'S_POST_SORT_KEY'		=> $s_sort_post_key,
					'S_POST_SORT_DIR'		=> $s_sort_post_dir,

					'DATE_FORMAT'			=> $data['dateformat'],
					'S_DATEFORMAT_OPTIONS'	=> $dateformat_options,
					'S_CUSTOM_DATEFORMAT'	=> $s_custom,
					'DEFAULT_DATEFORMAT'	=> $config['default_dateformat'],
					'A_DEFAULT_DATEFORMAT'	=> addslashes($config['default_dateformat']),

					'S_LANG_OPTIONS'	=> language_select($data['lang']),
					'S_STYLE_OPTIONS'	=> style_select($data['style']),
					'S_TZ_OPTIONS'		=> tz_select($data['tz'], true),
					)
				);

			break;

			case 'avatar':

				include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
				include($phpbb_root_path . 'includes/functions_user.' . $phpEx);

				$can_upload = (file_exists($phpbb_root_path . $config['avatar_path']) && @is_writable($phpbb_root_path . $config['avatar_path']) && $file_uploads) ? true : false;

				if ($submit)
				{

					if (!check_form_key($form_name))
					{
							trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					if (avatar_process_user($error, $user_row))
					{
						trigger_error($user->lang['USER_AVATAR_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_row['user_id']));
					}

					// Replace "error" strings with their real, localised form
					$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
				}

				// Generate users avatar
				$avatar_img = ($user_row['user_avatar']) ? get_user_avatar($user_row['user_avatar'], $user_row['user_avatar_type'], $user_row['user_avatar_width'], $user_row['user_avatar_height']) : '<img src="' . $phpbb_admin_path . 'images/no_avatar.gif" alt="" />';

				$display_gallery = (isset($_POST['display_gallery'])) ? true : false;
				$avatar_select = basename(request_var('avatar_select', ''));
				$category = basename(request_var('category', ''));

				if ($config['allow_avatar_local'] && $display_gallery)
				{
					avatar_gallery($category, $avatar_select, 4);
				}

				$template->assign_vars(array(
					'S_AVATAR'			=> true,
					'S_CAN_UPLOAD'		=> ($can_upload && $config['allow_avatar_upload']) ? true : false,
					'S_ALLOW_REMOTE'	=> ($config['allow_avatar_remote']) ? true : false,
					'S_DISPLAY_GALLERY'	=> ($config['allow_avatar_local'] && !$display_gallery) ? true : false,
					'S_IN_GALLERY'		=> ($config['allow_avatar_local'] && $display_gallery) ? true : false,

					'AVATAR_IMAGE'			=> $avatar_img,
					'AVATAR_MAX_FILESIZE'	=> $config['avatar_filesize'],
					'USER_AVATAR_WIDTH'		=> $user_row['user_avatar_width'],
					'USER_AVATAR_HEIGHT'	=> $user_row['user_avatar_height'],

					'L_AVATAR_EXPLAIN'	=> sprintf($user->lang['AVATAR_EXPLAIN'], $config['avatar_max_width'], $config['avatar_max_height'], round($config['avatar_filesize'] / 1024)))
				);

			break;

			case 'rank':

				if ($submit)
				{
					if (!check_form_key($form_name))
					{
						trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					$rank_id = request_var('user_rank', 0);

					$sql = 'UPDATE ' . USERS_TABLE . "
						SET user_rank = $rank_id
						WHERE user_id = $user_id";
					$db->sql_query($sql);

					trigger_error($user->lang['USER_RANK_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
				}
				
				$sql = 'SELECT *
					FROM ' . RANKS_TABLE . '
					WHERE rank_special = 1
					ORDER BY rank_title';
				$result = $db->sql_query($sql);

				$s_rank_options = '<option value="0"' . ((!$user_row['user_rank']) ? ' selected="selected"' : '') . '>' . $user->lang['NO_SPECIAL_RANK'] . '</option>';

				while ($row = $db->sql_fetchrow($result))
				{
					$selected = ($user_row['user_rank'] && $row['rank_id'] == $user_row['user_rank']) ? ' selected="selected"' : '';
					$s_rank_options .= '<option value="' . $row['rank_id'] . '"' . $selected . '>' . $row['rank_title'] . '</option>';
				}
				$db->sql_freeresult($result);

				$template->assign_vars(array(
					'S_RANK'			=> true,
					'S_RANK_OPTIONS'	=> $s_rank_options)
				);

			break;
			
			case 'sig':
			
				include_once($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
				include_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);

				$enable_bbcode	= ($config['allow_sig_bbcode']) ? ((request_var('disable_bbcode', !$user->optionget('bbcode'))) ? false : true) : false;
				$enable_smilies	= ($config['allow_sig_smilies']) ? ((request_var('disable_smilies', !$user->optionget('smilies'))) ? false : true) : false;
				$enable_urls	= ($config['allow_sig_links']) ? ((request_var('disable_magic_url', false)) ? false : true) : false;
				$signature		= utf8_normalize_nfc(request_var('signature', (string) $user_row['user_sig'], true));

				$preview		= (isset($_POST['preview'])) ? true : false;

				if ($submit || $preview)
				{
					include_once($phpbb_root_path . 'includes/message_parser.' . $phpEx);

					$message_parser = new parse_message($signature);

					// Allowing Quote BBCode
					$message_parser->parse($enable_bbcode, $enable_urls, $enable_smilies, $config['allow_sig_img'], $config['allow_sig_flash'], true, $config['allow_sig_links'], true, 'sig');
						
					if (sizeof($message_parser->warn_msg))
					{
						$error[] = implode('<br />', $message_parser->warn_msg);
					}

					if (!check_form_key($form_name))
					{
						$error = 'FORM_INVALID';
					}

					if (!sizeof($error) && $submit)
					{
						$sql_ary = array(
							'user_sig'					=> (string) $message_parser->message,
							'user_sig_bbcode_uid'		=> (string) $message_parser->bbcode_uid,
							'user_sig_bbcode_bitfield'	=> (string) $message_parser->bbcode_bitfield
						);

						$sql = 'UPDATE ' . USERS_TABLE . '
							SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
							WHERE user_id = ' . $user_id;
						$db->sql_query($sql);

						trigger_error($user->lang['USER_SIG_UPDATED'] . adm_back_link($this->u_action . '&amp;u=' . $user_id));
					}
	
					// Replace "error" strings with their real, localised form
					$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
				}
				
				$signature_preview = '';
				
				if ($preview)
				{
					// Now parse it for displaying
					$signature_preview = $message_parser->format_display($enable_bbcode, $enable_urls, $enable_smilies, false);
					unset($message_parser);
				}

				decode_message($signature, $user_row['user_sig_bbcode_uid']);

				$template->assign_vars(array(
					'S_SIGNATURE'		=> true,

					'SIGNATURE'			=> $signature,
					'SIGNATURE_PREVIEW'	=> $signature_preview,

					'S_BBCODE_CHECKED'		=> (!$enable_bbcode) ? ' checked="checked"' : '',
					'S_SMILIES_CHECKED'		=> (!$enable_smilies) ? ' checked="checked"' : '',
					'S_MAGIC_URL_CHECKED'	=> (!$enable_urls) ? ' checked="checked"' : '',

					'BBCODE_STATUS'			=> ($config['allow_sig_bbcode']) ? sprintf($user->lang['BBCODE_IS_ON'], '<a href="' . append_sid("{$phpbb_root_path}faq.$phpEx", 'mode=bbcode') . '">', '</a>') : sprintf($user->lang['BBCODE_IS_OFF'], '<a href="' . append_sid("{$phpbb_root_path}faq.$phpEx", 'mode=bbcode') . '">', '</a>'),
					'SMILIES_STATUS'		=> ($config['allow_sig_smilies']) ? $user->lang['SMILIES_ARE_ON'] : $user->lang['SMILIES_ARE_OFF'],
					'IMG_STATUS'			=> ($config['allow_sig_img']) ? $user->lang['IMAGES_ARE_ON'] : $user->lang['IMAGES_ARE_OFF'],
					'FLASH_STATUS'			=> ($config['allow_sig_flash']) ? $user->lang['FLASH_IS_ON'] : $user->lang['FLASH_IS_OFF'],
					'URL_STATUS'			=> ($config['allow_sig_links']) ? $user->lang['URL_IS_ON'] : $user->lang['URL_IS_OFF'],

					'L_SIGNATURE_EXPLAIN'	=> sprintf($user->lang['SIGNATURE_EXPLAIN'], $config['max_sig_chars']),

					'S_BBCODE_ALLOWED'		=> $config['allow_sig_bbcode'],
					'S_SMILIES_ALLOWED'		=> $config['allow_sig_smilies'],
					'S_BBCODE_IMG'			=> ($config['allow_sig_img']) ? true : false,
					'S_BBCODE_FLASH'		=> ($config['allow_sig_flash']) ? true : false,
					'S_LINKS_ALLOWED'		=> ($config['allow_sig_links']) ? true : false)
				);

				// Assigning custom bbcodes
				display_custom_bbcodes();

			break;

			case 'attach':

				$start		= request_var('start', 0);
				$deletemark = (isset($_POST['delmarked'])) ? true : false;
				$marked		= request_var('mark', array(0));

				// Sort keys
				$sort_key	= request_var('sk', 'a');
				$sort_dir	= request_var('sd', 'd');

				if ($deletemark && sizeof($marked))
				{
					$sql = 'SELECT attach_id
						FROM ' . ATTACHMENTS_TABLE . '
						WHERE poster_id = ' . $user_id . '
							AND is_orphan = 0
							AND ' . $db->sql_in_set('attach_id', $marked);
					$result = $db->sql_query($sql);

					$marked = array();
					while ($row = $db->sql_fetchrow($result))
					{
						$marked[] = $row['attach_id'];
					}
					$db->sql_freeresult($result);
				}

				if ($deletemark && sizeof($marked))
				{
					if (confirm_box(true))
					{
						$sql = 'SELECT real_filename
							FROM ' . ATTACHMENTS_TABLE . '
							WHERE ' . $db->sql_in_set('attach_id', $marked);
						$result = $db->sql_query($sql);

						$log_attachments = array();
						while ($row = $db->sql_fetchrow($result))
						{
							$log_attachments[] = $row['real_filename'];
						}
						$db->sql_freeresult($result);

						delete_attachments('attach', $marked);

						$message = (sizeof($log_attachments) == 1) ? $user->lang['ATTACHMENT_DELETED'] : $user->lang['ATTACHMENTS_DELETED'];

						add_log('admin', 'LOG_ATTACHMENTS_DELETED', implode(', ', $log_attachments));
						trigger_error($message . adm_back_link($this->u_action . '&amp;u=' . $user_id));
					}
					else
					{
						confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
							'u'				=> $user_id,
							'i'				=> $id,
							'mode'			=> $mode,
							'action'		=> $action,
							'delmarked'		=> true,
							'mark'			=> $marked))
						);
					}
				}

				$sk_text = array('a' => $user->lang['SORT_FILENAME'], 'c' => $user->lang['SORT_EXTENSION'], 'd' => $user->lang['SORT_SIZE'], 'e' => $user->lang['SORT_DOWNLOADS'], 'f' => $user->lang['SORT_POST_TIME'], 'g' => $user->lang['SORT_TOPIC_TITLE']);
				$sk_sql = array('a' => 'a.real_filename', 'c' => 'a.extension', 'd' => 'a.filesize', 'e' => 'a.download_count', 'f' => 'a.filetime', 'g' => 't.topic_title');

				$sd_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);

				$s_sort_key = '';
				foreach ($sk_text as $key => $value)
				{
					$selected = ($sort_key == $key) ? ' selected="selected"' : '';
					$s_sort_key .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
				}

				$s_sort_dir = '';
				foreach ($sd_text as $key => $value)
				{
					$selected = ($sort_dir == $key) ? ' selected="selected"' : '';
					$s_sort_dir .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
				}

				if (!isset($sk_sql[$sort_key]))
				{
					$sort_key = 'a';
				}

				$order_by = $sk_sql[$sort_key] . ' ' . (($sort_dir == 'a') ? 'ASC' : 'DESC');

				$sql = 'SELECT COUNT(attach_id) as num_attachments
					FROM ' . ATTACHMENTS_TABLE . "
					WHERE poster_id = $user_id
						AND is_orphan = 0";
				$result = $db->sql_query_limit($sql, 1);
				$num_attachments = (int) $db->sql_fetchfield('num_attachments');
				$db->sql_freeresult($result);

				$sql = 'SELECT a.*, t.topic_title, p.message_subject as message_title
					FROM ' . ATTACHMENTS_TABLE . ' a
						LEFT JOIN ' . TOPICS_TABLE . ' t ON (a.topic_id = t.topic_id
							AND a.in_message = 0)
						LEFT JOIN ' . PRIVMSGS_TABLE . ' p ON (a.post_msg_id = p.msg_id
							AND a.in_message = 1)
					WHERE a.poster_id = ' . $user_id . "
						AND a.is_orphan = 0
					ORDER BY $order_by";
				$result = $db->sql_query_limit($sql, $config['posts_per_page'], $start);

				while ($row = $db->sql_fetchrow($result))
				{
					if ($row['in_message'])
					{
						$view_topic = append_sid("{$phpbb_root_path}ucp.$phpEx", "i=pm&amp;p={$row['post_msg_id']}");
					}
					else
					{
						$view_topic = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "t={$row['topic_id']}&amp;p={$row['post_msg_id']}") . '#p' . $row['post_msg_id'];
					}

					$template->assign_block_vars('attach', array(
						'REAL_FILENAME'		=> $row['real_filename'],
						'COMMENT'			=> nl2br($row['attach_comment']),
						'EXTENSION'			=> $row['extension'],
						'SIZE'				=> ($row['filesize'] >= 1048576) ? ($row['filesize'] >> 20) . ' ' . $user->lang['MB'] : (($row['filesize'] >= 1024) ? ($row['filesize'] >> 10) . ' ' . $user->lang['KB'] : $row['filesize'] . ' ' . $user->lang['BYTES']),
						'DOWNLOAD_COUNT'	=> $row['download_count'],
						'POST_TIME'			=> $user->format_date($row['filetime']),
						'TOPIC_TITLE'		=> ($row['in_message']) ? $row['message_title'] : $row['topic_title'],

						'ATTACH_ID'			=> $row['attach_id'],
						'POST_ID'			=> $row['post_msg_id'],
						'TOPIC_ID'			=> $row['topic_id'],
				
						'S_IN_MESSAGE'		=> $row['in_message'],

						'U_DOWNLOAD'		=> append_sid("{$phpbb_root_path}download/file.$phpEx", 'mode=view&amp;id=' . $row['attach_id']),
						'U_VIEW_TOPIC'		=> $view_topic)
					);
				}
				$db->sql_freeresult($result);
		
				$template->assign_vars(array(
					'S_ATTACHMENTS'		=> true,
					'S_ON_PAGE'			=> on_page($num_attachments, $config['topics_per_page'], $start),
					'S_SORT_KEY'		=> $s_sort_key,
					'S_SORT_DIR'		=> $s_sort_dir,

					'PAGINATION'		=> generate_pagination($this->u_action . "&amp;u=$user_id&amp;sk=$sort_key&amp;sd=$sort_dir", $num_attachments, $config['topics_per_page'], $start, true))
				);

			break;
		
			case 'groups':

				include($phpbb_root_path . 'includes/functions_user.' . $phpEx);

				$user->add_lang(array('groups', 'acp/groups'));
				$group_id = request_var('g', 0);
				
				if ($group_id)
				{
					// Check the founder only entry for this group to make sure everything is well
					$sql = 'SELECT group_founder_manage
						FROM ' . GROUPS_TABLE . '
						WHERE group_id = ' . $group_id;
					$result = $db->sql_query($sql);
					$founder_manage = (int) $db->sql_fetchfield('group_founder_manage');
					$db->sql_freeresult($result);
					
					if ($user->data['user_type'] != USER_FOUNDER && $founder_manage)
					{
						trigger_error($user->lang['NOT_ALLOWED_MANAGE_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}
				}
				else
				{
					$founder_manage = 0;
				}
				
				switch ($action)
				{
					case 'demote':
					case 'promote':
					case 'default':
						if (!$group_id)
						{
							trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
						}
						group_user_attributes($action, $group_id, $user_id);

						if ($action == 'default')
						{
							$user_row['group_id'] = $group_id;
						}
					break;

					case 'delete':

						if (confirm_box(true))
						{
							if (!$group_id)
							{
								trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}

							if ($error = group_user_del($group_id, $user_id))
							{
								trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
							}
						
							$error = array();
						}
						else
						{
							confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
								'u'				=> $user_id,
								'i'				=> $id,
								'mode'			=> $mode,
								'action'		=> $action,
								'g'				=> $group_id))
							);
						}
	
					break;
				}

				// Add user to group?
				if ($submit)
				{

					if (!check_form_key($form_name))
					{
						trigger_error($user->lang['FORM_INVALID'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					if (!$group_id)
					{
						trigger_error($user->lang['NO_GROUP'] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					// Add user/s to group
					if ($error = group_user_add($group_id, $user_id))
					{
						trigger_error($user->lang[$error] . adm_back_link($this->u_action . '&amp;u=' . $user_id), E_USER_WARNING);
					}

					$error = array();
				}


				$sql = 'SELECT ug.*, g.*
					FROM ' . GROUPS_TABLE . ' g, ' . USER_GROUP_TABLE . " ug
					WHERE ug.user_id = $user_id
						AND g.group_id = ug.group_id
					ORDER BY g.group_type DESC, ug.user_pending ASC, g.group_name";
				$result = $db->sql_query($sql);

				$i = 0;
				$group_data = $id_ary = array();
				while ($row = $db->sql_fetchrow($result))
				{
					$type = ($row['group_type'] == GROUP_SPECIAL) ? 'special' : (($row['user_pending']) ? 'pending' : 'normal');

					$group_data[$type][$i]['group_id']		= $row['group_id'];
					$group_data[$type][$i]['group_name']	= $row['group_name'];
					$group_data[$type][$i]['group_leader']	= ($row['group_leader']) ? 1 : 0;

					$id_ary[] = $row['group_id'];

					$i++;
				}
				$db->sql_freeresult($result);

				// Select box for other groups
				$sql = 'SELECT group_id, group_name, group_type, group_founder_manage
					FROM ' . GROUPS_TABLE . '
					' . ((sizeof($id_ary)) ? 'WHERE ' . $db->sql_in_set('group_id', $id_ary, true) : '') . '
					ORDER BY group_type DESC, group_name ASC';
				$result = $db->sql_query($sql);

				$s_group_options = '';
				while ($row = $db->sql_fetchrow($result))
				{
					if (!$config['coppa_enable'] && $row['group_name'] == 'REGISTERED_COPPA')
					{
						continue;
					}

					// Do not display those groups not allowed to be managed
					if ($user->data['user_type'] != USER_FOUNDER && $row['group_founder_manage'])
					{
						continue;
					}

					$s_group_options .= '<option' . (($row['group_type'] == GROUP_SPECIAL) ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '">' . (($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name']) . '</option>';
				}
				$db->sql_freeresult($result);

				$current_type = '';
				foreach ($group_data as $group_type => $data_ary)
				{
					if ($current_type != $group_type)
					{
						$template->assign_block_vars('group', array(
							'S_NEW_GROUP_TYPE'		=> true,
							'GROUP_TYPE'			=> $user->lang['USER_GROUP_' . strtoupper($group_type)])
						);
					}

					foreach ($data_ary as $data)
					{
						$template->assign_block_vars('group', array(
							'U_EDIT_GROUP'		=> append_sid("{$phpbb_admin_path}index.$phpEx", "i=groups&amp;mode=manage&amp;action=edit&amp;u=$user_id&amp;g={$data['group_id']}&amp;back_link=acp_users_groups"),
							'U_DEFAULT'			=> $this->u_action . "&amp;action=default&amp;u=$user_id&amp;g=" . $data['group_id'],
							'U_DEMOTE_PROMOTE'	=> $this->u_action . '&amp;action=' . (($data['group_leader']) ? 'demote' : 'promote') . "&amp;u=$user_id&amp;g=" . $data['group_id'],
							'U_DELETE'			=> $this->u_action . "&amp;action=delete&amp;u=$user_id&amp;g=" . $data['group_id'],

							'GROUP_NAME'		=> ($group_type == 'special') ? $user->lang['G_' . $data['group_name']] : $data['group_name'],
							'L_DEMOTE_PROMOTE'	=> ($data['group_leader']) ? $user->lang['GROUP_DEMOTE'] : $user->lang['GROUP_PROMOTE'],

							'S_NO_DEFAULT'		=> ($user_row['group_id'] != $data['group_id']) ? true : false,
							'S_SPECIAL_GROUP'	=> ($group_type == 'special') ? true : false,
							)
						);
					}
				}

				$template->assign_vars(array(
					'S_GROUPS'			=> true,
					'S_GROUP_OPTIONS'	=> $s_group_options)
				);

			break;

			case 'perm':

				include_once($phpbb_root_path . 'includes/acp/auth.' . $phpEx);

				$auth_admin = new auth_admin();

				$user->add_lang('acp/permissions');
				add_permission_language();

				$forum_id = request_var('f', 0);

				// Global Permissions
				if (!$forum_id)
				{
					// Select auth options
					$sql = 'SELECT auth_option, is_local, is_global
						FROM ' . ACL_OPTIONS_TABLE . '
						WHERE auth_option ' . $db->sql_like_expression($db->any_char . '_') . '
							AND is_global = 1
						ORDER BY auth_option';
					$result = $db->sql_query($sql);

					$hold_ary = array();
					
					while ($row = $db->sql_fetchrow($result))
					{
						$hold_ary = $auth_admin->get_mask('view', $user_id, false, false, $row['auth_option'], 'global', ACL_NEVER);
						$auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', false, false);
					}
					$db->sql_freeresult($result);

					unset($hold_ary);
				}
				else
				{
					$sql = 'SELECT auth_option, is_local, is_global
						FROM ' . ACL_OPTIONS_TABLE . "
						WHERE auth_option " . $db->sql_like_expression($db->any_char . '_') . "
							AND is_local = 1
						ORDER BY is_global DESC, auth_option";
					$result = $db->sql_query($sql);

					while ($row = $db->sql_fetchrow($result))
					{
						$hold_ary = $auth_admin->get_mask('view', $user_id, false, $forum_id, $row['auth_option'], 'local', ACL_NEVER);
						$auth_admin->display_mask('view', $row['auth_option'], $hold_ary, 'user', true, false);
					}
					$db->sql_freeresult($result);
				}

				$s_forum_options = '<option value="0"' . ((!$forum_id) ? ' selected="selected"' : '') . '>' . $user->lang['VIEW_GLOBAL_PERMS'] . '</option>';
				$s_forum_options .= make_forum_select($forum_id, false, true, false, false, false);

				$template->assign_vars(array(
					'S_PERMISSIONS'				=> true,

					'S_GLOBAL'					=> (!$forum_id) ? true : false,
					'S_FORUM_OPTIONS'			=> $s_forum_options,

					'U_ACTION'					=> $this->u_action . '&amp;u=' . $user_id,
					'U_USER_PERMISSIONS'		=> append_sid("{$phpbb_admin_path}index.$phpEx" ,'i=permissions&amp;mode=setting_user_global&amp;user_id[]=' . $user_id),
					'U_USER_FORUM_PERMISSIONS'	=> append_sid("{$phpbb_admin_path}index.$phpEx", 'i=permissions&amp;mode=setting_user_local&amp;user_id[]=' . $user_id))
				);
			
			break;

		}

		// Assign general variables
		$template->assign_vars(array(
			'S_ERROR'			=> (sizeof($error)) ? true : false,
			'ERROR_MSG'			=> (sizeof($error)) ? implode('<br />', $error) : '')
		);
	}
Exemplo n.º 7
0
/**
* Disapprove Post/Topic
*/
function disapprove_post($post_id_list, $id, $mode)
{
    global $db, $template, $user, $config;
    global $phpEx, $phpbb_root_path;
    if (!check_ids($post_id_list, POSTS_TABLE, 'post_id', array('m_approve'))) {
        trigger_error('NOT_AUTHORISED');
    }
    $redirect = request_var('redirect', build_url(array('t', 'mode', 'quickmod')) . "&amp;mode={$mode}");
    $reason = utf8_normalize_nfc(request_var('reason', '', true));
    $reason_id = request_var('reason_id', 0);
    $success_msg = $additional_msg = '';
    $s_hidden_fields = build_hidden_fields(array('i' => $id, 'mode' => $mode, 'post_id_list' => $post_id_list, 'action' => 'disapprove', 'redirect' => $redirect));
    $notify_poster = isset($_REQUEST['notify_poster']) ? true : false;
    $disapprove_reason = '';
    if ($reason_id) {
        $sql = 'SELECT reason_title, reason_description
			FROM ' . REPORTS_REASONS_TABLE . "\n\t\t\tWHERE reason_id = {$reason_id}";
        $result = $db->sql_query($sql);
        $row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if (!$row || !$reason && strtolower($row['reason_title']) == 'other') {
            $additional_msg = $user->lang['NO_REASON_DISAPPROVAL'];
            unset($_POST['confirm']);
        } else {
            // If the reason is defined within the language file, we will use the localized version, else just use the database entry...
            $disapprove_reason = strtolower($row['reason_title']) != 'other' ? isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])]) ? $user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])] : $row['reason_description'] : '';
            $disapprove_reason .= $reason ? "\n\n" . $reason : '';
            if (isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])])) {
                $disapprove_reason_lang = strtoupper($row['reason_title']);
            }
            $email_disapprove_reason = $disapprove_reason;
        }
    }
    $post_info = get_post_data($post_id_list, 'm_approve');
    if (confirm_box(true)) {
        // If Topic -> forum_topics_real -= 1
        // If Post -> topic_replies_real -= 1
        $num_disapproved = 0;
        $forum_topics_real = $topic_id_list = $forum_id_list = $topic_replies_real_sql = $post_disapprove_sql = $disapprove_log = array();
        foreach ($post_info as $post_id => $post_data) {
            $topic_id_list[$post_data['topic_id']] = 1;
            if ($post_data['forum_id']) {
                $forum_id_list[$post_data['forum_id']] = 1;
            }
            // Topic or Post. ;)
            /**
             * @todo this probably is a different method than the one used by delete_posts, does this cause counter inconsistency?
             */
            if ($post_data['topic_first_post_id'] == $post_id && $post_data['topic_last_post_id'] == $post_id) {
                if ($post_data['forum_id']) {
                    if (!isset($forum_topics_real[$post_data['forum_id']])) {
                        $forum_topics_real[$post_data['forum_id']] = 0;
                    }
                    $forum_topics_real[$post_data['forum_id']]++;
                    $num_disapproved++;
                }
                $disapprove_log[] = array('type' => 'topic', 'post_subject' => $post_data['post_subject'], 'forum_id' => $post_data['forum_id'], 'topic_id' => 0);
            } else {
                if (!isset($topic_replies_real_sql[$post_data['topic_id']])) {
                    $topic_replies_real_sql[$post_data['topic_id']] = 0;
                }
                $topic_replies_real_sql[$post_data['topic_id']]++;
                $disapprove_log[] = array('type' => 'post', 'post_subject' => $post_data['post_subject'], 'forum_id' => $post_data['forum_id'], 'topic_id' => $post_data['topic_id']);
            }
            $post_disapprove_sql[] = $post_id;
        }
        unset($post_data);
        if (sizeof($forum_topics_real)) {
            foreach ($forum_topics_real as $forum_id => $topics_real) {
                $sql = 'UPDATE ' . FORUMS_TABLE . "\n\t\t\t\t\tSET forum_topics_real = forum_topics_real - {$topics_real}\n\t\t\t\t\tWHERE forum_id = {$forum_id}";
                $db->sql_query($sql);
            }
        }
        if (sizeof($topic_replies_real_sql)) {
            foreach ($topic_replies_real_sql as $topic_id => $num_replies) {
                $sql = 'UPDATE ' . TOPICS_TABLE . "\n\t\t\t\t\tSET topic_replies_real = topic_replies_real - {$num_replies}\n\t\t\t\t\tWHERE topic_id = {$topic_id}";
                $db->sql_query($sql);
            }
        }
        if (sizeof($post_disapprove_sql)) {
            if (!function_exists('delete_posts')) {
                include_once $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts
            delete_posts('post_id', $post_disapprove_sql);
            foreach ($disapprove_log as $log_data) {
                add_log('mod', $log_data['forum_id'], $log_data['topic_id'], $log_data['type'] == 'topic' ? 'LOG_TOPIC_DISAPPROVED' : 'LOG_POST_DISAPPROVED', $log_data['post_subject'], $disapprove_reason);
            }
        }
        unset($post_disapprove_sql, $topic_replies_real_sql);
        update_post_information('topic', array_keys($topic_id_list));
        if (sizeof($forum_id_list)) {
            update_post_information('forum', array_keys($forum_id_list));
        }
        unset($topic_id_list, $forum_id_list);
        $messenger = new messenger();
        // Notify Poster?
        if ($notify_poster) {
            $lang_reasons = array();
            foreach ($post_info as $post_id => $post_data) {
                if ($post_data['poster_id'] == ANONYMOUS) {
                    continue;
                }
                if (isset($disapprove_reason_lang)) {
                    // Okay we need to get the reason from the posters language
                    if (!isset($lang_reasons[$post_data['user_lang']])) {
                        // Assign the current users translation as the default, this is not ideal but getting the board default adds another layer of complexity.
                        $lang_reasons[$post_data['user_lang']] = $user->lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang];
                        // Only load up the language pack if the language is different to the current one
                        if ($post_data['user_lang'] != $user->lang_name && file_exists($phpbb_root_path . '/language/' . $post_data['user_lang'] . '/mcp.' . $phpEx)) {
                            // Load up the language pack
                            $lang = array();
                            @(include $phpbb_root_path . '/language/' . $post_data['user_lang'] . '/mcp.' . $phpEx);
                            // If we find the reason in this language pack use it
                            if (isset($lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang])) {
                                $lang_reasons[$post_data['user_lang']] = $lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang];
                            }
                            unset($lang);
                            // Free memory
                        }
                    }
                    $email_disapprove_reason = $lang_reasons[$post_data['user_lang']];
                    $email_disapprove_reason .= $reason ? "\n\n" . $reason : '';
                }
                $email_template = $post_data['post_id'] == $post_data['topic_first_post_id'] && $post_data['post_id'] == $post_data['topic_last_post_id'] ? 'topic_disapproved' : 'post_disapproved';
                $messenger->template($email_template, $post_data['user_lang']);
                $messenger->to($post_data['user_email'], $post_data['username']);
                $messenger->im($post_data['user_jabber'], $post_data['username']);
                $messenger->assign_vars(array('USERNAME' => htmlspecialchars_decode($post_data['username']), 'REASON' => htmlspecialchars_decode($email_disapprove_reason), 'POST_SUBJECT' => htmlspecialchars_decode(censor_text($post_data['post_subject'])), 'TOPIC_TITLE' => htmlspecialchars_decode(censor_text($post_data['topic_title']))));
                $messenger->send($post_data['user_notify_type']);
            }
            unset($lang_reasons);
        }
        unset($post_info, $disapprove_reason, $email_disapprove_reason, $disapprove_reason_lang);
        $messenger->save_queue();
        if (sizeof($forum_topics_real)) {
            $success_msg = $num_disapproved == 1 ? 'TOPIC_DISAPPROVED_SUCCESS' : 'TOPICS_DISAPPROVED_SUCCESS';
        } else {
            $success_msg = sizeof($post_id_list) == 1 ? 'POST_DISAPPROVED_SUCCESS' : 'POSTS_DISAPPROVED_SUCCESS';
        }
    } else {
        include_once $phpbb_root_path . 'includes/functions_display.' . $phpEx;
        display_reasons($reason_id);
        $show_notify = false;
        foreach ($post_info as $post_data) {
            if ($post_data['poster_id'] == ANONYMOUS) {
                continue;
            } else {
                $show_notify = true;
                break;
            }
        }
        $template->assign_vars(array('S_NOTIFY_POSTER' => $show_notify, 'S_APPROVE' => false, 'REASON' => $reason, 'ADDITIONAL_MSG' => $additional_msg));
        confirm_box(false, 'DISAPPROVE_POST' . (sizeof($post_id_list) == 1 ? '' : 'S'), $s_hidden_fields, 'mcp_approve.html');
    }
    $redirect = request_var('redirect', "index.{$phpEx}");
    $redirect = reapply_sid($redirect);
    if (!$success_msg) {
        redirect($redirect);
    } else {
        meta_refresh(3, $redirect);
        trigger_error($user->lang[$success_msg] . '<br /><br />' . sprintf($user->lang['RETURN_PAGE'], "<a href=\"{$redirect}\">", '</a>'));
    }
}
Exemplo n.º 8
0
    private function bh_del_posts()
    {
        $user_id = $this->user_id;
        // Close reports.
        // Topics can have more than one reported post so we need to get them first.
        $sql = 'SELECT p.post_id, p.topic_id, p.poster_id, p.post_reported, p.forum_id, t.topic_id, t.topic_first_post_id, t.topic_poster
				FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . " t\n\t\t\t\tWHERE p.poster_id = {$user_id}\n\t\t\t\t\tAND t.topic_id = p.topic_id\n\t\t\t\tORDER BY t.topic_id ASC, p.post_id ASC";
        $result = $this->db->sql_query($sql);
        $posts = $topics = array();
        // Step through the topics and count reported posts in each topic where this user is reported.
        while ($row = $this->db->sql_fetchrow($result)) {
            $posts[$row['post_id']] = $row;
            if ($row['post_reported'] == 1) {
                $topics[$row['topic_id']] = isset($topics[$row['topic_id']]) ? ++$topics[$row['topic_id']] : 1;
            }
        }
        $this->db->sql_freeresult($result);
        // And now handle the reports.
        $sql = 'SELECT report_id, post_id, report_closed
				FROM ' . REPORTS_TABLE . '
				WHERE report_closed = 0
					AND post_id <> 0';
        $result = $this->db->sql_query($sql);
        $close_reports = $unreport_topics = array();
        while ($row = $this->db->sql_fetchrow($result)) {
            if (!empty($row['post_id']) && !empty($posts[$row['post_id']])) {
                // A reported post.
                $close_reports[] = (int) $row['report_id'];
                // Check if the topic has more reported posts
                if (isset($topics[$posts[$row['post_id']]['topic_id']]) && --$topics[$posts[$row['post_id']]['topic_id']] <= 0) {
                    $unreport_topics[] = (int) $posts[$row['post_id']]['topic_id'];
                }
            }
        }
        $this->db->sql_freeresult($result);
        // Close reports. Posts will be deleted so there is no need to unmark them as reported.
        if (!empty($close_reports)) {
            $sql = 'UPDATE ' . REPORTS_TABLE . '
					SET report_closed = 1
					WHERE ' . $this->db->sql_in_set('report_id', $close_reports);
            $this->db->sql_query($sql);
        }
        // Unreport topics
        if (!empty($unreport_topics)) {
            $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_reported = 0
					WHERE ' . $this->db->sql_in_set('topic_id', $unreport_topics);
            $this->db->sql_query($sql);
        }
        // Delete some posts.
        if (!function_exists('delete_posts')) {
            include $this->root_path . 'includes/functions_admin.' . $this->php_ext;
        }
        delete_posts('post_id', array_keys($posts));
        // Delete from other tables.
        $this->db->sql_query('DELETE FROM ' . BOOKMARKS_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . DRAFTS_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . FORUMS_WATCH_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . MODERATOR_CACHE_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . NOTIFICATIONS_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . POLL_VOTES_TABLE . " WHERE vote_user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . TOPICS_POSTED_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . TOPICS_WATCH_TABLE . " WHERE user_id = {$user_id}");
        $this->db->sql_query('DELETE FROM ' . USER_NOTIFICATIONS_TABLE . " WHERE user_id = {$user_id}");
    }
            if ($config['asacp_ocban_deactivate']) {
                user_active_flip('deactivate', $user_id, INACTIVE_MANUAL);
            }
            // Move the user to a certain group
            if ($config['asacp_ocban_move_to_group']) {
                $sql = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . $user_id;
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    group_user_del($row['group_id'], array($user_id), array($username));
                }
                $db->sql_freeresult($result);
                group_user_add($config['asacp_ocban_move_to_group'], array($user_id), array($username), false, true);
            }
            // Delete the user's posts
            if ($config['asacp_ocban_delete_posts']) {
                delete_posts('poster_id', $user_id);
            }
            // Delete the user's avatar
            if ($config['asacp_ocban_delete_avatar'] && $user_row['user_avatar']) {
                avatar_delete('user', $user_row, true);
            }
            // Delete the user's signature
            if ($config['asacp_ocban_delete_signature']) {
                $sql = 'UPDATE ' . USERS_TABLE . '
					SET ' . $db->sql_build_array('UPDATE', array('user_sig' => '', 'user_sig_bbcode_uid' => '', 'user_sig_bbcode_bitfield' => '')) . '
					WHERE user_id = ' . $user_id;
                $db->sql_query($sql);
            }
            // Delete the user's blog
            if ($config['asacp_ocban_blog'] && file_exists($phpbb_root_path . 'blog/includes/functions_admin.' . $phpEx)) {
                if (!function_exists('blog_delete_user')) {
Exemplo n.º 10
0
 public function main()
 {
     // Output the page
     $this->template->assign_vars(array('MAPS_PAGE_TITLE' => $this->config['maps_title']));
     $userid = $this->user->data['user_id'];
     $groups = $this->config['maps_group'];
     $groups_edit = $this->config['maps_group_edit'];
     $groups_delete = $this->config['maps_group_delete'];
     $placemark_posts = $this->config['maps_Placemark_posts'];
     $maps_post = $this->config['maps_post'];
     $maps_posts_forum = $this->config['maps_posts_forum'];
     $senter_maps = $this->config['maps_center'];
     $reputation = $this->config['maps_reputation'];
     $bounds = $this->config['maps_bounds'];
     if ($groups == '') {
         $groups = 0;
     }
     if ($groups_edit == '') {
         $groups_edit = 0;
     }
     if ($groups_delete == '') {
         $groups_delete = 0;
     }
     if ($bounds == '1') {
         $bounds_maps = " \n\t\t\tmyMap.setBounds(clusterer.getBounds(), {\n\t\t\t\tcheckZoomRange: true\n\t\t\t});\n\t\t";
     } else {
         $bounds_maps = '';
     }
     $sql = "SELECT *\n\t\t\tFROM " . USER_TABLE . "\n\t\t\t\tWHERE group_id IN ({$groups})\n\t\t\t\t\tAND user_id = {$userid}";
     $res = $this->db->sql_query($sql);
     $row = $this->db->sql_fetchrow($res);
     if ($this->user->data['group_id'] != $row['group_id']) {
         if ($this->user->data['user_id'] != ANONYMOUS) {
             trigger_error('NOT_AUTHORISED');
         } else {
             login_box('', $this->user->lang['LOGIN_EXPLAIN_VIEW_MAPS_PAGE']);
         }
     }
     $sql = "SELECT t.id, t.user_id, t.title, t.descr, t.coord, t.repa, t.topic, t.forum, s.username, s.user_type, s.user_colour, s.user_id \n\t\tFROM " . MAP . " AS t LEFT JOIN " . USER_TABLE . " AS s ON (s.user_id = t.user_id)";
     $result = $this->db->sql_query($sql);
     while ($row = $this->db->sql_fetchrow($result)) {
         $id = $row['id'];
         $titles = str_replace(array("\r\n", "\r", "\n"), "<br />", $row['title']);
         $descr = str_replace(array("\r\n", "\r", "\n"), "<br />", $row['descr']);
         $coord = $row['coord'];
         $user_id = $row['user_id'];
         $t_id = $row['topic'];
         $f_id = $row['forum'];
         $repa = $row['repa'];
         $username = get_username_string($row['user_type'] == USER_IGNORE ? 'no_profile' : 'full', $row['user_id'], $row['username'], $row['user_colour']);
         if ($row) {
             $url = append_sid("{$this->phpbb_root_path}viewtopic.{$this->php_ext}", "f={$f_id}&amp;t={$t_id}");
             if ($t_id != 0) {
                 $url = "<br /><a href=" . append_sid("{$this->phpbb_root_path}viewtopic.{$this->php_ext}", "f={$f_id}&amp;t={$t_id}") . ">" . $this->user->lang('MAPS_FORUM_MARK') . "</a>";
             } else {
                 $url = "";
             }
             $sql_delete = "SELECT *\n\t\t\t\t\tFROM " . USER_TABLE . "\n\t\t\t\t\t\tWHERE group_id IN ({$groups_delete})\n\t\t\t\t\t\t\tAND user_id = {$userid}";
             $res_delete = $this->db->sql_query($sql_delete);
             $row_delete = $this->db->sql_fetchrow($res_delete);
             if ($this->user->data['group_id'] == $row_delete['group_id']) {
                 $delete = "<hr size=1><form method=\"post\"><input type=\"hidden\" name=\"del\" value=\"" . $id . "\"><input type=\"hidden\" name=\"tid\" value=\"" . $t_id . "\"><input type=\"submit\" value=\"" . $this->user->lang('MAPS_DELELE') . "\" name=\"delete\" ></form>";
             } else {
                 $delete = "";
             }
             if ($repa < 0) {
                 $r = "color:red; text-align:center; FONT-WEIGHT: bold; FONT-SIZE:11px";
                 $r2 = "" . $repa . "";
             } elseif ($repa == 0) {
                 $r = "color:blue; text-align:center; FONT-WEIGHT: bold; FONT-SIZE:11px";
                 $r2 = "" . $repa . "";
             } else {
                 $r = "color:green; text-align:center; FONT-WEIGHT: bold; FONT-SIZE:11px";
                 $r2 = "+" . $repa . "";
             }
             if ($reputation == '1') {
                 $repca = "<hr size=1>" . "<form method=\"post\" style=\"float:left;\">" . "<input type=\"hidden\" name=\"id\" value=\"{$id}\">" . "Репутация метки: <input type=\"submit\" class=\"up_submit\" name=\"up\" value=\"up\" /></form>" . "<form method=\"post\" style=\"float:left;\">" . "<input type=\"hidden\" name=\"id\" value=\"{$id}\">" . "<input type=\"text\" name=\"text\" value=\"{$r2}\" SIZE=\"4\" style=\"{$r}\">" . "<input type=\"submit\" class=\"down_submit\" name=\"down\" value=\"down\" /></form><br />";
             } else {
                 $repca = '';
             }
             $this->template->assign_block_vars('row', array('PLACEMARK' => "\n\t\t\t\t.add(new ymaps.Placemark([{$coord}], {\n\t\t\t\t\thintContent: '{$titles}',\n\t\t\t\t\tballoonContentHeader: '<strong><big>{$titles}</big></strong>',\n\t\t\t\t\tballoonContentBody: '<hr size=1>{$descr}',\n\t\t\t\t\tballoonContentFooter: '" . $this->user->lang('MAPS_USER_MARK') . ": {$username} {$url} {$repca} {$delete} <hr size=1>" . $this->user->lang('MAPS_CLICK_COORD') . ": {$coord}'\n\t\t\t\t}))\n\t\t\t"));
         } else {
             $this->template->assign_block_vars('row', array('PLACEMARK' => ""));
         }
     }
     $sql_edit = "SELECT *\n\t\t\tFROM " . USER_TABLE . "\n\t\t\t\tWHERE group_id IN ({$groups_edit})\n\t\t\t\t\tAND user_id = {$userid}";
     $res_edit = $this->db->sql_query($sql_edit);
     $row_edit = $this->db->sql_fetchrow($res_edit);
     if ($this->user->data['group_id'] == $row_edit['group_id']) {
         $this->template->assign_block_vars('edit', array('EDIT' => "\n\t\t\tmyMap.events.add('click', function (e) {\n\t\t\t\tif (!myMap.balloon.isOpen()) {\n\t\t\t\t\tvar coords = e.get('coords');\n\t\t\t\t\tmyMap.balloon.open(coords, {\n\t\t\t\t\t\tcontentHeader:'" . $this->user->lang('MAPS_ADD_MARK') . "',\n\t\t\t\t\t\tcontentBody:'<form method=\"post\"><p>" . $this->user->lang('MAPS_TITLE_MARK') . ":<br /><input type=\"text\" name=\"title\" maxlength=\"255\"></p><p>" . $this->user->lang('MAPS_DESCR_MARK') . ":<br /><textarea rows=\"5\" cols=\"30\" name=\"descriptpoint\"></textarea></p><input name=\"pcoord\" type=\"hidden\" value=\"'+ [coords[0].toPrecision(11),coords[1].toPrecision(11)].join(', ') +'\" ><p><input type=\"submit\" value=\"" . $this->user->lang('MAPS_SUBMIT') . "\" name=\"but\" ></p></form><hr size=1>" . $this->user->lang('MAPS_CLICK_COORD') . ": '+ [coords[0].toPrecision(11),coords[1].toPrecision(11)].join(', ') +''\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmyMap.balloon.close();\n\t\t\t\t}\n\t\t\t});\n"));
     }
     $this->template->assign_block_vars('map', array('HEADER' => "\n\t\t\t<script type=\"text/javascript\">\n\t\t\t\tymaps.ready(function () {\n\t\t\t\t\tvar myMap = new ymaps.Map('map', {\n\t\t\t\t\t\tcenter: [{$senter_maps}],\n\t\t\t\t\t\tzoom: 10\n\t\t\t\t\t}),\n\n\t\t\t\tclusterer = new ymaps.Clusterer({\n\t\t\t\tgroupByCoordinates: false,\n\t\t\t\tclusterDisableClickZoom: true,\n\t\t\t\tclusterHideIconOnBalloonOpen: false,\n\t\t\t\tgeoObjectHideIconOnBalloonOpen: false\n\t\t\t\t}),\n\n\t\t\t\tgeoObjects = new ymaps.GeoObject({\n\t\t\t\t\tgeometry: {\n\t\t\t\t\t\ttype: 'Point',\n\t\t\t\t\t\tcoordinates: [{$senter_maps}]\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tclusterer\n\t\t", 'FOOTER' => "\n\t\t\tclusterer.options.set({\n\t\t\t\tgridSize: 80,\n\t\t\t\tclusterDisableClickZoom: false\n\t\t\t});\n\n\t\t\tmyMap.geoObjects.add(clusterer);\n\t\t\t{$bounds_maps}\n\t\t\t\t});\n\t\t\t</script>\n\t\t", 'CONTAINER' => "\n<div id='map' class='container_map'></div>\n<br /><center>Copyright © <a href='http://www.ribak72.ru/community/maps'>Карта рыболовных мест</a></center>\n\t\t"));
     if (isset($_POST['up'])) {
         $map_id = request_var('id', '', true);
         if ($this->user->data['user_id'] != ANONYMOUS) {
             $sql = "SELECT *\n\t\t\tFROM " . MAP_REPA . "\n\t\t\t\tWHERE map_id = {$map_id}\n\t\t\t\t\tAND user_id = {$userid}";
             $res = $this->db->sql_query($sql);
             $row = $this->db->sql_fetchrow($res);
             if ($row > 0) {
                 $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_UP_DOWN_NO') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
             } else {
                 $insert = $this->db->sql_query("INSERT INTO " . MAP_REPA . " (user_id, map_id) VALUES ('{$userid}', '{$map_id}')");
                 $update = $this->db->sql_query("UPDATE " . MAP . " SET repa=repa+1 WHERE id='{$map_id}'");
                 if ($insert and $update) {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_UP_DOWN_YES') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 } else {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_ERROR_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 }
             }
         } else {
             login_box('', $this->user->lang['LOGIN_REPUTATION_PAGE']);
         }
     }
     if (isset($_POST['down'])) {
         $map_id = request_var('id', '', true);
         if ($this->user->data['user_id'] != ANONYMOUS) {
             $sql = "SELECT *\n\t\t\tFROM " . MAP_REPA . "\n\t\t\t\tWHERE map_id = {$map_id}\n\t\t\t\t\tAND user_id = {$userid}";
             $res = $this->db->sql_query($sql);
             $row = $this->db->sql_fetchrow($res);
             if ($row > 0) {
                 $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_UP_DOWN_NO') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
             } else {
                 $insert = $this->db->sql_query("INSERT INTO " . MAP_REPA . " (user_id, map_id) VALUES ('{$userid}', '{$map_id}')");
                 $update = $this->db->sql_query("UPDATE " . MAP . " SET repa=repa-1 WHERE id='{$map_id}'");
                 if ($insert and $update) {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_UP_DOWN_YES') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 } else {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_ERROR_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 }
             }
         } else {
             login_box('', $this->user->lang['LOGIN_REPUTATION_PAGE']);
         }
     }
     if (isset($_POST['delete'])) {
         $del = request_var('del', '', true);
         $tid = request_var('tid', '', true);
         $delete = $this->db->sql_query("DELETE FROM " . MAP . " WHERE id = {$del}");
         if ($delete) {
             if ($tid != 0) {
                 $sql = "SELECT post_id \n\t\t\t               FROM " . POSTS_TABLE . " \n\t\t\t               WHERE topic_id = {$tid}";
                 $result = $this->db->sql_query($sql);
                 $row = $this->db->sql_fetchrow($result);
                 $this->db->sql_freeresult($result);
                 if ($row) {
                     if (!function_exists('delete_posts')) {
                         include $this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext;
                     }
                     delete_posts('post_id', $row);
                 }
             }
             $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_DELELE_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
         } else {
             $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_ERROR_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
         }
     }
     if (isset($_POST['but'])) {
         $pcoord = request_var('pcoord', '', true);
         $descriptpoint = strip_tags(str_replace("'", '"', html_entity_decode(request_var('descriptpoint', '', true), ENT_QUOTES)));
         $title = strip_tags(str_replace("'", '"', html_entity_decode(request_var('title', '', true), ENT_QUOTES)));
         if ($maps_post == '1') {
             $bbmaps = '[yandexmaps=' . $title . ']' . $pcoord . '[/yandexmaps]<br />' . $descriptpoint . '';
         } else {
             $bbmaps = "{$descriptpoint}";
         }
         if ($descriptpoint == '') {
             unset($descriptpoint);
         }
         if ($title == '') {
             unset($title);
         }
         if (isset($title) && isset($descriptpoint)) {
             $sql = "SELECT * \n\t\t\tFROM " . MAP . " \n\t\t\tWHERE coord \n\t\t\tLIKE '{$pcoord}'";
             $res = $this->db->sql_query($sql);
             if ($this->db->sql_affectedrows($res) != 0) {
                 $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_EXISTS_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
             } else {
                 if ($placemark_posts == 1) {
                     include $this->phpbb_root_path . '/includes/functions_posting.' . $this->php_ext;
                     global $post_data;
                     $poll = $uid = $bitfield = $options = '';
                     generate_text_for_storage($title, $uid, $bitfield, $options, false, false, false);
                     generate_text_for_storage($bbmaps, $uid, $bitfield, $options, true, true, true);
                     $post_data = array('topic_type' => POST_NORMAL, 'post_subject' => $title);
                     $data = array('forum_id' => $maps_posts_forum, 'icon_id' => false, 'enable_bbcode' => (bool) true, 'enable_smilies' => (bool) true, 'enable_urls' => (bool) true, 'enable_sig' => (bool) true, 'message' => $bbmaps, 'message_md5' => (string) '', 'bbcode_bitfield' => $bitfield, 'bbcode_uid' => $uid, 'post_edit_locked' => 0, 'topic_title' => $title, 'notify_set' => false, 'notify' => false, 'post_time' => 0, 'forum_name' => '', 'enable_indexing' => (bool) false, 'post_id' => '', 'topic_first_post_id' => '', 'force_approved_state' => 1);
                     submit_post('post', $title, '', POST_NORMAL, $poll, $data);
                     $topic = $data['topic_id'];
                 } else {
                     $topic = 0;
                 }
                 $insert = $this->db->sql_query("INSERT INTO " . MAP . " (user_id, title, descr, coord, repa, topic, forum) VALUES ('{$userid}', '{$title}', '{$descriptpoint}', '{$pcoord}', '0', '{$topic}', '{$maps_posts_forum}')");
                 if ($insert) {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_SAVE_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 } else {
                     $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_ERROR_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
                 }
             }
         } else {
             $this->template->assign_block_vars('info', array('TEXT' => "<center><h3>" . $this->user->lang('MAPS_ERROR2_MARK') . "</h3></center><meta http-equiv=\"refresh\" content=\"2; url=maps\">"));
         }
     }
     page_header($this->config['maps_title']);
     $this->template->set_filenames(array('body' => 'maps_body.html'));
     page_footer();
     return new Response($this->template->return_display('body'), 200);
 }
/**
* Delete Post
*/
function delete_post($forum_id, $topic_id, $post_id, &$data)
{
    global $_CLASS, $config;
    // Specify our post mode
    $post_mode = $data['topic_first_post_id'] == $data['topic_last_post_id'] ? 'delete_topic' : ($data['topic_first_post_id'] == $post_id ? 'delete_first_post' : ($data['topic_last_post_id'] == $post_id ? 'delete_last_post' : 'delete'));
    $sql_data = array();
    $next_post_id = 0;
    require_once SITE_FILE_ROOT . 'includes/forums/functions_admin.php';
    $_CLASS['core_db']->transaction();
    if (!delete_posts('post_id', array($post_id), false, false)) {
        // Try to delete topic, we may had an previous error causing inconsistency
        if ($post_mode == 'delete_topic') {
            delete_topics('topic_id', array($topic_id), false);
        }
        trigger_error('ALREADY_DELETED');
    }
    $_CLASS['core_db']->transaction('commit');
    // Collect the necessary information for updating the tables
    $sql_data[FORUMS_FORUMS_TABLE] = '';
    switch ($post_mode) {
        case 'delete_topic':
            delete_topics('topic_id', array($topic_id), false);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] .= 'forum_posts = forum_posts - 1, forum_topics_real = forum_topics_real - 1';
                $sql_data[FORUMS_FORUMS_TABLE] .= $data['topic_approved'] ? ', forum_topics = forum_topics - 1' : '';
            }
            $update_sql = update_post_information('forum', $forum_id, true);
            if (sizeof($update_sql)) {
                $sql_data[FORUMS_FORUMS_TABLE] .= $sql_data[FORUMS_FORUMS_TABLE] ? ', ' : '';
                $sql_data[FORUMS_FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
            }
            break;
        case 'delete_first_post':
            $sql = 'SELECT p.post_id, p.poster_id, p.post_username, u.username
				FROM ' . FORUMS_POSTS_TABLE . ' p, ' . CORE_USERS_TABLE . " u\r\n\t\t\t\tWHERE p.topic_id = {$topic_id}\r\n\t\t\t\t\tAND p.poster_id = u.user_id\r\n\t\t\t\tORDER BY p.post_time ASC";
            $result = $_CLASS['core_db']->query_limit($sql, 1);
            $row = $_CLASS['core_db']->fetch_row_assoc($result);
            $_CLASS['core_db']->free_result($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_first_post_id = ' . intval($row['post_id']) . ", topic_first_poster_name = '" . ($row['poster_id'] == ANONYMOUS ? $_CLASS['core_db']->escape($row['post_username']) : $_CLASS['core_db']->escape($row['username'])) . "'";
            $sql_data[FORUMS_TOPICS_TABLE] .= ', topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
            break;
        case 'delete_last_post':
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $update_sql = update_post_information('forum', $forum_id, true);
            if (sizeof($update_sql)) {
                $sql_data[FORUMS_FORUMS_TABLE] .= $sql_data[FORUMS_FORUMS_TABLE] ? ', ' : '';
                $sql_data[FORUMS_FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
            }
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_bumped = 0, topic_bumper = 0, topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $update_sql = update_post_information('topic', $topic_id, true);
            if (sizeof($update_sql)) {
                $sql_data[FORUMS_TOPICS_TABLE] .= ', ' . implode(', ', $update_sql[$topic_id]);
                $next_post_id = (int) str_replace('topic_last_post_id = ', '', $update_sql[$topic_id][0]);
            } else {
                $sql = 'SELECT MAX(post_id) as last_post_id
					FROM ' . FORUMS_POSTS_TABLE . "\r\n\t\t\t\t\tWHERE topic_id = {$topic_id} " . (!$_CLASS['forums_auth']->acl_get('m_approve', $forum_id) ? 'AND post_approved = 1' : '');
                $result = $_CLASS['core_db']->query($sql);
                $row = $_CLASS['core_db']->fetch_row_assoc($result);
                $_CLASS['core_db']->free_result($result);
                $next_post_id = (int) $row['last_post_id'];
            }
            break;
        case 'delete':
            $sql = 'SELECT post_id
				FROM ' . FORUMS_POSTS_TABLE . "\r\n\t\t\t\tWHERE topic_id = {$topic_id} " . (!$_CLASS['forums_auth']->acl_get('m_approve', $forum_id) ? 'AND post_approved = 1' : '') . '
					AND post_time > ' . $data['post_time'] . '
				ORDER BY post_time ASC';
            $result = $_CLASS['core_db']->query_limit($sql, 1);
            $row = $_CLASS['core_db']->fetch_row_assoc($result);
            $_CLASS['core_db']->free_result($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
            break;
    }
    //$sql_data[CORE_USERS_TABLE] = ($_CLASS['forums_auth']->acl_get('f_postcount', $forum_id)) ? 'user_posts = user_posts - 1' : '';
    $_CLASS['core_db']->transaction();
    $where_sql = array(FORUMS_FORUMS_TABLE => "forum_id = {$forum_id}", FORUMS_TOPICS_TABLE => "topic_id = {$topic_id}", CORE_USERS_TABLE => 'user_id = ' . $data['poster_id']);
    foreach ($sql_data as $table => $update_sql) {
        if ($update_sql) {
            $_CLASS['core_db']->query("UPDATE {$table} SET {$update_sql} WHERE " . $where_sql[$table]);
        }
    }
    unset($sql_data);
    $_CLASS['core_db']->transaction('commit');
    // Adjust posted info for this user by looking for a post by him/her within this topic...
    /*
    if ($post_mode != 'delete_topic' && $config['load_db_track'] && $_CLASS['core_user']->is_user)
    {
    	$sql = 'SELECT poster_id
    		FROM ' . POSTS_TABLE . '
    		WHERE topic_id = ' . $topic_id . '
    			AND poster_id = ' . $_CLASS['core_user']->data['user_id'];
    	$result = $_CLASS['core_db']->query_limit($sql, 1);
    	$poster_id = (int) $db->sql_fetchfield('poster_id');
    	$_CLASS['core_db']->free_result($result);
    
    	// The user is not having any more posts within this topic
    	if (!$poster_id)
    	{
    		$sql = 'DELETE FROM ' . TOPICS_POSTED_TABLE . '
    			WHERE topic_id = ' . $topic_id . '
    				AND user_id = ' . $_CLASS['core_user']->data['user_id'];
    		$_CLASS['core_db']->query($sql);
    	}
    }
    */
    if ($data['post_reported'] && $post_mode != 'delete_topic') {
        sync('topic_reported', 'topic_id', array($topic_id));
    }
    return $next_post_id;
}
Exemplo n.º 12
0
/**
* Disapprove Post/Topic
*/
function disapprove_post($post_id_list, $mode)
{
    global $_CLASS, $_CORE_CONFIG, $config;
    $forum_id = request_var('f', 0);
    if (!check_ids($post_id_list, FORUMS_POSTS_TABLE, 'post_id', 'm_approve')) {
        trigger_error('NOT_AUTHORIZED');
    }
    $redirect = request_var('redirect', $_CLASS['core_user']->data['session_page']);
    $reason = request_var('reason', '', true);
    $reason_id = request_var('reason_id', 0);
    $success_msg = $additional_msg = '';
    $s_hidden_fields = build_hidden_fields(array('i' => 'queue', 'f' => $forum_id, 'mode' => $mode, 'post_id_list' => $post_id_list, 'mode' => 'disapprove', 'redirect' => $redirect));
    $notify_poster = isset($_REQUEST['notify_poster']);
    $disapprove_reason = '';
    if ($reason_id) {
        $sql = 'SELECT reason_title, reason_description
			FROM ' . FORUMS_REPORTS_REASONS_TABLE . " \n\t\t\tWHERE reason_id = {$reason_id}";
        $result = $_CLASS['core_db']->query($sql);
        $row = $_CLASS['core_db']->fetch_row_assoc($result);
        $_CLASS['core_db']->free_result($result);
        if (!$row || !$reason && $row['reason_name'] === 'other') {
            $additional_msg = $_CLASS['core_user']->lang['NO_REASON_DISAPPROVAL'];
            unset($_POST['confirm']);
        } else {
            $disapprove_reason = $row['reason_title'] != 'other' ? isset($_CLASS['core_user']->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])]) ? $_CLASS['core_user']->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])] : $row['reason_description'] : '';
            $disapprove_reason .= $reason ? "\n\n" . $reason : '';
            unset($reason);
        }
    }
    require_once SITE_FILE_ROOT . 'includes/forums/functions_display.php';
    $reason = display_reasons($reason_id);
    $_CLASS['core_template']->assign_array(array('S_NOTIFY_POSTER' => true, 'S_APPROVE' => false, 'REASON' => $reason, 'ADDITIONAL_MSG' => $additional_msg));
    if (display_confirmation($_CLASS['core_user']->get_lang('DISAPPROVE_POST' . (sizeof($post_id_list) == 1 ? '' : 'S')), $s_hidden_fields, 'modules/forums/mcp_approve.html')) {
        $post_info = get_post_data($post_id_list, 'm_approve');
        // If Topic -> forum_topics_real -= 1
        // If Post -> topic_replies_real -= 1
        $forum_topics_real = 0;
        $topic_replies_real_sql = $post_disapprove_sql = $topic_id_list = array();
        foreach ($post_info as $post_id => $post_data) {
            $topic_id_list[$post_data['topic_id']] = 1;
            // Topic or Post. ;)
            if ($post_data['topic_first_post_id'] == $post_id && $post_data['topic_last_post_id'] == $post_id) {
                if ($post_data['forum_id']) {
                    $forum_topics_real++;
                }
            } else {
                if (!isset($topic_replies_real_sql[$post_data['topic_id']])) {
                    $topic_replies_real_sql[$post_data['topic_id']] = 1;
                } else {
                    $topic_replies_real_sql[$post_data['topic_id']]++;
                }
            }
            $post_disapprove_sql[] = $post_id;
        }
        if ($forum_topics_real) {
            $sql = 'UPDATE ' . FORUMS_FORUMS_TABLE . "\n\t\t\t\tSET forum_topics_real = forum_topics_real - {$forum_topics_real}\n\t\t\t\tWHERE forum_id = {$forum_id}";
            $_CLASS['core_db']->query($sql);
        }
        if (!empty($topic_replies_real_sql)) {
            foreach ($topic_replies_real_sql as $topic_id => $num_replies) {
                $sql = 'UPDATE ' . FORUMS_TOPICS_TABLE . "\n\t\t\t\t\tSET topic_replies_real = topic_replies_real - {$num_replies}\n\t\t\t\t\tWHERE topic_id = {$topic_id}";
                $_CLASS['core_db']->query($sql);
            }
        }
        if (sizeof($post_disapprove_sql)) {
            if (!function_exists('delete_posts')) {
                require_once SITE_FILE_ROOT . 'includes/forums/functions_admin.php';
            }
            // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts
            delete_posts('post_id', $post_disapprove_sql);
        }
        unset($post_disapprove_sql, $topic_replies_real_sql);
        update_post_information('topic', array_keys($topic_id_list));
        update_post_information('forum', $forum_id);
        unset($topic_id_list);
        // Notify Poster?
        if ($notify_poster) {
            require_once SITE_FILE_ROOT . 'includes/mailer.php';
            $mailer = new core_mailer();
            foreach ($post_info as $post_id => $post_data) {
                if ($post_data['poster_id'] == ANONYMOUS) {
                    continue;
                }
                $post_data['post_subject'] = censor_text($post_data['post_subject'], true);
                $post_data['topic_title'] = censor_text($post_data['topic_title'], true);
                if ($post_data['post_id'] == $post_data['topic_first_post_id'] && $post_data['post_id'] == $post_data['topic_last_post_id']) {
                    $email_template = 'topic_disapproved.txt';
                    $subject = 'Topic Disapproved - ' . $post_data['topic_title'];
                } else {
                    $email_template = 'post_disapproved.txt';
                    $subject = 'Post Disapproved - ' . $post_data['post_subject'];
                }
                $mailer->to($post_data['user_email'], $post_data['username']);
                //$mailer->reply_to($_CORE_CONFIG['email']['site_email']);
                $mailer->subject($subject);
                //$messenger->im($post_data['user_jabber'], $post_data['username']);
                $_CLASS['core_template']->assign_array(array('SITENAME' => $_CORE_CONFIG['global']['site_name'], 'USERNAME' => $post_data['username'], 'REASON' => stripslashes($disapprove_reason), 'POST_SUBJECT' => $post_data['post_subject'], 'TOPIC_TITLE' => $post_data['topic_title']));
                $mailer->message = trim($_CLASS['core_template']->display('email/forums/' . $email_template, true));
                $mailer->send();
            }
        }
        unset($post_info, $disapprove_reason);
        if ($forum_topics_real) {
            $success_msg = $forum_topics_real == 1 ? 'TOPIC_DISAPPROVED_SUCCESS' : 'TOPICS_DISAPPROVED_SUCCESS';
        } else {
            $success_msg = sizeof($post_id_list) == 1 ? 'POST_DISAPPROVED_SUCCESS' : 'POSTS_DISAPPROVED_SUCCESS';
        }
    }
    $redirect = request_var('redirect', generate_link('forums'));
    if (!$success_msg) {
        redirect($redirect);
    } else {
        $_CLASS['core_display']->meta_refresh(3, generate_link("forums&amp;file=viewforum&amp;f={$forum_id}"));
        trigger_error($_CLASS['core_user']->lang[$success_msg] . '<br /><br />' . sprintf($_CLASS['core_user']->lang['RETURN_FORUM'], '<a href="' . generate_link('forums&amp;file=viewforum&amp;f=' . $forum_id) . '">', '</a>'));
    }
}
Exemplo n.º 13
0
/**
* Remove User
*/
function user_delete($mode, $user_id, $post_username = false)
{
    global $config, $db, $user, $auth;
    $db->sql_transaction('begin');
    switch ($mode) {
        case 'retain':
            $sql = 'UPDATE ' . FORUMS_TABLE . '
				SET forum_last_poster_id = ' . ANONYMOUS . ($post_username !== false ? ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "'" : '') . "\n\t\t\t\tWHERE forum_last_poster_id = {$user_id}";
            $db->sql_query($sql);
            $sql = 'UPDATE ' . POSTS_TABLE . '
				SET poster_id = ' . ANONYMOUS . ($post_username !== false ? ", post_username = '******'" : '') . "\n\t\t\t\tWHERE poster_id = {$user_id}";
            $db->sql_query($sql);
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_poster = ' . ANONYMOUS . "\n\t\t\t\tWHERE topic_poster = {$user_id}";
            $db->sql_query($sql);
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_last_poster_id = ' . ANONYMOUS . ($post_username !== false ? ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "'" : '') . "\n\t\t\t\tWHERE topic_last_poster_id = {$user_id}";
            $db->sql_query($sql);
            break;
        case 'remove':
            if (!function_exists('delete_posts')) {
                global $phpbb_root_path, $phpEx;
                include_once $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
				FROM ' . POSTS_TABLE . "\n\t\t\t\tWHERE poster_id = {$user_id}\n\t\t\t\tGROUP BY topic_id";
            $result = $db->sql_query($sql);
            $topic_id_ary = array();
            while ($row = $db->sql_fetchrow($result)) {
                $topic_id_ary[$row['topic_id']] = $row['total_posts'];
            }
            $db->sql_freeresult($result);
            if (sizeof($topic_id_ary)) {
                $sql = 'SELECT topic_id, topic_replies, topic_replies_real
					FROM ' . TOPICS_TABLE . '
					WHERE topic_id IN (' . implode(', ', array_keys($topic_id_ary)) . ')';
                $result = $db->sql_query($sql);
                $del_topic_ary = array();
                while ($row = $db->sql_fetchrow($result)) {
                    if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']]) {
                        $del_topic_ary[] = $row['topic_id'];
                    }
                }
                $db->sql_freeresult($result);
                if (sizeof($del_topic_ary)) {
                    $sql = 'DELETE FROM ' . TOPICS_TABLE . '
						WHERE topic_id IN (' . implode(', ', $del_topic_ary) . ')';
                    $db->sql_query($sql);
                }
            }
            // Delete posts, attachments, etc.
            delete_posts('poster_id', $user_id);
            break;
    }
    $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE);
    foreach ($table_ary as $table) {
        $sql = "DELETE FROM {$table}\n\t\t\tWHERE user_id = {$user_id}";
        $db->sql_query($sql);
    }
    // Reset newest user info if appropriate
    if ($config['newest_user_id'] == $user_id) {
        update_last_username();
    }
    set_config('num_users', $config['num_users'] - 1, true);
    $db->sql_transaction('commit');
    return false;
}
Exemplo n.º 14
0
function mcp_delete_post($post_ids)
{
    global $_CLASS;
    if (!check_ids($post_ids, FORUMS_POSTS_TABLE, 'post_id', 'm_delete')) {
        return;
    }
    $redirect = get_variable('redirect', 'POST', $_CLASS['core_user']->data['session_url']);
    $hidden_fields = generate_hidden_fields(array('post_id_list' => $post_ids, 'mode' => 'delete_post', 'redirect' => $redirect));
    $success_msg = '';
    $message = $_CLASS['core_user']->get_lang(count($post_ids) === 1 ? 'DELETE_POST' : 'DELETE_POSTS');
    if (display_confirmation($message, $hidden_fields)) {
        // Count the number of topics that are affected
        // I did not use COUNT(DISTINCT ...) because I remember having problems
        // with it on older versions of MySQL -- Ashe
        $sql = 'SELECT DISTINCT topic_id
			FROM ' . FORUMS_POSTS_TABLE . '
			WHERE post_id IN (' . implode(', ', $post_ids) . ')';
        $result = $_CLASS['core_db']->query($sql);
        $topic_id_list = array();
        while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
            $topic_id_list[] = $row['topic_id'];
        }
        $_CLASS['core_db']->free_result($result);
        $affected_topics = count($topic_id_list);
        $post_data = get_post_data($post_ids);
        foreach ($post_data as $id => $row) {
            add_log('mod', $row['forum_id'], $row['topic_id'], 'LOG_DELETE_POST', $row['post_subject']);
        }
        unset($post_data);
        // Now delete the posts, topics and forums are automatically resync'ed
        delete_posts('post_id', $post_ids);
        $sql = 'SELECT COUNT(topic_id) AS topics_left
			FROM ' . FORUMS_TOPICS_TABLE . '
			WHERE topic_id IN (' . implode(', ', $topic_id_list) . ')';
        $result = $_CLASS['core_db']->query($sql);
        $row = $_CLASS['core_db']->fetch_row_assoc($result);
        $_CLASS['core_db']->free_result($result);
        $deleted_topics = $row['topics_left'] ? $affected_topics - $row['topics_left'] : $affected_topics;
        $topic_id = request_var('t', 0);
        // Return links
        $return_link = array();
        if ($affected_topics === 1 && !$deleted_topics && $topic_id) {
            $return_link[] = sprintf($_CLASS['core_user']->lang['RETURN_TOPIC'], '<a href="' . generate_link("forums&amp;file=viewtopic&amp;f={$forum_id}&amp;t={$topic_id}") . '">', '</a>');
        }
        $return_link[] = sprintf($_CLASS['core_user']->lang['RETURN_FORUM'], '<a href="' . generate_link('forums&amp;file=viewforum&amp;f=' . $forum_id) . '">', '</a>');
        if (count($post_ids) === 1) {
            if ($deleted_topics) {
                // We deleted the only post of a topic, which in turn has
                // been removed from the database
                $success_msg = $_CLASS['core_user']->lang['TOPIC_DELETED_SUCCESS'];
            } else {
                $success_msg = $_CLASS['core_user']->lang['POST_DELETED_SUCCESS'];
            }
        } else {
            if ($deleted_topics) {
                // Some of topics disappeared
                $success_msg = $_CLASS['core_user']->lang['POSTS_DELETED_SUCCESS'] . '<br /><br />' . $_CLASS['core_user']->lang['EMPTY_TOPICS_REMOVED_WARNING'];
            } else {
                $success_msg = $_CLASS['core_user']->lang['POSTS_DELETED_SUCCESS'];
            }
        }
    }
    $redirect = generate_link('forums');
    if (!$success_msg) {
        redirect($redirect);
    } else {
        $_CLASS['core_display']->meta_refresh(3, $redirect);
        trigger_error($success_msg . '<br /><br />' . sprintf($_CLASS['core_user']->lang['RETURN_PAGE'], '<a href="' . $redirect . '">', '</a>') . '<br /><br />' . implode('<br /><br />', $return_link));
    }
}
Exemplo n.º 15
0
 /**
  * Deletes an idea and the topic to go with it.
  *
  * @param int $id       The ID of the idea to be deleted.
  * @param int $topic_id The ID of the idea topic. Optional, but preferred.
  *
  * @return boolean Whether the idea was deleted or not.
  */
 public function delete($id, $topic_id = 0)
 {
     if (!$topic_id) {
         $idea = $this->get_idea($id);
         $topic_id = $idea['topic_id'];
     }
     // Delete topic
     delete_posts('topic_id', $topic_id);
     // Delete idea
     $deleted = $this->delete_idea_data($id, 'table_ideas');
     // Delete votes
     $this->delete_idea_data($id, 'table_votes');
     return $deleted;
 }
Exemplo n.º 16
0
/**
* Delete Posts
*/
function mcp_delete_post($post_ids)
{
    global $auth, $user, $db, $phpEx, $phpbb_root_path;
    if (!check_ids($post_ids, POSTS_TABLE, 'post_id', array('m_delete'))) {
        return;
    }
    $redirect = request_var('redirect', build_url(array('action', 'quickmod')));
    $forum_id = request_var('f', 0);
    $s_hidden_fields = build_hidden_fields(array('post_id_list' => $post_ids, 'f' => $forum_id, 'action' => 'delete_post', 'redirect' => $redirect));
    $success_msg = '';
    if (confirm_box(true)) {
        if (!function_exists('delete_posts')) {
            include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
        }
        // Count the number of topics that are affected
        // I did not use COUNT(DISTINCT ...) because I remember having problems
        // with it on older versions of MySQL -- Ashe
        $sql = 'SELECT DISTINCT topic_id
			FROM ' . POSTS_TABLE . '
			WHERE ' . $db->sql_in_set('post_id', $post_ids);
        $result = $db->sql_query($sql);
        $topic_id_list = array();
        while ($row = $db->sql_fetchrow($result)) {
            $topic_id_list[] = $row['topic_id'];
        }
        $affected_topics = sizeof($topic_id_list);
        $db->sql_freeresult($result);
        $post_data = get_post_data($post_ids);
        foreach ($post_data as $id => $row) {
            $post_username = $row['poster_id'] == ANONYMOUS && !empty($row['post_username']) ? $row['post_username'] : $row['username'];
            add_log('mod', $row['forum_id'], $row['topic_id'], 'LOG_DELETE_POST', $row['post_subject'], $post_username);
        }
        // Now delete the posts, topics and forums are automatically resync'ed
        delete_posts('post_id', $post_ids);
        $sql = 'SELECT COUNT(topic_id) AS topics_left
			FROM ' . TOPICS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_id', $topic_id_list);
        $result = $db->sql_query_limit($sql, 1);
        $deleted_topics = ($row = $db->sql_fetchrow($result)) ? $affected_topics - $row['topics_left'] : $affected_topics;
        $db->sql_freeresult($result);
        $topic_id = request_var('t', 0);
        // Return links
        $return_link = array();
        if ($affected_topics == 1 && !$deleted_topics && $topic_id) {
            $return_link[] = sprintf($user->lang['RETURN_TOPIC'], '<a href="' . append_sid("{$phpbb_root_path}viewtopic.{$phpEx}", "f={$forum_id}&amp;t={$topic_id}") . '">', '</a>');
        }
        $return_link[] = sprintf($user->lang['RETURN_FORUM'], '<a href="' . append_sid("{$phpbb_root_path}viewforum.{$phpEx}", 'f=' . $forum_id) . '">', '</a>');
        if (sizeof($post_ids) == 1) {
            if ($deleted_topics) {
                // We deleted the only post of a topic, which in turn has
                // been removed from the database
                $success_msg = $user->lang['TOPIC_DELETED_SUCCESS'];
            } else {
                $success_msg = $user->lang['POST_DELETED_SUCCESS'];
            }
        } else {
            if ($deleted_topics) {
                // Some of topics disappeared
                $success_msg = $user->lang['POSTS_DELETED_SUCCESS'] . '<br /><br />' . $user->lang['EMPTY_TOPICS_REMOVED_WARNING'];
            } else {
                $success_msg = $user->lang['POSTS_DELETED_SUCCESS'];
            }
        }
    } else {
        confirm_box(false, sizeof($post_ids) == 1 ? 'DELETE_POST' : 'DELETE_POSTS', $s_hidden_fields);
    }
    $redirect = request_var('redirect', "index.{$phpEx}");
    $redirect = reapply_sid($redirect);
    if (!$success_msg) {
        redirect($redirect);
    } else {
        if ($affected_topics != 1 || $deleted_topics || !$topic_id) {
            $redirect = append_sid("{$phpbb_root_path}mcp.{$phpEx}", "f={$forum_id}&i=main&mode=forum_view", false);
        }
        meta_refresh(3, $redirect);
        trigger_error($success_msg . '<br /><br />' . sprintf($user->lang['RETURN_PAGE'], '<a href="' . $redirect . '">', '</a>') . '<br /><br />' . implode('<br /><br />', $return_link));
    }
}
Exemplo n.º 17
0
/**
 * Remove User
 *
 * @param string	$mode		Either 'retain' or 'remove'
 * @param mixed		$user_ids	Either an array of integers or an integer
 * @param bool		$retain_username
 * @return bool
 */
function user_delete($mode, $user_ids, $retain_username = true)
{
    global $cache, $config, $db, $user, $phpbb_dispatcher, $phpbb_container;
    global $phpbb_root_path, $phpEx;
    $db->sql_transaction('begin');
    $user_rows = array();
    if (!is_array($user_ids)) {
        $user_ids = array($user_ids);
    }
    $user_id_sql = $db->sql_in_set('user_id', $user_ids);
    $sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE ' . $user_id_sql;
    $result = $db->sql_query($sql);
    while ($row = $db->sql_fetchrow($result)) {
        $user_rows[(int) $row['user_id']] = $row;
    }
    $db->sql_freeresult($result);
    if (empty($user_rows)) {
        return false;
    }
    /**
     * Event before a user is deleted
     *
     * @event core.delete_user_before
     * @var	string	mode		Mode of deletion (retain/delete posts)
     * @var	array	user_ids	IDs of the deleted user
     * @var	mixed	retain_username	True if username should be retained
     *				or false if not
     * @since 3.1.0-a1
     */
    $vars = array('mode', 'user_ids', 'retain_username');
    extract($phpbb_dispatcher->trigger_event('core.delete_user_before', compact($vars)));
    // Before we begin, we will remove the reports the user issued.
    $sql = 'SELECT r.post_id, p.topic_id
		FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
		WHERE ' . $db->sql_in_set('r.user_id', $user_ids) . '
			AND p.post_id = r.post_id';
    $result = $db->sql_query($sql);
    $report_posts = $report_topics = array();
    while ($row = $db->sql_fetchrow($result)) {
        $report_posts[] = $row['post_id'];
        $report_topics[] = $row['topic_id'];
    }
    $db->sql_freeresult($result);
    if (sizeof($report_posts)) {
        $report_posts = array_unique($report_posts);
        $report_topics = array_unique($report_topics);
        // Get a list of topics that still contain reported posts
        $sql = 'SELECT DISTINCT topic_id
			FROM ' . POSTS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
				AND post_reported = 1
				AND ' . $db->sql_in_set('post_id', $report_posts, true);
        $result = $db->sql_query($sql);
        $keep_report_topics = array();
        while ($row = $db->sql_fetchrow($result)) {
            $keep_report_topics[] = $row['topic_id'];
        }
        $db->sql_freeresult($result);
        if (sizeof($keep_report_topics)) {
            $report_topics = array_diff($report_topics, $keep_report_topics);
        }
        unset($keep_report_topics);
        // Now set the flags back
        $sql = 'UPDATE ' . POSTS_TABLE . '
			SET post_reported = 0
			WHERE ' . $db->sql_in_set('post_id', $report_posts);
        $db->sql_query($sql);
        if (sizeof($report_topics)) {
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_reported = 0
				WHERE ' . $db->sql_in_set('topic_id', $report_topics);
            $db->sql_query($sql);
        }
    }
    // Remove reports
    $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE ' . $user_id_sql);
    $num_users_delta = 0;
    // Get auth provider collection in case accounts might need to be unlinked
    $provider_collection = $phpbb_container->get('auth.provider_collection');
    // Some things need to be done in the loop (if the query changes based
    // on which user is currently being deleted)
    $added_guest_posts = 0;
    foreach ($user_rows as $user_id => $user_row) {
        if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == 'avatar.driver.upload') {
            avatar_delete('user', $user_row);
        }
        // Unlink accounts
        foreach ($provider_collection as $provider_name => $auth_provider) {
            $provider_data = $auth_provider->get_auth_link_data($user_id);
            if ($provider_data !== null) {
                $link_data = array('user_id' => $user_id, 'link_method' => 'user_delete');
                // BLOCK_VARS might contain hidden fields necessary for unlinking accounts
                if (isset($provider_data['BLOCK_VARS']) && is_array($provider_data['BLOCK_VARS'])) {
                    foreach ($provider_data['BLOCK_VARS'] as $provider_service) {
                        if (!array_key_exists('HIDDEN_FIELDS', $provider_service)) {
                            $provider_service['HIDDEN_FIELDS'] = array();
                        }
                        $auth_provider->unlink_account(array_merge($link_data, $provider_service['HIDDEN_FIELDS']));
                    }
                } else {
                    $auth_provider->unlink_account($link_data);
                }
            }
        }
        // Decrement number of users if this user is active
        if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE) {
            --$num_users_delta;
        }
        switch ($mode) {
            case 'retain':
                if ($retain_username === false) {
                    $post_username = $user->lang['GUEST'];
                } else {
                    $post_username = $user_row['username'];
                }
                // If the user is inactive and newly registered
                // we assume no posts from the user, and save
                // the queries
                if ($user_row['user_type'] != USER_INACTIVE || $user_row['user_inactive_reason'] != INACTIVE_REGISTER || $user_row['user_posts']) {
                    // When we delete these users and retain the posts, we must assign all the data to the guest user
                    $sql = 'UPDATE ' . FORUMS_TABLE . '
						SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''\n\t\t\t\t\t\tWHERE forum_last_poster_id = {$user_id}";
                    $db->sql_query($sql);
                    $sql = 'UPDATE ' . POSTS_TABLE . '
						SET poster_id = ' . ANONYMOUS . ", post_username = '******'\n\t\t\t\t\t\tWHERE poster_id = {$user_id}";
                    $db->sql_query($sql);
                    $sql = 'UPDATE ' . TOPICS_TABLE . '
						SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''\n\t\t\t\t\t\tWHERE topic_poster = {$user_id}";
                    $db->sql_query($sql);
                    $sql = 'UPDATE ' . TOPICS_TABLE . '
						SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''\n\t\t\t\t\t\tWHERE topic_last_poster_id = {$user_id}";
                    $db->sql_query($sql);
                    // Since we change every post by this author, we need to count this amount towards the anonymous user
                    if ($user_row['user_posts']) {
                        $added_guest_posts += $user_row['user_posts'];
                    }
                }
                break;
            case 'remove':
                // there is nothing variant specific to deleting posts
                break;
        }
    }
    if ($num_users_delta != 0) {
        set_config_count('num_users', $num_users_delta, true);
    }
    // Now do the invariant tasks
    // all queries performed in one call of this function are in a single transaction
    // so this is kosher
    if ($mode == 'retain') {
        // Assign more data to the Anonymous user
        $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
			SET poster_id = ' . ANONYMOUS . '
			WHERE ' . $db->sql_in_set('poster_id', $user_ids);
        $db->sql_query($sql);
        $sql = 'UPDATE ' . USERS_TABLE . '
			SET user_posts = user_posts + ' . $added_guest_posts . '
			WHERE user_id = ' . ANONYMOUS;
        $db->sql_query($sql);
    } else {
        if ($mode == 'remove') {
            if (!function_exists('delete_posts')) {
                include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            // Delete posts, attachments, etc.
            // delete_posts can handle any number of IDs in its second argument
            delete_posts('poster_id', $user_ids);
        }
    }
    $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
    // Delete the miscellaneous (non-post) data for the user
    foreach ($table_ary as $table) {
        $sql = "DELETE FROM {$table}\n\t\t\tWHERE " . $user_id_sql;
        $db->sql_query($sql);
    }
    $cache->destroy('sql', MODERATOR_CACHE_TABLE);
    // Change user_id to anonymous for posts edited by this user
    $sql = 'UPDATE ' . POSTS_TABLE . '
		SET post_edit_user = '******'
		WHERE ' . $db->sql_in_set('post_edit_user', $user_ids);
    $db->sql_query($sql);
    // Change user_id to anonymous for pms edited by this user
    $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
		SET message_edit_user = '******'
		WHERE ' . $db->sql_in_set('message_edit_user', $user_ids);
    $db->sql_query($sql);
    // Change user_id to anonymous for posts deleted by this user
    $sql = 'UPDATE ' . POSTS_TABLE . '
		SET post_delete_user = '******'
		WHERE ' . $db->sql_in_set('post_delete_user', $user_ids);
    $db->sql_query($sql);
    // Change user_id to anonymous for topics deleted by this user
    $sql = 'UPDATE ' . TOPICS_TABLE . '
		SET topic_delete_user = '******'
		WHERE ' . $db->sql_in_set('topic_delete_user', $user_ids);
    $db->sql_query($sql);
    // Delete user log entries about this user
    $sql = 'DELETE FROM ' . LOG_TABLE . '
		WHERE ' . $db->sql_in_set('reportee_id', $user_ids);
    $db->sql_query($sql);
    // Change user_id to anonymous for this users triggered events
    $sql = 'UPDATE ' . LOG_TABLE . '
		SET user_id = ' . ANONYMOUS . '
		WHERE ' . $user_id_sql;
    $db->sql_query($sql);
    // Delete the user_id from the zebra table
    $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
		WHERE ' . $user_id_sql . '
			OR ' . $db->sql_in_set('zebra_id', $user_ids);
    $db->sql_query($sql);
    // Delete the user_id from the banlist
    $sql = 'DELETE FROM ' . BANLIST_TABLE . '
		WHERE ' . $db->sql_in_set('ban_userid', $user_ids);
    $db->sql_query($sql);
    // Delete the user_id from the session table
    $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
		WHERE ' . $db->sql_in_set('session_user_id', $user_ids);
    $db->sql_query($sql);
    // Clean the private messages tables from the user
    if (!function_exists('phpbb_delete_user_pms')) {
        include $phpbb_root_path . 'includes/functions_privmsgs.' . $phpEx;
    }
    phpbb_delete_users_pms($user_ids);
    $phpbb_notifications = $phpbb_container->get('notification_manager');
    $phpbb_notifications->delete_notifications('notification.type.admin_activate_user', $user_ids);
    $db->sql_transaction('commit');
    /**
     * Event after a user is deleted
     *
     * @event core.delete_user_after
     * @var	string	mode		Mode of deletion (retain/delete posts)
     * @var	array	user_ids	IDs of the deleted user
     * @var	mixed	retain_username	True if username should be retained
     *				or false if not
     * @since 3.1.0-a1
     */
    $vars = array('mode', 'user_ids', 'retain_username');
    extract($phpbb_dispatcher->trigger_event('core.delete_user_after', compact($vars)));
    // Reset newest user info if appropriate
    if (in_array($config['newest_user_id'], $user_ids)) {
        update_last_username();
    }
    return false;
}
Exemplo n.º 18
0
function disapprove_post($post_id_list)
{
    global $_CLASS, $_CORE_CONFIG, $config;
    if (!($forum_id = check_ids($post_id_list, POSTS_TABLE, 'post_id', 'm_approve'))) {
        trigger_error('NOT_AUTHORIZED');
    }
    $redirect = request_var('redirect', $_CLASS['core_user']->data['session_page']);
    $reason = request_var('reason', '');
    $reason_id = request_var('reason_id', 0);
    $success_msg = $additional_msg = '';
    $s_hidden_fields = build_hidden_fields(array('post_id_list' => $post_id_list, 'f' => $forum_id, 'mode' => 'disapprove', 'redirect' => $redirect));
    $notify_poster = isset($_REQUEST['notify_poster']) ? true : false;
    if ($reason_id) {
        $sql = 'SELECT reason_name 
			FROM ' . REASONS_TABLE . " \n\t\t\tWHERE reason_id = {$reason_id}";
        $result = $_CLASS['core_db']->query($sql);
        if (!($row = $_CLASS['core_db']->fetch_row_assoc($result)) || !$reason && $row['reason_name'] == 'other') {
            $additional_msg = 'Please give an appropiate reason for disapproval';
            unset($_POST['confirm']);
        } else {
            $disapprove_reason = $row['reason_name'] != 'other' ? $_CLASS['core_user']->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_name'])] : '';
            $disapprove_reason .= $reason ? "\n\n" . $_REQUEST['reason'] : '';
            unset($reason);
        }
        $_CLASS['core_db']->free_result($result);
    }
    if (confirm_box(true)) {
        $post_info = get_post_data($post_id_list, 'm_approve');
        // If Topic -> forum_topics_real -= 1
        // If Post -> topic_replies_real -= 1
        $forum_topics_real = 0;
        $topic_replies_real_sql = $post_disapprove_sql = $topic_id_list = array();
        foreach ($post_info as $post_id => $post_data) {
            $topic_id_list[$post_data['topic_id']] = 1;
            // Topic or Post. ;)
            if ($post_data['topic_first_post_id'] == $post_id && $post_data['topic_last_post_id'] == $post_id) {
                if ($post_data['forum_id']) {
                    $forum_topics_real++;
                }
            } else {
                if (!isset($topic_replies_real_sql[$post_data['topic_id']])) {
                    $topic_replies_real_sql[$post_data['topic_id']] = 1;
                } else {
                    $topic_replies_real_sql[$post_data['topic_id']]++;
                }
            }
            $post_disapprove_sql[] = $post_id;
        }
        if ($forum_topics_real) {
            $sql = 'UPDATE ' . FORUMS_TABLE . "\n\t\t\t\tSET forum_topics_real = forum_topics_real - {$forum_topics_real}\n\t\t\t\tWHERE forum_id = {$forum_id}";
            $_CLASS['core_db']->query($sql);
        }
        if (sizeof($topic_replies_real_sql)) {
            foreach ($topic_replies_real_sql as $topic_id => $num_replies) {
                $sql = 'UPDATE ' . TOPICS_TABLE . "\n\t\t\t\t\tSET topic_replies_real = topic_replies_real - {$num_replies}\n\t\t\t\t\tWHERE topic_id = {$topic_id}";
                $_CLASS['core_db']->query($sql);
            }
        }
        if (sizeof($post_disapprove_sql)) {
            // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts
            delete_posts('post_id', $post_disapprove_sql);
        }
        unset($post_disapprove_sql, $topic_replies_real_sql);
        update_post_information('topic', array_keys($topic_id_list));
        update_post_information('forum', $forum_id);
        unset($topic_id_list);
        $messenger = new messenger();
        // Notify Poster?
        if ($notify_poster) {
            $email_sig = str_replace('<br />', "\n", "-- \n" . $config['board_email_sig']);
            foreach ($post_info as $post_id => $post_data) {
                if ($post_data['poster_id'] == ANONYMOUS) {
                    continue;
                }
                $email_template = $post_data['post_id'] == $post_data['topic_first_post_id'] && $post_data['post_id'] == $post_data['topic_last_post_id'] ? 'topic_disapproved' : 'post_disapproved';
                $messenger->template($email_template, $post_data['user_lang']);
                $messenger->replyto($config['board_email']);
                $messenger->to($post_data['user_email'], $post_data['username']);
                $messenger->im($post_data['user_jabber'], $post_data['username']);
                $messenger->assign_vars(array('EMAIL_SIG' => $email_sig, 'SITENAME' => $_CORE_CONFIG['global']['sitename'], 'USERNAME' => $post_data['username'], 'REASON' => stripslashes($disapprove_reason), 'POST_SUBJECT' => censor_text($post_data['post_subject']), 'TOPIC_TITLE' => censor_text($post_data['topic_title'])));
                $messenger->send($post_data['user_notify_type']);
                $messenger->reset();
            }
            $messenger->save_queue();
        }
        unset($post_info, $disapprove_reason);
        if ($forum_topics_real) {
            $success_msg = $forum_topics_real == 1 ? 'TOPIC_DISAPPROVED_SUCCESS' : 'TOPICS_DISAPPROVED_SUCCESS';
        } else {
            $success_msg = sizeof($post_id_list) == 1 ? 'POST_DISAPPROVED_SUCCESS' : 'POSTS_DISAPPROVED_SUCCESS';
        }
    } else {
        $sql = 'SELECT * 
			FROM ' . REASONS_TABLE . ' 
			ORDER BY reason_priority ASC';
        $result = $_CLASS['core_db']->query($sql);
        while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
            $row['reason_name'] = strtoupper($row['reason_name']);
            $reason_title = !empty($_CLASS['core_user']->lang['report_reasons']['TITLE'][$row['reason_name']]) ? $_CLASS['core_user']->lang['report_reasons']['TITLE'][$row['reason_name']] : ucwords(str_replace('_', ' ', $row['reason_name']));
            $reason_desc = !empty($_CLASS['core_user']->lang['report_reasons']['DESCRIPTION'][$row['reason_name']]) ? $_CLASS['core_user']->lang['report_reasons']['DESCRIPTION'][$row['reason_name']] : $row['reason_desc'];
            $_CLASS['core_template']->assign_vars_array('reason', array('ID' => $row['reason_id'], 'NAME' => htmlspecialchars($reason_title), 'DESCRIPTION' => htmlspecialchars($reason_desc), 'S_SELECTED' => $row['reason_id'] == $reason_id ? true : false));
        }
        $_CLASS['core_db']->free_result($result);
        $_CLASS['core_template']->assign_array(array('S_NOTIFY_POSTER' => true, 'S_APPROVE' => false, 'REASON' => $reason, 'ADDITIONAL_MSG' => $additional_msg));
        confirm_box(false, 'DISAPPROVE_POST' . (sizeof($post_id_list) == 1 ? '' : 'S'), $s_hidden_fields, 'mcp_approve.html');
    }
    $redirect = request_var('redirect', generate_link('Forums'));
    if (!$success_msg) {
        url_redirect($redirect);
    } else {
        $_CLASS['core_display']->meta_refresh(3, generate_link("Forums&amp;file=viewforum&amp;f={$forum_id}"));
        trigger_error($_CLASS['core_user']->lang[$success_msg] . '<br /><br />' . sprintf($_CLASS['core_user']->lang['RETURN_FORUM'], '<a href="' . generate_link('Forums&amp;file=viewforum&amp;f=' . $forum_id) . '">', '</a>'));
    }
}
/**
* Delete Post
*/
function delete_post($forum_id, $topic_id, $post_id, &$data)
{
    global $db, $user, $auth;
    global $config, $phpEx, $phpbb_root_path;
    // Specify our post mode
    $post_mode = 'delete';
    if ($data['topic_first_post_id'] === $data['topic_last_post_id'] && $data['topic_replies_real'] == 0) {
        $post_mode = 'delete_topic';
    } else {
        if ($data['topic_first_post_id'] == $post_id) {
            $post_mode = 'delete_first_post';
        } else {
            if ($data['topic_last_post_id'] == $post_id) {
                $post_mode = 'delete_last_post';
            }
        }
    }
    $sql_data = array();
    $next_post_id = false;
    include_once $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
    $db->sql_transaction('begin');
    // we must make sure to update forums that contain the shadow'd topic
    if ($post_mode == 'delete_topic') {
        $shadow_forum_ids = array();
        $sql = 'SELECT forum_id
			FROM ' . TOPICS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_moved_id', $topic_id);
        $result = $db->sql_query($sql);
        while ($row = $db->sql_fetchrow($result)) {
            if (!isset($shadow_forum_ids[(int) $row['forum_id']])) {
                $shadow_forum_ids[(int) $row['forum_id']] = 1;
            } else {
                $shadow_forum_ids[(int) $row['forum_id']]++;
            }
        }
        $db->sql_freeresult($result);
    }
    if (!delete_posts('post_id', array($post_id), false, false)) {
        // Try to delete topic, we may had an previous error causing inconsistency
        if ($post_mode == 'delete_topic') {
            delete_topics('topic_id', array($topic_id), false);
        }
        trigger_error('ALREADY_DELETED');
    }
    $db->sql_transaction('commit');
    // Collect the necessary information for updating the tables
    $sql_data[FORUMS_TABLE] = '';
    switch ($post_mode) {
        case 'delete_topic':
            foreach ($shadow_forum_ids as $updated_forum => $topic_count) {
                // counting is fun! we only have to do sizeof($forum_ids) number of queries,
                // even if the topic is moved back to where its shadow lives (we count how many times it is in a forum)
                $db->sql_query('UPDATE ' . FORUMS_TABLE . ' SET forum_topics_real = forum_topics_real - ' . $topic_count . ', forum_topics = forum_topics - ' . $topic_count . ' WHERE forum_id = ' . $updated_forum);
                update_post_information('forum', $updated_forum);
            }
            delete_topics('topic_id', array($topic_id), false);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_TABLE] .= 'forum_topics_real = forum_topics_real - 1';
                $sql_data[FORUMS_TABLE] .= $data['topic_approved'] ? ', forum_posts = forum_posts - 1, forum_topics = forum_topics - 1' : '';
            }
            $update_sql = update_post_information('forum', $forum_id, true);
            if (sizeof($update_sql)) {
                $sql_data[FORUMS_TABLE] .= $sql_data[FORUMS_TABLE] ? ', ' : '';
                $sql_data[FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
            }
            break;
        case 'delete_first_post':
            $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username, u.user_colour
				FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . " u\n\t\t\t\tWHERE p.topic_id = {$topic_id}\n\t\t\t\t\tAND p.poster_id = u.user_id\n\t\t\t\tORDER BY p.post_time ASC";
            $result = $db->sql_query_limit($sql, 1);
            $row = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_TABLE] = $data['post_approved'] ? 'forum_posts = forum_posts - 1' : '';
            }
            $sql_data[TOPICS_TABLE] = 'topic_poster = ' . intval($row['poster_id']) . ', topic_first_post_id = ' . intval($row['post_id']) . ", topic_first_poster_colour = '" . $db->sql_escape($row['user_colour']) . "', topic_first_poster_name = '" . ($row['poster_id'] == ANONYMOUS ? $db->sql_escape($row['post_username']) : $db->sql_escape($row['username'])) . "', topic_time = " . (int) $row['post_time'];
            // Decrementing topic_replies here is fine because this case only happens if there is more than one post within the topic - basically removing one "reply"
            $sql_data[TOPICS_TABLE] .= ', topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
            break;
        case 'delete_last_post':
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_TABLE] = $data['post_approved'] ? 'forum_posts = forum_posts - 1' : '';
            }
            $update_sql = update_post_information('forum', $forum_id, true);
            if (sizeof($update_sql)) {
                $sql_data[FORUMS_TABLE] .= $sql_data[FORUMS_TABLE] ? ', ' : '';
                $sql_data[FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
            }
            $sql_data[TOPICS_TABLE] = 'topic_bumped = 0, topic_bumper = 0, topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $update_sql = update_post_information('topic', $topic_id, true);
            if (sizeof($update_sql)) {
                $sql_data[TOPICS_TABLE] .= ', ' . implode(', ', $update_sql[$topic_id]);
                $next_post_id = (int) str_replace('topic_last_post_id = ', '', $update_sql[$topic_id][0]);
            } else {
                $sql = 'SELECT MAX(post_id) as last_post_id
					FROM ' . POSTS_TABLE . "\n\t\t\t\t\tWHERE topic_id = {$topic_id} " . (!$auth->acl_get('m_approve', $forum_id) ? 'AND post_approved = 1' : '');
                $result = $db->sql_query($sql);
                $row = $db->sql_fetchrow($result);
                $db->sql_freeresult($result);
                $next_post_id = (int) $row['last_post_id'];
            }
            break;
        case 'delete':
            $sql = 'SELECT post_id
				FROM ' . POSTS_TABLE . "\n\t\t\t\tWHERE topic_id = {$topic_id} " . (!$auth->acl_get('m_approve', $forum_id) ? 'AND post_approved = 1' : '') . '
					AND post_time > ' . $data['post_time'] . '
				ORDER BY post_time ASC';
            $result = $db->sql_query_limit($sql, 1);
            $row = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_TABLE] = $data['post_approved'] ? 'forum_posts = forum_posts - 1' : '';
            }
            $sql_data[TOPICS_TABLE] = 'topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
            break;
    }
    if ($post_mode == 'delete' || $post_mode == 'delete_last_post' || $post_mode == 'delete_first_post') {
        $sql = 'SELECT 1 AS has_attachments
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE topic_id = ' . $topic_id;
        $result = $db->sql_query_limit($sql, 1);
        $has_attachments = (int) $db->sql_fetchfield('has_attachments');
        $db->sql_freeresult($result);
        if (!$has_attachments) {
            $sql_data[TOPICS_TABLE] .= ', topic_attachment = 0';
        }
    }
    //	$sql_data[USERS_TABLE] = ($data['post_postcount']) ? 'user_posts = user_posts - 1' : '';
    $db->sql_transaction('begin');
    $where_sql = array(FORUMS_TABLE => "forum_id = {$forum_id}", TOPICS_TABLE => "topic_id = {$topic_id}", USERS_TABLE => 'user_id = ' . $data['poster_id']);
    foreach ($sql_data as $table => $update_sql) {
        if ($update_sql) {
            $db->sql_query("UPDATE {$table} SET {$update_sql} WHERE " . $where_sql[$table]);
        }
    }
    // Adjust posted info for this user by looking for a post by him/her within this topic...
    if ($post_mode != 'delete_topic' && $config['load_db_track'] && $data['poster_id'] != ANONYMOUS) {
        $sql = 'SELECT poster_id
			FROM ' . POSTS_TABLE . '
			WHERE topic_id = ' . $topic_id . '
				AND poster_id = ' . $data['poster_id'];
        $result = $db->sql_query_limit($sql, 1);
        $poster_id = (int) $db->sql_fetchfield('poster_id');
        $db->sql_freeresult($result);
        // The user is not having any more posts within this topic
        if (!$poster_id) {
            $sql = 'DELETE FROM ' . TOPICS_POSTED_TABLE . '
				WHERE topic_id = ' . $topic_id . '
					AND user_id = ' . $data['poster_id'];
            $db->sql_query($sql);
        }
    }
    $db->sql_transaction('commit');
    if ($data['post_reported'] && $post_mode != 'delete_topic') {
        sync('topic_reported', 'topic_id', array($topic_id));
    }
    return $next_post_id;
}
Exemplo n.º 20
0
 function delete()
 {
     if (!$this->post_id) {
         trigger_error('NO_POST', E_USER_ERROR);
     }
     $ret = delete_posts('post_id', $this->post_id);
     //remove references to the deleted post so calls to submit() will create a
     //new post instead of trying to update the post which does not exist anymore
     $this->post_id = NULL;
     return $ret;
 }
function sync($mode, $where_type = '', $where_ids = '', $resync_parents = FALSE, $sync_extra = FALSE)
{
    global $_CLASS;
    if (is_array($where_ids)) {
        $where_ids = array_unique($where_ids);
    } elseif ($where_type != 'range') {
        $where_ids = $where_ids ? array($where_ids) : array();
    }
    if ($mode == 'forum' || $mode == 'topic') {
        if (!$where_type) {
            $where_sql = '';
            $where_sql_and = 'WHERE';
        } elseif ($where_type == 'range') {
            // Only check a range of topics/forums. For instance: 'topic_id BETWEEN 1 AND 60'
            $where_sql = 'WHERE (' . $mode[0] . ".{$where_ids})";
            $where_sql_and = $where_sql . "\n\tAND";
        } else {
            if (!sizeof($where_ids)) {
                // Empty array with IDs. This means that we don't have any work to do. Just return.
                return;
            }
            // Limit the topics/forums we are syncing, use specific topic/forum IDs.
            // $where_type contains the field for the where clause (forum_id, topic_id)
            $where_sql = 'WHERE ' . $mode[0] . ".{$where_type} IN (" . implode(', ', $where_ids) . ')';
            $where_sql_and = $where_sql . "\n\tAND";
        }
    } else {
        if (!sizeof($where_ids)) {
            return;
        }
        // $where_type contains the field for the where clause (forum_id, topic_id)
        $where_sql = 'WHERE ' . $mode[0] . ".{$where_type} IN (" . implode(', ', $where_ids) . ')';
        $where_sql_and = $where_sql . "\n\tAND";
    }
    switch ($mode) {
        case 'topic_moved':
            switch ($_CLASS['core_db']->db_layer) {
                case 'mysql4':
                case 'mysqli':
                    $sql = 'DELETE FROM ' . FORUMS_TOPICS_TABLE . '
						USING ' . FORUMS_TOPICS_TABLE . ' t1, ' . FORUMS_TOPICS_TABLE . " t2\n\t\t\t\t\t\tWHERE t1.topic_moved_id = t2.topic_id\n\t\t\t\t\t\t\tAND t1.forum_id = t2.forum_id";
                    $_CLASS['core_db']->query($sql);
                    break;
                default:
                    $sql = 'SELECT t1.topic_id
						FROM ' . FORUMS_TOPICS_TABLE . ' t1, ' . FORUMS_TOPICS_TABLE . " t2\n\t\t\t\t\t\tWHERE t1.topic_moved_id = t2.topic_id\n\t\t\t\t\t\t\tAND t1.forum_id = t2.forum_id";
                    $result = $_CLASS['core_db']->query($sql);
                    if ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                        $topic_id_ary = array();
                        do {
                            $topic_id_ary[] = $row['topic_id'];
                        } while ($row = $_CLASS['core_db']->fetch_row_assoc($result));
                        $sql = 'DELETE FROM ' . TOPICS_TABLE . '
							WHERE topic_id IN (' . implode(', ', $topic_id_ary) . ')';
                        $_CLASS['core_db']->query($sql);
                        unset($topic_id_ary);
                    }
                    $_CLASS['core_db']->free_result($result);
            }
            break;
        case 'topic_approved':
            switch ($_CLASS['core_db']->db_layer) {
                case 'mysql4':
                case 'mysqli':
                    $sql = 'UPDATE ' . FORUMS_TOPICS_TABLE . ' t, ' . FORUMS_POSTS_TABLE . " p\n\t\t\t\t\t\tSET t.topic_approved = p.post_approved\n\t\t\t\t\t\t{$where_sql_and} t.topic_first_post_id = p.post_id";
                    $_CLASS['core_db']->query($sql);
                    break;
                default:
                    $sql = 'SELECT t.topic_id, p.post_approved
						FROM ' . FORUMS_TOPICS_TABLE . ' t, ' . FORUMS_POSTS_TABLE . " p\n\t\t\t\t\t\t{$where_sql_and} p.post_id = t.topic_first_post_id\n\t\t\t\t\t\t\tAND p.post_approved <> t.topic_approved";
                    $result = $_CLASS['core_db']->query($sql);
                    $topic_ids = array();
                    while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                        $topic_ids[] = $row['topic_id'];
                    }
                    $_CLASS['core_db']->free_result();
                    if (!sizeof($topic_ids)) {
                        return;
                    }
                    $sql = 'UPDATE ' . FORUMS_TOPICS_TABLE . '
						SET topic_approved = 1 - topic_approved
						WHERE topic_id IN (' . implode(', ', $topic_ids) . ')';
                    $_CLASS['core_db']->query($sql);
            }
            break;
        case 'post_reported':
            $post_ids = $post_reported = array();
            $sql = 'SELECT p.post_id, p.post_reported
				FROM ' . FORUMS_POSTS_TABLE . " p\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY p.post_id, p.post_reported";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $post_ids[$row['post_id']] = $row['post_id'];
                if ($row['post_reported']) {
                    $post_reported[$row['post_id']] = 1;
                }
            }
            $sql = 'SELECT DISTINCT(post_id)
				FROM ' . FORUMS_REPORTS_TABLE . '
				WHERE post_id IN (' . implode(', ', $post_ids) . ')';
            $result = $_CLASS['core_db']->query($sql);
            $post_ids = array();
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if (!isset($post_reported[$row['post_id']])) {
                    $post_ids[] = $row['post_id'];
                } else {
                    unset($post_reported[$row['post_id']]);
                }
            }
            // $post_reported should be empty by now, if it's not it contains
            // posts that are falsely flagged as reported
            foreach ($post_reported as $post_id => $void) {
                $post_ids[] = $post_id;
            }
            if (sizeof($post_ids)) {
                $sql = 'UPDATE ' . FORUMS_POSTS_TABLE . '
					SET post_reported = 1 - post_reported
					WHERE post_id IN (' . implode(', ', $post_ids) . ')';
                $_CLASS['core_db']->query($sql);
            }
            break;
        case 'topic_reported':
            if ($sync_extra) {
                sync('post_reported', $where_type, $where_ids);
            }
            $topic_ids = $topic_reported = array();
            $sql = 'SELECT DISTINCT(t.topic_id)
				FROM ' . FORUMS_POSTS_TABLE . " t\n\t\t\t\t{$where_sql_and} t.post_reported = 1";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_reported[$row['topic_id']] = 1;
            }
            $sql = 'SELECT t.topic_id, t.topic_reported
				FROM ' . FORUMS_TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if ($row['topic_reported'] ^ isset($topic_reported[$row['topic_id']])) {
                    $topic_ids[] = $row['topic_id'];
                }
            }
            if (sizeof($topic_ids)) {
                $sql = 'UPDATE ' . FORUMS_TOPICS_TABLE . '
					SET topic_reported = 1 - topic_reported
					WHERE topic_id IN (' . implode(', ', $topic_ids) . ')';
                $_CLASS['core_db']->query($sql);
            }
            break;
        case 'post_attachment':
            $post_ids = $post_attachment = array();
            $sql = 'SELECT p.post_id, p.post_attachment
				FROM ' . FORUMS_POSTS_TABLE . " p\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY p.post_id, p.post_attachment";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $post_ids[$row['post_id']] = $row['post_id'];
                if ($row['post_attachment']) {
                    $post_attachment[$row['post_id']] = 1;
                }
            }
            $sql = 'SELECT DISTINCT(post_msg_id)
				FROM ' . FORUMS_ATTACHMENTS_TABLE . '
				WHERE post_msg_id IN (' . implode(', ', $post_ids) . ')
					AND in_message = 0';
            $post_ids = array();
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if (!isset($post_attachment[$row['post_id']])) {
                    $post_ids[] = $row['post_id'];
                } else {
                    unset($post_attachment[$row['post_id']]);
                }
            }
            // $post_attachment should be empty by now, if it's not it contains
            // posts that are falsely flagged as having attachments
            foreach ($post_attachment as $post_id => $void) {
                $post_ids[] = $post_id;
            }
            if (sizeof($post_ids)) {
                $sql = 'UPDATE ' . FORUMS_POSTS_TABLE . '
					SET post_attachment = 1 - post_attachment
					WHERE post_id IN (' . implode(', ', $post_ids) . ')';
                $_CLASS['core_db']->query($sql);
            }
            break;
        case 'topic_attachment':
            if ($sync_extra) {
                sync('post_attachment', $where_type, $where_ids);
            }
            $topic_ids = $topic_attachment = array();
            $sql = 'SELECT DISTINCT(t.topic_id)
				FROM ' . FORUMS_POSTS_TABLE . " t\n\t\t\t\t{$where_sql_and} t.post_attachment = 1";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_attachment[$row['topic_id']] = 1;
            }
            $sql = 'SELECT t.topic_id, t.topic_attachment
				FROM ' . FORUMS_TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if ($row['topic_attachment'] ^ isset($topic_attachment[$row['topic_id']])) {
                    $topic_ids[] = $row['topic_id'];
                }
            }
            if (sizeof($topic_ids)) {
                $sql = 'UPDATE ' . FORUMS_TOPICS_TABLE . '
					SET topic_attachment = 1 - topic_attachment
					WHERE topic_id IN (' . implode(', ', $topic_ids) . ')';
                $_CLASS['core_db']->query($sql);
            }
            break;
        case 'forum':
            // 1: Get the list of all forums
            $sql = 'SELECT f.*
				FROM ' . FORUMS_FORUMS_TABLE . " f\n\t\t\t\t{$where_sql}";
            $result = $_CLASS['core_db']->query($sql);
            $forum_data = $forum_ids = $post_ids = $last_post_id = $post_info = array();
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if ($row['forum_type'] == FORUM_LINK) {
                    continue;
                }
                $forum_id = (int) $row['forum_id'];
                $forum_ids[$forum_id] = $forum_id;
                $forum_data[$forum_id] = $row;
                $forum_data[$forum_id]['posts'] = 0;
                $forum_data[$forum_id]['topics'] = 0;
                $forum_data[$forum_id]['topics_real'] = 0;
                $forum_data[$forum_id]['last_post_id'] = 0;
                $forum_data[$forum_id]['last_post_time'] = 0;
                $forum_data[$forum_id]['last_poster_id'] = 0;
                $forum_data[$forum_id]['last_poster_name'] = '';
            }
            // 2: Get topic counts for each forum
            $sql = 'SELECT forum_id, topic_approved, COUNT(topic_id) AS forum_topics
				FROM ' . FORUMS_TOPICS_TABLE . '
				WHERE forum_id IN (' . implode(', ', $forum_ids) . ')
				GROUP BY forum_id, topic_approved';
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $forum_id = (int) $row['forum_id'];
                $forum_data[$forum_id]['topics_real'] += $row['forum_topics'];
                if ($row['topic_approved']) {
                    $forum_data[$forum_id]['topics'] = $row['forum_topics'];
                }
            }
            // 3: Get post count and last_post_id for each forum
            $sql = 'SELECT forum_id, COUNT(post_id) AS forum_posts, MAX(post_id) AS last_post_id
				FROM ' . FORUMS_POSTS_TABLE . '
				WHERE forum_id IN (' . implode(', ', $forum_ids) . ')
					AND post_approved = 1
				GROUP BY forum_id';
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $forum_id = (int) $row['forum_id'];
                $forum_data[$forum_id]['posts'] = intval($row['forum_posts']);
                $forum_data[$forum_id]['last_post_id'] = intval($row['last_post_id']);
                $post_ids[] = $row['last_post_id'];
            }
            // 4: Retrieve last_post infos
            if (sizeof($post_ids)) {
                $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username
					FROM ' . FORUMS_POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
					WHERE p.post_id IN (' . implode(', ', $post_ids) . ')
						AND p.poster_id = u.user_id';
                $result = $_CLASS['core_db']->query($sql);
                while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                    $post_info[intval($row['post_id'])] = $row;
                }
                $_CLASS['core_db']->free_result($result);
                foreach ($forum_data as $forum_id => $data) {
                    if ($data['last_post_id']) {
                        if (isset($post_info[$data['last_post_id']])) {
                            $forum_data[$forum_id]['last_post_time'] = $post_info[$data['last_post_id']]['post_time'];
                            $forum_data[$forum_id]['last_poster_id'] = $post_info[$data['last_post_id']]['poster_id'];
                            $forum_data[$forum_id]['last_poster_name'] = $post_info[$data['last_post_id']]['poster_id'] != ANONYMOUS ? $post_info[$data['last_post_id']]['username'] : $post_info[$data['last_post_id']]['post_username'];
                        } else {
                            // For some reason we did not find the post in the db
                            $forum_data[$forum_id]['last_post_id'] = 0;
                            $forum_data[$forum_id]['last_post_time'] = 0;
                            $forum_data[$forum_id]['last_poster_id'] = 0;
                            $forum_data[$forum_id]['last_poster_name'] = '';
                        }
                    }
                }
                unset($post_info);
            }
            // 5: Now do that thing
            $fieldnames = array('posts', 'topics', 'topics_real', 'last_post_id', 'last_post_time', 'last_poster_id', 'last_poster_name');
            foreach ($forum_data as $forum_id => $row) {
                $sql = array();
                foreach ($fieldnames as $fieldname) {
                    if ($row['forum_' . $fieldname] != $row[$fieldname]) {
                        if (preg_match('#name$#', $fieldname)) {
                            $sql['forum_' . $fieldname] = (string) $row[$fieldname];
                        } else {
                            $sql['forum_' . $fieldname] = (int) $row[$fieldname];
                        }
                    }
                }
                if (sizeof($sql)) {
                    $sql = 'UPDATE ' . FORUMS_FORUMS_TABLE . '
						SET ' . $_CLASS['core_db']->sql_build_array('UPDATE', $sql) . '
						WHERE forum_id = ' . $forum_id;
                    $_CLASS['core_db']->query($sql);
                }
            }
            break;
        case 'topic':
            $topic_data = $post_ids = $approved_unapproved_ids = $resync_forums = $delete_topics = $delete_posts = array();
            $sql = 'SELECT t.topic_id, t.forum_id, t.topic_approved, ' . ($sync_extra ? 't.topic_attachment, t.topic_reported, ' : '') . 't.topic_poster, t.topic_time, t.topic_replies, t.topic_replies_real, t.topic_first_post_id, t.topic_first_poster_name, t.topic_last_post_id, t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_post_time
				FROM ' . FORUMS_TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_id = (int) $row['topic_id'];
                $topic_data[$topic_id] = $row;
                $topic_data[$topic_id]['replies_real'] = -1;
                $topic_data[$topic_id]['first_post_id'] = 0;
                $topic_data[$topic_id]['last_post_id'] = 0;
                unset($topic_data[$topic_id]['topic_id']);
                // This array holds all topic_ids
                $delete_topics[$topic_id] = '';
                if ($sync_extra) {
                    $topic_data[$topic_id]['reported'] = 0;
                    $topic_data[$topic_id]['attachment'] = 0;
                }
            }
            $_CLASS['core_db']->free_result($result);
            // Use "t" as table alias because of the $where_sql clause
            // NOTE: 't.post_approved' in the GROUP BY is causing a major slowdown.
            $sql = 'SELECT t.topic_id, t.post_approved, COUNT(t.post_id) AS total_posts, MIN(t.post_id) AS first_post_id, MAX(t.post_id) AS last_post_id
				FROM ' . FORUMS_POSTS_TABLE . " t\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY t.topic_id";
            //, t.post_approved";
            $result = $_CLASS['core_db']->query($sql);
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_id = (int) $row['topic_id'];
                $row['first_post_id'] = (int) $row['first_post_id'];
                $row['last_post_id'] = (int) $row['last_post_id'];
                if (!isset($topic_data[$topic_id])) {
                    // Hey, these posts come from a topic that does not exist
                    $delete_posts[$topic_id] = '';
                } else {
                    // Unset the corresponding entry in $delete_topics
                    // When we'll be done, only topics with no posts will remain
                    unset($delete_topics[$topic_id]);
                    $topic_data[$topic_id]['replies_real'] += $row['total_posts'];
                    $topic_data[$topic_id]['first_post_id'] = !$topic_data[$topic_id]['first_post_id'] ? $row['first_post_id'] : min($topic_data[$topic_id]['first_post_id'], $row['first_post_id']);
                    if ($row['post_approved'] || !$topic_data[$topic_id]['last_post_id']) {
                        $topic_data[$topic_id]['replies'] = $row['total_posts'] - 1;
                        $topic_data[$topic_id]['last_post_id'] = $row['last_post_id'];
                    }
                }
            }
            $_CLASS['core_db']->free_result($result);
            foreach ($topic_data as $topic_id => $row) {
                $post_ids[] = $row['first_post_id'];
                if ($row['first_post_id'] != $row['last_post_id']) {
                    $post_ids[] = $row['last_post_id'];
                }
            }
            // Now we delete empty topics and orphan posts
            if (sizeof($delete_posts)) {
                delete_posts('topic_id', array_keys($delete_posts), FALSE);
                unset($delete_posts);
            }
            if (!sizeof($topic_data)) {
                // If we get there, topic ids were invalid or topics did not contain any posts
                delete_topics($where_type, $where_ids, TRUE);
                return;
            }
            if (sizeof($delete_topics)) {
                $delete_topic_ids = array();
                foreach ($delete_topics as $topic_id => $void) {
                    unset($topic_data[$topic_id]);
                    $delete_topic_ids[] = $topic_id;
                }
                delete_topics('topic_id', $delete_topic_ids, FALSE);
                unset($delete_topics, $delete_topic_ids);
            }
            $sql = 'SELECT p.post_id, p.topic_id, p.post_approved, p.poster_id, p.post_username, p.post_time, u.username
				FROM ' . FORUMS_POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
				WHERE p.post_id IN (' . implode(',', $post_ids) . ')
					AND u.user_id = p.poster_id';
            $result = $_CLASS['core_db']->query($sql);
            $post_ids = array();
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_id = intval($row['topic_id']);
                if ($row['post_id'] == $topic_data[$topic_id]['first_post_id']) {
                    if ($topic_data[$topic_id]['topic_approved'] != $row['post_approved']) {
                        $approved_unapproved_ids[] = $topic_id;
                    }
                    $topic_data[$topic_id]['time'] = $row['post_time'];
                    $topic_data[$topic_id]['poster'] = $row['poster_id'];
                    $topic_data[$topic_id]['first_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                }
                if ($row['post_id'] == $topic_data[$topic_id]['last_post_id']) {
                    $topic_data[$topic_id]['last_poster_id'] = $row['poster_id'];
                    $topic_data[$topic_id]['last_post_time'] = $row['post_time'];
                    $topic_data[$topic_id]['last_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                }
            }
            $_CLASS['core_db']->free_result($result);
            // approved becomes unapproved, and vice-versa
            if (sizeof($approved_unapproved_ids)) {
                $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_approved = 1 - topic_approved
					WHERE topic_id IN (' . implode(', ', $approved_unapproved_ids) . ')';
                $_CLASS['core_db']->query($sql);
            }
            unset($approved_unapproved_ids);
            // These are fields that will be synchronised
            $fieldnames = array('time', 'replies', 'replies_real', 'poster', 'first_post_id', 'first_poster_name', 'last_post_id', 'last_post_time', 'last_poster_id', 'last_poster_name');
            if ($sync_extra) {
                // This routine assumes that post_reported values are correct
                // if they are not, use sync('post_reported') first
                $sql = 'SELECT t.topic_id, p.post_id
					FROM ' . FORUMS_TOPICS_TABLE . ' t, ' . FORUMS_POSTS_TABLE . " p\n\t\t\t\t\t{$where_sql_and} p.topic_id = t.topic_id\n\t\t\t\t\t\tAND p.post_reported = 1\n\t\t\t\t\tGROUP BY t.topic_id";
                $result = $_CLASS['core_db']->query($sql);
                $fieldnames[] = 'reported';
                while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                    $topic_data[intval($row['topic_id'])]['reported'] = 1;
                }
                $_CLASS['core_db']->free_result($result);
                // This routine assumes that post_attachment values are correct
                // if they are not, use sync('post_attachment') first
                $sql = 'SELECT t.topic_id, p.post_id
					FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p\n\t\t\t\t\t{$where_sql_and} p.topic_id = t.topic_id\n\t\t\t\t\t\tAND p.post_attachment = 1\n\t\t\t\t\tGROUP BY t.topic_id";
                $result = $_CLASS['core_db']->query($sql);
                $fieldnames[] = 'attachment';
                while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                    $topic_data[intval($row['topic_id'])]['attachment'] = 1;
                }
                $_CLASS['core_db']->free_result($result);
            }
            foreach ($topic_data as $topic_id => $row) {
                $sql = array();
                foreach ($fieldnames as $fieldname) {
                    if ($row['topic_' . $fieldname] != $row[$fieldname]) {
                        $sql['topic_' . $fieldname] = $row[$fieldname];
                    }
                }
                if (sizeof($sql)) {
                    $sql = 'UPDATE ' . TOPICS_TABLE . '
						SET ' . $_CLASS['core_db']->sql_build_array('UPDATE', $sql) . '
						WHERE topic_id = ' . $topic_id;
                    $_CLASS['core_db']->query($sql);
                    $resync_forums[$row['forum_id']] = $row['forum_id'];
                }
            }
            unset($topic_data);
            // if some topics have been resync'ed then resync parent forums
            // except when we're only syncing a range, we don't want to sync forums during
            // batch processing.
            if ($resync_parents && sizeof($resync_forums) && $where_type != 'range') {
                sync('forum', 'forum_id', $resync_forums, TRUE);
            }
            break;
    }
}
Exemplo n.º 22
0
    /**
     * Disapprove Post
     *
     * @param $post_id_list	array	IDs of the posts to disapprove/delete
     * @param $id			mixed	Category of the current active module
     * @param $mode			string	Active module
     * @return null
     */
    public static function disapprove_posts($post_id_list, $id, $mode)
    {
        global $db, $template, $user, $config, $phpbb_container, $phpbb_dispatcher;
        global $phpEx, $phpbb_root_path, $request, $phpbb_log;
        if (!phpbb_check_ids($post_id_list, POSTS_TABLE, 'post_id', array('m_approve'))) {
            trigger_error('NOT_AUTHORISED');
        }
        $redirect = $request->variable('redirect', build_url(array('t', 'mode', 'quickmod')) . "&amp;mode={$mode}");
        $redirect = reapply_sid($redirect);
        $reason = $request->variable('reason', '', true);
        $reason_id = $request->variable('reason_id', 0);
        $success_msg = $additional_msg = '';
        $s_hidden_fields = build_hidden_fields(array('i' => $id, 'mode' => $mode, 'post_id_list' => $post_id_list, 'action' => 'disapprove', 'redirect' => $redirect));
        $notify_poster = $request->is_set('notify_poster');
        $disapprove_reason = '';
        if ($reason_id) {
            $sql = 'SELECT reason_title, reason_description
				FROM ' . REPORTS_REASONS_TABLE . "\n\t\t\t\tWHERE reason_id = {$reason_id}";
            $result = $db->sql_query($sql);
            $row = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            if (!$row || !$reason && strtolower($row['reason_title']) == 'other') {
                $additional_msg = $user->lang['NO_REASON_DISAPPROVAL'];
                $request->overwrite('confirm', null, \phpbb\request\request_interface::POST);
                $request->overwrite('confirm_key', null, \phpbb\request\request_interface::POST);
                $request->overwrite('confirm_key', null, \phpbb\request\request_interface::REQUEST);
            } else {
                // If the reason is defined within the language file, we will use the localized version, else just use the database entry...
                $disapprove_reason = strtolower($row['reason_title']) != 'other' ? isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])]) ? $user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])] : $row['reason_description'] : '';
                $disapprove_reason .= $reason ? "\n\n" . $reason : '';
                if (isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])])) {
                    $disapprove_reason_lang = strtoupper($row['reason_title']);
                }
            }
        }
        $post_info = phpbb_get_post_data($post_id_list, 'm_approve');
        $is_disapproving = false;
        foreach ($post_info as $post_id => $post_data) {
            if ($post_data['post_visibility'] == ITEM_DELETED) {
                continue;
            }
            $is_disapproving = true;
        }
        if (confirm_box(true)) {
            $disapprove_log = $disapprove_log_topics = $disapprove_log_posts = array();
            $topic_posts_unapproved = $post_disapprove_list = $topic_information = array();
            // Build a list of posts to be disapproved and get the related topics real replies count
            foreach ($post_info as $post_id => $post_data) {
                $post_disapprove_list[$post_id] = $post_data['topic_id'];
                if (!isset($topic_posts_unapproved[$post_data['topic_id']])) {
                    $topic_information[$post_data['topic_id']] = $post_data;
                    $topic_posts_unapproved[$post_data['topic_id']] = 0;
                }
                $topic_posts_unapproved[$post_data['topic_id']]++;
            }
            // Now we build the log array
            foreach ($post_disapprove_list as $post_id => $topic_id) {
                // If the count of disapproved posts for the topic is equal
                // to the number of unapproved posts in the topic, and there are no different
                // posts, we disapprove the hole topic
                if ($topic_information[$topic_id]['topic_posts_approved'] == 0 && $topic_information[$topic_id]['topic_posts_softdeleted'] == 0 && $topic_information[$topic_id]['topic_posts_unapproved'] == $topic_posts_unapproved[$topic_id]) {
                    // Don't write the log more than once for every topic
                    if (!isset($disapprove_log_topics[$topic_id])) {
                        // Build disapproved topics log
                        $disapprove_log_topics[$topic_id] = array('type' => 'topic', 'post_subject' => $post_info[$post_id]['topic_title'], 'forum_id' => $post_info[$post_id]['forum_id'], 'topic_id' => 0, 'post_username' => $post_info[$post_id]['poster_id'] == ANONYMOUS && !empty($post_info[$post_id]['post_username']) ? $post_info[$post_id]['post_username'] : $post_info[$post_id]['username']);
                    }
                } else {
                    // Build disapproved posts log
                    $disapprove_log_posts[] = array('type' => 'post', 'post_subject' => $post_info[$post_id]['post_subject'], 'forum_id' => $post_info[$post_id]['forum_id'], 'topic_id' => $post_info[$post_id]['topic_id'], 'post_username' => $post_info[$post_id]['poster_id'] == ANONYMOUS && !empty($post_info[$post_id]['post_username']) ? $post_info[$post_id]['post_username'] : $post_info[$post_id]['username']);
                }
            }
            // Get disapproved posts/topics counts separately
            $num_disapproved_topics = sizeof($disapprove_log_topics);
            $num_disapproved_posts = sizeof($disapprove_log_posts);
            // Build the whole log
            $disapprove_log = array_merge($disapprove_log_topics, $disapprove_log_posts);
            // Unset unneeded arrays
            unset($post_data, $disapprove_log_topics, $disapprove_log_posts);
            // Let's do the job - delete disapproved posts
            if (sizeof($post_disapprove_list)) {
                if (!function_exists('delete_posts')) {
                    include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
                }
                // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts
                // Note: function delete_posts triggers related forums/topics sync,
                // so we don't need to call update_post_information later and to adjust real topic replies or forum topics count manually
                delete_posts('post_id', array_keys($post_disapprove_list));
                foreach ($disapprove_log as $log_data) {
                    if ($is_disapproving) {
                        $l_log_message = $log_data['type'] == 'topic' ? 'LOG_TOPIC_DISAPPROVED' : 'LOG_POST_DISAPPROVED';
                        $phpbb_log->add('mod', $user->data['user_id'], $user->ip, $l_log_message, false, array('forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['post_subject'], $disapprove_reason, $log_data['post_username']));
                    } else {
                        $l_log_message = $log_data['type'] == 'topic' ? 'LOG_DELETE_TOPIC' : 'LOG_DELETE_POST';
                        $phpbb_log->add('mod', $user->data['user_id'], $user->ip, $l_log_message, false, array('forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['post_subject'], $log_data['post_username']));
                    }
                }
            }
            /* @var $phpbb_notifications \phpbb\notification\manager */
            $phpbb_notifications = $phpbb_container->get('notification_manager');
            $lang_reasons = array();
            foreach ($post_info as $post_id => $post_data) {
                $disapprove_all_posts_in_topic = $topic_information[$topic_id]['topic_posts_approved'] == 0 && $topic_information[$topic_id]['topic_posts_softdeleted'] == 0 && $topic_information[$topic_id]['topic_posts_unapproved'] == $topic_posts_unapproved[$topic_id];
                $phpbb_notifications->delete_notifications('notification.type.post_in_queue', $post_id);
                // Do we disapprove the whole topic? Remove potential notifications
                if ($disapprove_all_posts_in_topic) {
                    $phpbb_notifications->delete_notifications('notification.type.topic_in_queue', $post_data['topic_id']);
                }
                // Notify Poster?
                if ($notify_poster) {
                    if ($post_data['poster_id'] == ANONYMOUS) {
                        continue;
                    }
                    $post_data['disapprove_reason'] = $disapprove_reason;
                    if (isset($disapprove_reason_lang)) {
                        // Okay we need to get the reason from the posters language
                        if (!isset($lang_reasons[$post_data['user_lang']])) {
                            // Assign the current users translation as the default, this is not ideal but getting the board default adds another layer of complexity.
                            $lang_reasons[$post_data['user_lang']] = $user->lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang];
                            // Only load up the language pack if the language is different to the current one
                            if ($post_data['user_lang'] != $user->lang_name && file_exists($phpbb_root_path . '/language/' . $post_data['user_lang'] . '/mcp.' . $phpEx)) {
                                // Load up the language pack
                                $lang = array();
                                @(include $phpbb_root_path . '/language/' . basename($post_data['user_lang']) . '/mcp.' . $phpEx);
                                // If we find the reason in this language pack use it
                                if (isset($lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang])) {
                                    $lang_reasons[$post_data['user_lang']] = $lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang];
                                }
                                unset($lang);
                                // Free memory
                            }
                        }
                        $post_data['disapprove_reason'] = $lang_reasons[$post_data['user_lang']];
                        $post_data['disapprove_reason'] .= $reason ? "\n\n" . $reason : '';
                    }
                    if ($disapprove_all_posts_in_topic && $topic_information[$topic_id]['topic_posts_unapproved'] == 1) {
                        // If there is only 1 post when disapproving the topic,
                        // we send the user a "disapprove topic" notification...
                        $phpbb_notifications->add_notifications('notification.type.disapprove_topic', $post_data);
                    } else {
                        // ... otherwise there are multiple unapproved posts and
                        // all of them are disapproved as posts.
                        $phpbb_notifications->add_notifications('notification.type.disapprove_post', $post_data);
                    }
                }
            }
            if ($num_disapproved_topics) {
                $success_msg = $num_disapproved_topics == 1 ? 'TOPIC' : 'TOPICS';
            } else {
                $success_msg = $num_disapproved_posts == 1 ? 'POST' : 'POSTS';
            }
            if ($is_disapproving) {
                $success_msg .= '_DISAPPROVED_SUCCESS';
            } else {
                $success_msg .= '_DELETED_SUCCESS';
            }
            // If we came from viewtopic, we try to go back to it.
            if (strpos($redirect, $phpbb_root_path . 'viewtopic.' . $phpEx) === 0) {
                if ($num_disapproved_topics == 0) {
                    // So we need to remove the post id part from the Url
                    $redirect = str_replace("&amp;p={$post_id_list[0]}#p{$post_id_list[0]}", '', $redirect);
                } else {
                    // However this is only possible if the topic still exists,
                    // Otherwise we go back to the viewforum page
                    $redirect = append_sid($phpbb_root_path . 'viewforum.' . $phpEx, 'f=' . $request->variable('f', 0));
                }
            }
            /**
             * Perform additional actions during post(s) disapproval
             *
             * @event core.disapprove_posts_after
             * @var	array	post_info					Array containing info for all posts being disapproved
             * @var	array	topic_information			Array containing information for the topics
             * @var	array	topic_posts_unapproved		Array containing list of topic ids and the count of disapproved posts in them
             * @var	array	post_disapprove_list		Array containing list of posts and their topic id
             * @var	int		num_disapproved_topics		Variable containing the number of disapproved topics
             * @var	int		num_disapproved_posts		Variable containing the number of disapproved posts
             * @var array	lang_reasons				Array containing the language keys for reasons
             * @var	string	disapprove_reason			Variable containing the language key for the success message
             * @var	string	disapprove_reason_lang		Variable containing the language key for the success message
             * @var bool	is_disapproving				Variable telling if anything is going to be disapproved
             * @var bool	notify_poster				Variable telling if the post should be notified or not
             * @var	string	success_msg					Variable containing the language key for the success message
             * @var string	redirect					Variable containing the redirect url
             * @since 3.1.4-RC1
             */
            $vars = array('post_info', 'topic_information', 'topic_posts_unapproved', 'post_disapprove_list', 'num_disapproved_topics', 'num_disapproved_posts', 'lang_reasons', 'disapprove_reason', 'disapprove_reason_lang', 'is_disapproving', 'notify_poster', 'success_msg', 'redirect');
            extract($phpbb_dispatcher->trigger_event('core.disapprove_posts_after', compact($vars)));
            unset($lang_reasons, $post_info, $disapprove_reason, $disapprove_reason_lang);
            meta_refresh(3, $redirect);
            $message = $user->lang[$success_msg];
            if ($request->is_ajax()) {
                $json_response = new \phpbb\json_response();
                $json_response->send(array('MESSAGE_TITLE' => $user->lang['INFORMATION'], 'MESSAGE_TEXT' => $message, 'REFRESH_DATA' => null, 'visible' => false));
            }
            $message .= '<br /><br />' . $user->lang('RETURN_PAGE', '<a href="' . $redirect . '">', '</a>');
            trigger_error($message);
        } else {
            $show_notify = false;
            foreach ($post_info as $post_data) {
                if ($post_data['poster_id'] == ANONYMOUS) {
                    continue;
                } else {
                    $show_notify = true;
                    break;
                }
            }
            $l_confirm_msg = 'DISAPPROVE_POST';
            $confirm_template = 'mcp_approve.html';
            if ($is_disapproving) {
                $phpbb_container->get('phpbb.report.report_reason_list_provider')->display_reasons($reason_id);
            } else {
                $user->add_lang('posting');
                $l_confirm_msg = 'DELETE_POST_PERMANENTLY';
                $confirm_template = 'confirm_delete_body.html';
            }
            $l_confirm_msg .= sizeof($post_id_list) == 1 ? '' : 'S';
            $template->assign_vars(array('S_NOTIFY_POSTER' => $show_notify, 'S_APPROVE' => false, 'REASON' => $is_disapproving ? $reason : '', 'ADDITIONAL_MSG' => $additional_msg));
            confirm_box(false, $l_confirm_msg, $s_hidden_fields, $confirm_template);
        }
        redirect($redirect);
    }
Exemplo n.º 23
0
/**
* Delete Post
*/
function delete_post($forum_id, $topic_id, $post_id, &$data, $is_soft = false, $softdelete_reason = '')
{
    global $db, $user, $auth, $phpbb_container;
    global $config, $phpEx, $phpbb_root_path;
    // Specify our post mode
    $post_mode = 'delete';
    if ($data['topic_first_post_id'] === $data['topic_last_post_id'] && $data['topic_posts_approved'] + $data['topic_posts_unapproved'] + $data['topic_posts_softdeleted'] == 1) {
        $post_mode = 'delete_topic';
    } else {
        if ($data['topic_first_post_id'] == $post_id) {
            $post_mode = 'delete_first_post';
        } else {
            if ($data['topic_last_post_id'] == $post_id) {
                $post_mode = 'delete_last_post';
            }
        }
    }
    $sql_data = array();
    $next_post_id = false;
    include_once $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
    $db->sql_transaction('begin');
    // we must make sure to update forums that contain the shadow'd topic
    if ($post_mode == 'delete_topic') {
        $shadow_forum_ids = array();
        $sql = 'SELECT forum_id
			FROM ' . TOPICS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_moved_id', $topic_id);
        $result = $db->sql_query($sql);
        while ($row = $db->sql_fetchrow($result)) {
            if (!isset($shadow_forum_ids[(int) $row['forum_id']])) {
                $shadow_forum_ids[(int) $row['forum_id']] = 1;
            } else {
                $shadow_forum_ids[(int) $row['forum_id']]++;
            }
        }
        $db->sql_freeresult($result);
    }
    /* @var $phpbb_content_visibility \phpbb\content_visibility */
    $phpbb_content_visibility = $phpbb_container->get('content.visibility');
    // (Soft) delete the post
    if ($is_soft && $post_mode != 'delete_topic') {
        $phpbb_content_visibility->set_post_visibility(ITEM_DELETED, $post_id, $topic_id, $forum_id, $user->data['user_id'], time(), $softdelete_reason, $data['topic_first_post_id'] == $post_id, $data['topic_last_post_id'] == $post_id);
    } else {
        if (!$is_soft) {
            if (!delete_posts('post_id', array($post_id), false, false, false)) {
                // Try to delete topic, we may had an previous error causing inconsistency
                if ($post_mode == 'delete_topic') {
                    delete_topics('topic_id', array($topic_id), false);
                }
                trigger_error('ALREADY_DELETED');
            }
        }
    }
    $db->sql_transaction('commit');
    // Collect the necessary information for updating the tables
    $sql_data[FORUMS_TABLE] = $sql_data[TOPICS_TABLE] = '';
    switch ($post_mode) {
        case 'delete_topic':
            foreach ($shadow_forum_ids as $updated_forum => $topic_count) {
                // counting is fun! we only have to do sizeof($forum_ids) number of queries,
                // even if the topic is moved back to where its shadow lives (we count how many times it is in a forum)
                $sql = 'UPDATE ' . FORUMS_TABLE . '
					SET forum_topics_approved = forum_topics_approved - ' . $topic_count . '
					WHERE forum_id = ' . $updated_forum;
                $db->sql_query($sql);
                update_post_information('forum', $updated_forum);
            }
            if ($is_soft) {
                $topic_row = array();
                $phpbb_content_visibility->set_topic_visibility(ITEM_DELETED, $topic_id, $forum_id, $user->data['user_id'], time(), $softdelete_reason);
            } else {
                delete_topics('topic_id', array($topic_id), false);
                $phpbb_content_visibility->remove_topic_from_statistic($data, $sql_data);
                $update_sql = update_post_information('forum', $forum_id, true);
                if (sizeof($update_sql)) {
                    $sql_data[FORUMS_TABLE] .= $sql_data[FORUMS_TABLE] ? ', ' : '';
                    $sql_data[FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
                }
            }
            break;
        case 'delete_first_post':
            $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username, u.user_colour
				FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . " u\n\t\t\t\tWHERE p.topic_id = {$topic_id}\n\t\t\t\t\tAND p.poster_id = u.user_id\n\t\t\t\t\tAND p.post_visibility = " . ITEM_APPROVED . '
				ORDER BY p.post_time ASC, p.post_id ASC';
            $result = $db->sql_query_limit($sql, 1);
            $row = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            if (!$row) {
                // No approved post, so the first is a not-approved post (unapproved or soft deleted)
                $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username, u.user_colour
					FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . " u\n\t\t\t\t\tWHERE p.topic_id = {$topic_id}\n\t\t\t\t\t\tAND p.poster_id = u.user_id\n\t\t\t\t\tORDER BY p.post_time ASC, p.post_id ASC";
                $result = $db->sql_query_limit($sql, 1);
                $row = $db->sql_fetchrow($result);
                $db->sql_freeresult($result);
            }
            $next_post_id = (int) $row['post_id'];
            $sql_data[TOPICS_TABLE] = $db->sql_build_array('UPDATE', array('topic_poster' => (int) $row['poster_id'], 'topic_first_post_id' => (int) $row['post_id'], 'topic_first_poster_colour' => $row['user_colour'], 'topic_first_poster_name' => $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'], 'topic_time' => (int) $row['post_time']));
            break;
        case 'delete_last_post':
            if (!$is_soft) {
                // Update last post information when hard deleting. Soft delete already did that by itself.
                $update_sql = update_post_information('forum', $forum_id, true);
                if (sizeof($update_sql)) {
                    $sql_data[FORUMS_TABLE] = ($sql_data[FORUMS_TABLE] ? $sql_data[FORUMS_TABLE] . ', ' : '') . implode(', ', $update_sql[$forum_id]);
                }
                $sql_data[TOPICS_TABLE] = ($sql_data[TOPICS_TABLE] ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_bumped = 0, topic_bumper = 0';
                $update_sql = update_post_information('topic', $topic_id, true);
                if (!empty($update_sql)) {
                    $sql_data[TOPICS_TABLE] .= ', ' . implode(', ', $update_sql[$topic_id]);
                    $next_post_id = (int) str_replace('topic_last_post_id = ', '', $update_sql[$topic_id][0]);
                }
            }
            if (!$next_post_id) {
                $sql = 'SELECT MAX(post_id) as last_post_id
					FROM ' . POSTS_TABLE . "\n\t\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\t\tAND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id);
                $result = $db->sql_query($sql);
                $next_post_id = (int) $db->sql_fetchfield('last_post_id');
                $db->sql_freeresult($result);
            }
            break;
        case 'delete':
            $sql = 'SELECT post_id
				FROM ' . POSTS_TABLE . "\n\t\t\t\tWHERE topic_id = {$topic_id}\n\t\t\t\t\tAND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id) . '
					AND post_time > ' . $data['post_time'] . '
				ORDER BY post_time ASC, post_id ASC';
            $result = $db->sql_query_limit($sql, 1);
            $next_post_id = (int) $db->sql_fetchfield('post_id');
            $db->sql_freeresult($result);
            break;
    }
    if ($post_mode == 'delete' || $post_mode == 'delete_last_post' || $post_mode == 'delete_first_post') {
        if (!$is_soft) {
            $phpbb_content_visibility->remove_post_from_statistic($data, $sql_data);
        }
        $sql = 'SELECT 1 AS has_attachments
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE topic_id = ' . $topic_id;
        $result = $db->sql_query_limit($sql, 1);
        $has_attachments = (int) $db->sql_fetchfield('has_attachments');
        $db->sql_freeresult($result);
        if (!$has_attachments) {
            $sql_data[TOPICS_TABLE] = ($sql_data[TOPICS_TABLE] ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_attachment = 0';
        }
    }
    $db->sql_transaction('begin');
    $where_sql = array(FORUMS_TABLE => "forum_id = {$forum_id}", TOPICS_TABLE => "topic_id = {$topic_id}", USERS_TABLE => 'user_id = ' . $data['poster_id']);
    foreach ($sql_data as $table => $update_sql) {
        if ($update_sql) {
            $db->sql_query("UPDATE {$table} SET {$update_sql} WHERE " . $where_sql[$table]);
        }
    }
    // Adjust posted info for this user by looking for a post by him/her within this topic...
    if ($post_mode != 'delete_topic' && $config['load_db_track'] && $data['poster_id'] != ANONYMOUS) {
        $sql = 'SELECT poster_id
			FROM ' . POSTS_TABLE . '
			WHERE topic_id = ' . $topic_id . '
				AND poster_id = ' . $data['poster_id'];
        $result = $db->sql_query_limit($sql, 1);
        $poster_id = (int) $db->sql_fetchfield('poster_id');
        $db->sql_freeresult($result);
        // The user is not having any more posts within this topic
        if (!$poster_id) {
            $sql = 'DELETE FROM ' . TOPICS_POSTED_TABLE . '
				WHERE topic_id = ' . $topic_id . '
					AND user_id = ' . $data['poster_id'];
            $db->sql_query($sql);
        }
    }
    $db->sql_transaction('commit');
    if ($data['post_reported'] && $post_mode != 'delete_topic') {
        sync('topic_reported', 'topic_id', array($topic_id));
    }
    return $next_post_id;
}
Exemplo n.º 24
0
/**
* Remove User
*/
function user_delete($mode, $user_id, $post_username = false)
{
    global $cache, $config, $db, $user, $auth;
    global $phpbb_root_path, $phpEx;
    $sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE user_id = ' . $user_id;
    $result = $db->sql_query($sql);
    $user_row = $db->sql_fetchrow($result);
    $db->sql_freeresult($result);
    if (!$user_row) {
        return false;
    }
    // Before we begin, we will remove the reports the user issued.
    $sql = 'SELECT r.post_id, p.topic_id
		FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
		WHERE r.user_id = ' . $user_id . '
			AND p.post_id = r.post_id';
    $result = $db->sql_query($sql);
    $report_posts = $report_topics = array();
    while ($row = $db->sql_fetchrow($result)) {
        $report_posts[] = $row['post_id'];
        $report_topics[] = $row['topic_id'];
    }
    $db->sql_freeresult($result);
    if (sizeof($report_posts)) {
        $report_posts = array_unique($report_posts);
        $report_topics = array_unique($report_topics);
        // Get a list of topics that still contain reported posts
        $sql = 'SELECT DISTINCT topic_id
			FROM ' . POSTS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
				AND post_reported = 1
				AND ' . $db->sql_in_set('post_id', $report_posts, true);
        $result = $db->sql_query($sql);
        $keep_report_topics = array();
        while ($row = $db->sql_fetchrow($result)) {
            $keep_report_topics[] = $row['topic_id'];
        }
        $db->sql_freeresult($result);
        if (sizeof($keep_report_topics)) {
            $report_topics = array_diff($report_topics, $keep_report_topics);
        }
        unset($keep_report_topics);
        // Now set the flags back
        $sql = 'UPDATE ' . POSTS_TABLE . '
			SET post_reported = 0
			WHERE ' . $db->sql_in_set('post_id', $report_posts);
        $db->sql_query($sql);
        if (sizeof($report_topics)) {
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_reported = 0
				WHERE ' . $db->sql_in_set('topic_id', $report_topics);
            $db->sql_query($sql);
        }
    }
    // Remove reports
    $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
    if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD) {
        avatar_delete('user', $user_row);
    }
    switch ($mode) {
        case 'retain':
            $db->sql_transaction('begin');
            if ($post_username === false) {
                $post_username = $user->lang['GUEST'];
            }
            // If the user is inactive and newly registered we assume no posts from this user being there...
            if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts']) {
            } else {
                $sql = 'UPDATE ' . FORUMS_TABLE . '
					SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''\n\t\t\t\t\tWHERE forum_last_poster_id = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET poster_id = ' . ANONYMOUS . ", post_username = '******'\n\t\t\t\t\tWHERE poster_id = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET post_edit_user = '******'UPDATE ' . TOPICS_TABLE . '
					SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''\n\t\t\t\t\tWHERE topic_poster = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''\n\t\t\t\t\tWHERE topic_last_poster_id = {$user_id}";
                $db->sql_query($sql);
                $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
					SET poster_id = ' . ANONYMOUS . "\n\t\t\t\t\tWHERE poster_id = {$user_id}";
                $db->sql_query($sql);
                // Since we change every post by this author, we need to count this amount towards the anonymous user
                // Update the post count for the anonymous user
                if ($user_row['user_posts']) {
                    $sql = 'UPDATE ' . USERS_TABLE . '
						SET user_posts = user_posts + ' . $user_row['user_posts'] . '
						WHERE user_id = ' . ANONYMOUS;
                    $db->sql_query($sql);
                }
            }
            $db->sql_transaction('commit');
            break;
        case 'remove':
            if (!function_exists('delete_posts')) {
                include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            // Delete posts, attachments, etc.
            delete_posts('poster_id', $user_id);
            break;
    }
    $db->sql_transaction('begin');
    $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
    foreach ($table_ary as $table) {
        $sql = "DELETE FROM {$table}\n\t\t\tWHERE user_id = {$user_id}";
        $db->sql_query($sql);
    }
    $cache->destroy('sql', MODERATOR_CACHE_TABLE);
    // Delete user log entries about this user
    $sql = 'DELETE FROM ' . LOG_TABLE . '
		WHERE reportee_id = ' . $user_id;
    $db->sql_query($sql);
    // Change user_id to anonymous for this users triggered events
    $sql = 'UPDATE ' . LOG_TABLE . '
		SET user_id = ' . ANONYMOUS . '
		WHERE user_id = ' . $user_id;
    $db->sql_query($sql);
    // Delete the user_id from the zebra table
    $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
		WHERE user_id = ' . $user_id . '
			OR zebra_id = ' . $user_id;
    $db->sql_query($sql);
    // Delete the user_id from the banlist
    $sql = 'DELETE FROM ' . BANLIST_TABLE . '
		WHERE ban_userid = ' . $user_id;
    $db->sql_query($sql);
    // Delete the user_id from the session table
    $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
		WHERE session_user_id = ' . $user_id;
    $db->sql_query($sql);
    // Clean the private messages tables from the user
    if (!function_exists('phpbb_delete_user_pms')) {
        include $phpbb_root_path . 'includes/functions_privmsgs.' . $phpEx;
    }
    phpbb_delete_user_pms($user_id);
    $db->sql_transaction('commit');
    // Reset newest user info if appropriate
    if ($config['newest_user_id'] == $user_id) {
        update_last_username();
    }
    // Decrement number of users if this user is active
    if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE) {
        set_config_count('num_users', -1, true);
    }
    return false;
}
Exemplo n.º 25
0
/**
* Delete Posts
*/
function mcp_delete_post($post_ids, $is_soft = false, $soft_delete_reason = '', $action = 'delete_post')
{
    global $auth, $user, $db, $phpEx, $phpbb_root_path, $request, $phpbb_container, $phpbb_log;
    $check_permission = $is_soft ? 'm_softdelete' : 'm_delete';
    if (!phpbb_check_ids($post_ids, POSTS_TABLE, 'post_id', array($check_permission))) {
        return;
    }
    $redirect = $request->variable('redirect', build_url(array('action', 'quickmod')));
    $forum_id = $request->variable('f', 0);
    $s_hidden_fields = array('post_id_list' => $post_ids, 'f' => $forum_id, 'action' => $action, 'redirect' => $redirect);
    $success_msg = '';
    if (confirm_box(true) && $is_soft) {
        $post_info = phpbb_get_post_data($post_ids);
        $topic_info = $approve_log = array();
        // Group the posts by topic_id
        foreach ($post_info as $post_id => $post_data) {
            if ($post_data['post_visibility'] != ITEM_APPROVED) {
                continue;
            }
            $topic_id = (int) $post_data['topic_id'];
            $topic_info[$topic_id]['posts'][] = (int) $post_id;
            $topic_info[$topic_id]['forum_id'] = (int) $post_data['forum_id'];
            if ($post_id == $post_data['topic_first_post_id']) {
                $topic_info[$topic_id]['first_post'] = true;
            }
            if ($post_id == $post_data['topic_last_post_id']) {
                $topic_info[$topic_id]['last_post'] = true;
            }
            $approve_log[] = array('forum_id' => $post_data['forum_id'], 'topic_id' => $post_data['topic_id'], 'post_subject' => $post_data['post_subject'], 'poster_id' => $post_data['poster_id'], 'post_username' => $post_data['post_username'], 'username' => $post_data['username']);
        }
        /* @var $phpbb_content_visibility \phpbb\content_visibility */
        $phpbb_content_visibility = $phpbb_container->get('content.visibility');
        foreach ($topic_info as $topic_id => $topic_data) {
            $phpbb_content_visibility->set_post_visibility(ITEM_DELETED, $topic_data['posts'], $topic_id, $topic_data['forum_id'], $user->data['user_id'], time(), $soft_delete_reason, isset($topic_data['first_post']), isset($topic_data['last_post']));
        }
        $affected_topics = sizeof($topic_info);
        // None of the topics is really deleted, so a redirect won't hurt much.
        $deleted_topics = 0;
        $success_msg = sizeof($post_info) == 1 ? $user->lang['POST_DELETED_SUCCESS'] : $user->lang['POSTS_DELETED_SUCCESS'];
        foreach ($approve_log as $row) {
            $post_username = $row['poster_id'] == ANONYMOUS && !empty($row['post_username']) ? $row['post_username'] : $row['username'];
            $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_SOFTDELETE_POST', false, array('forum_id' => $row['forum_id'], 'topic_id' => $row['topic_id'], 'post_id' => $row['post_id'], $row['post_subject'], $post_username, $soft_delete_reason));
        }
        $topic_id = $request->variable('t', 0);
        // Return links
        $return_link = array();
        if ($affected_topics == 1 && $topic_id) {
            $return_link[] = sprintf($user->lang['RETURN_TOPIC'], '<a href="' . append_sid("{$phpbb_root_path}viewtopic.{$phpEx}", "f={$forum_id}&amp;t={$topic_id}") . '">', '</a>');
        }
        $return_link[] = sprintf($user->lang['RETURN_FORUM'], '<a href="' . append_sid("{$phpbb_root_path}viewforum.{$phpEx}", 'f=' . $forum_id) . '">', '</a>');
    } else {
        if (confirm_box(true)) {
            if (!function_exists('delete_posts')) {
                include $phpbb_root_path . 'includes/functions_admin.' . $phpEx;
            }
            // Count the number of topics that are affected
            // I did not use COUNT(DISTINCT ...) because I remember having problems
            // with it on older versions of MySQL -- Ashe
            $sql = 'SELECT DISTINCT topic_id
			FROM ' . POSTS_TABLE . '
			WHERE ' . $db->sql_in_set('post_id', $post_ids);
            $result = $db->sql_query($sql);
            $topic_id_list = array();
            while ($row = $db->sql_fetchrow($result)) {
                $topic_id_list[] = $row['topic_id'];
            }
            $affected_topics = sizeof($topic_id_list);
            $db->sql_freeresult($result);
            $post_data = phpbb_get_post_data($post_ids);
            foreach ($post_data as $id => $row) {
                $post_username = $row['poster_id'] == ANONYMOUS && !empty($row['post_username']) ? $row['post_username'] : $row['username'];
                $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_DELETE_POST', false, array('forum_id' => $row['forum_id'], 'topic_id' => $row['topic_id'], 'post_id' => $row['post_id'], $row['post_subject'], $post_username, $soft_delete_reason));
            }
            // Now delete the posts, topics and forums are automatically resync'ed
            delete_posts('post_id', $post_ids);
            $sql = 'SELECT COUNT(topic_id) AS topics_left
			FROM ' . TOPICS_TABLE . '
			WHERE ' . $db->sql_in_set('topic_id', $topic_id_list);
            $result = $db->sql_query_limit($sql, 1);
            $deleted_topics = ($row = $db->sql_fetchrow($result)) ? $affected_topics - $row['topics_left'] : $affected_topics;
            $db->sql_freeresult($result);
            $topic_id = $request->variable('t', 0);
            // Return links
            $return_link = array();
            if ($affected_topics == 1 && !$deleted_topics && $topic_id) {
                $return_link[] = sprintf($user->lang['RETURN_TOPIC'], '<a href="' . append_sid("{$phpbb_root_path}viewtopic.{$phpEx}", "f={$forum_id}&amp;t={$topic_id}") . '">', '</a>');
            }
            $return_link[] = sprintf($user->lang['RETURN_FORUM'], '<a href="' . append_sid("{$phpbb_root_path}viewforum.{$phpEx}", 'f=' . $forum_id) . '">', '</a>');
            if (sizeof($post_ids) == 1) {
                if ($deleted_topics) {
                    // We deleted the only post of a topic, which in turn has
                    // been removed from the database
                    $success_msg = $user->lang['TOPIC_DELETED_SUCCESS'];
                } else {
                    $success_msg = $user->lang['POST_DELETED_SUCCESS'];
                }
            } else {
                if ($deleted_topics) {
                    // Some of topics disappeared
                    $success_msg = $user->lang['POSTS_DELETED_SUCCESS'] . '<br /><br />' . $user->lang['EMPTY_TOPICS_REMOVED_WARNING'];
                } else {
                    $success_msg = $user->lang['POSTS_DELETED_SUCCESS'];
                }
            }
        } else {
            global $template;
            $user->add_lang('posting');
            $only_softdeleted = false;
            if ($auth->acl_get('m_delete', $forum_id) && $auth->acl_get('m_softdelete', $forum_id)) {
                // If there are only soft deleted posts, we display a message why the option is not available
                $sql = 'SELECT post_id
				FROM ' . POSTS_TABLE . '
				WHERE ' . $db->sql_in_set('post_id', $post_ids) . '
					AND post_visibility <> ' . ITEM_DELETED;
                $result = $db->sql_query_limit($sql, 1);
                $only_softdeleted = !$db->sql_fetchfield('post_id');
                $db->sql_freeresult($result);
            }
            $template->assign_vars(array('S_SOFTDELETED' => $only_softdeleted, 'S_ALLOWED_DELETE' => $auth->acl_get('m_delete', $forum_id), 'S_ALLOWED_SOFTDELETE' => $auth->acl_get('m_softdelete', $forum_id)));
            $l_confirm = sizeof($post_ids) == 1 ? 'DELETE_POST' : 'DELETE_POSTS';
            if ($only_softdeleted) {
                $l_confirm .= '_PERMANENTLY';
                $s_hidden_fields['delete_permanent'] = '1';
            } else {
                if (!$auth->acl_get('m_softdelete', $forum_id)) {
                    $s_hidden_fields['delete_permanent'] = '1';
                }
            }
            confirm_box(false, $l_confirm, build_hidden_fields($s_hidden_fields), 'confirm_delete_body.html');
        }
    }
    $redirect = $request->variable('redirect', "index.{$phpEx}");
    $redirect = reapply_sid($redirect);
    if (!$success_msg) {
        redirect($redirect);
    } else {
        if ($affected_topics != 1 || $deleted_topics || !$topic_id) {
            $redirect = append_sid("{$phpbb_root_path}mcp.{$phpEx}", "f={$forum_id}&i=main&mode=forum_view", false);
        }
        meta_refresh(3, $redirect);
        trigger_error($success_msg . '<br /><br />' . sprintf($user->lang['RETURN_PAGE'], '<a href="' . $redirect . '">', '</a>') . '<br /><br />' . implode('<br /><br />', $return_link));
    }
}
Exemplo n.º 26
0
function delete_post($mode, $post_id, $topic_id, $forum_id, &$data)
{
    global $config, $_CLASS;
    // Specify our post mode
    $post_mode = $data['topic_first_post_id'] == $data['topic_last_post_id'] ? 'delete_topic' : ($data['topic_first_post_id'] == $post_id ? 'delete_first_post' : ($data['topic_last_post_id'] == $post_id ? 'delete_last_post' : 'delete'));
    $sql_data = array();
    $next_post_id = 0;
    $_CLASS['core_db']->transaction();
    if (!delete_posts('post_id', array($post_id), false)) {
        // Try to delete topic, we may had an previous error causing inconsistency
        /*
        if ($post_mode = 'delete_topic')
        {
        	delete_topics('topic_id', array($topic_id), false);
        }
        */
        trigger_error('ALREADY_DELETED');
    }
    $_CLASS['core_db']->transaction('commit');
    // Collect the necessary informations for updating the tables
    $sql_data[FORUMS_FORUMS_TABLE] = '';
    switch ($post_mode) {
        case 'delete_topic':
            delete_topics('topic_id', array($topic_id), false);
            set_config('num_topics', $config['num_topics'] - 1, true);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] .= 'forum_posts = forum_posts - 1, forum_topics_real = forum_topics_real - 1';
                $sql_data[FORUMS_FORUMS_TABLE] .= $data['topic_approved'] ? ', forum_topics = forum_topics - 1' : '';
                $sql_data[FORUMS_FORUMS_TABLE] .= ', ';
            }
            $sql_data[FORUMS_FORUMS_TABLE] .= implode(', ', update_last_post_information('forum', $forum_id));
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            break;
        case 'delete_first_post':
            $sql = 'SELECT p.post_id, p.poster_id, p.post_username, u.username 
				FROM ' . FORUMS_POSTS_TABLE . ' p, ' . FORUMS_USERS_TABLE . " u\n\t\t\t\tWHERE p.topic_id = {$topic_id} \n\t\t\t\t\tAND p.poster_id = u.user_id \n\t\t\t\tORDER BY p.post_time ASC";
            $result = $_CLASS['core_db']->query_limit($sql, 1);
            $row = $_CLASS['core_db']->fetch_row_assoc($result);
            $_CLASS['core_db']->free_result($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_first_post_id = ' . intval($row['post_id']) . ", topic_first_poster_name = '" . ($row['poster_id'] == ANONYMOUS ? $_CLASS['core_db']->sql_escape($row['post_username']) : $_CLASS['core_db']->sql_escape($row['username'])) . "'";
            $sql_data[FORUMS_TOPICS_TABLE] .= ', topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
            break;
        case 'delete_last_post':
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $sql_data[FORUMS_FORUMS_TABLE] .= $sql_data[FORUMS_FORUMS_TABLE] ? ', ' : '';
            $sql_data[FORUMS_FORUMS_TABLE] .= implode(', ', update_last_post_information('forum', $forum_id));
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_bumped = 0, topic_bumper = 0, topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $update = update_last_post_information('topic', $topic_id);
            if (sizeof($update)) {
                $sql_data[FORUMS_TOPICS_TABLE] .= ', ' . implode(', ', $update);
                $next_post_id = (int) str_replace('topic_last_post_id = ', '', $update[0]);
            } else {
                $sql = 'SELECT MAX(post_id) as last_post_id
					FROM ' . FORUMS_POSTS_TABLE . "\n\t\t\t\t\tWHERE topic_id = {$topic_id} " . (!$_CLASS['auth']->acl_get('m_approve') ? 'AND post_approved = 1' : '');
                $result = $_CLASS['core_db']->query($sql);
                $row = $_CLASS['core_db']->fetch_row_assoc($result);
                $_CLASS['core_db']->free_result($result);
                $next_post_id = (int) $row['last_post_id'];
            }
            break;
        case 'delete':
            $sql = 'SELECT post_id
				FROM ' . FORUMS_POSTS_TABLE . "\n\t\t\t\tWHERE topic_id = {$topic_id} " . (!$_CLASS['auth']->acl_get('m_approve') ? 'AND post_approved = 1' : '') . '
					AND post_time > ' . $data['post_time'] . '
				ORDER BY post_time ASC';
            $result = $_CLASS['core_db']->query_limit($sql, 1);
            $row = $_CLASS['core_db']->fetch_row_assoc($result);
            $_CLASS['core_db']->free_result($result);
            if ($data['topic_type'] != POST_GLOBAL) {
                $sql_data[FORUMS_FORUMS_TABLE] = 'forum_posts = forum_posts - 1';
            }
            $sql_data[FORUMS_TOPICS_TABLE] = 'topic_replies_real = topic_replies_real - 1' . ($data['post_approved'] ? ', topic_replies = topic_replies - 1' : '');
            $next_post_id = (int) $row['post_id'];
    }
    $sql_data[USERS_TABLE] = $_CLASS['auth']->acl_get('f_postcount', $forum_id) ? 'user_posts = user_posts - 1' : '';
    set_config('num_posts', $config['num_posts'] - 1, true);
    $_CLASS['core_db']->transaction();
    $where_sql = array(FORUMS_FORUMS_TABLE => "forum_id = {$forum_id}", FORUMS_TOPICS_TABLE => "topic_id = {$topic_id}", USERS_TABLE => 'user_id = ' . $data['poster_id']);
    foreach ($sql_data as $table => $update_sql) {
        if ($update_sql) {
            $_CLASS['core_db']->query("UPDATE {$table} SET {$update_sql} WHERE " . $where_sql[$table]);
        }
    }
    $_CLASS['core_db']->transaction('commit');
    return $next_post_id;
}
Exemplo n.º 27
0
/**
* All-encompasing sync function
*
* Exaples:
* <code>
* sync('topic', 'topic_id', 123);			// resync topic #123
* sync('topic', 'forum_id', array(2, 3));	// resync topics from forum #2 and #3
* sync('topic');							// resync all topics
* sync('topic', 'range', 'topic_id BETWEEN 1 AND 60');	// resync a range of topics/forums (only available for 'topic' and 'forum' modes)
* </code>
*
* Modes:
* - forum				Resync complete forum
* - topic				Resync topics
* - topic_moved			Removes topic shadows that would be in the same forum as the topic they link to
* - topic_visibility	Resyncs the topic_visibility flag according to the status of the first post
* - post_reported		Resyncs the post_reported flag, relying on actual reports
* - topic_reported		Resyncs the topic_reported flag, relying on post_reported flags
* - post_attachement	Same as post_reported, but with attachment flags
* - topic_attachement	Same as topic_reported, but with attachment flags
*/
function sync($mode, $where_type = '', $where_ids = '', $resync_parents = false, $sync_extra = false)
{
    global $db;
    if (is_array($where_ids)) {
        $where_ids = array_unique($where_ids);
        $where_ids = array_map('intval', $where_ids);
    } else {
        if ($where_type != 'range') {
            $where_ids = $where_ids ? array((int) $where_ids) : array();
        }
    }
    if ($mode == 'forum' || $mode == 'topic' || $mode == 'topic_visibility' || $mode == 'topic_reported' || $mode == 'post_reported') {
        if (!$where_type) {
            $where_sql = '';
            $where_sql_and = 'WHERE';
        } else {
            if ($where_type == 'range') {
                // Only check a range of topics/forums. For instance: 'topic_id BETWEEN 1 AND 60'
                $where_sql = 'WHERE (' . $mode[0] . ".{$where_ids})";
                $where_sql_and = $where_sql . "\n\tAND";
            } else {
                // Do not sync the "global forum"
                $where_ids = array_diff($where_ids, array(0));
                if (!sizeof($where_ids)) {
                    // Empty array with IDs. This means that we don't have any work to do. Just return.
                    return;
                }
                // Limit the topics/forums we are syncing, use specific topic/forum IDs.
                // $where_type contains the field for the where clause (forum_id, topic_id)
                $where_sql = 'WHERE ' . $db->sql_in_set($mode[0] . '.' . $where_type, $where_ids);
                $where_sql_and = $where_sql . "\n\tAND";
            }
        }
    } else {
        if (!sizeof($where_ids)) {
            return;
        }
        // $where_type contains the field for the where clause (forum_id, topic_id)
        $where_sql = 'WHERE ' . $db->sql_in_set($mode[0] . '.' . $where_type, $where_ids);
        $where_sql_and = $where_sql . "\n\tAND";
    }
    switch ($mode) {
        case 'topic_moved':
            $db->sql_transaction('begin');
            switch ($db->get_sql_layer()) {
                case 'mysql4':
                case 'mysqli':
                    $sql = 'DELETE FROM ' . TOPICS_TABLE . '
						USING ' . TOPICS_TABLE . ' t1, ' . TOPICS_TABLE . " t2\n\t\t\t\t\t\tWHERE t1.topic_moved_id = t2.topic_id\n\t\t\t\t\t\t\tAND t1.forum_id = t2.forum_id";
                    $db->sql_query($sql);
                    break;
                default:
                    $sql = 'SELECT t1.topic_id
						FROM ' . TOPICS_TABLE . ' t1, ' . TOPICS_TABLE . " t2\n\t\t\t\t\t\tWHERE t1.topic_moved_id = t2.topic_id\n\t\t\t\t\t\t\tAND t1.forum_id = t2.forum_id";
                    $result = $db->sql_query($sql);
                    $topic_id_ary = array();
                    while ($row = $db->sql_fetchrow($result)) {
                        $topic_id_ary[] = $row['topic_id'];
                    }
                    $db->sql_freeresult($result);
                    if (!sizeof($topic_id_ary)) {
                        return;
                    }
                    $sql = 'DELETE FROM ' . TOPICS_TABLE . '
						WHERE ' . $db->sql_in_set('topic_id', $topic_id_ary);
                    $db->sql_query($sql);
                    break;
            }
            $db->sql_transaction('commit');
            break;
        case 'topic_visibility':
            $db->sql_transaction('begin');
            $sql = 'SELECT t.topic_id, p.post_visibility
				FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p\n\t\t\t\t{$where_sql_and} p.topic_id = t.topic_id\n\t\t\t\t\tAND p.post_visibility = " . ITEM_APPROVED;
            $result = $db->sql_query($sql);
            $topics_approved = array();
            while ($row = $db->sql_fetchrow($result)) {
                $topics_approved[] = (int) $row['topic_id'];
            }
            $db->sql_freeresult($result);
            $sql = 'SELECT t.topic_id, p.post_visibility
				FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p\n\t\t\t\t{$where_sql_and} " . $db->sql_in_set('t.topic_id', $topics_approved, true, true) . '
					AND p.topic_id = t.topic_id
					AND p.post_visibility = ' . ITEM_DELETED;
            $result = $db->sql_query($sql);
            $topics_softdeleted = array();
            while ($row = $db->sql_fetchrow($result)) {
                $topics_softdeleted[] = (int) $row['topic_id'];
            }
            $db->sql_freeresult($result);
            $topics_softdeleted = array_diff($topics_softdeleted, $topics_approved);
            $topics_not_unapproved = array_merge($topics_softdeleted, $topics_approved);
            $update_ary = array(ITEM_UNAPPROVED => !empty($topics_not_unapproved) ? $where_sql_and . ' ' . $db->sql_in_set('topic_id', $topics_not_unapproved, true) : '', ITEM_APPROVED => !empty($topics_approved) ? ' WHERE ' . $db->sql_in_set('topic_id', $topics_approved) : '', ITEM_DELETED => !empty($topics_softdeleted) ? ' WHERE ' . $db->sql_in_set('topic_id', $topics_softdeleted) : '');
            foreach ($update_ary as $visibility => $sql_where) {
                if ($sql_where) {
                    $sql = 'UPDATE ' . TOPICS_TABLE . '
						SET topic_visibility = ' . $visibility . '
						' . $sql_where;
                    $db->sql_query($sql);
                }
            }
            $db->sql_transaction('commit');
            break;
        case 'post_reported':
            $post_ids = $post_reported = array();
            $db->sql_transaction('begin');
            $sql = 'SELECT p.post_id, p.post_reported
				FROM ' . POSTS_TABLE . " p\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY p.post_id, p.post_reported";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $post_ids[$row['post_id']] = $row['post_id'];
                if ($row['post_reported']) {
                    $post_reported[$row['post_id']] = 1;
                }
            }
            $db->sql_freeresult($result);
            $sql = 'SELECT DISTINCT(post_id)
				FROM ' . REPORTS_TABLE . '
				WHERE ' . $db->sql_in_set('post_id', $post_ids) . '
					AND report_closed = 0';
            $result = $db->sql_query($sql);
            $post_ids = array();
            while ($row = $db->sql_fetchrow($result)) {
                if (!isset($post_reported[$row['post_id']])) {
                    $post_ids[] = $row['post_id'];
                } else {
                    unset($post_reported[$row['post_id']]);
                }
            }
            $db->sql_freeresult($result);
            // $post_reported should be empty by now, if it's not it contains
            // posts that are falsely flagged as reported
            foreach ($post_reported as $post_id => $void) {
                $post_ids[] = $post_id;
            }
            if (sizeof($post_ids)) {
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET post_reported = 1 - post_reported
					WHERE ' . $db->sql_in_set('post_id', $post_ids);
                $db->sql_query($sql);
            }
            $db->sql_transaction('commit');
            break;
        case 'topic_reported':
            if ($sync_extra) {
                sync('post_reported', $where_type, $where_ids);
            }
            $topic_ids = $topic_reported = array();
            $db->sql_transaction('begin');
            $sql = 'SELECT DISTINCT(t.topic_id)
				FROM ' . POSTS_TABLE . " t\n\t\t\t\t{$where_sql_and} t.post_reported = 1";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $topic_reported[$row['topic_id']] = 1;
            }
            $db->sql_freeresult($result);
            $sql = 'SELECT t.topic_id, t.topic_reported
				FROM ' . TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                if ($row['topic_reported'] ^ isset($topic_reported[$row['topic_id']])) {
                    $topic_ids[] = $row['topic_id'];
                }
            }
            $db->sql_freeresult($result);
            if (sizeof($topic_ids)) {
                $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_reported = 1 - topic_reported
					WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
                $db->sql_query($sql);
            }
            $db->sql_transaction('commit');
            break;
        case 'post_attachment':
            $post_ids = $post_attachment = array();
            $db->sql_transaction('begin');
            $sql = 'SELECT p.post_id, p.post_attachment
				FROM ' . POSTS_TABLE . " p\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY p.post_id, p.post_attachment";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $post_ids[$row['post_id']] = $row['post_id'];
                if ($row['post_attachment']) {
                    $post_attachment[$row['post_id']] = 1;
                }
            }
            $db->sql_freeresult($result);
            $sql = 'SELECT DISTINCT(post_msg_id)
				FROM ' . ATTACHMENTS_TABLE . '
				WHERE ' . $db->sql_in_set('post_msg_id', $post_ids) . '
					AND in_message = 0';
            $result = $db->sql_query($sql);
            $post_ids = array();
            while ($row = $db->sql_fetchrow($result)) {
                if (!isset($post_attachment[$row['post_msg_id']])) {
                    $post_ids[] = $row['post_msg_id'];
                } else {
                    unset($post_attachment[$row['post_msg_id']]);
                }
            }
            $db->sql_freeresult($result);
            // $post_attachment should be empty by now, if it's not it contains
            // posts that are falsely flagged as having attachments
            foreach ($post_attachment as $post_id => $void) {
                $post_ids[] = $post_id;
            }
            if (sizeof($post_ids)) {
                $sql = 'UPDATE ' . POSTS_TABLE . '
					SET post_attachment = 1 - post_attachment
					WHERE ' . $db->sql_in_set('post_id', $post_ids);
                $db->sql_query($sql);
            }
            $db->sql_transaction('commit');
            break;
        case 'topic_attachment':
            if ($sync_extra) {
                sync('post_attachment', $where_type, $where_ids);
            }
            $topic_ids = $topic_attachment = array();
            $db->sql_transaction('begin');
            $sql = 'SELECT DISTINCT(t.topic_id)
				FROM ' . POSTS_TABLE . " t\n\t\t\t\t{$where_sql_and} t.post_attachment = 1";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $topic_attachment[$row['topic_id']] = 1;
            }
            $db->sql_freeresult($result);
            $sql = 'SELECT t.topic_id, t.topic_attachment
				FROM ' . TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                if ($row['topic_attachment'] ^ isset($topic_attachment[$row['topic_id']])) {
                    $topic_ids[] = $row['topic_id'];
                }
            }
            $db->sql_freeresult($result);
            if (sizeof($topic_ids)) {
                $sql = 'UPDATE ' . TOPICS_TABLE . '
					SET topic_attachment = 1 - topic_attachment
					WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
                $db->sql_query($sql);
            }
            $db->sql_transaction('commit');
            break;
        case 'forum':
            $db->sql_transaction('begin');
            // 1: Get the list of all forums
            $sql = 'SELECT f.*
				FROM ' . FORUMS_TABLE . " f\n\t\t\t\t{$where_sql}";
            $result = $db->sql_query($sql);
            $forum_data = $forum_ids = $post_ids = $last_post_id = $post_info = array();
            while ($row = $db->sql_fetchrow($result)) {
                if ($row['forum_type'] == FORUM_LINK) {
                    continue;
                }
                $forum_id = (int) $row['forum_id'];
                $forum_ids[$forum_id] = $forum_id;
                $forum_data[$forum_id] = $row;
                if ($sync_extra) {
                    $forum_data[$forum_id]['posts_approved'] = 0;
                    $forum_data[$forum_id]['posts_unapproved'] = 0;
                    $forum_data[$forum_id]['posts_softdeleted'] = 0;
                    $forum_data[$forum_id]['topics_approved'] = 0;
                    $forum_data[$forum_id]['topics_unapproved'] = 0;
                    $forum_data[$forum_id]['topics_softdeleted'] = 0;
                }
                $forum_data[$forum_id]['last_post_id'] = 0;
                $forum_data[$forum_id]['last_post_subject'] = '';
                $forum_data[$forum_id]['last_post_time'] = 0;
                $forum_data[$forum_id]['last_poster_id'] = 0;
                $forum_data[$forum_id]['last_poster_name'] = '';
                $forum_data[$forum_id]['last_poster_colour'] = '';
            }
            $db->sql_freeresult($result);
            if (!sizeof($forum_ids)) {
                break;
            }
            $forum_ids = array_values($forum_ids);
            // 2: Get topic counts for each forum (optional)
            if ($sync_extra) {
                $sql = 'SELECT forum_id, topic_visibility, COUNT(topic_id) AS total_topics
					FROM ' . TOPICS_TABLE . '
					WHERE ' . $db->sql_in_set('forum_id', $forum_ids) . '
					GROUP BY forum_id, topic_visibility';
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $forum_id = (int) $row['forum_id'];
                    if ($row['topic_visibility'] == ITEM_APPROVED) {
                        $forum_data[$forum_id]['topics_approved'] = $row['total_topics'];
                    } else {
                        if ($row['topic_visibility'] == ITEM_UNAPPROVED || $row['topic_visibility'] == ITEM_REAPPROVE) {
                            $forum_data[$forum_id]['topics_unapproved'] = $row['total_topics'];
                        } else {
                            if ($row['topic_visibility'] == ITEM_DELETED) {
                                $forum_data[$forum_id]['topics_softdeleted'] = $row['total_topics'];
                            }
                        }
                    }
                }
                $db->sql_freeresult($result);
            }
            // 3: Get post count for each forum (optional)
            if ($sync_extra) {
                if (sizeof($forum_ids) == 1) {
                    $sql = 'SELECT SUM(t.topic_posts_approved) AS forum_posts_approved, SUM(t.topic_posts_unapproved) AS forum_posts_unapproved, SUM(t.topic_posts_softdeleted) AS forum_posts_softdeleted
						FROM ' . TOPICS_TABLE . ' t
						WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
							AND t.topic_status <> ' . ITEM_MOVED;
                } else {
                    $sql = 'SELECT t.forum_id, SUM(t.topic_posts_approved) AS forum_posts_approved, SUM(t.topic_posts_unapproved) AS forum_posts_unapproved, SUM(t.topic_posts_softdeleted) AS forum_posts_softdeleted
						FROM ' . TOPICS_TABLE . ' t
						WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
							AND t.topic_status <> ' . ITEM_MOVED . '
						GROUP BY t.forum_id';
                }
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $forum_id = sizeof($forum_ids) == 1 ? (int) $forum_ids[0] : (int) $row['forum_id'];
                    $forum_data[$forum_id]['posts_approved'] = (int) $row['forum_posts_approved'];
                    $forum_data[$forum_id]['posts_unapproved'] = (int) $row['forum_posts_unapproved'];
                    $forum_data[$forum_id]['posts_softdeleted'] = (int) $row['forum_posts_softdeleted'];
                }
                $db->sql_freeresult($result);
            }
            // 4: Get last_post_id for each forum
            if (sizeof($forum_ids) == 1) {
                $sql = 'SELECT MAX(t.topic_last_post_id) as last_post_id
					FROM ' . TOPICS_TABLE . ' t
					WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
						AND t.topic_visibility = ' . ITEM_APPROVED;
            } else {
                $sql = 'SELECT t.forum_id, MAX(t.topic_last_post_id) as last_post_id
					FROM ' . TOPICS_TABLE . ' t
					WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
						AND t.topic_visibility = ' . ITEM_APPROVED . '
					GROUP BY t.forum_id';
            }
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $forum_id = sizeof($forum_ids) == 1 ? (int) $forum_ids[0] : (int) $row['forum_id'];
                $forum_data[$forum_id]['last_post_id'] = (int) $row['last_post_id'];
                $post_ids[] = $row['last_post_id'];
            }
            $db->sql_freeresult($result);
            // 5: Retrieve last_post infos
            if (sizeof($post_ids)) {
                $sql = 'SELECT p.post_id, p.poster_id, p.post_subject, p.post_time, p.post_username, u.username, u.user_colour
					FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
					WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
						AND p.poster_id = u.user_id';
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $post_info[$row['post_id']] = $row;
                }
                $db->sql_freeresult($result);
                foreach ($forum_data as $forum_id => $data) {
                    if ($data['last_post_id']) {
                        if (isset($post_info[$data['last_post_id']])) {
                            $forum_data[$forum_id]['last_post_subject'] = $post_info[$data['last_post_id']]['post_subject'];
                            $forum_data[$forum_id]['last_post_time'] = $post_info[$data['last_post_id']]['post_time'];
                            $forum_data[$forum_id]['last_poster_id'] = $post_info[$data['last_post_id']]['poster_id'];
                            $forum_data[$forum_id]['last_poster_name'] = $post_info[$data['last_post_id']]['poster_id'] != ANONYMOUS ? $post_info[$data['last_post_id']]['username'] : $post_info[$data['last_post_id']]['post_username'];
                            $forum_data[$forum_id]['last_poster_colour'] = $post_info[$data['last_post_id']]['user_colour'];
                        } else {
                            // For some reason we did not find the post in the db
                            $forum_data[$forum_id]['last_post_id'] = 0;
                            $forum_data[$forum_id]['last_post_subject'] = '';
                            $forum_data[$forum_id]['last_post_time'] = 0;
                            $forum_data[$forum_id]['last_poster_id'] = 0;
                            $forum_data[$forum_id]['last_poster_name'] = '';
                            $forum_data[$forum_id]['last_poster_colour'] = '';
                        }
                    }
                }
                unset($post_info);
            }
            // 6: Now do that thing
            $fieldnames = array('last_post_id', 'last_post_subject', 'last_post_time', 'last_poster_id', 'last_poster_name', 'last_poster_colour');
            if ($sync_extra) {
                array_push($fieldnames, 'posts_approved', 'posts_unapproved', 'posts_softdeleted', 'topics_approved', 'topics_unapproved', 'topics_softdeleted');
            }
            foreach ($forum_data as $forum_id => $row) {
                $sql_ary = array();
                foreach ($fieldnames as $fieldname) {
                    if ($row['forum_' . $fieldname] != $row[$fieldname]) {
                        if (preg_match('#(name|colour|subject)$#', $fieldname)) {
                            $sql_ary['forum_' . $fieldname] = (string) $row[$fieldname];
                        } else {
                            $sql_ary['forum_' . $fieldname] = (int) $row[$fieldname];
                        }
                    }
                }
                if (sizeof($sql_ary)) {
                    $sql = 'UPDATE ' . FORUMS_TABLE . '
						SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
						WHERE forum_id = ' . $forum_id;
                    $db->sql_query($sql);
                }
            }
            $db->sql_transaction('commit');
            break;
        case 'topic':
            $topic_data = $post_ids = $resync_forums = $delete_topics = $delete_posts = $moved_topics = array();
            $db->sql_transaction('begin');
            $sql = 'SELECT t.topic_id, t.forum_id, t.topic_moved_id, t.topic_visibility, ' . ($sync_extra ? 't.topic_attachment, t.topic_reported, ' : '') . 't.topic_poster, t.topic_time, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_first_post_id, t.topic_first_poster_name, t.topic_first_poster_colour, t.topic_last_post_id, t.topic_last_post_subject, t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_poster_colour, t.topic_last_post_time
				FROM ' . TOPICS_TABLE . " t\n\t\t\t\t{$where_sql}";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                if ($row['topic_moved_id']) {
                    $moved_topics[] = $row['topic_id'];
                    continue;
                }
                $topic_id = (int) $row['topic_id'];
                $topic_data[$topic_id] = $row;
                $topic_data[$topic_id]['visibility'] = ITEM_UNAPPROVED;
                $topic_data[$topic_id]['posts_approved'] = 0;
                $topic_data[$topic_id]['posts_unapproved'] = 0;
                $topic_data[$topic_id]['posts_softdeleted'] = 0;
                $topic_data[$topic_id]['first_post_id'] = 0;
                $topic_data[$topic_id]['last_post_id'] = 0;
                unset($topic_data[$topic_id]['topic_id']);
                // This array holds all topic_ids
                $delete_topics[$topic_id] = '';
                if ($sync_extra) {
                    $topic_data[$topic_id]['reported'] = 0;
                    $topic_data[$topic_id]['attachment'] = 0;
                }
            }
            $db->sql_freeresult($result);
            // Use "t" as table alias because of the $where_sql clause
            // NOTE: 't.post_visibility' in the GROUP BY is causing a major slowdown.
            $sql = 'SELECT t.topic_id, t.post_visibility, COUNT(t.post_id) AS total_posts, MIN(t.post_id) AS first_post_id, MAX(t.post_id) AS last_post_id
				FROM ' . POSTS_TABLE . " t\n\t\t\t\t{$where_sql}\n\t\t\t\tGROUP BY t.topic_id, t.post_visibility";
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $topic_id = (int) $row['topic_id'];
                $row['first_post_id'] = (int) $row['first_post_id'];
                $row['last_post_id'] = (int) $row['last_post_id'];
                if (!isset($topic_data[$topic_id])) {
                    // Hey, these posts come from a topic that does not exist
                    $delete_posts[$topic_id] = '';
                } else {
                    // Unset the corresponding entry in $delete_topics
                    // When we'll be done, only topics with no posts will remain
                    unset($delete_topics[$topic_id]);
                    if ($row['post_visibility'] == ITEM_APPROVED) {
                        $topic_data[$topic_id]['posts_approved'] = $row['total_posts'];
                    } else {
                        if ($row['post_visibility'] == ITEM_UNAPPROVED || $row['post_visibility'] == ITEM_REAPPROVE) {
                            $topic_data[$topic_id]['posts_unapproved'] = $row['total_posts'];
                        } else {
                            if ($row['post_visibility'] == ITEM_DELETED) {
                                $topic_data[$topic_id]['posts_softdeleted'] = $row['total_posts'];
                            }
                        }
                    }
                    if ($row['post_visibility'] == ITEM_APPROVED) {
                        $topic_data[$topic_id]['visibility'] = ITEM_APPROVED;
                        $topic_data[$topic_id]['first_post_id'] = $row['first_post_id'];
                        $topic_data[$topic_id]['last_post_id'] = $row['last_post_id'];
                    } else {
                        if ($topic_data[$topic_id]['visibility'] != ITEM_APPROVED) {
                            // If there is no approved post, we take the min/max of the other visibilities
                            // for the last and first post info, because it is only visible to moderators anyway
                            $topic_data[$topic_id]['first_post_id'] = !empty($topic_data[$topic_id]['first_post_id']) ? min($topic_data[$topic_id]['first_post_id'], $row['first_post_id']) : $row['first_post_id'];
                            $topic_data[$topic_id]['last_post_id'] = max($topic_data[$topic_id]['last_post_id'], $row['last_post_id']);
                            if ($topic_data[$topic_id]['visibility'] == ITEM_UNAPPROVED || $topic_data[$topic_id]['visibility'] == ITEM_REAPPROVE) {
                                // Soft delete status is stronger than unapproved.
                                $topic_data[$topic_id]['visibility'] = $row['post_visibility'];
                            }
                        }
                    }
                }
            }
            $db->sql_freeresult($result);
            foreach ($topic_data as $topic_id => $row) {
                $post_ids[] = $row['first_post_id'];
                if ($row['first_post_id'] != $row['last_post_id']) {
                    $post_ids[] = $row['last_post_id'];
                }
            }
            // Now we delete empty topics and orphan posts
            if (sizeof($delete_posts)) {
                delete_posts('topic_id', array_keys($delete_posts), false);
                unset($delete_posts);
            }
            if (!sizeof($topic_data)) {
                // If we get there, topic ids were invalid or topics did not contain any posts
                delete_topics($where_type, $where_ids, true);
                return;
            }
            if (sizeof($delete_topics)) {
                $delete_topic_ids = array();
                foreach ($delete_topics as $topic_id => $void) {
                    unset($topic_data[$topic_id]);
                    $delete_topic_ids[] = $topic_id;
                }
                delete_topics('topic_id', $delete_topic_ids, false);
                unset($delete_topics, $delete_topic_ids);
            }
            $sql = 'SELECT p.post_id, p.topic_id, p.post_visibility, p.poster_id, p.post_subject, p.post_username, p.post_time, u.username, u.user_colour
				FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
				WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
					AND u.user_id = p.poster_id';
            $result = $db->sql_query($sql);
            while ($row = $db->sql_fetchrow($result)) {
                $topic_id = intval($row['topic_id']);
                if ($row['post_id'] == $topic_data[$topic_id]['first_post_id']) {
                    $topic_data[$topic_id]['time'] = $row['post_time'];
                    $topic_data[$topic_id]['poster'] = $row['poster_id'];
                    $topic_data[$topic_id]['first_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                    $topic_data[$topic_id]['first_poster_colour'] = $row['user_colour'];
                }
                if ($row['post_id'] == $topic_data[$topic_id]['last_post_id']) {
                    $topic_data[$topic_id]['last_poster_id'] = $row['poster_id'];
                    $topic_data[$topic_id]['last_post_subject'] = $row['post_subject'];
                    $topic_data[$topic_id]['last_post_time'] = $row['post_time'];
                    $topic_data[$topic_id]['last_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                    $topic_data[$topic_id]['last_poster_colour'] = $row['user_colour'];
                }
            }
            $db->sql_freeresult($result);
            // Make sure shadow topics do link to existing topics
            if (sizeof($moved_topics)) {
                $delete_topics = array();
                $sql = 'SELECT t1.topic_id, t1.topic_moved_id
					FROM ' . TOPICS_TABLE . ' t1
					LEFT JOIN ' . TOPICS_TABLE . ' t2 ON (t2.topic_id = t1.topic_moved_id)
					WHERE ' . $db->sql_in_set('t1.topic_id', $moved_topics) . '
						AND t2.topic_id IS NULL';
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $delete_topics[] = $row['topic_id'];
                }
                $db->sql_freeresult($result);
                if (sizeof($delete_topics)) {
                    delete_topics('topic_id', $delete_topics, false);
                }
                unset($delete_topics);
                // Make sure shadow topics having no last post data being updated (this only rarely happens...)
                $sql = 'SELECT topic_id, topic_moved_id, topic_last_post_id, topic_first_post_id
					FROM ' . TOPICS_TABLE . '
					WHERE ' . $db->sql_in_set('topic_id', $moved_topics) . '
						AND topic_last_post_time = 0';
                $result = $db->sql_query($sql);
                $shadow_topic_data = $post_ids = array();
                while ($row = $db->sql_fetchrow($result)) {
                    $shadow_topic_data[$row['topic_moved_id']] = $row;
                    $post_ids[] = $row['topic_last_post_id'];
                    $post_ids[] = $row['topic_first_post_id'];
                }
                $db->sql_freeresult($result);
                $sync_shadow_topics = array();
                if (sizeof($post_ids)) {
                    $sql = 'SELECT p.post_id, p.topic_id, p.post_visibility, p.poster_id, p.post_subject, p.post_username, p.post_time, u.username, u.user_colour
						FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
						WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
							AND u.user_id = p.poster_id';
                    $result = $db->sql_query($sql);
                    while ($row = $db->sql_fetchrow($result)) {
                        $topic_id = (int) $row['topic_id'];
                        // Ok, there should be a shadow topic. If there isn't, then there's something wrong with the db.
                        // However, there's not much we can do about it.
                        if (!empty($shadow_topic_data[$topic_id])) {
                            if ($row['post_id'] == $shadow_topic_data[$topic_id]['topic_first_post_id']) {
                                $orig_topic_id = $shadow_topic_data[$topic_id]['topic_id'];
                                if (!isset($sync_shadow_topics[$orig_topic_id])) {
                                    $sync_shadow_topics[$orig_topic_id] = array();
                                }
                                $sync_shadow_topics[$orig_topic_id]['topic_time'] = $row['post_time'];
                                $sync_shadow_topics[$orig_topic_id]['topic_poster'] = $row['poster_id'];
                                $sync_shadow_topics[$orig_topic_id]['topic_first_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                                $sync_shadow_topics[$orig_topic_id]['topic_first_poster_colour'] = $row['user_colour'];
                            }
                            if ($row['post_id'] == $shadow_topic_data[$topic_id]['topic_last_post_id']) {
                                $orig_topic_id = $shadow_topic_data[$topic_id]['topic_id'];
                                if (!isset($sync_shadow_topics[$orig_topic_id])) {
                                    $sync_shadow_topics[$orig_topic_id] = array();
                                }
                                $sync_shadow_topics[$orig_topic_id]['topic_last_poster_id'] = $row['poster_id'];
                                $sync_shadow_topics[$orig_topic_id]['topic_last_post_subject'] = $row['post_subject'];
                                $sync_shadow_topics[$orig_topic_id]['topic_last_post_time'] = $row['post_time'];
                                $sync_shadow_topics[$orig_topic_id]['topic_last_poster_name'] = $row['poster_id'] == ANONYMOUS ? $row['post_username'] : $row['username'];
                                $sync_shadow_topics[$orig_topic_id]['topic_last_poster_colour'] = $row['user_colour'];
                            }
                        }
                    }
                    $db->sql_freeresult($result);
                    $shadow_topic_data = array();
                    // Update the information we collected
                    if (sizeof($sync_shadow_topics)) {
                        foreach ($sync_shadow_topics as $sync_topic_id => $sql_ary) {
                            $sql = 'UPDATE ' . TOPICS_TABLE . '
								SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE topic_id = ' . $sync_topic_id;
                            $db->sql_query($sql);
                        }
                    }
                }
                unset($sync_shadow_topics, $shadow_topic_data);
            }
            // These are fields that will be synchronised
            $fieldnames = array('time', 'visibility', 'posts_approved', 'posts_unapproved', 'posts_softdeleted', 'poster', 'first_post_id', 'first_poster_name', 'first_poster_colour', 'last_post_id', 'last_post_subject', 'last_post_time', 'last_poster_id', 'last_poster_name', 'last_poster_colour');
            if ($sync_extra) {
                // This routine assumes that post_reported values are correct
                // if they are not, use sync('post_reported') first
                $sql = 'SELECT t.topic_id, p.post_id
					FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p\n\t\t\t\t\t{$where_sql_and} p.topic_id = t.topic_id\n\t\t\t\t\t\tAND p.post_reported = 1\n\t\t\t\t\tGROUP BY t.topic_id, p.post_id";
                $result = $db->sql_query($sql);
                $fieldnames[] = 'reported';
                while ($row = $db->sql_fetchrow($result)) {
                    $topic_data[intval($row['topic_id'])]['reported'] = 1;
                }
                $db->sql_freeresult($result);
                // This routine assumes that post_attachment values are correct
                // if they are not, use sync('post_attachment') first
                $sql = 'SELECT t.topic_id, p.post_id
					FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p\n\t\t\t\t\t{$where_sql_and} p.topic_id = t.topic_id\n\t\t\t\t\t\tAND p.post_attachment = 1\n\t\t\t\t\tGROUP BY t.topic_id, p.post_id";
                $result = $db->sql_query($sql);
                $fieldnames[] = 'attachment';
                while ($row = $db->sql_fetchrow($result)) {
                    $topic_data[intval($row['topic_id'])]['attachment'] = 1;
                }
                $db->sql_freeresult($result);
            }
            foreach ($topic_data as $topic_id => $row) {
                $sql_ary = array();
                foreach ($fieldnames as $fieldname) {
                    if (isset($row[$fieldname]) && isset($row['topic_' . $fieldname]) && $row['topic_' . $fieldname] != $row[$fieldname]) {
                        $sql_ary['topic_' . $fieldname] = $row[$fieldname];
                    }
                }
                if (sizeof($sql_ary)) {
                    $sql = 'UPDATE ' . TOPICS_TABLE . '
						SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
						WHERE topic_id = ' . $topic_id;
                    $db->sql_query($sql);
                    $resync_forums[$row['forum_id']] = $row['forum_id'];
                }
            }
            unset($topic_data);
            $db->sql_transaction('commit');
            // if some topics have been resync'ed then resync parent forums
            // except when we're only syncing a range, we don't want to sync forums during
            // batch processing.
            if ($resync_parents && sizeof($resync_forums) && $where_type != 'range') {
                sync('forum', 'forum_id', array_values($resync_forums), true, true);
            }
            break;
    }
    return;
}
function user_delete($mode, $user_id)
{
    global $config, $_CLASS;
    $_CLASS['core_db']->sql_transaction();
    switch ($mode) {
        case 'retain':
            $sql = 'UPDATE ' . FORUMS_TABLE . '
				SET forum_last_poster_id = ' . ANONYMOUS . " \r\n\t\t\t\tWHERE forum_last_poster_id = {$user_id}";
            $_CLASS['core_db']->query($sql);
            $sql = 'UPDATE ' . POSTS_TABLE . '
				SET poster_id = ' . ANONYMOUS . " \r\n\t\t\t\tWHERE poster_id = {$user_id}";
            $_CLASS['core_db']->query($sql);
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_poster = ' . ANONYMOUS . "\r\n\t\t\t\tWHERE topic_poster = {$user_id}";
            $_CLASS['core_db']->query($sql);
            $sql = 'UPDATE ' . TOPICS_TABLE . '
				SET topic_last_poster_id = ' . ANONYMOUS . "\r\n\t\t\t\tWHERE topic_last_poster_id = {$user_id}";
            $_CLASS['core_db']->query($sql);
            break;
        case 'remove':
            if (!function_exists('delete_posts')) {
                global $site_file_root;
                include $site_file_root . 'includes/forums/functions_admin.php';
            }
            $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts 
				FROM ' . POSTS_TABLE . " \r\n\t\t\t\tWHERE poster_id = {$user_id}\r\n\t\t\t\tGROUP BY topic_id";
            $result = $_CLASS['core_db']->query($sql);
            $topic_id_ary = array();
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                $topic_id_ary[$row['topic_id']] = $row['total_posts'];
            }
            $_CLASS['core_db']->free_result($result);
            if (!count($topic_id_ary)) {
                break;
            }
            $sql = 'SELECT topic_id, topic_replies, topic_replies_real 
				FROM ' . TOPICS_TABLE . ' 
				WHERE topic_id IN (' . implode(', ', array_keys($topic_id_ary)) . ')';
            $result = $_CLASS['core_db']->query($sql);
            $del_topic_ary = array();
            while ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
                if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']]) {
                    $del_topic_ary[] = $row['topic_id'];
                }
            }
            $_CLASS['core_db']->free_result($result);
            if (sizeof($del_topic_ary)) {
                $sql = 'DELETE FROM ' . TOPICS_TABLE . ' 
					WHERE topic_id IN (' . implode(', ', $del_topic_ary) . ')';
                $_CLASS['core_db']->query($sql);
            }
            // Delete posts, attachments, etc.
            delete_posts('poster_id', $user_id);
            break;
    }
    $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, FORUMS_TRACK_TABLE);
    foreach ($table_ary as $table) {
        $sql = "DELETE FROM {$table} \r\n\t\t\tWHERE user_id = {$user_id}";
        $_CLASS['core_db']->query($sql);
    }
    // Reset newest user info if appropriate
    if ($config['newest_user_id'] == $user_id) {
        $sql = 'SELECT user_id, username 
			FROM ' . USERS_TABLE . '
			WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
			ORDER BY user_id DESC
			LIMIT 1';
        $result = $_CLASS['core_db']->query($sql);
        if ($row = $_CLASS['core_db']->fetch_row_assoc($result)) {
            set_config('newest_user_id', $row['user_id']);
            set_config('newest_username', $row['username']);
        }
        $_CLASS['core_db']->freeresult($result);
    }
    set_config('num_users', $config['num_users'] - 1, TRUE);
    $_CLASS['core_db']->sql_transaction('commit');
    return false;
}