<?php
/*
Simple:Press Forum
Start Up Functions to support the forum
$LastChangedDate: 2010-03-11 18:21:03 -0700 (Thu, 11 Mar 2010) $
$Rev: 3696 $
*/

if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) {
	die('Access Denied');
}

# ------------------------------------------------------------------
# sf_load_front_js()
#
# Enqueue's necessary javascript and inline header script
# ------------------------------------------------------------------
function sf_load_front_js()
{
	global $sfvars;

	# Load up the javascript files
	wp_enqueue_script('jquery');

	if(SF_USE_PRETTY_CBOX)
	{
		wp_enqueue_script('jquery.checkboxes', SFJSCRIPT.'checkboxes/prettyCheckboxes.js', array('jquery'));
	}

	wp_enqueue_script('highslide', SFJSCRIPT.'highslide/highslide.js');
	wp_enqueue_script('sfjs', SFJSCRIPT.'forum/sf-forum.js');

	wp_enqueue_script('sftags', SFJSCRIPT.'tags/sf-tags.js', array('jquery'));
	wp_localize_script('sftags', 'sfSettings', array('url' => SF_PLUGIN_URL));

	wp_enqueue_script('sfprint', SFJSCRIPT.'print/jquery.jqprint.js', array('jquery'));

    # hack for pm detection since sfvars not set up yet
	$pmstuff = explode('/', $_SERVER['QUERY_STRING']);
    $pmpage = get_query_var('sf_pm');
    $pmoldpage = $_GET['pmaction'];
 	if (!empty($pmpage) || !empty($pmoldpage) || $pmstuff[1] == 'private-messaging')
	{
		wp_enqueue_script('sfautoc', SFJSCRIPT.'autocomplete/jquery.autocomplete.js', array('jquery'));
		wp_enqueue_script('sfsplitter', SFJSCRIPT.'jquery/splitter.js');
		wp_enqueue_script('sfcookie', SFJSCRIPT.'jquery/jquery.cookie.js');
		wp_enqueue_script('sfpmjs', SFJSCRIPT.'messaging/sf-messaging.js');
	}

	if(SF_USE_PRETTY_CBOX)
	{
		?>
		<script type='text/javascript'>
		var pcbExclusions = new Array(
		<?php
			$exc = sf_get_option('sfcbexclusions');
			if($exc)
			{
				$exc = rtrim($exc, ",");
				$exclist = explode(",", $exc);
				foreach($exclist as $item)
				{
					echo '"'.trim($item).'",';
				}
			}
			echo '"sfcbdummy"'."\n";
		?>
		);
		</script>
		<?php
	}
	return;
}

