<?php
/*======================================================================*\
|| #################################################################### ||
|| # vBExperience 3.8                                                 # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2006-2009 Marius Czyz. All Rights Reserved.           # ||
|| #################################################################### ||
\*======================================================================*/

error_reporting(E_ALL & ~E_NOTICE);
define('THIS_SCRIPT', 'xperience');

$phrasegroups = array('xperience', 'user', 'cpoption', 'socialgroups');


$specialtemplates = array(
	'xperience_singleaward'
);

$globaltemplates = array(
	'headinclude',
	'navbar',		
	'xperience_ranking',
	'xperience_ranking_bit',
	'xperience_awards',
	'xperience_singleaward',
	'xperience_award_bit',
	'xperience_awards_awardbit',
	'xperience_awards_awardbit_empty',
	'xperience_awards_bit',
	'xperience_navbar',
	'xperience_shop',
	'xperience_shop_cat',
	'xperience_shop_item_c',
	'xperience_shop_item_p',
	'xperience_shop_item',
	'xperience_shop_item_own',
	'xperience_stats',
	'xperience_stats_entries',
	'xperience_stats_entry',
	'xperience_stats_header',
	'xperience_stats_entries_empty',
	'xperience_stats_entry_empty',
	'xperience_promotion_entry',
	'xperience_promotions',
	'xperience_earn',
	'xperience_earn_entry',
	'xperience_shop_ga_choose',
	'xperience_shop_ta',
	'xperience_shop_ta_entry',	
	'xperience_groups_ranking',
	'xperience_groups_ranking_bit',
);

$actiontemplates = array();

require_once('./global.php');


if (!$vbulletin->options['xperience_enabled']) 
{
	eval('standard_error($vbphrase[xperience_disabled]);');

	exit;
}

