function sp_featured_do_uninstall()
{
    # delete our option
    sp_delete_option('featured');
    # remove our sfmeta
    sp_delete_sfmeta(0, 'featured');
}
function sp_admin_bar_do_deactivate()
{
    global $spGlobals;
    # remove the auth
    sp_deactivate_auth('bypass_akismet');
    # remove our auto update stuff
    $up = sp_get_sfmeta('autoupdate', 'admin');
    if ($up) {
        sp_delete_sfmeta($up[0]['meta_id']);
    }
}
function spa_save_messages_data()
{
    check_admin_referer('forum-adminform_messages', 'forum-adminform_messages');
    # custom message for editor
    $sfpostmsg = array();
    $sfpostmsg['sfpostmsgtext'] = sp_filter_text_save(trim($_POST['sfpostmsgtext']));
    $sfpostmsg['sfpostmsgtopic'] = isset($_POST['sfpostmsgtopic']);
    $sfpostmsg['sfpostmsgpost'] = isset($_POST['sfpostmsgpost']);
    sp_update_option('sfpostmsg', $sfpostmsg);
    sp_update_option('sfeditormsg', sp_filter_text_save(trim($_POST['sfeditormsg'])));
    # if set update, otherwise its empty, so remove
    if ($_POST['sfsneakpeek'] != '') {
        sp_add_sfmeta('sneakpeek', 'message', sp_filter_text_save(trim($_POST['sfsneakpeek'])));
    } else {
        $msg = sp_get_sfmeta('sneakpeek', 'message');
        if (!empty($msg)) {
            sp_delete_sfmeta($msg[0]['meta_id']);
        }
    }
    $sflogin = array();
    $sflogin = sp_get_option('sflogin');
    $sflogin['sfsneakredirect'] = sp_filter_save_cleanurl($_POST['sfsneakredirect']);
    sp_update_option('sflogin', $sflogin);
    # if set update, otherwise its empty, so remove
    if ($_POST['sfadminview'] != '') {
        sp_add_sfmeta('adminview', 'message', sp_filter_text_save(trim($_POST['sfadminview'])));
    } else {
        $msg = sp_get_sfmeta('adminview', 'message');
        if (!empty($msg)) {
            sp_delete_sfmeta($msg[0]['meta_id']);
        }
    }
    # if set update, otherwise its empty, so remove
    if ($_POST['sfuserview'] != '') {
        sp_add_sfmeta('userview', 'message', sp_filter_text_save(trim($_POST['sfuserview'])));
    } else {
        $msg = sp_get_sfmeta('userview', 'message');
        if (!empty($msg)) {
            sp_delete_sfmeta($msg[0]['meta_id']);
        }
    }
    do_action('sph_component_messages_save');
    $mess = spa_text('Custom messages updated');
    return $mess;
}
function sp_move_post()
{
    global $spVars, $spGlobals, $spThisUser;
    # extract data from POST
    $postid = sp_esc_int($_POST['postid']);
    $oldtopicid = sp_esc_int($_POST['oldtopicid']);
    $oldforumid = sp_esc_int($_POST['oldforumid']);
    $action = sp_esc_str($_POST['moveop']);
    # determine op type - new or exsiting topic
    if (isset($_POST['makepostmove1']) || isset($_POST['makepostmove3'])) {
        # new topic move or exsiting topic move called from notification
        # extract data from POST
        $newforumid = sp_esc_int($_POST['forumid']);
        if (!sp_get_auth('move_posts', $oldforumid) || !sp_get_auth('move_posts', $newforumid)) {
            if (!is_user_logged_in()) {
                $msg = sp_text('Access denied - are you logged in?');
            } else {
                $msg = sp_text('Access denied - you do not have permission');
            }
            sp_notify(SPFAILURE, $msg);
            return;
        }
        if (empty($newforumid)) {
            sp_notify(SPFAILURE, sp_text('Post move abandoned as no forum was selected'));
            return;
        }
        if (isset($_POST['makepostmove1'])) {
            # create new topic for a new topic post move only
            $newtopicname = sp_filter_title_save(trim($_POST['newtopicname']), SFTOPICS, 'topic_name');
            if (empty($newtopicname)) {
                sp_notify(SPFAILURE, sp_text('Post move abandoned as no topic was defined'));
                return;
            }
            # start with creating the new topic
            $newtopicslug = sp_create_slug($newtopicname, true, SFTOPICS, 'topic_slug');
            # now create the topic and post records
            $sql = 'INSERT INTO ' . SFTOPICS . "\n\t\t\t\t (topic_name, topic_slug, topic_date, forum_id, post_count, post_id, post_count_held, post_id_held)\n\t\t\t\t VALUES\n\t\t\t\t ('{$newtopicname}', '{$newtopicslug}', now(), {$newforumid}, 1, {$postid}, 1, {$postid});";
            if (spdb_query($sql) == false) {
                sp_notify(SPFAILURE, sp_text('Post move failed'));
                return;
            }
            $newtopicid = $spVars['insertid'];
            # check the topic slug and if empty use the topic id
            if (empty($newtopicslug)) {
                $newtopicslug = 'topic-' . $newtopicid;
                $thistopic = spdb_query('UPDATE ' . SFTOPICS . " SET\n\t\t\t\t\t\t\t\t\t\ttopic_slug='{$newtopicslug}'\n\t\t\t\t\t\t\t\t\t\tWHERE topic_id={$newtopicid}");
            }
        } else {
            # it's a re-entry
            $newtopicid = sp_esc_int($_POST['newtopicid']);
        }
        # Now determine the list of post ids to move
        $posts = array();
        switch ($action) {
            case 'single':
                $posts[] = $postid;
                break;
            case 'tostart':
                $sql = "SELECT post_id FROM " . SFPOSTS . " WHERE topic_id = {$oldtopicid} AND post_id <= {$postid}";
                $posts = spdb_select('col', $sql);
                break;
            case 'toend':
                $sql = "SELECT post_id FROM " . SFPOSTS . " WHERE topic_id = {$oldtopicid} AND post_id >= {$postid}";
                $posts = spdb_select('col', $sql);
                break;
            case 'select':
                $idlist = sp_esc_str(trim($_POST['idlist'], ","));
                if (empty($idlist)) {
                    $posts[] = $postid;
                } else {
                    $where = "topic_id = {$oldtopicid} AND post_index IN ({$idlist})";
                    $sql = "SELECT post_id FROM " . SFPOSTS . " WHERE topic_id = {$oldtopicid} AND post_index IN ({$idlist})";
                    $posts = spdb_select('col', $sql);
                }
                break;
        }
        if (empty($posts)) {
            sp_notify(SPFAILURE, sp_text('Post move abandoned as no posts were selected'));
            return;
        }
        # loop through and update post records and other housekeeping
        foreach ($posts as $post) {
            # update post record
            $sql = 'UPDATE ' . SFPOSTS . " SET\n\t\t\t\t \ttopic_id={$newtopicid},\n\t\t\t\t \tforum_id={$newforumid},\n\t\t\t\t \tpost_status=0\n\t\t\t\t \tWHERE post_id={$post}";
            spdb_query($sql);
            # update post if in sfwaiting
            spdb_query("UPDATE " . SFWAITING . " SET forum_id={$newforumid}, topic_id={$newtopicid} WHERE post_id={$post}");
            # notify author of move
            $thisPost = spdb_table(SFPOSTS, "post_id={$post}", 'row');
            $sfadminsettings = sp_get_option('sfadminsettings');
            if ($sfadminsettings['movenotice'] && $spThisUser->ID != $thisPost->user_id) {
                $nData = array();
                $nData['user_id'] = $thisPost->user_id;
                $nData['guest_email'] = $thisPost->guest_email;
                $nData['post_id'] = $post;
                $nData['link'] = sp_permalink_from_postid($post);
                $nData['link_text'] = spdb_table(SFTOPICS, "topic_id={$thisPost->topic_id}", 'topic_name');
                $nData['message'] = sp_text('A post of yours was moved to');
                $nData['expires'] = time() + 30 * 24 * 60 * 60;
                # 30 days; 24 hours; 60 mins; 60secs
                sp_add_notice($nData);
            }
        }
        # flush and rebuild topic cache (since one or more posts approved)
        sp_rebuild_topic_cache();
        # rebuild indexing on target topic and forum
        sp_build_post_index($newtopicid);
        sp_build_forum_index($newforumid);
        # determine if any posts left in old topic - just in case - delete or reindex
        $sql = "SELECT post_id FROM " . SFPOSTS . " WHERE topic_id = {$oldtopicid}";
        $posts = spdb_select('col', $sql);
        if (empty($posts)) {
            spdb_query("DELETE FROM " . SFTOPICS . " WHERE topic_id=" . $oldtopicid);
        } else {
            sp_build_post_index($oldtopicid);
            sp_build_forum_index($oldforumid);
        }
        do_action('sph_move_post', $oldtopicid, $newtopicid, $newforumid, $oldforumid, $postid, $spThisUser->ID);
        sp_notify(SPSUCCESS, sp_text('Post moved'));
    } elseif (isset($_POST['makepostmove2'])) {
        # must be a move to an exisiting topic action
        sp_add_sfmeta('post_move', 'post_move', $_POST, true);
    }
    if (isset($_POST['makepostmove3'])) {
        # if a re-entry for move to exisiting - clear the sfmeta record
        $meta = sp_get_sfmeta('post_move', 'post_move');
        if ($meta) {
            $id = $meta[0]['meta_id'];
            sp_delete_sfmeta($id);
            unset($spGlobals['post_move']);
        }
    }
}
function sp_render_forum($content)
{
    global $spIsForum, $spContentLoaded, $spVars, $spGlobals, $spThisUser, $spStatus;
    # make sure we are at least in the html body before outputting any content
    if (!sp_get_option('sfwpheadbypass') && !did_action('wp_head')) {
        return '';
    }
    if ($spIsForum && !post_password_required(get_post(sp_get_option('sfpage')))) {
        # Limit forum display to within the wp loop?
        if (sp_get_option('sfinloop') && !in_the_loop()) {
            return $content;
        }
        # Has forum content already been loaded and are we limiting?
        if (!sp_get_option('sfmultiplecontent') && $spContentLoaded) {
            return $content;
        }
        $spContentLoaded = true;
        sp_set_server_timezone();
        # offer a way for forum display to be short circuited but always show for admins unless an upgrade
        $message = sp_abort_display_forum();
        $content .= $message;
        if (!empty($message) && (!$spThisUser->admin || $spStatus != 'ok')) {
            return $content;
        }
        # process query arg actions
        # check for edit operation. Need tp check for '_x' in case using mobile as buttin is an image
        if (isset($_POST['editpost']) || isset($_POST['editpost_x'])) {
            sp_save_edited_post();
        }
        if (isset($_POST['edittopic'])) {
            sp_save_edited_topic();
        }
        if (isset($_POST['ordertopicpins'])) {
            sp_promote_pinned_topic();
        }
        if (isset($_POST['makepostreassign'])) {
            sp_reassign_post();
        }
        if (isset($_POST['approvepost'])) {
            sp_approve_post(false, sp_esc_int($_POST['approvepost']), $spVars['topicid']);
        }
        if (isset($_POST['unapprovepost'])) {
            sp_unapprove_post(sp_esc_int($_POST['unapprovepost']));
        }
        if (isset($_POST['doqueue'])) {
            sp_remove_waiting_queue();
        }
        if (isset($_POST['notifyuser'])) {
            sp_post_notification(sp_esc_str($_POST['sp_notify_user']), sp_esc_str($_POST['message']), sp_esc_int($_POST['postid']));
        }
        # move a topic and redirect to that topic
        if (isset($_POST['maketopicmove'])) {
            if (empty($_POST['forumid'])) {
                sp_notify(1, sp_text('Destination forum not selected'));
                return;
            }
            sp_move_topic();
            $forumslug = spdb_table(SFFORUMS, 'forum_id=' . sp_esc_int(sp_esc_int($_POST['forumid'])), 'forum_slug');
            $topicslug = spdb_table(SFTOPICS, 'topic_id=' . sp_esc_int(sp_esc_int($_POST['currenttopicid'])), 'topic_slug');
            $returnURL = sp_build_url($forumslug, $topicslug, 0);
            sp_redirect($returnURL);
        }
        # move a post and redirect to the post
        if (isset($_POST['makepostmove1']) || isset($_POST['makepostmove2']) || isset($_POST['makepostmove3'])) {
            sp_move_post();
            if (isset($_POST['makepostmove1'])) {
                $returnURL = sp_permalink_from_postid(sp_esc_int($_POST['postid']));
                sp_redirect($returnURL);
            }
        }
        # cancel a post move
        if (isset($_POST['cancelpostmove'])) {
            $meta = sp_get_sfmeta('post_move', 'post_move');
            if ($meta) {
                $id = $meta[0]['meta_id'];
                sp_delete_sfmeta($id);
                unset($spGlobals['post_move']);
            }
        }
        # rebuild the forum and post indexes
        if (isset($_POST['rebuildforum']) || isset($_POST['rebuildtopic'])) {
            sp_build_post_index(sp_esc_int($_POST['topicid']), true);
            sp_build_forum_index(sp_esc_int($_POST['forumid']), false);
        }
        # Set display mode if topic view (for editing posts)
        if ($spVars['pageview'] == 'topic' && isset($_POST['postedit'])) {
            $spVars['displaymode'] = 'edit';
            $spVars['postedit'] = $_POST['postedit'];
        } else {
            $spVars['displaymode'] = 'posts';
        }
        # clean cache of timed our records
        sp_clean_cache();
        #--Scratch Pad Area---Please Leave Here---------
        #--End Scratch Pad Area-------------------------
        # let other plugins check for posted actions
        do_action('sph_setup_forum');
        # do we use output buffering?
        $ob = sp_get_option('sfuseob');
        if ($ob) {
            ob_start();
        }
        # set up some stuff before wp page content
        $content .= sp_display_banner();
        $content = apply_filters('sph_before_wp_page_content', $content);
        # run any other wp filters on page content but exclude ours
        if (!$ob) {
            remove_filter('the_content', 'sp_render_forum', 1);
            $content = apply_filters('the_content', $content);
            $content = wpautop($content);
            add_filter('the_content', 'sp_render_forum', 1);
        }
        # set up some stuff after wp page content
        $content = apply_filters('sph_after_wp_page_content', $content);
        $content .= '<div id="dialogcontainer" style="display:none;"></div>';
        $content .= sp_js_check();
        # echo any wp page content
        echo $content;
        # now add our content
        do_action('sph_before_template_processing');
        sp_process_template();
        do_action('sph_after_template_processing');
        # Return if using output buffering
        if ($ob) {
            $forum = ob_get_contents();
            ob_end_clean();
            return $forum;
        }
    }
    # not returning any content since we output it already unless password needed
    if (post_password_required(get_post(sp_get_option('sfpage')))) {
        return $content;
    }
}
function spa_save_housekeeping_data()
{
    check_admin_referer('forum-adminform_housekeeping', 'forum-adminform_housekeeping');
    $mess = '';
    if (isset($_POST['rebuild-fidx'])) {
        $forumid = $_POST['forum_id'];
        if (is_numeric($forumid)) {
            $topics = spdb_table(SFTOPICS, "forum_id={$forumid}");
            if ($topics) {
                include_once SF_PLUGIN_DIR . '/forum/database/sp-db-management.php';
                foreach ($topics as $topic) {
                    sp_build_post_index($topic->topic_id);
                }
                # after reubuilding post indexes, rebuild the forum indexes
                sp_build_forum_index($forumid);
                do_action('sph_toolbox_housekeeping_forum_index');
                $mess = spa_text('Forum indexes rebuilt');
            } else {
                $mess = spa_text('Forum index rebuild failed - no topics in selected forum');
            }
        } else {
            $mess = spa_text('Forum index rebuild failed - no forum selected');
        }
    }
    if (isset($_POST['transient-cleanup'])) {
        include_once SF_PLUGIN_DIR . '/forum/database/sp-db-management.php';
        sp_transient_cleanup();
        do_action('sph_toolbox_housekeeping_transient');
        $mess = spa_text('WP transients cleaned');
    }
    if (isset($_POST['clean-newposts'])) {
        $days = isset($_POST['sfdays']) ? max(sp_esc_int($_POST['sfdays']), 0) : 30;
        $users = spdb_select('col', "SELECT user_id FROM " . SFMEMBERS . " WHERE lastvisit < DATE_SUB(CURDATE(), INTERVAL " . $days . " DAY)");
        if ($users) {
            foreach ($users as $user) {
                spdb_query('UPDATE ' . SFMEMBERS . " SET newposts='a:1:{i:0;i:0;}' WHERE user_id={$user}");
            }
        }
        do_action('sph_toolbox_housekeeping_newpost');
        $mess = spa_text('New posts lists cleaned');
    }
    if (isset($_POST['postcount-cleanup'])) {
        spdb_query('UPDATE ' . SFMEMBERS . ' SET posts = (SELECT COUNT(*) FROM ' . SFPOSTS . ' WHERE ' . SFPOSTS . '.user_id = ' . SFMEMBERS . '.user_id)');
        # force stats to update
        do_action('sph_stats_cron');
        do_action('sph_toolbox_housekeeping_postcount');
        $mess = spa_text('User post counts calculated');
    }
    if (isset($_POST['reset-tabs'])) {
        # clear out current tabs
        $tabs = sp_get_sfmeta('profile', 'tabs');
        sp_delete_sfmeta($tabs[0]['meta_id']);
        # start adding new ones
        spa_new_profile_setup();
        do_action('sph_toolbox_housekeeping_profile_tabs');
        $mess = spa_text('Profile tabs reset');
    }
    if (isset($_POST['reset-auths'])) {
        sp_reset_auths();
        do_action('sph_toolbox_housekeeping_auths');
        $mess = spa_text('Auths caches cleaned');
    }
    if (isset($_POST['reset-plugin-data'])) {
        sp_reset_member_plugindata();
        do_action('sph_toolbox_housekeeping_plugindata');
        $mess = spa_text('Users Plugin Data reset');
    }
    if (isset($_POST['reset-combinedcss'])) {
        sp_clear_combined_css('all');
        sp_clear_combined_css('mobile');
        sp_clear_combined_css('tablet');
        do_action('sph_toolbox_housekeeping_ccombined_css');
        $mess = spa_text('Combined CSS cache file removed');
    }
    if (isset($_POST['reset-combinedjs'])) {
        sp_clear_combined_scripts('desktop');
        sp_clear_combined_scripts('mobile');
        sp_clear_combined_scripts('tablet');
        do_action('sph_toolbox_housekeeping_combined_js');
        $mess = spa_text('Combined scripts cache files removed');
    }
    if (isset($_POST['flushcache'])) {
        sp_flush_cache('all');
        do_action('sph_toolbox_housekeeping_flush_cache');
        $mess = spa_text('General cache flushed');
    }
    do_action('sph_toolbox_housekeeping_save');
    return $mess;
}