# ------------------------------------------------------------------
# sf_setup_header()
#
# Constructs the header for the forum - Javascript and CSS
# ------------------------------------------------------------------
function sf_setup_header()
{
	global $wp_query, $current_user, $wp_rewrite, $sfglobals, $sfvars, $SFSTATUS;

	# The CSS is being set early in case we have to bow out quickly due to
	# the forum needing to be ugraded. This is to ensure that
	# this is the very FIRST thing to happen in the header
	echo '<link rel="stylesheet" type="text/css" href="' . SFSKINCSS .'" />' . "\n";

	# So - check if it needs to be upgraded...
	if($SFSTATUS != 'ok')
	{
		return sf_forum_unavailable();
	}

	# If page is password protected, ensure it matches before starting
	if (!empty($wp_query->post->post_password))
	{
		if ($_COOKIE['wp-postpass_'.COOKIEHASH] != $wp_query->post->post_password)
		{
			return;
		}
	}

	remove_filter('the_content','wpautop');
	remove_filter('the_content','convert_smilies');

	$value = SFSIZE;
	if(!empty($value))
	{
		$value=trim($value, '%');
		if(intval($value) != 0)
		{
			echo '<style type="text/css">';
			echo '#sforum {font-size: '.$value.'%; }';
			echo '</style>'."\n";
		}
	}

	# --------------------------------------------------------
	# now to start populatng all of the variables we need

	# set up the sfvars array
	sf_populate_query_vars();

	# determine page view type
	sf_setup_page_type();

	# do meta stuff
	sf_setup_meta_tags();

    # load page specific css
	if ($sfvars['pageview'] == 'topic')
	   echo '<link rel="stylesheet" type="text/css" href="'.SFPOSTCSS.'" />' . "\n";
	if ($sfvars['pageview'] == 'pm')
	   echo '<link rel="stylesheet" type="text/css" href="'.SFPMCSS.'" />' . "\n";
	if ($sfvars['pageview'] == 'profileedit' || $sfvars['pageview'] == 'profileshow')
	   echo '<link rel="stylesheet" type="text/css" href="'.SFPROFILECSS.'" />' . "\n";

	# --------------------------------------------------------
	# Set uop the rest of the header info
	?>
	<link rel="stylesheet" type="text/css" href="<?php echo(SFADMINCSS); ?>highslide/highslide.css" />

	<script type="text/javascript">
		hs.graphicsDir = "<?php echo(SFJSCRIPT); ?>highslide/support/";
		hs.outlineType = "rounded-white";
		hs.outlineWhileAnimating = true;
		hs.cacheAjax = false;
		hs.showCredits = false;
		hs.lang = {
			closeText : '',
			closeTitle : '<?php echo esc_js(__("Close", "sforum")); ?>',
			moveText  : '',
			moveTitle : '<?php echo esc_js(__("Move", "sforum")); ?>',
			loadingText  : '<?php echo esc_js(__("Loading", "sforum")); ?>'
		};

		/* pre-load wait image */
		waitImage = new Image(27,27);
		waitImage.src = '<?php echo(SFRESOURCES."wait.png"); ?>';
	</script>

	<?php if(SF_USE_PRETTY_CBOX) { ?>
	<script type="text/javascript">
		var jspf = jQuery.noConflict();
		jspf(document).ready(function()
		{ jspf("input[type=checkbox],input[type=radio]").prettyCheckboxes(); });
	</script>
	<?php }

	# load editor if required
	if(strpos("forum topic pm", $sfvars['pageview']) !== false)
	{
		switch($sfglobals['editor']['sfeditor'])
		{
		case RICHTEXT:
			include_once(SFEDITORDIR."tinymce/sf-tinyinit.php");
			break;
		case HTML:
			include_once(SFEDITORDIR."html/sf-htmlinit.php");
			break;
		case BBCODE:
			include_once(SFEDITORDIR."bbcode/sf-bbcodeinit.php");
			break;
		}
	}

	# Special case: if profile edit load uploader support
	if($sfvars['pageview'] == 'profileedit')
	{ ?>
		<script type='text/javascript' src="<?php echo(SFJSCRIPT); ?>ajaxupload/ajaxupload.js"></script>
		<script type='text/javascript' src="<?php echo(SFJSCRIPT); ?>admin/jquery.form.js"></script>
	<?php }
}