// permissions check
if (!($permissions['forumpermissions'] & $vbulletin->bf_ugp_forumpermissions['canview']) OR !($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canviewmembers']))
{
	print_no_permission();
}

// ######################### CLEAN GPC ############################
	$go = $vbulletin->input->clean_gpc('r', 'go', TYPE_NOHTML);
	$do = $vbulletin->input->clean_gpc('r', 'do', TYPE_NOHTML);
	$perpage = $vbulletin->input->clean_gpc('r', 'perpage', TYPE_UINT);
	$pagenumber = $vbulletin->input->clean_gpc('r', 'page', TYPE_UINT);
	$sortfield = unhtmlspecialchars($vbulletin->input->clean_gpc('r', 'sortfield', TYPE_NOHTML));
	$sortorder = unhtmlspecialchars($vbulletin->input->clean_gpc('r', 'sortorder', TYPE_NOHTML));
	

	$navbits = array();
	$navbits[$parent] = $vbphrase['xperience_ranking'];


	eval('$xperience_bar = "' . fetch_template('xperience_navbar') . '";');
	$xperience_version = $vbphrase['xperience_name']." 3.8.3";

	require_once('./includes/functions_xperience.php');
	require_once('./includes/class_xperience.php');

if ($go == "promotions")
{
	$navbits[$parent] = $vbphrase['xperience_promotions'];
	if (!$vbulletin->options['xperience_use_promotions'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}

	$promotionq = $vbulletin->db->query_read("SELECT
		g.usertitle, g.title, u.username, l.* 
		FROM " . TABLE_PREFIX . "xperience_promotion_log AS l
		INNER JOIN " . TABLE_PREFIX . "user AS u ON u.userid=l.userid
		INNER JOIN " . TABLE_PREFIX . "usergroup AS g ON g.usergroupid=l.to_ug
		ORDER BY dateline DESC, promotionid DESC
		LIMIT 50");
		$foundpromotion = 0;
		if ($vbulletin->db->num_rows($promotionq) > 0)
		{	
			$currentdate = "";
			while ($promotion = $vbulletin->db->fetch_array($promotionq))
			{
				$foundpromotion = 1;
				if (strlen($promotion['usertitle'])>1)
				{
					$promotion['usergroup'] = $promotion['usertitle'];
				} else {
					$promotion['usergroup'] = $promotion['title'];
				}
				$promotion['detaildate'] = vbdate($vbulletin->options['timeformat'], $promotion['dateline']);
				$promotion['date'] = vbdate($vbulletin->options['dateformat'], $promotion['dateline']);


				
				if ($currentdate <> $promotion['date'])
				{
					if ($currentdate <> "")
					{
						$promotions .="<br/>";
					}
					eval('$promotions .= "' . fetch_template('xperience_promotion_dateentry') . '";');
				}
				$currentdate = $promotion['date'];
				eval('$promotions .= "' . fetch_template('xperience_promotion_entry') . '";');
			}
				
		}
		$template = 'xperience_promotions';



}
elseif ($go == "stats")
{
	$navbits[$parent] = $vbphrase['xperience_stats'];
	if (!$vbulletin->options['xperience_use_stats'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}

	switch ($do) 
	{
		case "thread":
			$stats = fetch_statistics("thread");
			$statsname = $vbphrase['xperience_points_thread'];
			break;
		case "post":
			$stats = fetch_statistics("post");
			$statsname = $vbphrase['xperience_points_post'];
			break;
		case "misc":
			$stats = fetch_statistics("misc");
			$statsname = $vbphrase['xperience_points_misc'];
			break;
		default:
			$stats = fetch_statistics("user");
			$statsname = $vbphrase['xperience_points_user'];
	}
	$template = 'xperience_stats';



}
elseif ($go == "earn")
{

$navbits[$parent] = $vbphrase['xperience_earn'];
	if (!$vbulletin->options['xperience_use_earn'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}



	$settingphrase = array();
	$phrases = $db->query_read("
		SELECT varname, text
		FROM " . TABLE_PREFIX . "phrase
		WHERE fieldname = 'vbsettings' AND
			languageid=-1 OR languageid=" . LANGUAGEID . "
			ORDER BY languageid ASC
	");
	while($phrase = $db->fetch_array($phrases))
	{
		$settingphrase["$phrase[varname]"] = $phrase['text'];
	}

	switch ($do)
	{
		case "thread":
			$name = $vbphrase['xperience_points_for_thread'];
			$earnpoints .= ResolveAssociation("xperience_points_pt");
			$earnpoints .= ResolveAssociation("xperience_points_psgt");
			$earnpoints .= ResolveAssociation("xperience_points_pb");
			$earnpoints .= ResolveAssociation("xperience_points_po");
			$earnpoints .= ResolveAssociation("xperience_points_pr");
			$earnpoints .= ResolveAssociation("xperience_points_pv");
			$earnpoints .= ResolveAssociation("xperience_points_ps");
			
			($hook = vBulletinHook::fetch_hook('xperience_earn_thread')) ? eval($hook) : false;
			
			break;
		case "post":
			$name = $vbphrase['xperience_points_for_post'];
			$earnpoints .= ResolveAssociation("xperience_points_pp");
			$earnpoints .= ResolveAssociation("xperience_points_psgp");
			$earnpoints .= ResolveAssociation("xperience_points_pa");
			$earnpoints .= ResolveAssociation("xperience_points_pav", "attachmentviewslog");
			$earnpoints .= ResolveAssociation("xperience_points_ph", "thanks");
			$earnpoints .= ResolveAssociation("xperience_points_phu", "thanks");
			
			($hook = vBulletinHook::fetch_hook('xperience_earn_post')) ? eval($hook) : false;
			
			break;
		case "misc":
			$name = $vbphrase['xperience_points_for_misc'];
			$earnpoints .= ResolveAssociation("xperience_points_pw", "local_linkslink");
			$earnpoints .= ResolveAssociation("xperience_points_pw", "dl_files");
			$earnpoints .= ResolveAssociation("xperience_points_pl", "ppgal_images");
			$earnpoints .= ResolveAssociation("xperience_points_py", "cybppdonate");
			$earnpoints .= ResolveAssociation("xperience_points_po", "blog");
			$earnpoints .= ResolveAssociation("xperience_points_pr", "blog");
			$earnpoints .= ResolveAssociation("xperience_points_pv", "blog");
			$earnpoints .= ResolveAssociation("xperience_points_pn", "blog");
			
			($hook = vBulletinHook::fetch_hook('xperience_earn_misc')) ? eval($hook) : false;

			$name = $vbphrase['xperience_points_misc_custom'];
			$description = $vbphrase['xperience_points_misc_custom_desc'];
			
			global $bgclass, $altbgclass;
			exec_switch_bg();
			eval('$earnpoints .= "' . fetch_template('xperience_earn_entry') . '";');
			
			break;
		default:
			$name = $vbphrase['xperience_points_for_user'];
			$earnpoints .= ResolveAssociation("xperience_points_pi");
			$earnpoints .= ResolveAssociation("xperience_points_pu");
			$earnpoints .= ResolveAssociation("xperience_points_puu");
			$earnpoints .= ResolveAssociation("xperience_points_pd");
			$earnpoints .= ResolveAssociation("xperience_points_pg");
			$earnpoints .= ResolveAssociation("xperience_points_pe");
			$earnpoints .= ResolveAssociation("xperience_points_pm");
			$earnpoints .= ResolveAssociation("xperience_points_pc");
			$earnpoints .= ResolveAssociation("xperience_points_pf");
			$earnpoints .= ResolveAssociation("xperience_points_upr");			
			($hook = vBulletinHook::fetch_hook('xperience_earn_user')) ? eval($hook) : false;		


	}


	$template = 'xperience_earn';



}
elseif ($go == "shop")
{
	$navbits[$parent] = $vbphrase['xperience_shop'];
	if (!$vbulletin->options['xperience_use_shop'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}
	
	$cat = $vbulletin->input->clean_gpc('r', 'cat', TYPE_UINT);

	$ownitemsq=$vbulletin->db->query_read("SELECT COUNT(*) as cnt_items FROM " . TABLE_PREFIX . "xperience_shop_ta WHERE sell=0 AND ((buyer=".$vbulletin->userinfo['userid']." AND userid=0) OR (userid=".$vbulletin->userinfo['userid']."))  ORDER BY dateline");
	if ($vbulletin->db->num_rows($ownitemsq) > 0)
	{	
		$ownitems = $vbulletin->db->fetch_array($ownitemsq);	
	}


	if ($do == "own")
	{
		$userstats = fetch_xperience($vbulletin->userinfo['userid']);
		
		$itemsaq =$vbulletin->db->query_read("SELECT
			COUNT(t.itemid) as cnt_items, t.*, s.* 
			FROM " . TABLE_PREFIX . "xperience_shop_ta as t
			INNER JOIN " . TABLE_PREFIX . "xperience_shop as s ON s.itemid=t.itemid
			WHERE
			sell=0 AND
			((t.buyer=".$vbulletin->userinfo['userid']." AND t.userid=0) OR t.userid=".$vbulletin->userinfo['userid'].")
			GROUP BY t.itemid");

		if ($vbulletin->db->num_rows($itemsaq) > 0)
		{	
			while ($itemsa = $vbulletin->db->fetch_array($itemsaq))
				{
					global $bgclass, $altbgclass;
					exec_switch_bg();
					
					require_once(DIR . '/includes/class_bbcode.php');
					$bbcode_parser =& new vB_BbCodeParser($vbulletin, fetch_tag_list());
					$itemsa['itemdesc'] = $bbcode_parser->do_parse($itemsa['itemdesc'], true);
			
					if (strlen($itemsa['itempicture']) < 3)
					{
						$item['itempicture'] = $stylevar[imgdir_misc]."/level/icon_item.png";
					}
			
					$itemsa['available'] = true;
					$itemsa['buyable'] = false;
					if ($vbulletin->options['xperience_shop_sell_rate'] > 0)
					{
						$itemsa['sellcosts'] = number_format(($itemsa['costs'] / 100) * $vbulletin->options['xperience_shop_sell_rate'], 0);
					}
					$buyphrase = "xperience_shop_err_own";
					$itemsa['costs'] = vb_number_format($itemsa['costs']);
					$itemsa['costfield'] = $vbphrase['xperience_'.$itemsa[costfield]];
					$ga = false;
					if ($itemsa['userid'] == $vbulletin->userinfo['userid'])
					{
						$dateline_ga = vbdate($vbulletin->options['dateformat'] . ' ' .  $vbulletin->options['timeformat'], $itemsa['dateline_ga']); 
						$gauser = fetch_userinfo($itemsa['buyer']);
						$ga = true;
					}
					
					$dateline = vbdate($vbulletin->options['dateformat'] . ' ' .  $vbulletin->options['timeformat'], $itemsa['dateline']); 
					$cols = 2;
					eval('$items .= "' . fetch_template('xperience_shop_item_own') . '";');
				}
		}
		$template = 'xperience_shop';

	}
	elseif ($do == "ta")
	{
			global $bgclass, $altbgclass;
					
		$transactionq = $vbulletin->db->query_read("SELECT
			t.*, s.itemname
			FROM " . TABLE_PREFIX . "xperience_shop_ta AS t
			INNER JOIN " . TABLE_PREFIX . "xperience_shop as s ON t.itemid=s.itemid
			WHERE
			buyer=".$vbulletin->userinfo['userid']." OR
			userid=".$vbulletin->userinfo['userid']."
			ORDER BY dateline DESC, taid DESC
			LIMIT 50");
		
		$foundtransaction = 0;
		if ($vbulletin->db->num_rows($transactionq) > 0)
		{	
			
			$aTA = array();
			while ($transaction = $vbulletin->db->fetch_array($transactionq))
			{

				if ($transaction['dateline_sell'] > 0)
				{
					AddTransaction($transaction, 1);
				}
				elseif ($transaction['dateline_ga'] > 0)
				{
					if ($transaction['buyer'] == $vbulletin->userinfo['userid'])
					{
						AddTransaction($transaction, 2);
					}
					else
					{
						AddTransaction($transaction, 3);
					}
				}
				else
				{
					AddTransaction($transaction, 0);
				}
				arsort($aTA);
				foreach ($aTA AS $TA)
				{
					exec_switch_bg();
					eval('$transactions .= "' . fetch_template('xperience_shop_ta_entry') . '";');	
				}
				
				
			}
				
		}
		$template = 'xperience_shop_ta';
	}
	elseif ($do == "giveaway")
	{
		$taid = $vbulletin->input->clean_gpc('r', 'taid', TYPE_INT);
		$template = 'xperience_shop_ga_choose';
	}
	elseif ($do == "dogiveaway")
	{
		
		if (!$vbulletin->options['xperience_shop_gift'])
		{
			$vbulletin->url = $vbulletin->options['bburl']."/xperience.php?go=shop";
			eval(print_standard_redirect('xperience_shop_ga_failed', true, true));
		}
		
		$taid = $vbulletin->input->clean_gpc('r', 'taid', TYPE_INT);
		$username = $vbulletin->input->clean_gpc('p', 'choose_ga_user', TYPE_STR);
		$username = $db->escape_string_like(htmlspecialchars_uni($username));

		$getuseridq = $vbulletin->db->query_read("SELECT userid, username FROM " . TABLE_PREFIX . "user WHERE username='".$username."'");
		if ($db->num_rows($getuseridq) > 0)
		{
			$userinfo = $vbulletin->db->fetch_array($getuseridq);
		
			$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "xperience_shop_ta
				SET userid=".$userinfo['userid'].", dateline_ga=".mktime(date("H"), date("i"), 0, date("m"), date("d"), date("Y"))."
				WHERE taid=".$taid);

			WriteShopItems($userinfo);
			WriteShopItems($vbulletin->userinfo['userid']);


			if ($vbulletin->options['xperience_shop_write_pm_ga'])
			{
				
				$itemsaq = $vbulletin->db->query_read("SELECT
					c.catname, s.itemname
					FROM " . TABLE_PREFIX . "xperience_shop_ta AS t
					INNER JOIN " . TABLE_PREFIX . "xperience_shop as s ON t.itemid=s.itemid
					INNER JOIN " . TABLE_PREFIX . "xperience_shop_cat as c ON c.catid = s.catid
					WHERE t.taid=".$taid);
				
				if ($db->num_rows($itemsaq) > 0)
				{
				
					$itemsa = $vbulletin->db->fetch_array($itemsaq);
					
					$message = construct_phrase($vbphrase['xperience_shop_ga_text'], $vbulletin->options['bburl']."/member.php?u=".$vbulletin->userinfo['userid'], $vbulletin->userinfo['username'], $itemsa['itemname'], $itemsa['catname']);
					$pmdm =& datamanager_init('PM', $vbulletin, ERRTYPE_SILENT);
					$pmdm->overridequota = true;
					$pmdm->set_info('is_automated', true);
					$pmdm->set('fromuserid', $vbulletin->userinfo['userid']);
					$pmdm->set('fromusername', $vbulletin->userinfo['username']);
					$pmdm->setr('title', $vbphrase['xperience_shop_ga_title']);
					$pmdm->setr('message', $message);
				 	$pmdm->set_recipients($userinfo['username'], $botpermissions, 'cc');
					$pmdm->set('dateline', TIMENOW);
					$pmdm->save(); 
				}
			}

			$vbulletin->url = $vbulletin->options['bburl']."/xperience.php?go=shop";
			eval(print_standard_redirect('xperience_shop_ga_successfully', true, true));
		}
		else
		{
			eval(print_standard_redirect('xperience_shop_ga_failed', true, true));
			
		}


	}
	elseif ($do == "sell")
	{
		
		$vbulletin->url = $vbulletin->options['bburl']."/xperience.php?go=shop";
				
		if ($vbulletin->options['xperience_shop_sell_rate'] == 0)
		{
			eval(print_standard_redirect('xperience_sell_failed', true, true));
		}
				
		$itemid = $vbulletin->input->clean_gpc('r', 'itemid', TYPE_INT);
		$userstats = fetch_xperience($vbulletin->userinfo['userid']);
		
		$itemsaq =$vbulletin->db->query_read("SELECT
			*
			FROM " . TABLE_PREFIX . "xperience_shop_ta as t
			INNER JOIN " . TABLE_PREFIX . "xperience_shop as s ON t.itemid = s.itemid
			INNER JOIN " . TABLE_PREFIX . "xperience_shop_cat as c ON c.catid = s.catid
			WHERE t.itemid=".$itemid."
			AND t.sell=0
			AND t.userid=0
			AND t.buyer=".$vbulletin->userinfo['userid']."
			ORDER BY t.dateline ASC
			LIMIT 1"
			);
		
		if ($vbulletin->db->num_rows($itemsaq) > 0)
		{	
			$itemsa = $vbulletin->db->fetch_array($itemsaq);
			$sellcosts = number_format(($itemsa['costs'] / 100) * $vbulletin->options['xperience_shop_sell_rate'], 0);
			$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "xperience_shop_ta
				SET sell='".$sellcosts."', dateline_sell=".mktime(date("H"), date("i"), 0, date("m"), date("d"), date("Y"))."
				WHERE taid=".$itemsa['taid']);
			
			$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "xperience_shop
				SET quantity=quantity+1
				WHERE itemid=".$itemid);
		 		 
		 		 
			if ($vbulletin->options['xperience_shop_write_pm_sell'])
			{
				$message = construct_phrase($vbphrase['xperience_shop_sell_text'], $vbulletin->options['bburl']."/member.php?u=".$vbulletin->userinfo['userid'], $vbulletin->userinfo['username'], $itemsa['itemname'], $itemsa['catname']);
				$pmdm =& datamanager_init('PM', $vbulletin, ERRTYPE_SILENT);
				$pmdm->overridequota = true;
				$pmdm->set_info('is_automated', true);
				$pmdm->set('fromuserid', $vbulletin->userinfo['userid']);
				$pmdm->set('fromusername', $vbulletin->userinfo['username']);
				$pmdm->setr('title', $vbphrase['xperience_shop_sell_title']);
				$pmdm->setr('message', $message);
			 	$pmdm->set_recipients(unhtmlspecialchars($vbulletin->options['xperience_shop_pm_rec']), $botpermissions, 'cc');
				$pmdm->set('dateline', TIMENOW);
				$pmdm->save(); 
			}
		 		 
		 	WriteShopItems($vbulletin->userinfo);
		 		 
		 	$xPerience =& new xPerience;
		 	$xPerience->CalculateXP($vbulletin->userinfo, 0);
		

			eval(print_standard_redirect('xperience_sell_successfully', true, true));
		}
		else
		{
			eval(print_standard_redirect('xperience_sell_failed', true, true));
		}

	}
	elseif ($do == "confirm_buy")
	{
		
		$itemid = $vbulletin->input->clean_gpc('r', 'item', TYPE_INT);
		$userstats = fetch_xperience($vbulletin->userinfo['userid']);
		
		$itemsaq =$vbulletin->db->query_read("SELECT
		*
		FROM " . TABLE_PREFIX . "xperience_shop as s
		INNER JOIN " . TABLE_PREFIX . "xperience_shop_cat as c ON c.catid = s.catid
		WHERE s.itemstatus>0 AND s.itemid=".$itemid);
		
		if ($vbulletin->db->num_rows($itemsaq) > 0)
		{	
			$itemsa = $vbulletin->db->fetch_array($itemsaq);
		}
	
		$vbulletin->url = $vbulletin->options['bburl']."/xperience.php?go=shop";
		if (CheckBuyConditions($itemsa, $userstats))
		{
			$vbulletin->db->query_write("INSERT INTO " . TABLE_PREFIX . "xperience_shop_ta
				(itemid, buyer, dateline, costs, costfield) VALUES (
				".$itemsa['itemid'].",
				".$vbulletin->userinfo['userid'].",
				".mktime(date("H"), date("i"), 0, date("m"), date("d"), date("Y")).",
				".$itemsa['costs'].",
				'".$itemsa['costfield']."'		
				)");
	
			$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "xperience_shop
				SET quantity=quantity-1
				WHERE itemid=".$itemid);
			
			if ($vbulletin->options['xperience_shop_write_pm'])
			{
				$message = construct_phrase($vbphrase['xperience_shop_buy_text'], $vbulletin->options['bburl']."/member.php?u=".$vbulletin->userinfo['userid'], $vbulletin->userinfo['username'], $itemsa['itemname'], $itemsa['catname']);
				$pmdm =& datamanager_init('PM', $vbulletin, ERRTYPE_SILENT);
				$pmdm->overridequota = true;
				$pmdm->set_info('is_automated', true);
				$pmdm->set('fromuserid', $vbulletin->userinfo['userid']);
				$pmdm->set('fromusername', $vbulletin->userinfo['username']);
				$pmdm->setr('title', $vbphrase['xperience_shop_buy_title']);
				$pmdm->setr('message', $message);
			 	$pmdm->set_recipients(unhtmlspecialchars($vbulletin->options['xperience_shop_pm_rec']), $botpermissions, 'cc');
				$pmdm->set('dateline', TIMENOW);
				$pmdm->save(); 
			}
		 		 
		 	$xPerience =& new xPerience;
		 	$xPerience->CalculateXP($vbulletin->userinfo, 0);
			
			eval(print_standard_redirect('xperience_sale_successfully', true, true));
		} else {
			eval(print_standard_redirect('xperience_sale_failed', true, true));		
		}
	
	}
	elseif ($do == "details")
	{
		$itemid = $vbulletin->input->clean_gpc('r', 'item', TYPE_INT);
		$userstats = fetch_xperience($vbulletin->userinfo['userid']);
		
		$itemsaq =$vbulletin->db->query_read("SELECT
		*
		FROM " . TABLE_PREFIX . "xperience_shop as s
		INNER JOIN " . TABLE_PREFIX . "xperience_shop_cat as c ON c.catid = s.catid
		WHERE s.itemstatus>0 AND s.itemid=".$itemid);
		
		if ($vbulletin->db->num_rows($itemsaq) > 0)
		{	
			$itemsa = $vbulletin->db->fetch_array($itemsaq);
			
			$categories = construct_xp_categories(0, $cat);
			
			require_once(DIR . '/includes/class_bbcode.php');
			$bbcode_parser =& new vB_BbCodeParser($vbulletin, fetch_tag_list());
			$itemsa['itemdesc'] = $bbcode_parser->do_parse($itemsa['itemdesc'], true);
			
			if (strlen($itemsa['itempicture']) < 3)
			{
				$itemsa['itempicture'] = $stylevar[imgdir_misc]."/level/icon_item.png";
			}
			
			$itemsa['buyable'] = CheckBuyConditions($itemsa, $userstats);
			$buyphrase = CheckBuyConditions($itemsa, $userstats, true);
			$owncredits = vb_number_format($userstats["$itemsa[costfield]"]);
			$itemsa['costs'] = vb_number_format($itemsa['costs']);
			$itemsa['costfield'] = $vbphrase['xperience_'.$itemsa[costfield]];
			$itemsa['quantity'] = vb_number_format($itemsa['quantity']);
			$cols = 2;
			eval('$items .= "' . fetch_template('xperience_shop_item') . '";');
			
		}
		$template = 'xperience_shop';
		
		
		
	}
	else
	{
	
			
		$categories = construct_xp_categories(0, $cat);
		
		if ($cat > 0)
		{
			$userstats = fetch_xperience($vbulletin->userinfo['userid']);
			
			$itemsaq =$vbulletin->db->query_read("SELECT * FROM " . TABLE_PREFIX . "xperience_shop WHERE itemstatus>0 AND catid=".$cat." ORDER BY itemstatus, itemname");
			if ($vbulletin->db->num_rows($itemsaq) > 0)
			{	
				while ($itemsa = $vbulletin->db->fetch_array($itemsaq))
				{

					
					$itemsa['available'] = true;
					
					
					if (strlen($itemsa['itemthumb']) < 3)
					{
						$itemsa['itemthumb'] = $stylevar[imgdir_misc]."/level/icon_item.png";
					}

					$owncredits = vb_number_format($userstats["$itemsa[costfield]"]);
					$itemsa['costs'] = vb_number_format($itemsa['costs']);
					$itemsa['costfield'] = $vbphrase['xperience_'.$itemsa[costfield]];
					$itemsa['quantity'] = vb_number_format($itemsa['quantity']);
					$cols = 3;
					global $bgclass, $altbgclass;
					exec_switch_bg();
					eval('$items .= "' . fetch_template('xperience_shop_item_c') . '";');
					$printeditem++;
					if ($printeditem > 2)
					{
						$cols = 3;
						$printeditem=0;

						$items.='</tr><tr class="'.$bgclass.'">';
					}
				}
			} else {
				$cols = 2;
			
				eval('$items .= "' . fetch_template('xperience_shop_item_no') . '";');
			}
		}

		if ($printeditem == 1)
		{
			
			exec_switch_bg();			
			$items.='<td width="33%" class="'.$bgclass.'">&nbsp;</td>';

			exec_switch_bg();			
			$items.='<td width="33%" class="'.$bgclass.'">&nbsp;</td>';
		}
		if ($printeditem == 2)
		{
			exec_switch_bg();
			$items.='<td width="33%" class="'.$bgclass.'">&nbsp;</td>';
		}

		$template = 'xperience_shop';
	}
	


}
elseif ($go == "awards") 
{
	$navbits[$parent] = $vbphrase['xperience_awards'];
	
	if (!$vbulletin->options['xperience_use_awards'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}

	$count_awards=0;
	$foundaward=0;
	require_once(DIR . '/includes/functions_user.php');
	$awardsq =$vbulletin->db->query_read("SELECT * FROM " . TABLE_PREFIX . "xperience_awards WHERE awardstatus>0 ORDER BY awardstatus");
	if ($vbulletin->db->num_rows($awardsq) > 0)
	{

		$count_awards=$vbulletin->db->num_rows($awardsq);
		$width_awards=ceil(100/$vbulletin->db->num_rows($awardsq));
		if ($count_awards>3) $count_awards=3;		

		while ($myawards = $vbulletin->db->fetch_array($awardsq))
		{

			$myrows = $vbulletin->db->query_read("SELECT
				u.userid,
				u.username,
				u.xperience_awards
				" . ($vbulletin->options['avatarenabled'] ? ",u.avatarrevision, avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustomavatar, customavatar.dateline AS avatardateline,customavatar.width AS avwidth,customavatar.height AS avheight" : "") . "
				FROM " . TABLE_PREFIX . "user AS u
				" . ($vbulletin->options['avatarenabled'] ? "LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON(avatar.avatarid = u.avatarid) LEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON(customavatar.userid = u.userid)" : "") . "
				WHERE u.xperience_awards LIKE '%".$myawards['awardid']."|".addslashes($myawards['awardname'])."|".addslashes($myawards['awardtitle'])."%'");  

			if ($vbulletin->db->num_rows($myrows) > 0)
			{
				$foundaward=1;
				while ($myrow = $vbulletin->db->fetch_array($myrows))
				{

					if (function_exists(fetch_avatar_from_userinfo))
					{
						fetch_avatar_from_userinfo($myrow, true, true);
						$avatarurl = GetAvatar($myrow);
					} else {
						//Compatibility to vB 3.6.x
						$arravatarurl = fetch_avatar_url($myrow['userid']);
						$avatarurl = $arravatarurl[0];
					}
				if (strlen($avatarurl)<3) $avatarurl=$stylevar[imgdir_misc].'/level/unknown.gif';
				

			if (strlen($myawards['awardurl']) > 0)
			{
				$showaward='<img class="inlineimg" border="0" src="'.$myawards['awardurl'].'" title="'.$myawards['awardtitle'].'">';
			}
			else
			{
				if ($vbulletin->options['xperience_awardgfx'])
				{
					$awardextension=".png";
				} else {
					$awardextension=".gif";
				}
					
				$showaward='<img border="0" src="'.$stylevar[imgdir_misc].'/level/award_'.$myawards['awardname'].$awardextension.'" title="'.$myawards['awardtitle'].'">';
			}
	
					eval('$awardbit.= "' . fetch_template('xperience_awards_awardbit') . '";');
					$printedaward++;
					if ($printedaward>2)
					{
						$printedaward=0;
						$awardbit.='</tr><tr class="alt1">';
					}
				
				}
			}

		}
						if ($printedaward > 0 AND $printedaward < 3 )
				{
					for($i=$printedaward; $i <= 2; $i++)
					{
						eval('$awardbit .= "' . fetch_template('xperience_awards_awardbit_empty') . '";');
					}
				}

	}

	$template = 'xperience_awards';;
} elseif ($go == "groups") {

	if (!$vbulletin->options['xperience_use_groups'])
	{
		eval('standard_error($vbphrase[xperience_disabled]);');
		exit;
	}


	$vbulletin->input->clean_array_gpc('r', array(
		'agroupname'      => TYPE_NOHTML,
	));

	$search_username = $vbulletin->GPC['agroupname'];

	$condition = '1=1';
	if (strlen($vbulletin->GPC['agroupname']) > 0)
	{
		$condition  .=  " AND name LIKE '%" . $db->escape_string_like(htmlspecialchars_uni($vbulletin->GPC['agroupname'])) . "%' ";
	}

	$groups = $vbulletin->db->query_first("SELECT
		COUNT(*) AS groups
		FROM " . TABLE_PREFIX . "xperience_groups as x
		INNER JOIN " . TABLE_PREFIX . "socialgroup AS g ON g.groupid=x.groupid
		WHERE ".$condition); 
	$groupcount = $groups['groups'];


	sanitize_pageresults($groupcount, $pagenumber, $perpage, 100, $vbulletin->options['memberlistperpage']);

	$limitlower = ($pagenumber - 1) * $perpage + 1;
	$limitupper = $pagenumber * $perpage;
	if ($limitupper > $groupcount)
	{
		$limitupper = $groupcount;
		if ($limitlower > $groupcount)
		{
			$limitlower = $groupcount - $perpage;
		}
	}
	if ($limitlower <= 0)
	{
		$limitlower = 1;
	}

	$oppositesort = iif($sortorder == 'desc', 'asc', 'desc');

	if ($sortorder != '') 
	{
		$switchOrder = ($sortorder)?$sortorder:"";
	} else {
		$switchOrder = "";
	}

	switch ($switchOrder) 
	{
		case "asc":
			$deasc = " ASC";
			break;
		case "desc":
			$deasc = " DESC";
			break;
		default:
			$deasc = " DESC";
	}

	
	if ($sortfield != '') 
	{
		$switchSort = ($sortfield)?$sortfield:"";
	} else {
		$switchSort = "";
	}

	switch ($switchSort) 
	{
		case "xp":
		default :
			$sort_query = "x.points " . $deasc; 
			break;
		case "groupname":
			$sort_query = "g.name " . $deasc;
			break;
		case "members":
			$sort_query = "x.members " . $deasc. ", x.points DESC"; 
			break;
		case "pmin":
			$sort_query = "x.points_min " . $deasc. ", x.points DESC"; 
			break;
		case "pmax":
			$sort_query = "x.points_max " . $deasc. ", x.points DESC"; 
			break;
	}


	//construct_page_nav($pagenumber, $perpage, $results, $address, $address2 = '', $anchor = '')
	// 
	$sortstring = "sortfield=".$switchSort."&amp;sortorder=".$sortorder."&amp;agroupname=".urlencode($search_username);	
	$pagenav = construct_page_nav($pagenumber, $perpage, $userscount, 'xperience.php?do=groups' . $vbulletin->session->vars['sessionurl'], $sortstring);


global $bgclass, $altbgclass;
	$myquery="SELECT 
		x.*,
		g.name
		" . ($vbulletin->options['sg_enablesocialgroupicons'] ? ', socialgroupicon.dateline AS icondateline, socialgroupicon.width AS iconwidth, socialgroupicon.height AS iconheight, socialgroupicon.thumbnail_width AS iconthumb_width, socialgroupicon.thumbnail_height AS iconthumb_height' : '') . " 
		FROM " . TABLE_PREFIX . "xperience_groups AS x
		INNER JOIN " . TABLE_PREFIX . "socialgroup AS g ON g.groupid=x.groupid
		".($vbulletin->options['sg_enablesocialgroupicons'] ?
			"LEFT JOIN " . TABLE_PREFIX . "socialgroupicon AS socialgroupicon ON
				(socialgroupicon.groupid = g.groupid)" : '')." 
		WHERE ".$condition." 
		ORDER BY " . $sort_query . "
		LIMIT " . ($limitlower - 1) . "," . $perpage;

	$myrows = $vbulletin->db->query_read($myquery);
	
	if ($vbulletin->db->num_rows($myrows) > 0)
	{
		$groupcount = 0;
		require_once('./includes/functions_socialgroup.php');
		
		while ($myrow = $vbulletin->db->fetch_array ($myrows)) 
		{

				$xperience['members']=vb_number_format($myrow['members']);
				$xperience['points']=vb_number_format($myrow['points']);
				$xperience['points_max']=vb_number_format($myrow['points_max']);
				$xperience['points_min']=vb_number_format($myrow['points_min']);
				
				$groupcount++;
				$xperience['groupiconurl'] = '';
				if ($groupcount < 4)
				{
					if (function_exists(fetch_socialgroupicon_url))
					{
						$xperience['groupiconurl'] = fetch_socialgroupicon_url($myrow, true);
					}
				}
	
				
				exec_switch_bg(); 
				eval('$xperience_ranking_bit.= "' . fetch_template('xperience_groups_ranking_bit') . '";');
			}
		}
	
	$template = 'xperience_groups_ranking';

	
} else {

	$vbulletin->input->clean_array_gpc('r', array(
		'ausername'      => TYPE_NOHTML,
	));

	$search_username = $vbulletin->GPC['ausername'];

	$condition = '1=1';
	if (strlen($vbulletin->GPC['ausername']) > 0)
	{
		$condition  .=  " AND username LIKE '%" . $db->escape_string_like(htmlspecialchars_uni($vbulletin->GPC['ausername'])) . "%' ";
	}

	if (strlen($vbulletin->options['xperience_ignore_users']) > 0)
	{
		$condition .= " AND u.userid NOT IN(".$vbulletin->options['xperience_ignore_users'].") ";
	}
	
	$members = $vbulletin->db->query_first("SELECT
		COUNT(*) AS users
		FROM " . TABLE_PREFIX . "user as u
		WHERE ".$condition); 
	$userscount = $members['users'];


	sanitize_pageresults($userscount, $pagenumber, $perpage, 100, $vbulletin->options['memberlistperpage']);

	$limitlower = ($pagenumber - 1) * $perpage + 1;
	$limitupper = $pagenumber * $perpage;
	if ($limitupper > $userscount)
	{
		$limitupper = $userscount;
		if ($limitlower > $userscount)
		{
			$limitlower = $userscount - $perpage;
		}
	}
	if ($limitlower <= 0)
	{
		$limitlower = 1;
	}

	$oppositesort = iif($sortorder == 'desc', 'asc', 'desc');

	if ($sortorder != '') 
	{
		$switchOrder = ($sortorder)?$sortorder:"";
	} else {
		$switchOrder = "";
	}

	switch ($switchOrder) 
	{
		case "asc":
			$deasc = " ASC";
			break;
		case "desc":
			$deasc = " DESC";
			break;
		default:
			$deasc = " DESC";
	}

	
	if ($sortfield != '') 
	{
		$switchSort = ($sortfield)?$sortfield:"";
	} else {
		$switchSort = "";
	}

	switch ($switchSort) 
	{
		case "xp":
		default : $sort_query = "u.xperience " . $deasc;
			break;
		case "xu":
			$sort_query = "s.points_user " . $deasc. ", u.xperience DESC"; 
			break;
		case "xt":
			$sort_query = "s.points_thread " . $deasc. ", u.xperience DESC"; 
			break;
		case "xo":
			$sort_query = "s.points_post " . $deasc. ", u.xperience DESC"; 
			break;
		case "xn":
			$sort_query = "u.username " . $deasc;
			break;
		case "xl":
			$sort_query = "u.xperience_level " . $deasc. ", u.xperience DESC"; 
			break;
		case "xm":
			$sort_query = "s.points_misc " . $deasc. ", u.xperience DESC"; 
			break;
		case "xd":
			$sort_query = "u.xperience_ppd " . $deasc. ", u.xperience DESC"; 
			break;
		case "xr":
			$sort_query = "u.reputation " . $deasc. ", u.xperience ASC"; 
			break;
	}


	//construct_page_nav($pagenumber, $perpage, $results, $address, $address2 = '', $anchor = '')
	// 
	$sortstring = "sortfield=".$switchSort."&amp;sortorder=".$sortorder."&amp;ausername=".urlencode($search_username);	
	$pagenav = construct_page_nav($pagenumber, $perpage, $userscount, 'xperience.php?' . $vbulletin->session->vars['sessionurl'], $sortstring);


global $bgclass, $altbgclass;
	$myquery="SELECT 
		u.userid,
		u.usergroupid,
		u.membergroupids,
		u.username,
		u.xperience_level,
		u.xperience,
		u.xperience_ppd,
		u.xperience_awards,
		u.reputation,
		s.points_user,
		s.points_thread,
		s.points_post,
		s.points_misc
		FROM " . TABLE_PREFIX . "xperience_stats AS s
		INNER JOIN " . TABLE_PREFIX . "user AS u ON u.userid=s.userid
		WHERE ".$condition." 
		ORDER BY " . $sort_query . "
		LIMIT " . ($limitlower - 1) . "," . $perpage;

	$myrows = $vbulletin->db->query_read($myquery);

	if ($vbulletin->db->num_rows($myrows) > 0)
	{
		while ($myrow = $vbulletin->db->fetch_array ($myrows)) 
		{
		
			$DisplayUser=1;
			if (strlen($vbulletin->options['xperience_ignore_usergroupsids']) > 0) 
			{
				$usergroups=explode(",", $vbulletin->options['xperience_ignore_usergroupsids']);
				for ($i = 0; $i < count($usergroups); $i ++) 
				{
					if (is_member_of($myrow, $usergroups[$i])) 
					{
						$DisplayUser=0;
					}
				}
			}
		
		
			if ($DisplayUser==1) 
			{
				$xperience['xperience']=vb_number_format($myrow['xperience']);
				$xperience['points_user']=vb_number_format($myrow['points_user']);
				$xperience['points_thread']=vb_number_format($myrow['points_thread']);
				$xperience['points_post']=vb_number_format($myrow['points_post']);
				$xperience['points_misc']=vb_number_format($myrow['points_misc']);
				
				
				$awards = GetAwards($myrow['xperience_awards']);
				
							
				
				exec_switch_bg(); 
				eval('$xperience_ranking_bit.= "' . fetch_template('xperience_ranking_bit') . '";');
			}
		}
	}
	$template = 'xperience_ranking';
	
}
	$navbits[$parent] = $vbphrase['xperience_vbnav']." ".$navbits[$parent];
	$navbits = construct_navbits($navbits); 
	eval('$navbar = "' . fetch_template('navbar') . '";');
	eval ('print_output("' . fetch_template($template) . '");');



	
?>
