function sp_fix_shortened_links()
{
    $postCount = spdb_count(SFPOSTS);
    $limit = 1000;
    for ($offset = 0; $offset < $postCount; $offset += $limit) {
        $posts = spdb_select('set', 'SELECT post_id, post_content FROM ' . SFPOSTS . " ORDER BY post_id ASC LIMIT {$offset}, {$limit}");
        foreach ($posts as $post) {
            /*
                Matches would be:
                0 = The entire string
                1 = The link in the <a> tag
                2 = The rest of the parameters in the <a> tag (nofollow, target, etc.)
                3 = The part after the 5 periods
            
                So then we want to replace 0 with 1 for each result
            
                We are assuming that the links have 5 consecutive periods
            */
            $postContent = stripslashes($post->post_content);
            preg_match_all("/<a href=\"(.*?)\"(.*?)\\.\\.\\.\\.\\.(.*?)<\\/a>/is", $postContent, $linkMatches);
            if (!empty($linkMatches[0])) {
                foreach ($linkMatches[0] as $index => $stringMatch) {
                    $postContent = str_replace($stringMatch, $linkMatches[1][$index], $postContent);
                }
                $postContent = esc_sql($postContent);
                spdb_query('UPDATE ' . SFPOSTS . " SET post_content = '{$postContent}' WHERE post_id = {$post->post_id}");
            }
        }
    }
}
function sp_display_item_stats($table, $key, $value, $label)
{
    $c = spdb_count($table, "{$key} = {$value}");
    echo '<span class="spItemStat">' . $label . ' <b>' . $c . '</b></span>';
}
function sp_get_activity_exists($type, $value)
{
    $value = (int) $value;
    if (empty($value) || empty($type)) {
        return false;
    }
    return spdb_count(SFUSERACTIVITY, "item_id={$value} AND type_id={$type}");
}
function sp_build_forum_index($forumid, $returnmsg = false)
{
    if (!$forumid) {
        return '';
    }
    # get the topic count for this forum
    $topiccount = spdb_count(SFTOPICS, "forum_id={$forumid}");
    # get the post count and post count held
    $postcount = spdb_sum(SFTOPICS, 'post_count', "forum_id={$forumid}");
    $postcountheld = spdb_sum(SFTOPICS, 'post_count_held', "forum_id={$forumid}");
    # get the last post id and last post held id that appeared in a topic within this forum
    $postid = spdb_table(SFPOSTS, "forum_id={$forumid}", 'post_id', 'post_id DESC', '1');
    $postidheld = spdb_table(SFPOSTS, "forum_id={$forumid} AND post_status=0", 'post_id', 'post_id DESC', '1');
    if (!$topiccount) {
        $topiccount = 0;
    }
    if (!$postcount) {
        $postcount = 0;
    }
    if (!isset($postid)) {
        $postid = 'NULL';
    }
    if (!$postcountheld) {
        $postcountheld = 0;
    }
    if (!isset($postidheld)) {
        $postidheld = 'NULL';
    }
    # update forum record
    spdb_query('UPDATE ' . SFFORUMS . " SET\n\t\t\t\tpost_id={$postid},\n\t\t\t\tpost_id_held={$postidheld},\n\t\t\t\tpost_count={$postcount},\n\t\t\t\tpost_count_held={$postcountheld},\n\t\t\t\ttopic_count={$topiccount}\n\t\t\t\tWHERE forum_id={$forumid}");
    if ($returnmsg) {
        sp_notify(SPSUCCESS, sp_text('Verification complete'));
    }
}
function sp_guests_browsing()
{
    global $spVars;
    $where = '';
    # Check that pageview is  set as this might be called from outside of the forum
    if (!empty($spVars['pageview'])) {
        if ($spVars['pageview'] == 'forum') {
            $where = "forum_id=" . $spVars['forumid'];
        }
        if ($spVars['pageview'] == 'topic') {
            $where = "topic_id=" . $spVars['topicid'];
        }
    }
    if (empty($where)) {
        return;
    }
    return spdb_count(SFTRACK, "trackuserid = 0 AND " . $where);
}
 function saveData()
 {
     global $spVars, $spGlobals;
     $this->abort = false;
     $this->newpost['action'] = $this->action;
     # make the entire class object available for modification before saving
     # warning:  note the passing by reference.  other end could wreak havoc
     do_action_ref_array('sph_new_post_pre_save', array(&$this));
     # Write the topic if needed
     if ($this->action == 'topic') {
         $this->newpost = apply_filters('sph_new_topic_pre_data_saved', $this->newpost);
         $spdb = new spdbComplex();
         $spdb->table = SFTOPICS;
         $spdb->fields = array('topic_name', 'topic_slug', 'topic_date', 'forum_id', 'topic_status', 'topic_pinned', 'user_id');
         $spdb->data = array($this->newpost['topicname'], $this->newpost['topicslug'], $this->newpost['postdate'], $this->newpost['forumid'], $this->newpost['topicstatus'], $this->newpost['topicpinned'], $this->newpost['userid']);
         $spdb = apply_filters('sph_new_topic_data', $spdb);
         $this->newpost['db'] = $spdb->insert();
         if ($this->newpost['db'] == true) {
             $this->newpost['topicid'] = $spVars['insertid'];
             $this->newpost = apply_filters('sph_new_topic_data_saved', $this->newpost);
         } else {
             $this->abort = true;
             $this->message = sp_text('Unable to save new topic record');
             return;
         }
         # failsafe: check the topic slug and if empty use the topic id
         if (empty($this->newpost['topicslug'])) {
             $this->newpost['topicslug'] = 'topic-' . $this->newpost['topicid'];
             spdb_query('UPDATE ' . SFTOPICS . " SET topic_slug='" . $this->newpost['topicslug'] . "' WHERE topic_id=" . $this->newpost['topicid']);
         }
     }
     # Write the post
     # Double check forum id is correct - it has been known for a topic to have just been moved!
     $this->newpost['forumid'] = spdb_table(SFTOPICS, 'topic_id=' . $this->newpost['topicid'], 'forum_id');
     # Get post count in topic to enable post index setting
     $index = spdb_count(SFPOSTS, 'topic_id = ' . $this->newpost['topicid']);
     $index++;
     $this->newpost['postindex'] = $index;
     # if topic lock set in post reply update topic (post only)
     if ($this->action == 'post' && $this->newpost['topicstatus']) {
         spdb_query('UPDATE ' . SFTOPICS . ' SET topic_status=1 WHERE topic_id=' . $this->newpost['topicid']);
     }
     $this->newpost = apply_filters('sph_new_post_pre_data_saved', $this->newpost);
     $spdb = new spdbComplex();
     $spdb->table = SFPOSTS;
     $spdb->fields = array('post_content', 'post_date', 'topic_id', 'forum_id', 'user_id', 'guest_name', 'guest_email', 'post_pinned', 'post_index', 'post_status', 'poster_ip', 'source');
     $spdb->data = array($this->newpost['postcontent'], $this->newpost['postdate'], $this->newpost['topicid'], $this->newpost['forumid'], $this->newpost['userid'], $this->newpost['guestname'], $this->newpost['guestemail'], $this->newpost['postpinned'], $this->newpost['postindex'], $this->newpost['poststatus'], $this->newpost['posterip'], $this->newpost['source']);
     $spdb = apply_filters('sph_new_post_data', $spdb);
     $this->newpost['db'] = $spdb->insert();
     if ($this->newpost['db'] == true) {
         $this->newpost['postid'] = $spVars['insertid'];
         $this->newpost = apply_filters('sph_new_post_data_saved', $this->newpost);
     } else {
         $this->abort = true;
         $this->message = sp_text('Unable to save new post message');
         return;
     }
     # Update the timestamp of the last post
     sp_update_option('poststamp', $this->newpost['postdate']);
     $this->returnURL = sp_build_url($this->newpost['forumslug'], $this->newpost['topicslug'], 0, $this->newpost['postid']);
     if ($this->newpost['poststatus']) {
         $this->newpost['submsg'] .= ' - ' . sp_text('placed in moderation') . ' ';
     }
     # Now for all that post-save processing required
     if ($this->guest) {
         $sfguests = sp_get_option('sfguests');
         if ($sfguests['storecookie']) {
             sp_write_guest_cookie($this->newpost['guestname'], $this->newpost['guestemail']);
         }
     } else {
         $postcount = sp_get_member_item($this->newpost['userid'], 'posts');
         $postcount++;
         sp_update_member_item($this->newpost['userid'], 'posts', $postcount);
         # see if postcount qualifies member for new user group membership
         # get rankings information
         if (!$this->admin) {
             # ignore for admins as they dont belong to user groups
             global $spGlobals;
             if (!empty($spGlobals['forum_rank'])) {
                 $index = 0;
                 foreach ($spGlobals['forum_rank'] as $x => $info) {
                     $rankdata['title'][$index] = $x;
                     $rankdata['posts'][$index] = $info['posts'];
                     $rankdata['usergroup'][$index] = $info['usergroup'];
                     $index++;
                 }
                 # sort rankings
                 array_multisort($rankdata['posts'], SORT_ASC, $rankdata['title'], $rankdata['usergroup']);
                 # check for new ranking
                 for ($x = 0; $x < count($rankdata['posts']); $x++) {
                     if ($postcount <= $rankdata['posts'][$x] && !empty($rankdata['usergroup'][$x])) {
                         # if a user group is tied to forum rank add member to the user group
                         if ($rankdata['usergroup'][$x] != 'none') {
                             sp_add_membership($rankdata['usergroup'][$x], $this->newpost['userid']);
                         }
                         break;
                         # only update highest rank
                     }
                 }
             }
         }
     }
     # set new url for email
     $this->newpost['url'] = $this->returnURL;
     # allow plugins to add to post message
     $this->newpost['submsg'] = apply_filters('sph_post_message', $this->newpost['submsg'], $this->newpost);
     # add to or remove from admins new post queue
     if ($this->admin || $this->moderator) {
         # remove topic from waiting...
         sp_remove_from_waiting(false, $this->newpost['topicid']);
     } else {
         # add topic to waiting
         sp_add_to_waiting($this->newpost['topicid'], $this->newpost['forumid'], $this->newpost['postid'], $this->newpost['userid']);
     }
     # if a new post remove topic from the users new post list if in it
     if ($this->action == 'post') {
         sp_remove_users_newposts($this->newpost['topicid'], $this->newpost['userid']);
     }
     # do we need to approve any posts in moderation in this topic?
     if ($this->admin && $spGlobals['admin']['sfadminapprove'] || $this->moderator && $spGlobals['admin']['sfmoderapprove']) {
         sp_approve_post(true, 0, $this->newpost['topicid'], false, $this->newpost['forumid']);
     }
     # if post in moderatiuon then add entry to notices
     if ($this->newpost['poststatus'] != 0) {
         $nData = array();
         $nData['user_id'] = $this->newpost['userid'];
         $nData['guest_email'] = $this->newpost['guestemail'];
         $nData['post_id'] = $this->newpost['postid'];
         $nData['link'] = $this->newpost['url'];
         $nData['link_text'] = $this->newpost['topicname'];
         $nData['message'] = sp_text('Your post is awaiting moderation in the topic');
         $nData['expires'] = time() + 30 * 24 * 60 * 60;
         # 30 days; 24 hours; 60 mins; 60secs
         sp_add_notice($nData);
     }
     # Add this new item to the new tpic/post cache
     $meta = sp_get_sfmeta_key('topic_cache', 'new');
     $cacheSize = sp_get_option('topic_cache');
     $a = array();
     $a[LISTFORUM] = (int) $this->newpost['forumid'];
     $a[LISTTOPIC] = (int) $this->newpost['topicid'];
     $a[LISTPOST] = (int) $this->newpost['postid'];
     $a[LISTSTATUS] = (int) $this->newpost['poststatus'];
     if (isset($spGlobals['topic_cache']['new']) && !empty($spGlobals['topic_cache']['new'])) {
         array_unshift($spGlobals['topic_cache']['new'], $a);
         if (count($spGlobals['topic_cache']['new']) > $cacheSize) {
             array_pop($spGlobals['topic_cache']['new']);
         }
     }
     sp_update_sfmeta('topic_cache', 'new', $spGlobals['topic_cache']['new'], $meta, true);
     # remove group level caches to accommodate new post
     spdb_query('DELETE FROM ' . SFCACHE . " WHERE cache_id LIKE '%*group'");
     # save post in cache for flood control
     sp_add_cache('floodcontrol', time() + sp_get_option('floodcontrol'));
     # Update forum, topic and post index data
     sp_build_post_index($this->newpost['topicid']);
     sp_build_forum_index($this->newpost['forumid']);
     # send out email notifications
     sp_email_notifications($this->newpost);
     # one final filter - just in case
     do_action_ref_array('sph_post_new_completed', array(&$this));
     # and a final action hook
     do_action('sph_new_post', $this->newpost);
     do_action('sph_post_create', $this->newpost);
 }