# ------------------------------------------------------------------
# sf_populate_query_vars()
#
# Populate the forum  query variables from the URL
# ------------------------------------------------------------------
function sf_populate_query_vars()
{
	global $sfvars, $sfglobals, $wp_rewrite;

	if ($sfglobals['queryvarsdone'] == true) return;

	# load query vars

	$sfglobals['queryvarsdone'] = true;

	$sfvars['error'] = false;
	$sfvars['forumid'] = 0;
	$sfvars['topicid'] = 0;
	$sfvars['action'] = '';

	# We can check to see if the url is a pre V3 url
	# this checks for numeric value. Fine as long as
	# someone doesn't name their forum with simply a number!
	if((isset($_GET['forum'])) && (is_numeric($_GET['forum'])))
	{
		# suggests an old url
		$sfvars['forumslug'] = sf_get_forum_slug(sf_esc_int($_GET['forum']));
		if(isset($_GET['topic'])) $sfvars['topicslug'] = sf_get_topic_slug(sf_esc_int($_GET['topic']));
		sf_populate_support_vars();
		return;
	}

	# if V3 link and user has permalinks
	if($wp_rewrite->using_permalinks())
	{
		# post V3 permalinks
		# using permalinks so get the values from the query vars

		$sfvars['forumslug'] = urlencode(sf_esc_str(get_query_var('sf_forum')));
		if(empty($sfvars['forumslug']) && isset($_GET['search']))
		{
			$sfvars['forumslug']=urlencode(sf_esc_str($_GET['forum']));
		}
		$sfvars['topicslug'] = urlencode(sf_esc_str(get_query_var('sf_topic')));
		$sfvars['profile'] = urlencode(sf_esc_str(get_query_var('sf_profile')));
		$sfvars['member'] = urlencode(sf_esc_str(get_query_var('sf_member')));
		$sfvars['list'] = urlencode(sf_esc_str(get_query_var('sf_list')));
		$sfvars['newposts'] = urlencode(sf_esc_str(get_query_var('sf_newposts')));
		$sfvars['pm'] = urlencode(sf_esc_str(get_query_var('sf_pm')));
		$sfvars['box'] = urlencode(sf_esc_str(get_query_var('sf_box')));
		if (get_query_var('sf_page') != '')
		{
			$sfvars['page'] = sf_esc_int(get_query_var('sf_page'));
		}

		sf_populate_support_vars();
		return;
	} else {
		# post V3 but using default
		# Not using permalinks so we need to parse the query string from the url and do it ourselves

		$stuff=array();
		$stuff=explode('/', $_SERVER['QUERY_STRING']);

		# deal with non-standard cases first
		if (isset($_GET['search']))
		{
			sf_build_search_vars($stuff);
		} else {
			sf_build_standard_vars($stuff);
		}

		sf_populate_support_vars();

		if(empty($sfvars['forumid'])) $sfvars['forumid']=0;
		if(empty($sfvars['topicid'])) $sfvars['topicid']=0;
		if(empty($sfvars['profile'])) $sfvars['profile']=0;
		if(empty($sfvars['member'])) $sfvars['member']=0;
		if(empty($sfvars['list'])) $sfvars['list']=0;
		if(empty($sfvars['newposts'])) $sfvars['newposts']=0;
		if(empty($sfvars['pm'])) $sfvars['pm']=0;
		if(empty($sfvars['box'])) $sfvars['box']=0;
		return;
	}
}

# ------------------------------------------------------------------
# sf_populate_support_vars()
#
# Query Variables support routine
# ------------------------------------------------------------------
function sf_populate_support_vars()
{
	global $sfvars;

	# Populate the rest of sfvars

	if(empty($sfvars['page']))
	{
		$sfvars['page'] = 1;
	}
	if(!empty($sfvars['forumslug']) && $sfvars['forumslug'] != 'all')
	{
		$record = sf_get_forum_record_from_slug($sfvars['forumslug']);
		$sfvars['forumid'] = $record->forum_id;
		if(empty($sfvars['forumid'])) $sfvars['forumid']=0;
		$sfvars['forumname'] = $record->forum_name;

		# Is it a subforum?
		$forumparent = $record->parent;

		while($forumparent > 0)
		{
			$parent = sf_get_forum_record($forumparent);
			$sfvars['parentforumid'][] = $forumparent;
			$sfvars['parentforumslug'][] = $parent->forum_slug;
			$sfvars['parentforumname'][] = $parent->forum_name;
			$forumparent = $parent->parent;
		}
	}
	if(!empty($sfvars['topicslug']))
	{
		$record = sf_get_topic_record_from_slug($sfvars['topicslug']);
		$sfvars['topicid'] = $record->topic_id;
		if(empty($sfvars['topicid'])) $sfvars['topicid']=0;
		$sfvars['topicname'] = $record->topic_name;
	}

	# Add Search Vars
	if(isset($_GET['search']))
	{
		if($_GET['search'] != '') $sfvars['searchpage'] = sf_esc_int($_GET['search']);
		if(isset($_GET['value']) ? $sfvars['searchvalue'] = stripslashes(urldecode($_GET['value'])) : $sfvars['searchvalue'] = '');
		if(isset($_GET['type']) ? $sfvars['searchtype'] = sf_esc_int($_GET['type']) : $sfvars['searchtype'] = 1);
		if(isset($_GET['include']) ? $sfvars['searchinclude'] = sf_esc_int($_GET['include']) : $sfvars['searchinclude'] = 1);
		if($sfvars['searchinclude'] == 0) $sfvars['searchinclude'] =1;
		if($sfvars['searchtype'] == 0) $sfvars['searchtype'] =1;
	} else {
		$sfvars['searchpage'] = 0;
	}
	$sfvars['searchresults']=0;

	return;
}

# ------------------------------------------------------------------
# sf_build_search_vars()
#
# Query Variables support routine
# ------------------------------------------------------------------
function sf_build_search_vars($stuff)
{
	global $sfvars;

	if(isset($_GET['forum']))
	{
		# means searching all
		$sfvars['forumslug'] = sf_esc_str($_GET['forum']);
	} else {
		# searching single forum
		if(!empty($stuff[1]))
		{
			$sfvars['forumslug'] = $stuff[1];
		}

		# (2) topic
		if(!empty($stuff[2]))
		{
			$parts = explode("&", $stuff[2]);
			$sfvars['topicslug'] = $parts[0];
		}
	}
	return;
}

# ------------------------------------------------------------------
# sf_build_standard_vars()
#
# Query Variables support routine
# ------------------------------------------------------------------
function sf_build_standard_vars($stuff)
{
	global $sfvars, $current_user;

	# (1) forum first
	if(!empty($stuff[1]))
	{
        if ($stuff[1] == 'profile')
        {
            if (empty($stuff[2]))
            {
                $sfvars['member'] = urlencode(sf_get_member_item($current_user->ID, 'display_name'));
                $sfvars['profile'] = 'edit';
            } else if ($stuff[2] == 'permissions' || $stuff[2] == 'buddies') {
                $sfvars['profile'] = sf_esc_str($stuff[2]);
            } else {
                $sfvars['profile'] = 'edit';
                if (!empty($stuff[2]))
                {
                    $sfvars['member'] = sf_esc_str($stuff[2]);
                } else {
                    $sfvars['member'] = urlencode(sf_get_member_item($current_user->ID, 'display_name'));
                }
            }
        } else if ($stuff[1] == 'members') {
            $sfvars['list'] = 'members';
    		if (preg_match("/page-(\d+)/", $stuff[2], $matches))
    		{
    			$sfvars['page'] = intval($matches[1]);
    		}
        } else if ($stuff[1] == 'newposts') {
            $sfvars['newposts'] = 'all';
        } else if ($stuff[1] == 'private-messaging') {
            $sfvars['pm'] = $stuff[2];
            $sfvars['box'] = $stuff[2];
        } else {
    		$substuff = explode('&', $stuff[1]);
            $sfvars['forumslug'] = $substuff[0];

        	# (2) topic or page?
        	if(!empty($stuff[2]))
        	{
        		$matches = array();
        		if(preg_match("/page-(\d+)/", $stuff[2], $matches))
        		{
        			$sfvars['page'] = intval($matches[1]);
        		} else {
        			$substuff = explode('&', $stuff[2]);
        			$sfvars['topicslug'] = $substuff[0];
        		}
        	}

        	# (3) if here must be page
        	if(!empty($stuff[3]))
        	{
        		if(preg_match("/page-(\d+)/", $stuff[3], $matches))
        		{
        			$sfvars['page'] = intval($matches[1]);
        		}
        	}
        }
	}

	return;
}