function spa_forums_create_forum_form()
{
    ?>
<script type="text/javascript">
    jQuery(document).ready(function() {
    	spjAjaxForm('sfforumnew', 'sfreloadfb');
    });
</script>
<?php 
    global $spPaths, $tab;
    spa_paint_options_init();
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=forums-loader&amp;sfnonce=' . wp_create_nonce('forum-ahah') . '&amp;saveform=createforum';
    ?>
	<form action="<?php 
    echo $ahahURL;
    ?>
" method="post" id="sfforumnew" name="sfforumnew">
<?php 
    echo sp_create_nonce('forum-adminform_forumnew');
    spa_paint_open_tab(spa_text('Forums') . ' - ' . spa_text('Create New Forum'), true);
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Create New Forum'), 'true', 'create-new-forum');
    # check there are groups before proceeding
    if (spdb_count(SFGROUPS) == 0) {
        echo '<br /><div class="sfoptionerror">';
        spa_etext('There are no groups defined');
        echo '<br />' . spa_text('Create new group');
        echo '</div><br />';
        spa_paint_close_fieldset();
        spa_paint_close_panel();
        spa_paint_close_container();
        spa_paint_close_tab();
        echo '</form>';
        return;
    }
    # Select the forum type first
    echo "<div class='sp-form-row'>\n";
    echo "<div class='wp-core-ui sflabel sp-label-40'>" . spa_text('What type of forum are you creating') . ":</div>\n";
    echo "<div class='wp-core-ui sp-radio'>";
    echo '<input type="radio" name="forumtype" id="sfradio1" tabindex="' . $tab . '" value="1" checked="checked" onchange="spjSetForumOptions(\'forum\');" />' . "\n";
    echo '<label for="sfradio1" class="wp-core-ui">' . spa_text('Standard Forum') . '</label><br>' . "\n";
    $tab++;
    # check there are forums before offering subforum creation!
    if (spdb_count(SFFORUMS) != 0) {
        echo '<input type="radio" name="forumtype" id="sfradio2" tabindex="' . $tab . '" value="2" onchange="spjSetForumOptions(\'subforum\');" />' . "\n";
        echo '<label for="sfradio2" class="wp-core-ui">' . spa_text('Sub or child forum') . '</label>' . "\n";
        $tab++;
    }
    echo '</div><div class="clearboth"></div></div>';
    # Now display the two select box options
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=forums&amp;sfnonce=' . wp_create_nonce('forum-ahah');
    $target = 'fseq';
    echo '<div id="groupselect" style="display:block;">';
    echo "<div class='sp-form-row'>\n";
    echo "<div class='wp-core-ui sflabel sp-label-40'>" . spa_text('Select group new forum will belong to') . ":</div>\n";
    echo '<select class="wp-core-ui  sp-input-60" tabindex="' . $tab . '" name="group_id"  onchange="spjSetForumSequence();">';
    echo spa_create_group_select(0, 1);
    echo "</select>\n";
    echo '<div class="clearboth"></div>';
    echo '</div>';
    $tab++;
    echo '</div>';
    echo '<div id="forumselect" style="display:none;">';
    echo "<div class='sp-form-row'>\n";
    echo "<div class='wp-core-ui sflabel sp-label-40'>" . spa_text('Select forum new subforum will belong to') . ":</div>\n";
    echo '<select class="wp-core-ui  sp-input-60" tabindex="' . $tab . '" name="forum_id"  onchange="spjSetForumSequence();">';
    echo sp_render_group_forum_select(false, false, false, true);
    echo "</select>\n";
    echo '<div class="clearboth"></div>';
    echo '</div>';
    $tab++;
    echo '</div>';
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    spa_paint_close_container();
    echo '<div class="sfform-panel-spacer"></div>';
    spa_paint_close_tab();
    echo '<div class="sfform-panel-spacer"></div>';
    echo '<div class="sfhidden" id="block1">';
    spa_paint_open_nohead_tab(false);
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Forum Details'), false);
    $target = 'thisforumslug';
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=forums&amp;sfnonce=' . wp_create_nonce('forum-ahah');
    # forum name and slug
    echo "<div class='sp-form-row'>";
    echo "<div class='wp-core-ui sflabel sp-label-40'>" . spa_text('Forum Name') . ':</div>';
    echo '<input type="text" class="wp-core-ui sp-input-60" tabindex="' . $tab . '" name="forum_name" value="" onchange="spjSetForumSlug(this, \'' . $ahahURL . '\', \'' . $target . '\', \'new\');" />';
    echo '<div class="clearboth"></div>';
    echo '</div>';
    $tab++;
    echo "<div class='sp-form-row'>\n";
    echo "<div class='wp-core-ui sflabel sp-label-40'>" . spa_text('Forum slug') . ":</div>";
    echo '<input type="text" class="wp-core-ui sp-input-60" tabindex="' . $tab . '" name="thisforumslug" id="thisforumslug" value="" disabled="disabled" onchange="spjSetForumSlug(this, \'' . $ahahURL . '\', \'' . $target . '\', \'new\');" />';
    echo '<div class="clearboth"></div>';
    echo '</div>';
    $tab++;
    spa_paint_input(spa_text('Description'), 'forum_desc', '', false, true);
    spa_paint_checkbox(spa_text('Locked'), 'forum_status', 0);
    spa_paint_checkbox(spa_text('Disable forum RSS feed so feed will not be generated'), 'forum_private', 0);
    echo '<div class="sfoptionerror spaceabove">';
    echo '<p><b>' . sp_text('Custom Icon Ordering') . '</b></br>';
    echo sp_text('When using custom forum or topic icons and multiple conditions exist, the following precedence is used:') . '</p>';
    echo sp_text('Locked') . '<br />';
    echo sp_text('Pinned') . '<br />';
    echo sp_text('Unread') . '<br />';
    echo sp_text('Custom') . '<br />';
    echo sp_text('Theme Default') . '<br />';
    echo '</div>';
    spa_paint_select_start(spa_text('Custom forum icon'), 'forum_icon', '');
    spa_select_icon_dropdown('forum_icon', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom forum icon when new posts'), 'forum_icon_new', '');
    spa_select_icon_dropdown('forum_icon_new', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom forum icon when locked'), 'forum_icon_locked', '');
    spa_select_icon_dropdown('forum_icon_locked', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom topic icon'), 'topic_icon', '');
    spa_select_icon_dropdown('topic_icon', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom topic icon when new posts'), 'topic_icon_new', '');
    spa_select_icon_dropdown('topic_icon_new', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom topic icon when locked'), 'topic_icon_locked', '');
    spa_select_icon_dropdown('topic_icon_locked', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Custom topic icon when pinned'), 'topic_icon_pinned', '');
    spa_select_icon_dropdown('topic_icon_pinned', spa_text('Select Custom Icon'), SF_STORE_DIR . '/' . $spPaths['custom-icons'] . '/', '', false);
    spa_paint_select_end();
    spa_paint_input(spa_text('Custom meta keywords (SEO option must be enabled)'), 'forum_keywords', '', false, true);
    spa_paint_wide_textarea('Special forum message to be displayed above forums', 'forum_message', '');
    spa_paint_close_fieldset();
    echo '<div class="sfoptionerror spaceabove">';
    echo sprintf(sp_text('To re-order your Groups, Forums and SubForums use the %s Order Groups and Forums %s option from the Forums Menu'), '<b>', '</b>');
    echo '</div>';
    spa_paint_close_panel();
    spa_paint_tab_right_cell();
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Extended Forum Options'), false);
    # As added by plugins
    do_action('sph_forum_create_forum_options');
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Add User Group Permissions'), false);
    echo '<div id="block2" class="sfhidden">';
    echo '<strong>' . spa_text('You can selectively set the permission sets for the forum below. If you want to use the default permissions for the selected group, then do not select anything') . '</strong>';
    # Permissions
    $usergroups = spa_get_usergroups_all();
    $roles = sp_get_all_roles();
    foreach ($usergroups as $usergroup) {
        echo '<input type="hidden" name="usergroup_id[]" value="' . $usergroup->usergroup_id . '" />';
        spa_paint_select_start(sp_filter_title_display($usergroup->usergroup_name), 'role[]', '');
        echo '<option value="-1">' . spa_text('Select permission set') . '</option>';
        foreach ($roles as $role) {
            echo '<option value="' . $role->role_id . '">' . sp_filter_title_display($role->role_name) . '</option>' . "\n";
        }
        spa_paint_select_end();
    }
    echo '</div>';
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    spa_paint_close_container();
    ?>
		<div class="sfform-submit-bar">
            <input type="submit" class="button-primary" id="saveit" name="saveit" value="<?php 
    spa_etext('Create New Forum');
    ?>
" />
		</div>
    	<?php 
    spa_paint_close_tab();
    ?>
        </div>
	</form>
	<div class="sfform-panel-spacer"></div>
<?php 
}
function sp_OnlineStats($args = '', $mostLabel = '', $currentLabel = '', $browsingLabel = '', $guestLabel = '')
{
    $defs = array('pMostClass' => 'spMostOnline', 'pCurrentClass' => 'spCurrentOnline', 'pBrowsingClass' => 'spCurrentBrowsing', 'link_names' => 1, 'usersOnly' => 0, 'echo' => 1, 'get' => 0);
    $a = wp_parse_args($args, $defs);
    $a = apply_filters('sph_OnlineStats_args', $a);
    extract($a, EXTR_SKIP);
    # sanitize before use
    $pMostClass = esc_attr($pMostClass);
    $pCurrentClass = esc_attr($pCurrentClass);
    $pBrowsingClass = esc_attr($pBrowsingClass);
    $link_names = (int) $link_names;
    $usersOnly = (int) $usersOnly;
    $echo = (int) $echo;
    $get = (int) $get;
    if (!empty($mostLabel)) {
        $mostLabel = sp_filter_title_display($mostLabel);
    }
    if (!empty($currentLabel)) {
        $currentLabel = sp_filter_title_display($currentLabel);
    }
    if (!empty($browsingLabel)) {
        $browsingLabel = sp_filter_title_display($browsingLabel);
    }
    if (!empty($guestLabel)) {
        $guestLabel = sp_filter_title_display($guestLabel);
    }
    # grab most online stat and update if new most
    $max = sp_get_option('spMostOnline');
    $online = spdb_count(SFTRACK);
    if ($online > $max) {
        $max = $online;
        sp_update_option('spMostOnline', $max);
    }
    $members = sp_get_members_online();
    if ($get) {
        $getData = new stdClass();
        $getData->max = $max;
        $getData->members = $members;
        return $getData;
    }
    # render the max online stats
    $out = "<p class='{$pMostClass}'><span>{$mostLabel}</span>{$max}</p>";
    # render the current online stats
    $browse = '';
    $out .= "<p class='{$pCurrentClass}'><span>{$currentLabel}</span>";
    # members online
    if ($members) {
        global $spThisUser, $spVars;
        $firstOnline = true;
        $firstBrowsing = true;
        $spMemberOpts = sp_get_option('sfmemberopts');
        foreach ($members as $user) {
            $userOpts = unserialize($user->user_options);
            if (!isset($userOpts['hidestatus'])) {
                $userOpts['hidestatus'] = false;
            }
            if ($spThisUser->admin || !$spMemberOpts['sfhidestatus'] || !$userOpts['hidestatus']) {
                if (!$firstOnline) {
                    $out .= ', ';
                }
                $out .= "<span class='spOnlineUser " . $user->display . "'>";
                $out .= sp_build_name_display($user->trackuserid, sp_filter_name_display($user->display_name), $link_names);
                $out .= '</span>';
                $firstOnline = false;
                # Set up the members browsing curent item list while here
                # Check that pageview is  set as this might be called from outside of the forum
                if (!empty($spVars['pageview'])) {
                    if ($spVars['pageview'] == 'forum' && $user->forum_id == $spVars['forumid'] || $spVars['pageview'] == 'topic' && $user->topic_id == $spVars['topicid']) {
                        if (!$firstBrowsing) {
                            $browse .= ', ';
                        }
                        $browse .= "<span class='spOnlineUser " . $user->display . "'>";
                        $browse .= sp_build_name_display($user->trackuserid, sp_filter_name_display($user->display_name), $link_names);
                        $browse .= '</span>';
                        $firstBrowsing = false;
                    }
                }
            }
        }
    }
    # guests online
    if (!$usersOnly && $online && $online > count($members)) {
        $guests = $online - count($members);
        $out .= "<br />{$guests} <span class='spOnlineUser spType-Guest'>{$guestLabel}</span>";
    }
    $out .= '</p>';
    # Members and guests browsing
    $out .= "<p class='{$pBrowsingClass}'>";
    $guestBrowsing = sp_guests_browsing();
    if ($browse || $guestBrowsing) {
        $out .= "<span>{$browsingLabel}</span>";
    }
    if ($browse) {
        $out .= $browse;
    }
    if (!$usersOnly && $guestBrowsing != 0) {
        $out .= "<br />{$guestBrowsing} <span class='spOnlineUser spType-Guest'>{$guestLabel}</span>";
    }
    $out .= "</p>\n";
    # finish it up
    $out = apply_filters('sph_OnlineStats', $out, $a);
    if ($echo) {
        echo $out;
    } else {
        return $out;
    }
}
function spa_forums_global_rss_form()
{
    ?>
<script type="text/javascript">
    jQuery(document).ready(function() {
    	spjAjaxForm('sfnewglobalrss', 'sfreloadfd');
    });
</script>
<?php 
    spa_paint_options_init();
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=forums-loader&amp;sfnonce=' . wp_create_nonce('forum-ahah') . '&amp;saveform=globalrss';
    ?>
	<form action="<?php 
    echo $ahahURL;
    ?>
" method="post" id="sfnewglobalrss" name="sfnewglobalrss">
<?php 
    echo sp_create_nonce('forum-adminform_globalrss');
    spa_paint_open_tab(spa_text('Forums') . ' - ' . spa_text('Global RSS Settings'), true);
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Globally Enable/Disable RSS Feeds'), true, 'global-rss');
    spa_paint_input(spa_text('Replacement external RSS URL for all RSS') . '<br />' . spa_text('Default') . ': <strong><small>' . sp_build_url('', '', 0, 0, 0, 1) . '</small></strong>', 'sfallrssurl', sp_get_option('sfallRSSurl'));
    $base = SFHOMEURL . 'index.php?sp_ahah=forums-loader&amp;sfnonce=' . wp_create_nonce('forum-ahah');
    $target = 'sfallrss';
    $image = SFADMINIMAGES;
    $rss_count = spdb_count(SFFORUMS, 'forum_rss_private=0');
    echo spa_text('Enabled Forum RSS feeds') . ': ' . $rss_count . '&nbsp;&nbsp;&nbsp;&nbsp;';
    $rss_count = spdb_count(SFFORUMS, 'forum_rss_private=1');
    echo spa_text('Disabled Forum RSS feeds') . ': ' . $rss_count . '<hr />';
    ?>
				<input type="button" class="button-secondary" value="<?php 
    echo spa_text('Disable All RSS Feeds');
    ?>
" onclick="spjLoadForm('globalrssset', '<?php 
    echo $base;
    ?>
', '<?php 
    echo $target;
    ?>
', '<?php 
    echo $image;
    ?>
', '1', '1');" />
				<input type="button" class="button-secondary" value="<?php 
    echo spa_text('Enable All RSS Feeds');
    ?>
" onclick="spjLoadForm('globalrssset', '<?php 
    echo $base;
    ?>
', '<?php 
    echo $target;
    ?>
', '<?php 
    echo $image;
    ?>
', '0', '1');" />

				<div class="sfinline-form">  <!-- This row will hold ahah forms for the all rss -->
				<div id="sfallrss"></div>
				</div>

<?php 
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    do_action('sph_forums_global_rss_panel');
    spa_paint_close_container();
    ?>
		<div class="sfform-submit-bar">
		<input type="submit" class="button-primary" id="saveit" name="saveit" value="<?php 
    spa_etext('Update Global RSS Settings');
    ?>
" />
		</div>
	</form>
	<?php 
    spa_paint_close_tab();
    ?>

	<div class="sfform-panel-spacer"></div>
<?php 
}
function sp_get_activity_count($userid, $type)
{
    $userid = (int) $userid;
    if (empty($userid) || empty($type)) {
        return false;
    }
    return spdb_count(SFUSERACTIVITY, "user_id={$userid} AND type_id={$type}");
}
function sp_go_install()
{
    global $current_user;
    add_option('sfInstallID', $current_user->ID);
    # use wp option table
    $phpfile = SFHOMEURL . 'index.php?sp_ahah=install&sfnonce=' . wp_create_nonce('forum-ahah');
    $image = SFCOMMONIMAGES . 'working.gif';
    # how many users passes at 200 a pop?
    $users = spdb_count(SFUSERS);
    $subphases = ceil($users / 200);
    $nextsubphase = 1;
    ?>
	<div class="wrap"><br />
		<div class="updated">
		<img class="stayleft" src="<?php 
    echo SFCOMMONIMAGES;
    ?>
sp-mini-logo.png" alt="" title="" />
		<h3><?php 
    spa_etext('Simple:Press is being installed');
    ?>
</h3></div>
		<div style="clear: both"></div>
		<br />
		<div class="wrap sfatag">
			<div class="imessage" id="imagezone"></div><br />
			<div class="pbar" id="progressbar"></div><br />
		</div>
		<div style="clear: both"></div>
		<table id="SPLOADINSTALLtable" style="padding:2px;border-spacing:6px;border-collapse:separate;">
			<tr><td><div class="zmessage" id="zone0"><?php 
    spa_text('Installing');
    ?>
...</div></td></tr>
			<tr><td><div class="zmessage" id="zone1"></div></td></tr>
			<tr><td><div class="zmessage" id="zone2"></div></td></tr>
			<tr><td><div class="zmessage" id="zone3"></div></td></tr>
			<tr><td><div class="zmessage" id="zone4"></div></td></tr>
			<tr><td><div class="zmessage" id="zone5"></div></td></tr>
			<tr><td><div class="zmessage" id="zone6"></div></td></tr>
			<tr><td><div class="zmessage" id="zone7"></div></td></tr>
			<tr><td><div class="zmessage" id="zone8"></div></td></tr>
			<tr><td><div class="zmessage" id="zone9"></div></td></tr>
			<tr><td><div class="zmessage" id="zone10"></div></td></tr>
			<tr><td><div class="zmessage" id="zone11"></div></td></tr>
		</table>
		<div class="zmessage" id="errorzone"></div>
		<div id="finishzone"></div>
<?php 
    $pass = 11;
    $curr = 0;
    $messages = esc_js(spa_text('Go to Forum Admin')) . '@' . esc_js(spa_text('Installation is in progress - please wait')) . '@' . esc_js(spa_text('Installation Completed')) . '@' . esc_js(spa_text('Installation has been Aborted'));
    $out = '<script type="text/javascript">' . "\n";
    $out .= 'spjPerformInstall("' . $phpfile . '", "' . $pass . '", "' . $curr . '", "' . $subphases . '", "' . $nextsubphase . '", "' . $image . '", "' . $messages . '");' . "\n";
    $out .= '</script>' . "\n";
    echo $out;
    ?>
	</div>
<?php 
}
function sp_AdminBarDashboardPosts()
{
    global $spThisUser;
    $out = '';
    # New/Unread Admin Post List
    $options = sp_get_option('spAdminBar');
    if ($options['dashboardposts']) {
        if ($spThisUser->admin) {
            $waiting = spdb_count(SFPOSTS, 'post_status != 0');
            $unreads = sp_AdminBarGetUnreadForums();
            $out .= '<p>' . __('The Admin postbag', 'spab') . '</p>';
        } else {
            $waiting = 0;
            $unreads = array();
            if ($spThisUser->newposts) {
                foreach ($spThisUser->newposts['forums'] as $index => $forum) {
                    $unreads[$index] = new stdClass();
                    $unreads[$index]->forum_slug = spdb_table(SFFORUMS, 'forum_id=' . $forum, 'forum_slug');
                    $topic = spdb_table(SFTOPICS, 'topic_id=' . $spThisUser->newposts['topics'][$index]);
                    if ($topic) {
                        $unreads[$index]->topic_id = $topic[0]->topic_id;
                        $unreads[$index]->post_id = $topic[0]->post_id;
                    } else {
                        $unreads[$index]->topic_id = 0;
                        $unreads[$index]->post_id = 0;
                    }
                }
            }
            $out .= '<p>' . __('Unread Posts', 'spab') . '</p>';
        }
        if ($unreads) {
            $out .= '<table class="sfdashtable">';
            foreach ($unreads as $unread) {
                if (!empty($unread)) {
                    $out .= '<tr>';
                    if ($spThisUser->admin) {
                        if ($unread->post_count == 1) {
                            $mess = sprintf(__('There is %s new post', 'spb'), $unread->post_count);
                        } else {
                            $mess = sprintf(__('There are %s new posts', 'spab'), $unread->post_count);
                        }
                        $out .= '<td>' . $mess . ' ' . __('in the forum topic', 'spab') . ':&nbsp;&nbsp;' . sp_AdminBarDashboardUrl($unread->forum_slug, $unread->topic_id, $unread->post_id) . '</td>';
                    } else {
                        $out .= '<td>' . __('You have new post(s) in the forum topic', 'spab') . ':&nbsp;&nbsp;' . sp_AdminBarDashboardUrl($unread->forum_slug, $unread->topic_id, $unread->post_id) . '</td>';
                    }
                    $out .= '</tr>';
                }
            }
            $out .= '</table>';
            if ($waiting == 1) {
                $out .= '<br /><table class="sfdashtable"><tr><td>' . __('There is 1 post awaiting approval', 'spab') . '</td></tr></table>';
            }
            if ($waiting > 1) {
                $out .= '<br /><table class="sfdashtable"><tr><td>' . __('There are', 'spab') . ' ' . $waiting . ' ' . __('posts awaiting approval', 'spab') . '.</td></tr></table>';
            }
        } else {
            $out .= '<p>' . __('There are no new forum posts', 'spab') . '</p>';
        }
    }
    echo $out;
}
function spa_usergroups_map_users()
{
    ?>
<script type="text/javascript">
    jQuery(document).ready(function() {
    	jQuery('#sfmapsettingsform').ajaxForm({
    		target: '#sfmsgspot',
    		success: function() {
    			jQuery('#sfreloadmu').click();
    			jQuery('#sfmsgspot').fadeIn();
    			jQuery('#sfmsgspot').fadeOut(6000);
    		}
    	});
    	jQuery('#sfmapusersform').ajaxForm({
    		target: '#sfmsgspot',
    	});
    });
</script>
<?php 
    global $wp_roles;
    $sfoptions = spa_get_mapping_data();
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=usergroups-loader&amp;sfnonce=' . wp_create_nonce('forum-ahah') . '&amp;saveform=mapsettings';
    ?>
	<form action="<?php 
    echo $ahahURL;
    ?>
" method="post" id="sfmapsettingsform" name="sfmapsettingsform">
	<?php 
    echo sp_create_nonce('forum-adminform_mapusers');
    spa_paint_options_init();
    spa_paint_open_tab(spa_text('User Groups') . ' - ' . spa_text('User Mapping Settings'), true);
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('User Memberships'), true, 'user-memberships');
    echo '<tr><td colspan="2"><br /><div class="sfoptionerror">';
    spa_etext('Warning: Use caution when setting the single usergroup membership option below. It should primarily be used in conjunction with a membership plugin (such as Wishlist) where strict usergroup membership is required.  Please note that auto usergroup membership by WP role or by forum rank may conflict or overwrite any manual usergroup memberships (such as moderator) you may set if you have single usergroup membership set');
    echo '</div><br />';
    echo '</td></tr>';
    spa_paint_checkbox(spa_text('Users are limited to single usergroup membership'), 'sfsinglemembership', $sfoptions['sfsinglemembership']);
    echo '<tr><td colspan="2"><p class="subhead">' . spa_text('Default usergroup membership') . ':</p></td></tr>';
    spa_paint_select_start(spa_text('Default usergroup for guests'), 'sfguestsgroup', 'sfguestsgroup');
    echo spa_create_usergroup_select($sfoptions['sfguestsgroup']);
    spa_paint_select_end();
    spa_paint_select_start(spa_text('Default usergroup for new members'), 'sfdefgroup', 'sfdefgroup');
    echo spa_create_usergroup_select($sfoptions['sfdefgroup']);
    spa_paint_select_end();
    $roles = array_keys($wp_roles->role_names);
    if ($roles) {
        echo '<tr><td colspan="2"><p class="subhead">' . spa_text('Usergroup memberships based on WP role') . ':</p></td></tr>';
        $sfoptions['role'] = array();
        foreach ($roles as $index => $role) {
            $value = sp_get_sfmeta('default usergroup', $role);
            if ($value) {
                $group = $value[0]['meta_value'];
            } else {
                $group = $sfoptions['sfdefgroup'];
            }
            echo '<input type="hidden" class="sfhiddeninput" name="sfoldrole[' . $index . ']" value="' . $group . '" />';
            spa_paint_select_start(spa_text('Default usergroup for') . ' ' . $role, "sfrole[{$index}]", 'sfguestsgroup');
            echo spa_create_usergroup_select($group);
            spa_paint_select_end();
        }
    }
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    do_action('sph_usergroups_mapping_settings_panel');
    spa_paint_close_container();
    ?>
	<div class="sfform-submit-bar">
	<input type="submit" class="button-primary" id="saveit" name="saveit" value="<?php 
    spa_etext('Update Mapping Settings');
    ?>
" />
	</div>
	</form>
	<?php 
    spa_paint_close_tab();
    ?>

	<div class="sfform-panel-spacer"></div>
<?php 
    $ahahURL = SFHOMEURL . 'index.php?sp_ahah=usergroups-loader&amp;sfnonce=' . wp_create_nonce('forum-ahah') . '&amp;saveform=mapusers';
    $uCount = spdb_count(SFMEMBERS);
    $url = SFHOMEURL . 'index.php?sp_ahah=usermapping&amp;sfnonce=' . wp_create_nonce('forum-ahah');
    $target = 'sfmsgspot';
    $smessage = esc_js(spa_text('Please Wait - Processing'));
    $emessage = $uCount . ' ' . esc_js(spa_text('Users mapped'));
    ?>
	<form action="<?php 
    echo $ahahURL;
    ?>
" method="post" id="sfmapusersform" name="sfmapusersform" onsubmit="spjBatch('sfmapusersform', '<?php 
    echo $url;
    ?>
', '<?php 
    echo $target;
    ?>
', '<?php 
    echo $smessage;
    ?>
', '<?php 
    echo $emessage;
    ?>
', 0, 500, <?php 
    echo $uCount;
    ?>
);">
<?php 
    echo sp_create_nonce('forum-adminform_mapusers');
    spa_paint_options_init();
    spa_paint_open_tab(spa_text('User Groups') . ' - ' . spa_text('Map Users'), true);
    spa_paint_open_panel();
    spa_paint_open_fieldset(spa_text('Map Users'), true, 'map-users');
    echo '<tr><td colspan="2"><br /><div class="sfoptionerror">';
    spa_etext("Warning: Use caution when mapping users. This will adjust your user's memberships in User Groups. Choose the criteria and options carefully. The mapping cannot be undone except by remapping or manual process. Also, make sure you have saved your mapping settings above before mapping as they are two distinct actions.");
    echo '</div><br />';
    echo '</td></tr>';
    $values = array(spa_text('Add user membership based on WP role to existing memberships'), spa_text('Replace all user memberships with a single membership based on WP role'));
    spa_paint_radiogroup(spa_text('Select mapping criteria'), 'mapoption', $values, 2, false, true);
    spa_paint_checkbox(spa_text('Ignore current SP Moderators when mapping'), 'ignoremods', true);
    spa_paint_close_fieldset();
    spa_paint_close_panel();
    do_action('sph_usergroups_map_users_panel');
    spa_paint_close_container();
    ?>
    	<div class="sfform-submit-bar">
        	<span><input type="submit" class="button-primary" id="saveit2" name="saveit2" value="<?php 
    spa_etext('Map Users');
    ?>
" /> <span class="button sfhidden" id='onFinish'></span></span>
        	<br />
        	<div class="pbar" id="progressbar"></div>
    	</div>
	</form>
<?php 
    spa_paint_close_tab();
}
    }
    # create new auth categories table
    $sql = '
		CREATE TABLE IF NOT EXISTS ' . SFAUTHCATS . ' (
			authcat_id tinyint(4) NOT NULL auto_increment,
			authcat_name varchar(50) NOT NULL,
			authcat_slug varchar(50) NOT NULL,
			authcat_desc tinytext,
			PRIMARY KEY	 (authcat_id),
			KEY authcat_slug_idx (authcat_slug)
		) ' . spdb_charset();
    spdb_query($sql);
    # lets rename bypass_spam_control auth to bypass_math_question
    spdb_query('UPDATE ' . SFAUTHS . " SET auth_name='bypass_math_question' WHERE auth_name='bypass_spam_control'");
    # create default categories
    if (spdb_count(SFAUTHCATS) == 0) {
        spa_setup_auth_cats();
    }
    sp_response($section);
}
$section = 8860;
if ($build < $section) {
    # clean out some leftover globals
    $sfdisplay = sp_get_option('sfdisplay');
    unset($sfdisplay['stats']);
    unset($sfdisplay['groups']);
    unset($sfdisplay['topics']['maxtags']);
    unset($sfdisplay['posts']['tagstop']);
    unset($sfdisplay['posts']['tagsbottom']);
    sp_update_option('sfdisplay', $sfdisplay);
    sp_response($section);
function spa_save_options_data()
{
    check_admin_referer('forum-adminform_options', 'forum-adminform_options');
    $mess = spa_text('Profile options updated');
    $sfprofile = sp_get_option('sfprofile');
    $old_sfprofile = $sfprofile;
    $sfprofile['nameformat'] = isset($_POST['nameformat']);
    $sfprofile['fixeddisplayformat'] = sp_esc_int($_POST['fixeddisplayformat']);
    $sfprofile['displaymode'] = sp_esc_int($_POST['displaymode']);
    $sfprofile['displaypage'] = sp_filter_save_cleanurl($_POST['displaypage']);
    $sfprofile['displayquery'] = sp_filter_title_save(trim($_POST['displayquery']));
    $sfprofile['formmode'] = sp_esc_int($_POST['formmode']);
    $sfprofile['formpage'] = sp_filter_save_cleanurl($_POST['formpage']);
    $sfprofile['formquery'] = sp_filter_title_save(trim($_POST['formquery']));
    $sfprofile['photosmax'] = sp_esc_int($_POST['photosmax']);
    $sfprofile['photoswidth'] = sp_esc_int($_POST['photoswidth']);
    $sfprofile['photosheight'] = sp_esc_int($_POST['photosheight']);
    if ($sfprofile['photosmax'] && $sfprofile['photoswidth'] == 0) {
        $sfprofile['photoswidth'] = 300;
    }
    $sfsigimagesize = array();
    $sfsigimagesize['sfsigwidth'] = sp_esc_int($_POST['sfsigwidth']);
    $sfsigimagesize['sfsigheight'] = sp_esc_int($_POST['sfsigheight']);
    sp_update_option('sfsigimagesize', $sfsigimagesize);
    $sfprofile['firstvisit'] = isset($_POST['firstvisit']);
    $sfprofile['forcepw'] = isset($_POST['forcepw']);
    $sfprofile['sfprofiletext'] = sp_filter_text_save(trim($_POST['sfprofiletext']));
    sp_update_option('sfprofile', $sfprofile);
    # if changed force pw from true to false, remove any users waiting for pw change
    if ($old_sfprofile['forcepw'] && !$sfprofile['forcepw']) {
        delete_metadata('user', 0, 'sp_change_pw', '', true);
    }
    # If the name format changes from dynamic to fixed, we need to update
    # the display_name field for all users based on the selection from the dropdown
    # If there is a conflict between display names, a numeric value will be added to the
    # end of the display name to make them unique.
    # ----------------------------------------------------------------------------------
    if ($old_sfprofile['nameformat'] != $sfprofile['nameformat'] && empty($sfprofile['nameformat']) || $old_sfprofile['fixeddisplayformat'] != $sfprofile['fixeddisplayformat'] && empty($sfprofile['nameformat'])) {
        # The display format determines the WHERE clause and the tables to join.
        # ----------------------------------------------------------------------
        $fields = '';
        $user_join = SFUSERS . ' ON ' . SFMEMBERS . '.user_id = ' . SFUSERS . '.ID';
        $first_name_join = SFUSERMETA . ' a ON (' . SFUSERS . '.ID = a.user_id AND a.meta_key = \'first_name\')';
        $last_name_join = SFUSERMETA . ' b ON (' . SFUSERS . '.ID = b.user_id AND b.meta_key = \'last_name\')';
        # Determine how many passes its going to take to update all users in the system
        # based on 100 users per pass.
        # -----------------------------------------------------------------------------
        $num_records = spdb_count(SFMEMBERS, '');
        $passes = ceil($num_records / 100);
        $dupes = array();
        for ($i = 0; $i <= $passes; $i++) {
            $limit = 100;
            $offset = $i * $limit;
            $fields = SFMEMBERS . '.user_id, ' . SFUSERS . '.user_login, ' . SFUSERS . '.display_name, a.meta_value as first_name, b.meta_value as last_name';
            $join = array($user_join, $first_name_join, $last_name_join);
            $spdb = new spdbComplex();
            $spdb->table = SFMEMBERS;
            $spdb->fields = $fields;
            $spdb->left_join = $join;
            $spdb->limits = $limit . ' OFFSET ' . $offset;
            $spdb->order = SFMEMBERS . '.user_id';
            $spdb = apply_filters('sph_fixeddisplayformat_query', $spdb);
            $records = $spdb->select();
            foreach ($records as $r) {
                switch ($sfprofile['fixeddisplayformat']) {
                    default:
                    case '0':
                        $display_name = $r->display_name;
                        break;
                    case '1':
                        $display_name = $r->user_login;
                        break;
                    case '2':
                        $display_name = $r->first_name;
                        break;
                    case '3':
                        $display_name = $r->last_name;
                        break;
                    case '4':
                        $display_name = $r->first_name . ' ' . $r->last_name;
                        break;
                    case '5':
                        $display_name = $r->last_name . ', ' . $r->first_name;
                        break;
                    case '6':
                        $display_name = $r->first_name[0] . ' ' . $r->last_name;
                        break;
                    case '7':
                        $display_name = $r->first_name . ' ' . $r->last_name[0];
                        break;
                    case '8':
                        $display_name = $r->first_name[0] . $r->last_name[0];
                        break;
                }
                # If the display name is empty for any reason, default to the user login name
                $display_name = trim($display_name);
                if (empty($display_name)) {
                    $display_name = $r->user_login;
                }
                # Check to see if there are any matching users with this display name.  If so
                # assign a random number to the end to eliminate the duplicate
                # ----------------------------------------------------------------------------
                $conflict = spdb_count(SFMEMBERS, 'display_name = "' . $display_name . '" AND user_id <> ' . $r->user_id);
                if ($conflict > 0) {
                    if (array_key_exists($display_name, $dupes)) {
                        $dupes[$display_name]++;
                    } else {
                        $dupes[$display_name] = 1;
                    }
                    $display_name = $display_name . $dupes[$display_name];
                }
                # Now Update the member record
                # ----------------------------
                $display_name = sp_filter_name_save($display_name);
                $query = 'UPDATE ' . SFMEMBERS . ' SET display_name = "' . $display_name . '" WHERE user_id = ' . $r->user_id;
                $result = spdb_query($query);
            }
        }
        # update the recent members in stats too
        sp_update_recent_members();
    }
    do_action('sph_profiles_options_save');
    return $mess;
}