function sf_setup_page_type()
{
	global $sfvars, $sfglobals, $current_user, $CACHE;

	if (isset($sfglobals['pagetypedone']) && $sfglobals['pagetypedone'] == true) return;
	$sfglobals['pagetypedone'] = true;

	sf_initialise_globals($sfvars['forumid']);

	# Maybe a profile edit or first time logged in?
	# If user has made no posts yet optionaly load the profile form
    $pageview = '';
	$sfvars['newuser'] = false;
	if ($current_user->member)
	{
		if(($sfglobals['member']['posts'] == -1) || (!isset($current_user->user_email) || empty($current_user->user_email)))
		{
			$sfprofile = sf_get_option('sfprofile');
			$sfvars['newuser'] = $sfprofile['firstvisit'];
			sf_update_member_item($current_user->ID, 'posts', 0);
			sf_push_newuser($current_user->display_name);
            $sfvars['member'] = urlencode($current_user->display_name);
            $pageview = 'profileedit';
            $sfvars['forumslug'] = '';
            $sfvars['topicslug'] = '';
		}
    }

    if ($pageview == '')
    {
        if (!empty($sfvars['forumslug'])) {
    		$pageview = 'forum';
    	} else if (!empty($sfvars['profile'])) {
    		if ($sfvars['profile'] == 'edit') $pageview = 'profileedit';
    		if ($sfvars['profile'] == 'show') $pageview = 'profileshow';
    		if ($sfvars['profile'] == 'permissions') $pageview = 'permissions';
    		if ($sfvars['profile'] == 'buddies') $pageview = 'buddies';
    	} else if (!empty($sfvars['newposts'])) {
    		$pageview = 'newposts';
    	} else if (!empty($sfvars['list'])) {
    		$pageview = 'list';
    	} else if (!empty($sfvars['pm'])) {
    		$pageview = 'pm';
    	} else {
    		$pageview = 'group';
    		# Check if single forum only is on
    		if (isset($sfglobals['display']['forums']['singleforum']) && $sfglobals['display']['forums']['singleforum'])
    		{
    			$fid = sf_single_forum_user();
    			if ($fid)
    			{
    				$cforum = sf_get_forum_record($fid);
    				$sfvars['forumid'] = $fid;
    				$sfvars['forumslug'] = urlencode($cforum->forum_slug);
    				$sfvars['forumname'] = $cforum->forum_name;
    				$CACHE = '';
    				sf_initialise_globals($sfvars['forumid']);
    				$pageview = 'forum';
    			}
    		}
    	}

    	if (!empty($sfvars['topicslug'])) $pageview = 'topic';

        # old style  query args still here for backward compat
    	if (isset($_GET['profile-edit']))
        {
            $userid = sf_esc_int($_GET['profile-edit']);
            $sfvars['member'] = urlencode(sf_get_member_item($userid, 'display_name'));
            $pageview = 'profileedit';
        }
    	if (isset($_GET['profile-show']))
        {
            $userid = sf_esc_int($_GET['profile-show']);
            $sfvars['member'] = urlencode(sf_get_member_item($userid, 'display_name'));
            $pageview = 'profileshow';
        }
    	if (isset($_GET['list']))
        {
    		$sfvars['list'] = sf_esc_str($_GET['list']);
            $pageview = 'list';
        }
    	if (isset($_GET['newposts']))
        {
    		$sfvars['newposts'] = sf_esc_str($_GET['newposts']);
            $pageview = 'newposts';
        }
    	if(isset($_GET['pmaction']))
        {
            if (sf_esc_str($_GET['pmaction']) == 'viewinpm')
            {
                $sfvars['pm'] = 'view';
                $sfvars['box'] = 'inbox';
            } else if (sf_esc_str($_GET['pmaction']) == 'viewoutpm') {
                $sfvars['pm'] = 'view';
                $sfvars['box'] = 'sentbox';
            } else if (sf_esc_str($_GET['pmaction']) == 'sendpm') {
                $sfvars['pm'] = 'send';
                $sfvars['box'] = 'inbox';
            }
            $pageview = 'pm';
        }
    }

	$sfvars['pageview'] = $pageview;
}

function sf_setup_meta_tags()
{
	global $sfvars, $sfglobals;

	$topic = '';
	$forum = '';

	if ($sfglobals['metadescription'] != true)
	{
		$description = sfc_get_metadescription();
		if ($description != '')
		{
			echo '<meta name="description" content="'.$description.'" />'."\n";
		}
	}

	if ($sfglobals['metakeywords'] != true)
	{
		$keywords = sfc_get_metakeywords();
		if ($keywords != '')
		{
			echo '<meta name="keywords" content="'.$keywords.'" />'."\n";
		}
	}

	if ($sfglobals['canonicalurl'] != true)
	{
		$url = sf_build_url($sfvars['forumslug'], $sfvars['topicslug'], $sfvars['page'], 0);
		echo '<link rel="canonical" href="'.$url.'" />'."\n";
	}

	return;
}

?>