Location: PHPKode > projects > SiteX > includes/functions.php
<?PHP

// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
// FUNCTIONS.PHP
// Created by: BJ Sintay (August 2004)
// Last updated by: PMills (2/28/2010)
// SiteX Project
// 0.8 Beta Core
// http://sitex.bjsintay.com
// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -


// - = - = - = - = - = - = - = - = -
// GLOBAL CODE
// - = - = - = - = - = - = - = - = - 

// Convert post, get, and server variables for shorthand use and
// register globals compatibility.  Strip javascript for XSS.

if (!empty($_POST)) 	foreach ($_POST as $k => $v) 	$$k = str_replace(array("<script>","</script>"),array("",""),$v);
if (!empty($_GET)) 		foreach ($_GET as $k => $v) 	$$k = str_replace(array("<script>","</script>"),array("",""),$v);
if (!empty($_SERVER)) 	foreach ($_SERVER as $k => $v) 	$$k = $v;
if (!empty($_COOKIE)) 	foreach ($_COOKIE as $k => $v) 	$$k = str_replace(array("<script>","</script>"),array("",""),$v);
if (!empty($_SESSION)) 	foreach ($_SESSION as $k => $v) $$k = str_replace(array("<script>","</script>"),array("",""),$v);

// Prevent PHP include vulnerability, initialize important vars, will be over-written

$sxSetup['Language'] 	= 'English';
$THEME 					= 1;
$THEME_FOLDER 			= 'Structure';
$sxTitleAddendum 		= '';
$sxBuild = 'Build 524';

// Current timestamp

$NOW = mktime();

// Global content directory variables

$sxContentDir = array();

$sxContentDir['Avatar']			= "content/avatars/";
$sxContentDir['FCK'] 			= "content/fck/";
$sxContentDir['FCKFile'] 		= "content/fck/File/";
$sxContentDir['FCKFlash'] 		= "content/fck/Flash/";
$sxContentDir['FCKImage'] 		= "content/fck/Image/";
$sxContentDir['FCKMedia'] 		= "content/fck/Media/";
$sxContentDir['FCKUpload'] 		= "content/fck/Upload/";
$sxContentDir['Files'] 			= "content/files/";
$sxContentDir['Photo']			= "content/photos/";
$sxContentDir['PhotoBatch'] 	= "content/photos/batch/";
$sxContentDir['PhotoFullsize'] 	= "content/photos/fullsize/";
$sxContentDir['PhotoScaled']	= "content/photos/scaled/";
$sxContentDir['PhotoThumb'] 	= "content/photos/thumbs/";
$sxContentDir['Root'] 			= "content/";
$sxContentDir['Security']		= "content/security/";
$sxContentDir['TitleImage'] 	= "content/title_pictures/";

if(!$sxSetupPage){	// Block these procedures from running during setup

// Ensure site is setup

verifySetup();

// Global connection of db (MySQL)

$Link = mysql_connect($HOST, $USER, $PASS) or queryError("137", mysql_error());
mysql_select_db($DATABASE, $Link) or queryError("136", mysql_error());

// Form table name variables

foreach (fetchTables() as $table_value)
{
	$new_prefixed_name = "DB".$table_value;
	$$new_prefixed_name = $DB_PREFIX.$table_value;
}

// Check for update

$sxUpdateQuery = "SELECT * FROM $DB_Setup WHERE setup_key='version' OR setup_key='Version'";
$sxUpdateResult = @mysql_query($sxUpdateQuery, $Link);

if (mysql_num_rows($sxUpdateResult))
{	
	$sxROW = @mysql_fetch_object($sxUpdateResult);
	if($sxROW->setup_value != '0.8.0')
	{
		// Grab URL
		$sxURLQuery = "SELECT setup_value FROM $DB_Setup WHERE setup_key='Url'";
		$sxURLResult = mysql_query($sxURLQuery, $Link) or die('SiteX get setup died with error: '.mysql_error());
		$sxURL = mysql_fetch_object($sxURLResult);
		
		// Include required upgrade file or die
		require(sxPathToRootPrimitive($sxURL->setup_value)."setup/upgrade.php");
	}
}
else
	die("SiteX is experiencing an unrecoverable error. This error should never be possible unless something bad has happened in the update script!");

// Pull setup variables from the db

$sxSetup = array();
$query = "SELECT * FROM $DB_Setup";
$result = mysql_query($query, $Link) or die('SiteX get setup died with error: '.mysql_error());
while($ROW = mysql_fetch_array($result))
	$sxSetup[$ROW['setup_key']] = $ROW['setup_value'];

// Check URL compliance at domain level (not subdirectory or http(s))

$sxStrippedURL = substr($sxSetup['Url'],7);
if(strpos($sxStrippedURL, '/'))
	$sxHostURL = substr($sxStrippedURL, 0, strpos($sxStrippedURL,'/'));
else
	$sxHostURL = $sxStrippedURL;
if($sxHostURL != $_SERVER['HTTP_HOST'])
{
	header("Location: ".$sxSetup['Url']."/index.php");
	die();
}
$sxTitleAddendum 		= $sxSetup['METATitleExt'];

// Pull theme information

$query = "SELECT * FROM $DB_Themes WHERE selected='1'";
$result = mysql_query($query, $Link) or queryError("91", mysql_error());
$ROW = mysql_fetch_object($result);

$THEME = $ROW->id;
$THEME_FOLDER = $ROW->folder;

$query = "SELECT * FROM $DB_Themes_Setup WHERE selected='1' AND themeid='$THEME'";
$result = mysql_query($query, $Link) or queryError("91", mysql_error());
$ROW = mysql_fetch_object($result);

$SCHEME_NAME = $ROW->name;

// Setup page design parameters

$query = "SELECT * FROM $DB_Themes_Setup WHERE themeid='$THEME' AND selected='1'";
$result = mysql_query($query, $Link) or queryError("92", mysql_error());
$ROW = mysql_fetch_object($result);

$sxTheme = array();

$sxTheme['ColorPrimary'] 		= $ROW->color_primary;
$sxTheme['ColorSecondary'] 		= $ROW->color_secondary;
$sxTheme['ColorBackground']		= $ROW->color_background;
$sxTheme['ColorTable']			= $ROW->color_table;
$sxTheme['ColorTableRow']		= $ROW->color_table_row;
$sxTheme['ColorText'] 			= $ROW->color_text;
$sxTheme['ColorTextSecondary'] 	= $ROW->color_text_secondary;
$sxTheme['ColorTextTable']		= $ROW->color_text_table;
$sxTheme['ColorLinks'] 			= $ROW->color_links;
$sxTheme['ColorLinksVisited'] 	= $ROW->color_links_visited;
$sxTheme['ColorLinksHover'] 	= $ROW->color_links_hover;
$sxTheme['ColorSiteName'] 		= $ROW->color_sitename;
$sxTheme['ShowSiteName']		= $ROW->show_sitename;

// Check for POST passed username (auth)

if ( isset($_POST['username']) AND (strlen($_POST['username']) > 0) )
	authenticate($_POST['username'], $_POST['password']);

// Setup user, maintenance, page hit, and log

$THIS_USER = get_THIS_USER();					// User's id

if (
   ($sxSetup['Maintenance'] == 1)AND			// Check for maintenance flag
   (!userAdmin())AND							// Check if user is admin
   (!$sxMaintenanceOverride)AND					// Check if override is on
   (!$sxMaintenance)							// Check if maintenance is already called
   )
	showMaintenancePage();						// Call maintenance message

// Catch a search

if (strlen($search_text) > 0)
{
	switch($search_type)
	{
		case 'google':
			submitGoogleSearch($search_text, 'google');
			break;
		case 'google-site':
			submitGoogleSearch($search_text, 'google-site');
			break;
		default :
			header("Location: ".sxPathToRoot()."search.php?search=".$search_text);
			die();
			break;
	}
}

countPageHit($_SERVER['REQUEST_URI']);			// Log page hit for statistics
logUser();										// Log user

// Cleaning routines

if ($sxSetup['UserCleaner'])
	inactiveUserCleaner();
if ($sxSetup['FormSecurity']) 
	sxSecurityImageCleaner();

} // end if setup

// - = - = - = - = - = - = - = - = -
// FUNCTION DEFINITIONS
// - = - = - = - = - = - = - = - = -

// Determine if a path needs ../ to root (does not account for
// more than one sub dir!)
function sxPathToRoot()
{
	global $sxSetup;
	return sxPathToRootPrimitive($sxSetup['Url']);
}

function sxPathToRootPrimitive($url)
{
	$path = pathinfo($_SERVER['SCRIPT_NAME']);
	$dirpath = explode('/', $path['dirname']);
	$sitepath = explode('/', $url);
	
	if($dirpath[count($dirpath)-1] == $sitepath[count($sitepath)-1])
		$path2root = '';
	else
		$path2root = '../';
	
	return $path2root;
}

// Delete old security images after a length of time ($overdue)
function sxSecurityImageCleaner()
{
	global $Link;
	global $NOW;
	global $DB_Security_Image;
	global $sxContentDir;
	
	$rootpath = sxPathToRoot();
	$overdue = $NOW - 300;	// Timestamp from 5 minutes ago
	
	$query = "SELECT * FROM $DB_Security_Image WHERE timestamp < '$overdue'";
	$result = mysql_query($query, $Link) or queryError("8", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		// Unlink current image
		@unlink($rootpath.$sxContentDir['Security'].$ROW->filename);
		$query2 = "DELETE FROM $DB_Security_Image WHERE id='$ROW->id'";
		$result2 = mysql_query($query2, $Link) or queryError("101002", mysql_error());
	}
}

// Markup variable based on magic quotes and possible injections
function sxSmartQuote($value)
{
	global $Link;
	
	// Strip slashes
	if (get_magic_quotes_gpc())
		$value = stripslashes($value);

	// Check if this function exists 
	if(function_exists("mysql_real_escape_string")) 
		$value = mysql_real_escape_string($value); 

	// For PHP version < 4.3.0 use addslashes 
	else 
		$value = addslashes($value); 

	return $value;
}

// Applies watermark to image resource and returns image
function sxWatermarkImage($image,$width,$height)
{
	global $Link;
	global $sxSetup;
	global $sxContentDir;
	
	// Watermark raw image
	if($sxSetup['GalleryWatermarking'] > 0)
	{
		// Create raw canvas
		if(imageCompatibility() == "truecolor")
		{
			$sxRawImage = imagecreatetruecolor($width, $height);
			imagecopyresampled($sxRawImage, $image, 0, 0, 0, 0, $width, $height, $width, $height);
		}
		elseif(imageCompatibility() == "normal")
		{
			$sxRawImage = imagecreate($width, $height);
			imagecopyresized($sxRawImage, $image, 0, 0, 0, 0, $width, $height, $width, $height);
		}
		
		// Watermark image			
		switch($sxSetup['GalleryWatermarkingType'])
		{
			// Text overlay
			case 'txt' :
				
				// Form color values
				$sxR = hexdec(substr($sxSetup['GalleryWatermarkingTextColor'],1,2));
				$sxG = hexdec(substr($sxSetup['GalleryWatermarkingTextColor'],3,2));
				$sxB = hexdec(substr($sxSetup['GalleryWatermarkingTextColor'],5,2));
				$sxA = $sxSetup['GalleryWatermarkingTextTrans'];
				
				// Setup string params
				if(imageCompatibility() == "truecolor")
				{
					$sxWMTextColor  = imagecolorallocatealpha($sxRawImage, $sxR, $sxG, $sxB, $sxA);
					$sxWMTextColorB = imagecolorallocatealpha($sxRawImage, 255, 255, 255, $sxA);
					$sxWMTextColorBox = imagecolorallocatealpha($sxRawImage, 0, 0, 0, $sxA);
				}
				elseif(imageCompatibility() == "normal")
				{
					$sxWMTextColor  = imagecolorallocate($sxRawImage, $sxR, $sxG, $sxB);
					$sxWMTextColorB = imagecolorallocate($sxRawImage, 255, 255, 255);
					$sxWMTextColorBox = imagecolorallocate($sxRawImage, 0, 0, 0);
				}

				$sxWMTextPadding = 10;		// Pads watermark
				
				switch($sxSetup['GalleryWatermarkingPosition'])
				{
					case 'center':
						$sxWMTextX = (int)($width/2)  - (int)(imagefontwidth($sxSetup['GalleryWatermarkingTextSize'])*strlen($sxSetup['GalleryWatermarkingText'])/2);
						$sxWMTextY = (int)($height/2) - (int)(imagefontheight($sxSetup['GalleryWatermarkingTextSize'])/2);
						break;
						
					case 'lowleft':
						$sxWMTextX = $sxWMTextPadding;
						$sxWMTextY = $height - $sxWMTextPadding - imagefontheight($sxSetup['GalleryWatermarkingTextSize']);
						break;
						
					case 'lowright':
						$sxWMTextX = $width  - $sxWMTextPadding - imagefontwidth($sxSetup['GalleryWatermarkingTextSize'])*strlen($sxSetup['GalleryWatermarkingText']);
						$sxWMTextY = $height - $sxWMTextPadding - imagefontheight($sxSetup['GalleryWatermarkingTextSize']);
						break;
				}
				
				// Image background rectangle
				$sxBoxXMargin = 5;
				$sxBoxYMargin = 2;
				$sxWMTextX2 = $sxWMTextX  + (int)(imagefontwidth($sxSetup['GalleryWatermarkingTextSize'])*strlen($sxSetup['GalleryWatermarkingText']));
				$sxWMTextY2 = $sxWMTextY  + (int)(imagefontheight($sxSetup['GalleryWatermarkingTextSize']));

				imagefilledrectangle ($sxRawImage, $sxWMTextX-$sxBoxXMargin, $sxWMTextY-$sxBoxYMargin, $sxWMTextX2+$sxBoxXMargin, $sxWMTextY2+$sxBoxYMargin, $sxWMTextColorBox);
				
				// Image string
				/*
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX+1, $sxWMTextY,   $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX+1, $sxWMTextY+1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX,   $sxWMTextY+1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX-1, $sxWMTextY,   $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX-1, $sxWMTextY-1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX,   $sxWMTextY-1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX-1, $sxWMTextY+1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX+1, $sxWMTextY-1, $sxSetup['GalleryWatermarkingText'], $sxWMTextColorB);
				*/
				imagestring($sxRawImage, $sxSetup['GalleryWatermarkingTextSize'], $sxWMTextX, $sxWMTextY, $sxSetup['GalleryWatermarkingText'], $sxWMTextColor);
				
				break;	// end text watermark
			
			// Image overlay
			case 'img' :
				
				$sxWMLocation = $sxSetup['Url'].'/'.$sxContentDir['Root'].$sxSetup['GalleryWatermarkingImage'];
				$sxWMImagePadding = 25;
				
				// Read raw image
				if((imageCompatibility() == "truecolor")OR(imageCompatibility() == "normal"))
				{
					$sxWMImageInfo = getimagesize($sxWMLocation);
					switch($sxWMImageInfo[2])
					{
						case 1: $sxWMImage = imagecreatefromgif($sxWMLocation);  break;
						case 2: $sxWMImage = imagecreatefromjpeg($sxWMLocation); break;
						case 3: $sxWMImage = imagecreatefrompng($sxWMLocation);  break;
						case 6: $sxWMImage = imagecreatefromwbmp($sxWMLocation); break;
					}
					$wm_width = $sxWMImageInfo[0];
					$wm_height = $sxWMImageInfo[1];
				}
				
				// Put image in the right place
				switch($sxSetup['GalleryWatermarkingPosition'])
				{
					case 'center':
						$sxWMImageX = (int)($width/2)  - (int)($wm_width/2);
						$sxWMImageY = (int)($height/2) - (int)($wm_height/2);
						break;

					case 'lowleft':
						$sxWMImageX = $sxWMImagePadding;
						$sxWMImageY = $height - $sxWMImagePadding - $wm_height;
						break;
						
					case 'lowright':
						$sxWMImageX = $width  - $sxWMImagePadding - $wm_width;
						$sxWMImageY = $height - $sxWMImagePadding - $wm_height;
						break;
				}
				
				// Merge watermark with original image
				imagecopymerge ($sxRawImage, $sxWMImage, $sxWMImageX, $sxWMImageY, 0, 0, $wm_width, $wm_height,  100);
				imagedestroy($sxWMImage);
				break;	// end image watermark
		}
	}
	return $sxRawImage;
}

function writeRSSXML()
{
	global $Link;
	global $sxLang;
	global $sxSetup;
	global $sxThemeConfig;
	global $NOW;
	global $DB_Journal;
	
	$error = 0;	
	$sxRSSFile = "../content/rss.xml";
	
	@unlink($sxRSSFile);
	if (!$handle = fopen($sxRSSFile, "w"))
		$error = 1;

	$sxRSSFeed  = '<?xml version="1.0" encoding="ISO-8859-1" ?>'."\n".'<rss version="2.0">'."\n".'<channel>'."\n"."\n";
	$sxRSSFeed .= '<title>' . sxCustomEntityReplace($sxSetup['SiteName']) . '</title>'."\n";
	
	if($sxSetup['MetaDescription'] != '')
		$sxRSSFeed .= '<description>' . sxCustomEntityReplace($sxSetup['MetaDescription']) . '</description>'."\n";
	else
		$sxRSSFeed .= '<description>'. $sxLang['RSSDescriptionNone'] .'</description>'."\n";

	$sxRSSFeed .= '<link>' . sxCustomEntityReplace($sxSetup['Url']) . '</link>'."\n"."\n";
	
	// Export XML items to feed
	$query = "SELECT * FROM $DB_Journal ORDER BY timestamp DESC LIMIT 0,".$sxSetup['JournalRSSCount'];
	$result = mysql_query($query, $Link) or queryError("8", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		$sxRSSFeed .= '<item>'."\n";
		
		if($ROW->title)
			$sxRSSFeed .= '<title>' . sxCustomEntityReplace($ROW->title) . '</title>'."\n";
		else
			$sxRSSFeed .= '<title>'. $sxLang['RSSPostNoTitle'] .'</title>'."\n";
			
		$sxRSSFeed .= '<description>' . sxCustomEntityReplace(str_replace("&nbsp;", "", limitString(strip_tags(parseSpecial($ROW->entry)), $sxThemeConfig['RSSDescriptionStringLimit']))) . '</description>';
		$sxRSSFeed .= '<link>' . sxCustomEntityReplace($sxSetup['Url']) . '/journal.php?sxEntryID=' . $ROW->id . '</link>';
		$sxRSSFeed .= '<guid>' . sxCustomEntityReplace($sxSetup['Url']) . '/journal.php?sxEntryID=' . $ROW->id . '</guid>';
		$sxRSSFeed .= '<pubDate>' . gmdate("r", $ROW->timestamp) . '</pubDate>';
		$sxRSSFeed .= '</item>'."\n"."\n";
	}
	
	$sxRSSFeed .= '</channel>'."\n"."\n".'</rss>';

	if (fwrite($handle, $sxRSSFeed) === FALSE)
	{
	   $error = 1;
	   exit;
	}
	
	fclose($handle);
	return $error;
}

// NOTES:	Returns string with entities replaced
// RETURNS: string
//--------------------------------------------------

function sxCustomEntityReplace($string)
{
	return $string; //str_replace(array_keys(sxFetchCharCodes()), array_values(sxFetchCharCodes()), $string);
}

// NOTES:	Returns array of key/value pairs which
// 			match entity definitions.
// RETURNS: array
//--------------------------------------------------

function sxFetchCharCodes()
{
	return array(
		'&nbsp;' => '&#160;', 
		'&iexcl;' => '&#161;', 
		'&cent;' => '&#162;', 
		'&pound;' => '&#163;', 
		'&curren;' => '&#164;', 
		'&yen;' => '&#165;', 
		'&brvbar;' => '&#166;', 
		'&sect;' => '&#167;', 
		'&uml;' => '&#168;', 
		'&copy;' => '&#169;', 
		'&ordf;' => '&#170;', 
		'&laquo;' => '&#171;', 
		'&not;' => '&#172;', 
		'&shy;' => '&#173;', 
		'&reg;' => '&#174;', 
		'&macr;' => '&#175;', 
		'&deg;' => '&#176;', 
		'&plusmn;' => '&#177;', 
		'&sup2;' => '&#178;', 
		'&sup3;' => '&#179;', 
		'&acute;' => '&#180;', 
		'&micro;' => '&#181;', 
		'&para;' => '&#182;', 
		'&middot;' => '&#183;', 
		'&cedil;' => '&#184;', 
		'&sup1;' => '&#185;', 
		'&ordm;' => '&#186;', 
		'&raquo;' => '&#187;', 
		'&frac14;' => '&#188;', 
		'&frac12;' => '&#189;', 
		'&frac34;' => '&#190;', 
		'&iquest;' => '&#191;', 
		'&Agrave;' => '&#192;', 
		'&Aacute;' => '&#193;', 
		'&Acirc;' => '&#194;', 
		'&Atilde;' => '&#195;', 
		'&Auml;' => '&#196;', 
		'&Aring;' => '&#197;', 
		'&AElig;' => '&#198;', 
		'&Ccedil;' => '&#199;', 
		'&Egrave;' => '&#200;', 
		'&Eacute;' => '&#201;', 
		'&Ecirc;' => '&#202;', 
		'&Euml;' => '&#203;', 
		'&Igrave;' => '&#204;', 
		'&Iacute;' => '&#205;', 
		'&Icirc;' => '&#206;', 
		'&Iuml;' => '&#207;', 
		'&ETH;' => '&#208;', 
		'&Ntilde;' => '&#209;', 
		'&Ograve;' => '&#210;', 
		'&Oacute;' => '&#211;', 
		'&Ocirc;' => '&#212;', 
		'&Otilde;' => '&#213;', 
		'&Ouml;' => '&#214;', 
		'&times;' => '&#215;', 
		'&Oslash;' => '&#216;', 
		'&Ugrave;' => '&#217;', 
		'&Uacute;' => '&#218;', 
		'&Ucirc;' => '&#219;', 
		'&Uuml;' => '&#220;', 
		'&Yacute;' => '&#221;', 
		'&THORN;' => '&#222;', 
		'&szlig;' => '&#223;', 
		'&agrave;' => '&#224;', 
		'&aacute;' => '&#225;', 
		'&acirc;' => '&#226;', 
		'&atilde;' => '&#227;', 
		'&auml;' => '&#228;', 
		'&aring;' => '&#229;', 
		'&aelig;' => '&#230;', 
		'&ccedil;' => '&#231;', 
		'&egrave;' => '&#232;', 
		'&eacute;' => '&#233;', 
		'&ecirc;' => '&#234;', 
		'&euml;' => '&#235;', 
		'&igrave;' => '&#236;', 
		'&iacute;' => '&#237;', 
		'&icirc;' => '&#238;', 
		'&iuml;' => '&#239;', 
		'&eth;' => '&#240;', 
		'&ntilde;' => '&#241;', 
		'&ograve;' => '&#242;', 
		'&oacute;' => '&#243;', 
		'&ocirc;' => '&#244;', 
		'&otilde;' => '&#245;', 
		'&ouml;' => '&#246;', 
		'&divide;' => '&#247;', 
		'&oslash;' => '&#248;', 
		'&ugrave;' => '&#249;', 
		'&uacute;' => '&#250;', 
		'&ucirc;' => '&#251;', 
		'&uuml;' => '&#252;', 
		'&yacute;' => '&#253;', 
		'&thorn;' => '&#254;', 
		'&yuml;' => '&#255;', 
		// entities defined in "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent"
		'&quot;' => '&#34;', 
		//'&amp;' => '&#38;#38;', 
		//'&lt;' => '&#38;#60;', 
		//'&gt;' => '&#62;', 
		'&apos;' => '&#39;', 
		'&OElig;' => '&#338;', 
		'&oelig;' => '&#339;', 
		'&Scaron;' => '&#352;', 
		'&scaron;' => '&#353;', 
		'&Yuml;' => '&#376;', 
		'&circ;' => '&#710;', 
		'&tilde;' => '&#732;', 
		'&ensp;' => '&#8194;', 
		'&emsp;' => '&#8195;', 
		'&thinsp;' => '&#8201;', 
		'&zwnj;' => '&#8204;', 
		'&zwj;' => '&#8205;', 
		'&lrm;' => '&#8206;', 
		'&rlm;' => '&#8207;', 
		'&ndash;' => '&#8211;', 
		'&mdash;' => '&#8212;', 
		'&lsquo;' => '&#8216;', 
		'&rsquo;' => '&#8217;', 
		'&sbquo;' => '&#8218;', 
		'&ldquo;' => '&#8220;', 
		'&rdquo;' => '&#8221;', 
		'&bdquo;' => '&#8222;', 
		'&dagger;' => '&#8224;', 
		'&Dagger;' => '&#8225;', 
		'&permil;' => '&#8240;', 
		'&lsaquo;' => '&#8249;', 
		'&rsaquo;' => '&#8250;', 
		'&euro;' => '&#8364;', 
		// entities defined in "http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent"
		'&fnof;' => '&#402;', 
		'&Alpha;' => '&#913;', 
		'&Beta;' => '&#914;', 
		'&Gamma;' => '&#915;', 
		'&Delta;' => '&#916;', 
		'&Epsilon;' => '&#917;', 
		'&Zeta;' => '&#918;', 
		'&Eta;' => '&#919;', 
		'&Theta;' => '&#920;', 
		'&Iota;' => '&#921;', 
		'&Kappa;' => '&#922;', 
		'&Lambda;' => '&#923;', 
		'&Mu;' => '&#924;', 
		'&Nu;' => '&#925;', 
		'&Xi;' => '&#926;', 
		'&Omicron;' => '&#927;', 
		'&Pi;' => '&#928;', 
		'&Rho;' => '&#929;', 
		'&Sigma;' => '&#931;', 
		'&Tau;' => '&#932;', 
		'&Upsilon;' => '&#933;', 
		'&Phi;' => '&#934;', 
		'&Chi;' => '&#935;', 
		'&Psi;' => '&#936;', 
		'&Omega;' => '&#937;', 
		'&alpha;' => '&#945;', 
		'&beta;' => '&#946;', 
		'&gamma;' => '&#947;', 
		'&delta;' => '&#948;', 
		'&epsilon;' => '&#949;', 
		'&zeta;' => '&#950;', 
		'&eta;' => '&#951;', 
		'&theta;' => '&#952;', 
		'&iota;' => '&#953;', 
		'&kappa;' => '&#954;', 
		'&lambda;' => '&#955;', 
		'&mu;' => '&#956;', 
		'&nu;' => '&#957;', 
		'&xi;' => '&#958;', 
		'&omicron;' => '&#959;', 
		'&pi;' => '&#960;', 
		'&rho;' => '&#961;', 
		'&sigmaf;' => '&#962;', 
		'&sigma;' => '&#963;', 
		'&tau;' => '&#964;', 
		'&upsilon;' => '&#965;', 
		'&phi;' => '&#966;', 
		'&chi;' => '&#967;', 
		'&psi;' => '&#968;', 
		'&omega;' => '&#969;', 
		'&thetasym;' => '&#977;', 
		'&upsih;' => '&#978;', 
		'&piv;' => '&#982;', 
		'&bull;' => '&#8226;', 
		'&hellip;' => '&#8230;', 
		'&prime;' => '&#8242;', 
		'&Prime;' => '&#8243;', 
		'&oline;' => '&#8254;', 
		'&frasl;' => '&#8260;', 
		'&weierp;' => '&#8472;', 
		'&image;' => '&#8465;', 
		'&real;' => '&#8476;', 
		'&trade;' => '&#8482;', 
		'&alefsym;' => '&#8501;', 
		'&larr;' => '&#8592;', 
		'&uarr;' => '&#8593;', 
		'&rarr;' => '&#8594;', 
		'&darr;' => '&#8595;', 
		'&harr;' => '&#8596;', 
		'&crarr;' => '&#8629;', 
		'&lArr;' => '&#8656;', 
		'&uArr;' => '&#8657;', 
		'&rArr;' => '&#8658;', 
		'&dArr;' => '&#8659;', 
		'&hArr;' => '&#8660;', 
		'&forall;' => '&#8704;', 
		'&part;' => '&#8706;', 
		'&exist;' => '&#8707;', 
		'&empty;' => '&#8709;', 
		'&nabla;' => '&#8711;', 
		'&isin;' => '&#8712;', 
		'&notin;' => '&#8713;', 
		'&ni;' => '&#8715;', 
		'&prod;' => '&#8719;', 
		'&sum;' => '&#8721;', 
		'&minus;' => '&#8722;', 
		'&lowast;' => '&#8727;', 
		'&radic;' => '&#8730;', 
		'&prop;' => '&#8733;', 
		'&infin;' => '&#8734;', 
		'&ang;' => '&#8736;', 
		'&and;' => '&#8743;', 
		'&or;' => '&#8744;', 
		'&cap;' => '&#8745;', 
		'&cup;' => '&#8746;', 
		'&int;' => '&#8747;', 
		'&there4;' => '&#8756;', 
		'&sim;' => '&#8764;', 
		'&cong;' => '&#8773;', 
		'&asymp;' => '&#8776;', 
		'&ne;' => '&#8800;', 
		'&equiv;' => '&#8801;', 
		'&le;' => '&#8804;', 
		'&ge;' => '&#8805;', 
		'&sub;' => '&#8834;', 
		'&sup;' => '&#8835;', 
		'&nsub;' => '&#8836;', 
		'&sube;' => '&#8838;', 
		'&supe;' => '&#8839;', 
		'&oplus;' => '&#8853;', 
		'&otimes;' => '&#8855;', 
		'&perp;' => '&#8869;', 
		'&sdot;' => '&#8901;', 
		'&lceil;' => '&#8968;', 
		'&rceil;' => '&#8969;', 
		'&lfloor;' => '&#8970;', 
		'&rfloor;' => '&#8971;', 
		'&lang;' => '&#9001;', 
		'&rang;' => '&#9002;', 
		'&loz;' => '&#9674;', 
		'&spades;' => '&#9824;', 
		'&clubs;' => '&#9827;', 
		'&hearts;' => '&#9829;', 
		'&diams;' => '&#9830;');
}

// Reads languages from /lang directory
function getLanguages($d)
{
	global $sxLang;
	
	$i = 0;
	if($current_dir = @opendir($d."lang/")){
		while($entryname = @readdir($current_dir)){
			if(($entryname != '.')AND($entryname != '..')AND($entryname != '.htaccess')){
				$files[$i] = ucfirst(str_replace('.php','',$entryname));
				$i++;
			}
		}
		@closedir($current_dir);
		return $files;
	}else die($sxLang['MessageLanguageDirError']);
}

// Deletes user data
function deleteUser($delete)
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	global $DB_Forums_Posts;
	global $DB_Forums_Unread;
	global $sxContentDir;
	
	$query = "SELECT avatar FROM $DB_Users WHERE id='$delete'";
	$result = mysql_query($query, $Link) or queryError("1006", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	@unlink(sxPathToRoot().$sxContentDir['Avatars'].$ROW->avatar);
	
	$query = "DELETE FROM $DB_Users WHERE id='$delete'";
	$result = mysql_query($query, $Link);
	
	$query = "DELETE FROM $DB_Users_Assoc WHERE userid='$delete'";
	$result = mysql_query($query, $Link);
	
	$query = "DELETE FROM $DB_Forums_Posts WHERE userid='$delete'";
	$result = mysql_query($query, $Link);
	
	$query = "DELETE FROM $DB_Forums_Unread WHERE userid='$delete'";
	$result = mysql_query($query, $Link);
}

function inactiveUserCleaner()
{	
	global $Link;
	global $DB_Users;
	global $NOW;
	global $sxLang;
	global $sxSetup;
	global $sxLangMail;
	
	$x = $NOW-($sxSetup['UserCleanerWarn']*60*60*24*7);
	$y = $NOW-($sxSetup['UserCleanerDelete']*60*60*24*7);
	
	// Warn users
	$query = "SELECT id, email FROM $DB_Users WHERE lastlogin<$x AND lastlogin>$y AND lastlogin!=0 AND warned='0'";
	$result = mysql_query($query, $Link) or queryError("1006", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		mail($ROW->email, $sxLangMail['SubjectUserInactive'], $sxLangMail['UserInactive'], "From:".$sxSetup['AdminEmail']);
		
		$query2 = "UPDATE $DB_Users SET warned='1' WHERE id='$ROW->id'";
		$result2 = mysql_query($query2, $Link) or queryError("1007", mysql_error());
	}
	
	// Delete users
	$query = "SELECT id FROM $DB_Users WHERE lastlogin<$y AND lastlogin!=0";
	$result = mysql_query($query, $Link) or queryError("1008", mysql_error());
	while($ROW = mysql_fetch_object($result))
		deleteUser($ROW->id);
}

function getMyTimezoneOffset()
{	
	global $Link;
	global $DB_Users;
	global $THIS_USER;
	
	$query = "SELECT * FROM $DB_Users WHERE id='$THIS_USER'";
	$result = mysql_query($query, $Link) or queryError("125", mysql_error());
	$ROW = mysql_fetch_object($result);
	return $ROW->timezone;
}

function showMaintenancePage()
{
	global $sxSetup;
	header("Location:".$sxSetup['Url']."/index.php?sxMaintenance=true");
	die();
}

function getURLFolder(){
	global $sxSetup;
	return str_replace($_SERVER['HTTP_HOST'], '', substr($sxSetup['Url'], 7, strlen($sxSetup['Url'])));
}

function echoMiniCalendar($sxMonth,$sxYear)
{
	global $Link;
	global $DB_Events;
	global $DB_Events_Private;
	global $DB_Users_Assoc;
	global $THIS_USER;
	global $NOW;
	global $sxLang;
	global $sxDaysExtraShort;
	global $sxMonths;
	global $sxSetup;
	
	$sxFirstDayOfWeekShift = $sxSetup['FirstDayOfWeek'];
	
	if(!$sxMonth)
	{
		$sxMonth = date("m");
		$sxYear = date("Y");
	}

	if($sxMonth < 12)
	{
		$sxNextMonth = $sxMonth + 1;
		$sxNextYear = $sxYear;
	}
	else
	{
		$sxNextMonth = 1;
		$sxNextYear = $sxYear + 1;
	}
	
	if($sxMonth == 1)
	{
		$sxLastMonth = 12;
		$sxLastYear = $sxYear - 1;
	}
	else
	{
		$sxLastMonth = $sxMonth - 1;
		$sxLastYear = $sxYear;
	}

	echo '<a name="miniCalendar"></a>'."\n";
	echo '<table border="0" cellpadding="5" cellspacing="2" width="200" align="center">'."\n";
	echo '	  <tr>'."\n";
	echo '	    <td align="left"><a href="' . $_SERVER['PHP_SELF'] . "?sxMonth=$sxLastMonth&sxYear=$sxLastYear#miniCalendar" . '">&lt;</a></td>'."\n";
	echo '		<td align="center"><strong>';

	$sxMonthString = date("F", mktime(0,0,0,$sxMonth,1,$sxYear));
	foreach($sxMonths as $sxKey => $sxValue)
		$sxMonthString = str_replace($sxKey, $sxValue, $sxMonthString);
		
	echo $sxMonthString.' '.$sxYear;
	
	echo '</strong></td>';
	echo '	    <td align="right"><a href="' . $_SERVER['PHP_SELF'] ."?sxMonth=$sxNextMonth&sxYear=$sxNextYear#miniCalendar" . '">></a></td>'."\n";
	echo '	  </tr>'."\n";
	
	// Print out weekday abbreviations
	echo '	  <tr>'."\n";
	echo '	    <td colspan="3">'."\n";
	echo '	      <table border="0" cellpadding="5" cellspacing="1" width="100%" class="eventCalendar">'."\n";
	echo '		    <tr>'."\n";
	
	if($sxFirstDayOfWeekShift != 1)
		echo '			  <td class="tableColumn">' . $sxDaysExtraShort[0]  . '</td>'."\n";

	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[1]  . '</td>'."\n";
	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[2]  . '</td>'."\n";
	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[3]  . '</td>'."\n";
	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[4]  . '</td>'."\n";
	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[5]  . '</td>'."\n";
	echo '			  <td class="tableColumn">' . $sxDaysExtraShort[6]  . '</td>'."\n";
	
	if($sxFirstDayOfWeekShift == 1)
		echo '			  <td class="tableColumn">' . $sxDaysExtraShort[0]  . '</td>'."\n";
	
	echo '			</tr>'."\n";
	
	$sxFirstDay = date("w", mktime(0, 0, 0, $sxMonth, 1, $sxYear));
	if($sxFirstDayOfWeekShift == 1)
	{
		if($sxFirstDay > 0)
			$sxFirstDay = $sxFirstDay-1;
		else
			$sxFirstDay = 6;
	}
	
	$sxCounter = 0;

	// Print out leading day blank spaces
	if ($sxCounter < $sxFirstDay)
		echo '<tr>'."\n";
	while ($sxCounter < $sxFirstDay)
	{
		echo '<td class="eventBlankDays" align="center">&nbsp;</td>' . "\n";
		$sxCounter++;
	}
	
	$sxDay = 1;
	$sxDayWeekCount = 1;
	$sxContinue = true;
	while($sxContinue)
	{
		if(checkdate($sxMonth, $sxDay, $sxYear))
		{
			$eventToday = false;
			$sxDayStart = mktime(0,0,0,$sxMonth,$sxDay,$sxYear);
			$sxDayEnd = mktime(23,59,59,$sxMonth,$sxDay,$sxYear);
			
			if($sxFirstDayOfWeekShift == 1)
			{
				if(date("w", mktime(0,0,0,$sxMonth,$sxDay,$sxYear)) == 1)
					echo '<tr>';
			}
			else
			{
				if(date("w", mktime(0,0,0,$sxMonth,$sxDay,$sxYear)) == 0)
					echo '<tr>';
			}
			
			$query = "SELECT * FROM $DB_Events 
					  WHERE ((start_timestamp >= '$sxDayStart' AND end_timestamp <= '$sxDayEnd') OR 
							(start_timestamp <= '$sxDayEnd' AND end_timestamp >= '$sxDayEnd') OR 
							(end_timestamp >= '$sxDayStart' AND end_timestamp <= '$sxDayEnd')) AND
							active='1'
					  ORDER BY start_timestamp ASC";
			$result = mysql_query($query, $Link) or queryError("71", mysql_error());			
			while($ROW = mysql_fetch_object($result))
			{
				if(eventAccess($ROW->id))
					$eventToday = true;
			}
			
			echo '<td valign="top" class="';
			if($sxDayStart == mktime(0,0,0,date("m"),date("d"),date("y")))
				echo 'eventTodayColor';
			else
				echo 'eventOffdayColor';
			
			echo '"><a';
			if(!$eventToday)
				echo ' style="text-decoration:none;"';
			else
				echo  ' style="text-decoration:underline;"';
			echo ' href="calendar_day.php?sxTimestamp=' . $sxDayStart . '">';
			if($eventToday)
				echo '<strong>';
			echo $sxDay;
			if($eventToday)
				echo '</strong>';
			echo '</a>';
			
			echo '</td>' . "\n";
			
			if($sxFirstDayOfWeekShift == 1)
			{
				if(date("w", mktime(0,0,0,$sxMonth,$sxDay,$sxYear)) == 0)
				{
					echo '</tr>';
					$sxDayWeekCount = 0;
				}
			}
			else
			{
				if(date("w", mktime(0,0,0,$sxMonth,$sxDay,$sxYear)) == 6)
				{
					echo '</tr>';
					$sxDayWeekCount = 0;
				}
			}

			$sxDay++;
			$sxDayWeekCount++;
		}
		else
		{
			$sxContinue = false;
			if($sxDayWeekCount > 1)
			{
				while($sxDayWeekCount <= 7)
				{
					echo '<td class="eventBlankDays" align="center">&nbsp;</td>'."\n";
					$sxDayWeekCount++;
				}
				echo '</tr>'."\n";
			}
		}
	}
	
	echo '	      </table>'."\n";
	echo '	    </td>'."\n";
	echo '	  </tr>'."\n";
	echo '	</table>'."\n";
}

function getUpcomingEvents($num)
{
	global $Link;
	global $DB_Events;
	global $DB_Events_Private;
	global $DB_Users_Assoc;
	global $THIS_USER;
	global $NOW;
	
	if(!$num)
		$num = 5;
	$count = 0;
	
	// Get event id's the user can access
	$query = "SELECT * FROM $DB_Events WHERE active='1' AND end_timestamp >= '$NOW' ORDER BY start_timestamp ASC";
	$result = mysql_query($query, $Link) or queryError("240", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		$query2 = "SELECT * FROM $DB_Events_Private WHERE eventid='$ROW->id'";
		$result2 = mysql_query($query2, $Link) or queryError("241", mysql_error());
		if(mysql_num_rows($result2))
		{
			$ROW2 = mysql_fetch_object($result2);
			
			$query3 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$THIS_USER' AND typeid='$ROW2->typeid'";
			$result3 = mysql_query($query3, $Link) or queryError("242", mysql_error());
			if(mysql_num_rows($result3))
				$myEvents[$count++] = $ROW->id;
		}
		else
			$myEvents[$count++] = $ROW->id;
	}
	
	// Trim array
	if( (is_array($myEvents) == TRUE) AND (count($myEvents) > $num) )
		$myEvents = array_splice($myEvents, 0, $num);
		
	return $myEvents;
}

function echoUpcomingEvents($num)
{
	global $Link;
	global $DB_Events;
	global $THIS_USER;
	global $sxLang;

	$event_array = getUpcomingEvents($num);
	
	if($event_array)
	{
		echo '<ul>'."\n";
		
		foreach($event_array as $event_id_value)
		{
			$query = "SELECT * FROM $DB_Events WHERE id='$event_id_value'";
			$result = mysql_query($query, $Link) or queryError("245", mysql_error());
			while($ROW = mysql_fetch_object($result))
			{
				echo '<li><a href="calendar_day.php?sxTimestamp=' . $ROW->start_timestamp . '">';
				echo getFormattedEventDate($ROW->allday, $ROW->start_timestamp, $ROW->end_timestamp, 1);
				echo ' - ' . stripslashes($ROW->shortname) . '</a>'."\n";
				echo ' </li>'."\n";
			}
		}
		echo '</ul>'."\n";
	}
}


function getRecentTopics($num)
{
	global $Link;
	global $DB_Forums;
	global $DB_Forums_Posts;
	global $DB_Forums_Private;
	global $DB_Users_Assoc;
	global $THIS_USER;
	
	if(!$num) $num = 5;
	$count = 0;
	
	// Get forum id's the user can access
	$query = "SELECT * FROM $DB_Forums";
	$result = mysql_query($query, $Link) or queryError("240", mysql_error());
	while($ROW = mysql_fetch_object($result)){
	
		$query2 = "SELECT * FROM $DB_Forums_Private WHERE forumid='$ROW->id'";
		$result2 = mysql_query($query2, $Link) or queryError("241", mysql_error());
		if(mysql_num_rows($result2)){
		
			$ROW2 = mysql_fetch_object($result2);
			
			$query3 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$THIS_USER' AND typeid='$ROW2->typeid'";
			$result3 = mysql_query($query3, $Link) or queryError("242", mysql_error());
			if(mysql_num_rows($result3)) $myForums[$count++] = $ROW->id;
			
		}else $myForums[$count++] = $ROW->id;
	}
	
	// Get posts from the forums
	if($myForums){
	
		$forum_selection = "";
		$first = true;
		foreach($myForums as $value){
			if(!$first) $forum_selection .= "OR";
			$forum_selection .=" forumid='$value' ";
			$first = false;
		}
		if($forum_selection) $forum_selection = "(" . $forum_selection . ")";
		
		$count = 0;
		$query = "SELECT * FROM $DB_Forums_Posts WHERE $forum_selection AND replyto='0' ORDER BY updated DESC LIMIT 0, $num";
		$result = mysql_query($query, $Link) or queryError("243", mysql_error());
		while($ROW = mysql_fetch_object($result)){
			$myTopics[$count++] = $ROW->id;
		}
		
		return $myTopics;
		
	}else return 0;
}

function echoRecentTopics($num)
{
	global $Link;
	global $DB_Forums_Posts;
	global $DB_Forums_Unread;
	global $THIS_USER;
	global $sxLang;

	$topic_array = getRecentTopics($num);
	
	if($topic_array)
	{
		echo '<ul>'."\n";
		
		foreach($topic_array as $topic_id_value)
		{
			$query = "SELECT * FROM $DB_Forums_Posts WHERE id='$topic_id_value'";
			$result = mysql_query($query, $Link) or queryError("245", mysql_error());
			while($ROW = mysql_fetch_object($result))
			{
				echo '<li><a href="forums_topic.php?topicid=' . $topic_id_value . '">' . fetchDate($ROW->updated, 1, 1) . ' - ' . limitStringForce($ROW->topic, 40) . '</a>'."\n";
				
				$query2 = "SELECT * FROM $DB_Forums_Unread WHERE postid='$topic_id_value' AND userid='$THIS_USER'";
				$result2 = mysql_query($query2, $Link) or queryError("246", mysql_error());
				
				if(mysql_num_rows($result2) > 0)
					echo ' <strong>*' . strtoupper($sxLang['New']) . '*</strong> ';
				else
				{
					$query2 = "SELECT * FROM $DB_Forums_Posts, $DB_Forums_Unread
							   WHERE $DB_Forums_Posts.replyto='$topic_id_value' AND
									 $DB_Forums_Posts.id=$DB_Forums_Unread.postid AND
									 $DB_Forums_Unread.userid=$THIS_USER";
					$result2 = mysql_query($query2, $Link) or queryError("246", mysql_error());
					if(mysql_num_rows($result2) > 0)
						echo ' <strong>*' . strtoupper($sxLang['New']) . '*</strong> '."\n";
				}
				echo ' </li>'."\n";
			}
		}
		echo '</ul>'."\n";
	}
}

function getRandomPhotos()
{
	global $Link;
	global $DB_Photos;
	global $DB_Photos_Albums;
	global $DB_Photos_Albums_Private;
	global $DB_Photos_Assoc;
	global $DB_Users_Assoc;
	global $THIS_USER;
	global $sxSetup;
	
	$found = false;
	$extraQuery = '';
	$myAlbums = array();
	$myPhotos = array();
	
	if(($sxSetup['HomepageRandomPhotosVert']  == 1)AND
	   ($sxSetup['HomepageRandomPhotosHoriz'] == 0)) 	 $extraQuery .= " AND $DB_Photos.width < $DB_Photos.height";
	
	elseif(($sxSetup['HomepageRandomPhotosVert']  == 0)AND
	       ($sxSetup['HomepageRandomPhotosHoriz'] == 1)) $extraQuery .= " AND $DB_Photos.width > $DB_Photos.height";
	
	// Find albums that the user can see and according to horiz/vert requirements
	$query = "SELECT id FROM $DB_Photos_Albums ";
	$result = mysql_query($query, $Link) or queryError("230", mysql_error());
	while($sxAlbum = mysql_fetch_object($result))
	{
		if(sxAlbumUserAccess($sxAlbum->id, $THIS_USER) == TRUE)
			array_push($myAlbums, $sxAlbum->id);
	}
	
	// Get unique list of photos from those albums
	if(count($myAlbums) > 0)
	{
		$query = "SELECT DISTINCT $DB_Photos.id FROM $DB_Photos_Assoc, $DB_Photos WHERE (";
		
		foreach($myAlbums as $value)
			$query .= "$DB_Photos_Assoc.albumid='$value' OR ";
		
		$query = substr($query, 0, strlen($query)-4).')';
		$query .= $extraQuery;
		$query .= " AND $DB_Photos.id=$DB_Photos_Assoc.photoid AND $DB_Photos.hide_random='0'";
		
		$result = mysql_query($query, $Link) or queryError("233", mysql_error());
		while($sxPhoto = mysql_fetch_object($result))
			array_push($myPhotos, $sxPhoto->id);
	}
	
	// Shuffle, cut, and return list of photos
	if($myPhotos)
		shuffle($myPhotos);

	if(count($myPhotos) > $sxSetup['HomepageRandomPhotosNum'])
		array_splice($myPhotos, $sxSetup['HomepageRandomPhotosNum']);
	
	if(count($myPhotos) == 0)
		$myPhotos = 0;
		
	return $myPhotos;
}

function echoRandomPhotos()
{
	echo fetchRandomPhotoHTML();
}

function fetchRandomPhotoHTML()
{
	global $Link;
	global $DB_Photos;
	global $sxContentDir;
	global $sxSetup;
	
	$content = '';
	
	if($sxSetup['HomepageRandomPhotos'])
	{
		$photo_array = getRandomPhotos();
		$count = 1;
		
		if($photo_array)
		{
			$content .= '<table border="0" cellspacing="0" cellpadding="0"><tr><td nowrap="nowrap">'."\n";
			foreach($photo_array as $photo_id_value)
			{
				$query = "SELECT * FROM $DB_Photos WHERE id='$photo_id_value'";
				$result = mysql_query($query, $Link) or queryError("244", mysql_error());
				while($ROW = mysql_fetch_object($result))
				{
					$content .= '<span class="sxRandomPhotos"><a href="' . $sxSetup['Url'] . '/photo.php?photoid=' . $photo_id_value . '"><img alt="' . $ROW->name . '" src="' . $sxSetup['Url'] . '/' . $sxContentDir['PhotoThumb'].$ROW->filename . '" style="border: 0;" height="75" /></a></span> '."\n";
					if($count == $sxSetup['HomepageRandomPhotosPerLine'])
					{
						$content .= '<br />';
						$count = 1;
					}else $count = $count + 1;
				}
			}
			$content .= '</td></tr></table>'."\n";
		}
	}
	return $content;
}

function movePhotoTop($photoid, $albumid){
	
	global $Link;
	global $DB_Photos_Assoc;
	
	if($photoid){
	
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$photoid' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("140", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE position<'$ROW->position' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("141", mysql_error());
		
		// If not last already
		if(mysql_num_rows($result)){
		
			while($ROW = mysql_fetch_object($result)){
			
				$position1 = $ROW->position;
				$position2 = $position1 + 1;
				
				$query2 = "UPDATE $DB_Photos_Assoc SET position='$position2' WHERE photoid='$ROW->photoid' AND albumid='$albumid'";
				$result2 = mysql_query($query2, $Link) or queryError("142", mysql_error());
				
			}
			
			$query = "UPDATE $DB_Photos_Assoc SET position='1' WHERE photoid='$photoid' AND albumid='$albumid'";
			$result = mysql_query($query, $Link) or queryError("144", mysql_error());
		}
	}
}

function movePhotoBottom($photoid, $albumid){
	
	global $Link;
	global $DB_Photos_Assoc;
	
	if($photoid){
	
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$photoid' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("140", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE position>'$ROW->position' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("141", mysql_error());
		
		// If not last already
		if(mysql_num_rows($result)){
		
			while($ROW = mysql_fetch_object($result)){
			
				$position1 = $ROW->position;
				$position2 = $position1 - 1;
				
				$query2 = "UPDATE $DB_Photos_Assoc SET position='$position2' WHERE photoid='$ROW->photoid' AND albumid='$albumid'";
				$result2 = mysql_query($query2, $Link) or queryError("142", mysql_error());
				
			}
			
			$query = "SELECT * FROM $DB_Photos_Assoc WHERE albumid='$albumid' ORDER BY position DESC LIMIT 0,1";
			$result = mysql_query($query, $Link) or queryError("143", mysql_error());
			$ROW = mysql_fetch_object($result);
			
			$last_position = $ROW->position + 1;
			
			$query = "UPDATE $DB_Photos_Assoc SET position='$last_position' WHERE photoid='$photoid' AND albumid='$albumid'";
			$result = mysql_query($query, $Link) or queryError("144", mysql_error());
		}
	}
}

function movePhotoDown($downid, $albumid){
	
	global $Link;
	global $DB_Photos_Assoc;
	
	if($downid){
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$downid' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("28", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$position1 = $ROW->position;
		$position2 = $position1 + 1;
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE albumid='$albumid' AND position='$position2'";
		$result = mysql_query($query, $Link) or queryError("27", mysql_error());
		
		if(mysql_num_rows($result)){
			
			$ROW = mysql_fetch_object($result);
			$changeID = $ROW->photoid;
			
			$query = "UPDATE $DB_Photos_Assoc SET position='$position2' WHERE photoid='$downid' AND albumid='$albumid'";
			$result = mysql_query($query, $Link);
			
			$query = "UPDATE $DB_Photos_Assoc SET position='$position1' WHERE photoid='$changeID' AND albumid='$albumid'";
			$result = mysql_query($query, $Link);
		}
	}
}

function movePhotoUp($upid, $albumid){
	
	global $Link;
	global $DB_Photos_Assoc;
	
	if($upid){
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$upid' AND albumid='$albumid'";
		$result = mysql_query($query, $Link) or queryError("28", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$position1 = $ROW->position;
		$position2 = $position1 - 1;
		
		$query = "SELECT * FROM $DB_Photos_Assoc WHERE albumid='$albumid' AND position='$position2'";
		$result = mysql_query($query, $Link) or queryError("27", mysql_error());
		
		if(mysql_num_rows($result)){
			
			$ROW = mysql_fetch_object($result);
			$changeID = $ROW->photoid;
			
			$query = "UPDATE $DB_Photos_Assoc SET position='$position2' WHERE photoid='$upid' AND albumid='$albumid'";
			$result = mysql_query($query, $Link);
			
			$query = "UPDATE $DB_Photos_Assoc SET position='$position1' WHERE photoid='$changeID' AND albumid='$albumid'";
			$result = mysql_query($query, $Link);
		}
	}
}

function moveAlbumTop($albumid){
	
	global $Link;
	global $DB_Photos_Albums;
	
	if($albumid){
	
		$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$albumid'";
		$result = mysql_query($query, $Link) or queryError("140", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$query = "SELECT * FROM $DB_Photos_Albums WHERE position<'$ROW->position'";
		$result = mysql_query($query, $Link) or queryError("141", mysql_error());
		
		// If not last already
		if(mysql_num_rows($result)){
		
			while($ROW = mysql_fetch_object($result)){
			
				$position1 = $ROW->position;
				$position2 = $position1 + 1;
				
				$query2 = "UPDATE $DB_Photos_Albums SET position='$position2' WHERE id='$ROW->id'";
				$result2 = mysql_query($query2, $Link) or queryError("142", mysql_error());
				
			}
			
			$query = "UPDATE $DB_Photos_Albums SET position='1' WHERE id='$albumid'";
			$result = mysql_query($query, $Link) or queryError("144", mysql_error());
		}
	}
}

function moveAlbumBottom($albumid){
	
	global $Link;
	global $DB_Photos_Albums;
	
	if($albumid){
	
		$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$albumid'";
		$result = mysql_query($query, $Link) or queryError("140", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$query = "SELECT * FROM $DB_Photos_Albums WHERE position>'$ROW->position'";
		$result = mysql_query($query, $Link) or queryError("141", mysql_error());
		
		// If not last already
		if(mysql_num_rows($result)){
		
			while($ROW = mysql_fetch_object($result)){
			
				$position1 = $ROW->position;
				$position2 = $position1 - 1;
				
				$query2 = "UPDATE $DB_Photos_Albums SET position='$position2' WHERE id='$ROW->id'";
				$result2 = mysql_query($query2, $Link) or queryError("142", mysql_error());
				
			}
			
			$query = "SELECT * FROM $DB_Photos_Albums ORDER BY position DESC LIMIT 0,1";
			$result = mysql_query($query, $Link) or queryError("143", mysql_error());
			$ROW = mysql_fetch_object($result);
			
			$last_position = $ROW->position + 1;
			
			$query = "UPDATE $DB_Photos_Albums SET position='$last_position' WHERE id='$albumid'";
			$result = mysql_query($query, $Link) or queryError("144", mysql_error());
		}
	}
}

function moveAlbumDown($downid){
	
	global $Link;
	global $DB_Photos_Albums;
	
	if($downid){

		$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$downid'";
		$result = mysql_query($query, $Link) or queryError("22", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$position1 = $ROW->position;
		$position2 = $position1 + 1;
		
		$query = "SELECT * FROM $DB_Photos_Albums WHERE position='$position2'";
		$result = mysql_query($query, $Link) or queryError("23", mysql_error());
		
		if(mysql_num_rows($result)){
		
			$ROW = mysql_fetch_object($result);
			
			$changeID = $ROW->id;
			
			$query = "UPDATE $DB_Photos_Albums SET position='$position2' WHERE id='$downid'";
			$result = mysql_query($query, $Link);
			
			$query = "UPDATE $DB_Photos_Albums SET position='$position1' WHERE id='$changeID'";
			$result = mysql_query($query, $Link);
		}
	}
}

function moveAlbumUp($upid){
	
	global $Link;
	global $DB_Photos_Albums;
	
	if($upid){
		
		$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$upid'";
		$result = mysql_query($query, $Link) or queryError("28", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		$position1 = $ROW->position;
		$position2 = $position1 - 1;
		
		$query = "SELECT * FROM $DB_Photos_Albums WHERE position='$position2'";
		$result = mysql_query($query, $Link) or queryError("27", mysql_error());
		
		if(mysql_num_rows($result)){
			$ROW = mysql_fetch_object($result);
		
			$changeID = $ROW->id;
			
			$query = "UPDATE $DB_Photos_Albums SET position='$position2' WHERE id='$upid'";
			$result = mysql_query($query, $Link);
			
			$query = "UPDATE $DB_Photos_Albums SET position='$position1' WHERE id='$changeID'";
			$result = mysql_query($query, $Link);
		}
		
	}
}

// NOTES:	Deletes specified photo album and all
//			associated photos if requested.
// RETURNS: NULL
//--------------------------------------------------
function deleteAlbum($delete, $allpics)
{	
	global $Link;
	global $DB_Photos;
	global $DB_Photos_Assoc;
	global $DB_Photos_Keywords;
	global $DB_Photos_Albums;
	global $DB_Photos_Albums_Private;
	global $sxLang;
	
	if($delete){
	
		if($allpics == 1){
		
			$query = "SELECT * FROM $DB_Photos, $DB_Photos_Assoc
					  WHERE $DB_Photos.id=$DB_Photos_Assoc.photoid AND
							$DB_Photos_Assoc.albumid='$delete'";
			$result = mysql_query($query, $Link) or queryError("33", mysql_error());
			while($ROW = mysql_fetch_object($result)){
				
				$query2 = "SELECT * FROM $DB_Photos, $DB_Photos_Assoc
						   WHERE $DB_Photos.id=$DB_Photos_Assoc.photoid AND
								 $DB_Photos.id='$ROW->photoid'";
				$result2 = mysql_query($query2, $Link) or queryError("34", mysql_error());
				if(mysql_num_rows($result2) < 2) deletePhoto($ROW->photoid);
			}
			
			$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$delete'";
			$result = mysql_query($query, $Link) or queryError("25", mysql_error());
			$ROW = mysql_fetch_object($result);
			$thisPos = $ROW->position;
			
			$query = "SELECT * FROM $DB_Photos_Albums WHERE position>'$thisPos'";
			$result = mysql_query($query, $Link) or queryError("26", mysql_error());
			while($ROW = mysql_fetch_object($result)){
				if($ROW->position > 1) $new_position = $ROW->position-1;
				else $new_position = $ROW->position;
				$query2 = "UPDATE $DB_Photos_Albums SET position='$new_position' WHERE id='$ROW->id'";
				$result2 = mysql_query($query2, $Link) or queryError("167", mysql_error());
			}
			
			$query = "DELETE FROM $DB_Photos_Assoc WHERE albumid='$delete'";
			$result = mysql_query($query, $Link) or queryError("168", mysql_error());
			$query = "DELETE FROM $DB_Photos_Albums_Private WHERE albumid='$delete'";
			$result = mysql_query($query, $Link) or queryError("169", mysql_error());
			$query = "DELETE FROM $DB_Photos_Albums WHERE id='$delete'";
			$result = mysql_query($query, $Link) or queryError("170", mysql_error());
			
			$message = $sxLang['MessagePhotoAlbumDeletedPhotos'];
		
		}else{
			
			$query = "SELECT * FROM $DB_Photos_Albums WHERE id='$delete'";
			$result = mysql_query($query, $Link) or queryError("172", mysql_error());
			$ROW = mysql_fetch_object($result);
			$thisPos = $ROW->position;
			
			$query = "SELECT * FROM $DB_Photos_Albums WHERE position>'$thisPos'";
			$result = mysql_query($query, $Link) or queryError("173", mysql_error());
			while($ROW = mysql_fetch_object($result)){
				
				if($ROW->position > 1) $new_position = $ROW->position-1;
				else $new_position = $ROW->position;
				
				$query2 = "UPDATE $DB_Photos_Albums SET position='$new_position' WHERE id='$ROW->id'";
				$result2 = mysql_query($query2, $Link) or queryError("171", mysql_error());
			}
			
			$query = "DELETE FROM $DB_Photos_Albums_Private WHERE albumid='$delete'";
			$result = mysql_query($query, $Link) or queryError("175", mysql_error());
			$query = "DELETE FROM $DB_Photos_Albums WHERE id='$delete'";
			$result = mysql_query($query, $Link) or queryError("176", mysql_error());
			
			$message = $sxLang['MessagePhotoAlbumDeleted'];
		}
	}
}

// NOTES:	Returns an array of table names.
// RETURNS: Array() of tables names
//--------------------------------------------------
function fetchTables()
{
	global $DB_PREFIX;
	
	$tables[0]  = '_Comments';
	$tables[1]  = '_Comments_Section';
	$tables[2]  = '_Components';
	$tables[3]  = '_Components_Rename';
	$tables[4]  = '_Files';
	$tables[5]  = '_Forums';
	$tables[6]  = '_Forums_Groups';
	$tables[7]  = '_Forums_Posts';
	$tables[8]  = '_Forums_Private';
	$tables[9]  = '_Forums_Unread';
	$tables[10] = '_Guestbook';
	$tables[11] = '_Hit_Counters';
	$tables[12] = '_Journal';
	$tables[13] = '_Links';
	$tables[14] = '_Links_Groups';
	$tables[15] = '_Navigation';
	$tables[16] = '_Pages';
	$tables[17] = '_Pages_Private';
	$tables[18] = '_Photos';
	$tables[19] = '_Photos_Albums';
	$tables[20] = '_Photos_Albums_Private';
	$tables[21] = '_Photos_Assoc';
	$tables[22] = '_Photos_Keywords';
	$tables[23] = '_Polls';
	$tables[24] = '_Polls_Values';
	$tables[25] = '_Setup';
	$tables[26] = '_Themes';
	$tables[27] = '_Themes_Setup';
	$tables[28] = '_Title_Pictures';
	$tables[29] = '_Users';
	$tables[30] = '_Users_Assoc';
	$tables[31] = '_Users_Types';
	$tables[32] = '_Visitors';
	$tables[33] = '_Events';
	$tables[34] = '_Events_Private';
	$tables[35] = '_Collections';
	$tables[36] = '_Collections_Items';
	$tables[37] = '_Security_Image';
	$tables[38] = '_Forums_Notify';
	$tables[39] = '_Files_Folders';
	$tables[40] = '_Collections';
	$tables[41] = '_Collections_Items';
	$tables[42] = '_Collections_Items_Files';
	$tables[43] = '_Collections_Items_Photos';
	$tables[44] = '_Collections_Private';
	
	return $tables;
}

function editAlbumAssociation($editid, $albums)
{
	global $Link;
	global $DB_Photos;
	global $DB_Photos_Assoc;
	global $DB_Photos_Albums;
	
	// Iterate through selected albums to figure out if photo-album pair exists
	for($i = 0; $i < count($albums); $i++)
	{
		// Figure out if an entry already exists for photo-album pair
		$query = "SELECT id FROM $DB_Photos_Assoc WHERE photoid='$editid' AND albumid='$albums[$i]'";
		$result = mysql_query($query, $Link) or queryError("172", mysql_error());
		
		// No entry exists, create
		if(!mysql_num_rows($result))
		{
			// Find position of new entry (either 1 or +1 of last photo)
			$query = "SELECT position FROM $DB_Photos_Assoc WHERE albumid='$albums[$i]' ORDER BY position DESC LIMIT 0,1";
			$result = mysql_query($query, $Link) or queryError("173", mysql_error());
			if(mysql_num_rows($result))
			{
				$ROW = mysql_fetch_object($result);
				$new_position = $ROW->position + 1;
			}
			else
				$new_position = 1;
			
			// Create new association
			$result = mysql_query("INSERT INTO $DB_Photos_Assoc (photoid, albumid, position) VALUES ('$editid', '$albums[$i]', '$new_position')", $Link);
		}
	}
	
	// Find all entries for photo and determine if pairs are still valid
	$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$editid'";
	$result = mysql_query($query, $Link) or queryError("174", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		$found = false;
		
		// See if pair is still valid for given album
		for($i = 0; $i < count($albums); $i++)
		{
			if($albums[$i] == $ROW->albumid)
				$found = TRUE;
		}
		
		// Pair is no longer valid, remove and reposition photos in album
		if(!$found)
		{
			$query4 = "SELECT * FROM $DB_Photos_Assoc WHERE id='$ROW->id'";
			$result4 = mysql_query($query4, $Link) or queryError("160", mysql_error());
			$ROW4 = mysql_fetch_object($result4);
			
			$query2 = "SELECT * FROM $DB_Photos_Assoc WHERE albumid='$ROW4->albumid' AND position>'$ROW4->position'";
			$result2 = mysql_query($query2, $Link) or queryError("161", mysql_error());
			while($ROW2 = mysql_fetch_object($result2))
			{
				$new_position = $ROW2->position - 1;
				$query3 = "UPDATE $DB_Photos_Assoc SET position='$new_position' WHERE id='$ROW2->id'";
				$result3 = mysql_query($query3, $Link) or queryError("161", mysql_error());
			}
			
			$query4 = "DELETE FROM $DB_Photos_Assoc WHERE id='$ROW->id'";
			$result4 = mysql_query($query4, $Link) or queryError("157", mysql_error());
			
			// Remove album thumb if set as the main thumbnail for album
			
			// First, get filename
			$query5 = "SELECT filename FROM $DB_Photos WHERE id='$editid'";
			$result5 = mysql_query($query5, $Link) or queryError("160", mysql_error());
			$sxPhotoFilename = mysql_fetch_object($result5);
			
			// Now, figure out album has this photo as its picture
			$query5 = "SELECT id FROM $DB_Photos_Albums WHERE id='$ROW->albumid' AND picture='$sxPhotoFilename->filename'";
			$result5 = mysql_query($query5, $Link) or queryError("160", mysql_error());
			if(mysql_num_rows($result5))
			{
				$query6 = "UPDATE $DB_Photos_Albums SET picture='' WHERE id='$ROW->albumid'";
				$result6 = mysql_query($query6, $Link) or queryError("160", mysql_error());
			}
		}
	}
}

// NOTES:	Deletes specified photo (via id) and all
//			relevant info/files.
// RETURNS: NULL
//--------------------------------------------------
function deletePhoto($photoid)
{
	global $Link;
	global $sxContentDir;
	global $DB_Photos;
	global $DB_Comments;
	global $DB_Photos_Albums;
	global $DB_Photos_Keywords;
	global $DB_Photos_Assoc;
	
	$query = "SELECT * FROM $DB_Photos WHERE id='$photoid'";
	$result = mysql_query($query, $Link) or queryError("40", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	// Delete files
	@unlink("../".$sxContentDir['PhotoFullsize'].$ROW->filename);
	@unlink("../".$sxContentDir['PhotoScaled'].$ROW->filename);
	@unlink("../".$sxContentDir['PhotoThumb'].$ROW->filename);
	
	// Clear album picture if assigned
	$query2 = "SELECT * FROM $DB_Photos_Albums WHERE picture='$ROW->filename'";
	$result2 = mysql_query($query2, $Link) or queryError("41", mysql_error());
	while($ROW2 = mysql_fetch_object($result2))
	{
		$query3 = "UPDATE $DB_Photos_Albums SET picture='' WHERE id='$ROW2->id'";
		$result3 = mysql_query($query3, $Link) or queryError("42", mysql_error());
	}
	// Adjust album photo positions
	$query = "SELECT * FROM $DB_Photos_Assoc WHERE photoid='$photoid'";
	$result = mysql_query($query, $Link) or queryError("160", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		$query2 = "SELECT * FROM $DB_Photos_Assoc WHERE albumid='$ROW->albumid' AND position>'$ROW->position'";
		$result2 = mysql_query($query2, $Link) or queryError("161", mysql_error());
		while($ROW2 = mysql_fetch_object($result2))
		{
			$new_position = $ROW2->position - 1;
			$query3 = "UPDATE $DB_Photos_Assoc SET position='$new_position' WHERE id='$ROW2->id'";
			$result3 = mysql_query($query3, $Link) or queryError("161", mysql_error());
		}
	}
	// Clear db entries
	$query3 = "DELETE FROM $DB_Photos_Keywords WHERE photoid='$photoid'";
	$result3 = mysql_query($query3, $Link) or queryError("35", mysql_error());
	
	$query3 = "DELETE FROM $DB_Photos_Assoc WHERE photoid='$photoid'";
	$result3 = mysql_query($query3, $Link) or queryError("36", mysql_error());
	
	$query3 = "DELETE FROM $DB_Photos WHERE id='$photoid'";
	$result3 = mysql_query($query3, $Link) or queryError("37", mysql_error());
	
	$query3 = "DELETE FROM $DB_Comments WHERE sectionid='2' AND rowid='$photoid'";
	$result3 = mysql_query($query3, $Link) or queryError("38928", mysql_error());
}

// NOTES:	Finds and replaces SiteX special text.
// RETURNS: parsed string
//--------------------------------------------------
function parseSpecial($content)
{
	global $Link;
	global $DB_Files;
	global $DB_Pages;
	
	// Add file links
	preg_match_all("|---FILE[0-9]+---|", $content, $matches);
	for($i = 0; $i < count($matches[0]); $i++)
	{
		$id = substr(substr($matches[0][$i], 7), 0, (count(substr($matches[0][$i], 7))-4));
		$query2 = "SELECT * FROM $DB_Files WHERE id='$id'";
		$result2 = mysql_query($query2, $Link) or queryError("7", mysql_error());
		if(mysql_num_rows($result2))
		{
			$ROW2 = mysql_fetch_object($result2);
			$content = str_replace($matches[0][$i], '<a href="redirect.php?fileid=' . (int)$id . '">' . $ROW2->name . '</a>', $content);
		}
		else
			$content = str_replace($matches[0][$i], '', $content);
	}
	
	// Add page links
	preg_match_all("|---PAGE[0-9]+---|", $content, $matches);
	for($i = 0; $i < count($matches[0]); $i++)
	{
		$id = substr(substr($matches[0][$i], 7), 0, (count(substr($matches[0][$i], 7))-4));
		$query2 = "SELECT * FROM $DB_Pages WHERE id='$id'";
		$result2 = mysql_query($query2, $Link) or queryError("7", mysql_error());
		if(mysql_num_rows($result2))
		{
			$ROW2 = mysql_fetch_object($result2);
			$content = str_replace($matches[0][$i], '<a href="page.php?page=' . $ROW2->name . '">' . $ROW2->name . '</a>', $content);
		}
		else
			$content = str_replace($matches[0][$i], '', $content);
	}
	return $content;
}

// NOTES:	Finds next hex value.
// RETURNS: next hex string
//--------------------------------------------------
function incrementHexValue($value)
{
	switch($value)
	{
		case '0' : return '1'; break;
		case '1' : return '2'; break;
		case '2' : return '3'; break;
		case '3' : return '4'; break;
		case '4' : return '5'; break;
		case '5' : return '6'; break;
		case '6' : return '7'; break;
		case '7' : return '8'; break;
		case '8' : return '9'; break;
		case '9' : return 'A'; break;
		case 'A' : return 'B'; break;
		case 'B' : return 'C'; break;
		case 'C' : return 'D'; break;
		case 'D' : return 'E'; break;
		case 'E' : return 'F'; break;
		case 'F' : return 'E'; break;
	}
}

function incrementHexNumber($hex)
{
	$new_hex = '';
	
	$new_hex .= '#';
	$new_hex .= incrementHexValue(substr($hex, 1, 1));
	$new_hex .= incrementHexValue(substr($hex, 2, 1));
	$new_hex .= incrementHexValue(substr($hex, 3, 1));
	$new_hex .= incrementHexValue(substr($hex, 4, 1));
	$new_hex .= incrementHexValue(substr($hex, 5, 1));
	$new_hex .= incrementHexValue(substr($hex, 6, 1));
	
	return $new_hex;
}

// NOTES:	Outputs formatted message.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function echoMessage($message)
{
	if(strlen($message) > 0)
		echo '<div class="message">' . str_replace('_', ' ', $message) . '</div>';
}

// NOTES:	Outputs formatted warning.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function sxEchoWarning($warning)
{
	if( (is_array($warning) == TRUE) AND (count($warning) > 0) AND ($warning != 0) )
	{
		echo '<div class="sxAdminWarning">';
		foreach($warning as $key => $text)
		{
			if($key == 0)
			{
				echo '<span class="sxWarningTitle">**&nbsp;' . $text .'&nbsp;**</span><ol>';
			}
			else
			{
				echo '<li>' . $text . '</li>';	// Separator
			}
		}
		echo '</ol></div>';
	}
}

function sxMaintenanceModeMessage()
{
	global $sxSetup;
	global $sxLang;
	
	if($sxSetup['Maintenance'] == 1)
		echo '<div class="sxMainMode">' . $sxLang['MaintenanceModeOn'] . '</div>';
}

// NOTES:	Fetches appropriate date with formatting.
// RETURNS: date/time combo
//--------------------------------------------------
function fetchDate($timestamp, $format, $offset)
{
	global $NOW;
	global $sxSetup;
	global $sxDays;
	global $sxMonths;
	global $sxTimeMeridiem;
	
	$date = '';
	$time = $timestamp;
	
	// Adjust for a user/server time difference
	if(($offset == 1)AND($timestamp > 0))
	{
		$myOffset = getMyTimezoneOffset();
		$time += ($myOffset*60*60) + ($sxSetup['ServerTimezone']*60*60);
	}
	
	// USA time format
	if($sxSetup['DateFormat']== 'mm/dd/yy')
	{
		switch($format)
		{
			case 1 :
				$date = date("m/d/y @ g:iA", $time);
				foreach($sxTimeMeridiem as $key => $value)
					$date = str_replace($key, $value, $date);
				break;
			case 2 :
				$date = date("m/d/y", $time);
				break;
			case 3 :
				$date = date("m-d-Y", $time);
				break;
			case 4 :
				$date = date("l, F j, Y", $time);
				foreach($sxDays as $key => $value)
					$date = str_replace($key, $value, $date);
				foreach($sxMonths as $key => $value)
					$date = str_replace($key, $value, $date);
				break;
			case 99 : 
				$date = date("m/d/y @ g:iA", $NOW);
				foreach($sxTimeMeridiem as $key => $value)
					$date = str_replace($key, $value, $date);
				break;
		}
	}
	
	// UK time format
	elseif($sxSetup['DateFormat'] == 'dd/mm/yy')
	{
		switch($format)
		{
			case 1 :
				$date = date("d/m/y @ g:iA", $time);
				foreach($sxTimeMeridiem as $key => $value)
					$date = str_replace($key, $value, $date);
				break;
			case 2 :
				$date = date("d/m/y", $time);
				break;
			case 3 :
				return date("d-m-Y", $time);
				break;
			case 4 :
				$date = date("l, j F Y", $time);
				foreach($sxDays as $key => $value)
					$date = str_replace($key, $value, $date);
				foreach($sxMonths as $key => $value)
					$date = str_replace($key, $value, $date);

				break;
			case 99 :
				$date = date("d/m/y @ g:iA", $NOW);
				foreach($sxTimeMeridiem as $key => $value)
					$date = str_replace($key, $value, $date);
				break;
		}
	}
	
	return $date;
}

// NOTES:	Fetches meta headers for a page.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function echoMETA($page_name, $addendum)
{
	global $Link;
	global $sxSetup;
	global $sxSetupCharset;
	global $DB_Pages;
	global $sxThemeConfig;
	
	if($page_name)
	{
		$query = "SELECT * FROM $DB_Pages WHERE name='$page_name'";
		$result = mysql_query($query, $Link) or queryError("16", mysql_error());
		if(!mysql_num_rows($result))
			$sitewide = true;
		else
			$sitewide = false;
		$ROW = mysql_fetch_object($result);
	}
	
	// Hide from crawlers
	$my_url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];
	$my_filename = str_replace($sxSetup['Url']."/","",$my_url);
	$ignore_files = explode(",", $sxThemeConfig['MetaIgnorePages']);
	foreach($ignore_files as $value)
	{
		if(trim($value) == $my_filename)
			echo '<meta name="robots" content="noindex, nofollow">'."\n";
	}
	
	//echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
	echo '<meta http-equiv="Content-Type" content="text/html; charset='.$sxSetupCharset.'" />'."\n";
	
	echo '<meta name="description" content="';
	if(($page_name)AND(!$sitewide)AND(!$sxSetup['MetaSitewide']))
		echo $ROW->meta_description;
	else
		echo $sxSetup['MetaDescription'];
	echo '" />'."\n";
	
	echo '<meta name="keywords" content="';
	if(($page_name)AND(!$sitewide)AND(!$sxSetup['MetaSitewide']))
	{
		if(strlen($ROW->meta_keywords) > 0)
		{
			echo $ROW->meta_keywords;
			if(strlen($addendum) > 0)
				echo ', ';
		}
	}
	else
	{
		if(strlen($sxSetup['MetaKeywords']) > 0)
		{
			echo $sxSetup['MetaKeywords'];
			if(strlen($addendum) > 0)
				echo ', ';
		}
	}
	if(strlen($addendum) > 0)
		echo $addendum;
	echo '" />'."\n";
}

// NOTES:	Protects a private page.
// RETURNS: true if user type agrees, false OW
//--------------------------------------------------
function protectPrivatePage($pageid)
{
	global $Link;
	global $THIS_USER;
	global $DB_Pages_Private;
	global $DB_Users_Assoc;
	
	$query = "SELECT * FROM $DB_Pages_Private WHERE pageid='$pageid'";
	$result = mysql_query($query, $Link) or queryError("16", mysql_error());
	if(!mysql_num_rows($result))
		return true;
	
	$query = "SELECT * FROM $DB_Users_Assoc WHERE userid='$THIS_USER'";
	$result = mysql_query($query, $Link) or queryError("16", mysql_error());	
	while($ROW = mysql_fetch_object($result))
	{
		$query2 = "SELECT * FROM $DB_Pages_Private WHERE typeid='$ROW->typeid' AND pageid='$pageid'";
		$result2 = mysql_query($query2, $Link) or queryError("16", mysql_error());
		if(mysql_num_rows($result2))
			return true;
	}
	return false;
}

// NOTES:	Trims string if necessary based on
// length but grabs whole words.
// RETURNS: string
//--------------------------------------------------
function limitString($string, $length)
{
	$length = $length - 3;
	if(strlen($string) > $length)
	{
		$tmp = trim(substr($string, 0, $length));
		return substr($tmp, 0, strrpos($tmp, ' ')).'...';
	}
	else
		return $string;

}

// NOTES:	Trims string if necessary based on length.
// RETURNS: string
//--------------------------------------------------
function limitStringForce($string, $length)
{
	$length = $length - 3;
	if(strlen($string) > $length)
	{
		return trim(substr($string, 0, $length)).'...';
	}
	else
	{
		return $string;
	}
}

// NOTES:	Protects private forums.
// RETURNS: NULL ! CAN REDIRECT
//--------------------------------------------------
function protectPrivateForum($forumid)
{
	global $sxLang;
	if(!forumAccess($forumid))
	{
		header("Location: forums.php?message=".str_replace(" ","_",$sxLang['MessageForumProtected']));
		die();
	}
}

// NOTES:	Returns if a user can access a forum
// RETURNS: True if access, False if none
//--------------------------------------------------
function forumAccess($forumid)
{
	global $Link;
	global $THIS_USER;
	global $DB_Forums_Private;
	global $DB_Users_Assoc;
	
	$query = "SELECT * FROM $DB_Forums_Private WHERE forumid='$forumid'";
	$result = mysql_query($query, $Link) or queryError("449", mysql_error());
	if(mysql_num_rows($result))
	{
		$query = "SELECT * FROM $DB_Forums_Private, $DB_Users_Assoc
				  WHERE $DB_Forums_Private.typeid=$DB_Users_Assoc.typeid AND
					    $DB_Users_Assoc.userid='$THIS_USER' AND
					    $DB_Forums_Private.forumid='$forumid'";
		$result = mysql_query($query, $Link) or queryError("450", mysql_error());
		if(!mysql_num_rows($result))
			return false;
		else
			return true;
	}
	else
		return true;
}

// NOTES:	Returns if a user can access an event
// RETURNS: True if access, False if none
//--------------------------------------------------
function eventAccess($eventid)
{
	global $Link;
	global $THIS_USER;
	global $DB_Events_Private;
	global $DB_Users_Assoc;
	
	$query = "SELECT * FROM $DB_Events_Private WHERE eventid='$eventid'";
	$result = mysql_query($query, $Link) or queryError("449", mysql_error());
	if(mysql_num_rows($result))
	{
		$query = "SELECT * FROM $DB_Events_Private, $DB_Users_Assoc
				WHERE $DB_Events_Private.typeid=$DB_Users_Assoc.typeid AND
					 $DB_Users_Assoc.userid='$THIS_USER' AND
					 $DB_Events_Private.eventid='$eventid'";
		$result = mysql_query($query, $Link) or queryError("450", mysql_error());
		if(!mysql_num_rows($result)) 
			return false;
		else
			return true;
	}
	else
		return true;
}

// NOTES:	Gets the formatted date string for the
// given event start/end.
// RETURNS: formatted event date string
//--------------------------------------------------
function getFormattedEventDate($allday, $start, $end, $short)
{
	if($allday)		$t = 2; 
	elseif($short)	$t = 2;
	else			$t = 1;
	
	$x = fetchDate($start, $t, 1); 
	if(($start != $end) AND ($allday != 1))
	{
		if(date("m/d/y", $start) == date("m/d/y", $end))
		{
			if(!$short)
				$x = $x." - ".date("g:ia", $end);
		}
		else
		{
			$x = $x." - ".fetchDate($end, $t, 1);
		}
	}
	return $x;
}

// NOTES:	Protects components that require write
// access to function.
// RETURNS: NULL ! CAN REDIRECT
//--------------------------------------------------
function protectWriteMode()
{
	global $sxSetup;
	global $sxLang;
	
	if($sxSetup['ContentWriteable'] != 1)
	{
		header("Location: index.php?message=".str_replace(" ","_",$sxLang['MessageWriteModeDisabled']));
		die();
	}
}

// NOTES: Submits appropriate search to google.com
// RETURNS: NULL ! Redirects offsite
//--------------------------------------------------
function submitGoogleSearch($keywords, $search_what){
	global $sxSetup;
	if($search_what == 'google') $key = $keywords;
	elseif($search_what = 'google-site') $key = 'site:' . str_replace('http://', '', $sxSetup['Url']) . ' '. $keywords;
	header("Location:http://www.google.com/search?hl=en&q=$key");
	die();
}

// NOTES:	Determines the number of comments for a
// given object.
// RETURNS: number of comments
//--------------------------------------------------
function objectNumComments($rowid, $sectionid){
	
	global $Link;
	global $DB_Comments;
	global $sxSetup;
	
	if($sxSetup['CommentsApproval'] == 1) $appr = " AND approved='1' ";
	
	$query = "SELECT * FROM $DB_Comments
			  WHERE rowid='$rowid' AND sectionid='$sectionid' $appr";
	$result = mysql_query($query, $Link) or queryError("91", mysql_error());
	return mysql_num_rows($result);
}

// NOTES:	Refactors image dimensions based on a max
// frame size.
// RETURNS: Array of dimensions
//--------------------------------------------------
function resizeDimensions($width, $height, $size){
	
	if($width >= $height){
		$factor = $size / $width;
		$dimensions[0] = $size;				// width
		$dimensions[1] = $height * $factor;	// height
	}else{
		$factor = $size / $height;
		$dimensions[1] = $size;
		$dimensions[0] = $width * $factor;
	}
	return $dimensions;
}

// NOTES:	Refactors image dimensions based on a max
// width if width is smaller.
// RETURNS: Array of dimensions
//--------------------------------------------------
function resizeDimensionsMaxWidth($width, $height, $max_width){

	if($max_width < $width){
		$dimensions[0] = $max_width;
		$dimensions[1] = $height*($max_width/$width);
	}else{
		$dimensions[0] = $width;
		$dimensions[1] = $height;
	}
	return $dimensions;
}

// NOTES:	Refactors image dimensions based on a max
// height if height is smaller.
// RETURNS: Array of dimensions
//--------------------------------------------------
function resizeDimensionsMaxHeight($width, $height, $max_height){

	if($max_height < $height){
		$dimensions[0] = $width*($max_height/$height);
		$dimensions[1] = $max_height;
	}else{
		$dimensions[0] = $width;
		$dimensions[1] = $height;
	}
	return $dimensions;
}

// NOTES:	Fetches previous image id from album.
// RETURNS: False | previous image id
//--------------------------------------------------
function getPrevPhoto($photoid, $albumid){
	
	global $Link;
	global $DB_Photos;
	global $DB_Photos_Assoc;
	
	$previous_id = 0;
	$prev = 0;
	
	$query = "SELECT $DB_Photos.id FROM $DB_Photos, $DB_Photos_Assoc
			  WHERE $DB_Photos.id=$DB_Photos_Assoc.photoid AND $DB_Photos_Assoc.albumid='$albumid'
			  ORDER BY $DB_Photos_Assoc.position ASC";
	$result = mysql_query($query, $Link) or queryError("92", mysql_error());
	
	while($ROW = mysql_fetch_object($result)){
		if($photoid == $ROW->id) $prev = $previous_id;
		$previous_id = $ROW->id;
	}
	
	if($prev != 0) return $prev;
	else return false;
}

// NOTES:	Fetches next image id from album.
// RETURNS: False | next image id
//--------------------------------------------------
function getNextPhoto($photoid, $albumid){
	
	global $Link;
	$next_id = 0;
	$next = 0;
	global $DB_Photos;
	global $DB_Photos_Assoc;
	
	$query = "SELECT $DB_Photos.id FROM $DB_Photos, $DB_Photos_Assoc
			  WHERE $DB_Photos.id=$DB_Photos_Assoc.photoid AND $DB_Photos_Assoc.albumid='$albumid'
			  ORDER BY $DB_Photos_Assoc.position DESC";
	$result = mysql_query($query, $Link) or queryError("93", mysql_error());
	
	while($ROW = mysql_fetch_object($result)){
		if($photoid == $ROW->id) $next = $next_id;
		$next_id = $ROW->id;
	}
	
	if($next != 0) return $next;
	else return false;
}

// NOTES:	Determines imaging functionality.
// RETURNS: 'truelcolor' | 'normal' | 'none'
//--------------------------------------------------
function imageCompatibility(){

	global $sxSetup;
	
	if($sxSetup['ImagingMode'] == 'auto')
	{
		if(function_exists("imagecreatetruecolor")) 	$image_ability = "truecolor";
		elseif(function_exists("imagecreate")) 			$image_ability = "normal";
		elseif(function_exists("imagick_readimage")) 	$image_ability = "imagemagick";
		else 											$image_ability = "none";
	}
	else
	{
		if(($sxSetup['ImagingMode'] == 'GD2') AND (function_exists("imagecolorallocatealpha")))
			$image_ability = "truecolor";
			
		elseif($sxSetup['ImagingMode'] == 'GD1')		$image_ability = "normal";
		elseif($sxSetup['ImagingMode'] == 'IM')			$image_ability = "imagemagick";
		else 											$image_ability = "none";
	}
	return	$image_ability;
}

// NOTES:	Tallies total visitors.
// RETURNS: Formatted number of visits
//--------------------------------------------------
function getVisitors()
{
	global $Link;
	global $DB_Visitors;
	
	$totalVisitors = 0;
	
	$query = "SELECT visits FROM $DB_Visitors";
	$result = mysql_query($query, $Link) or queryError("94", mysql_error());
	while($sxVisitor = mysql_fetch_object($result))
		$totalVisitors = $totalVisitors + $sxVisitor->visits;
	
	return number_format($totalVisitors);
}

// NOTES:	Logs the user's visit.
// RETURNS: NULL
//--------------------------------------------------
function logUser()
{
	global $Link;
	global $NOW;
	global $DB_Visitors;
	
	$uid = 0;
	$ip = $_SERVER['REMOTE_ADDR'];
	
	// Update browsing visitor
	if((session_is_registered('visitor_id'))AND(session_is_registered('visitor_time'))AND($_SESSION['visitor_id'] != ''))
	{
		$vid = $_SESSION['visitor_id'];
		
		if(session_is_registered('userid'))
			$uid = $_SESSION['userid'];
		
		$query = "SELECT pagehits FROM $DB_Visitors WHERE id='$vid'";
		$result = mysql_query($query, $Link) or queryError("95", mysql_error());
		$ROW = mysql_fetch_object($result);
		$pagehits = $ROW->pagehits + 1;
		
		$query = "UPDATE $DB_Visitors SET userid='$uid', lastip='$ip', pagehits='$pagehits', lastvisit='$NOW' WHERE id='$vid'";
		$result = mysql_query($query, $Link) or queryError("96", mysql_error());
	}
	
	// Log new visitor
	else
	{
		if(session_is_registered('userid'))
		{
			$uid = $_SESSION['userid'];
			$query = "SELECT id FROM $DB_Visitors WHERE userid='$uid'";
			$result = mysql_query($query, $Link) or queryError("97", mysql_error());
		}
		else
		{
			$query = "SELECT id FROM $DB_Visitors WHERE lastip='$ip'";
			$result = mysql_query($query, $Link) or queryError("98", mysql_error());
		}
		
		if(!mysql_num_rows($result))
		{
			$query = "INSERT INTO $DB_Visitors (userid, lastip, visits, pagehits, lastvisit) VALUES ('$uid', '$ip', '1', '1', '$NOW')";
			$result = mysql_query($query, $Link) or queryError("99", mysql_error());
			
			$query = "SELECT id FROM $DB_Visitors WHERE userid='$uid' AND lastip='$ip' AND lastvisit='$NOW' AND visits='1'";
			$result = mysql_query($query, $Link) or queryError("100", mysql_error());
			$ROW = mysql_fetch_object($result);
			$vid = $ROW->id;
		}
		else
		{
			$ROW = mysql_fetch_object($result);
			$vid = $ROW->id;
			
			$query = "SELECT visits, pagehits FROM $DB_Visitors WHERE id='$vid'";
			$result = mysql_query($query, $Link) or queryError("101", mysql_error());
			$ROW = mysql_fetch_object($result);
			
			$pagehits = $ROW->pagehits + 1;
			$visits = $ROW->visits + 1;
			
			$query = "UPDATE $DB_Visitors SET lastip='$ip', visits='$visits', pagehits='$pagehits', lastvisit='$NOW' WHERE id='$vid'";
			$result = mysql_query($query, $Link) or queryError("102", mysql_error());
		}
		session_register('visitor_id');
		$_SESSION['visitor_id'] = $vid;
		
		session_register('visitor_time');
		$_SESSION['visitor_time'] = $NOW;
	}
}

// NOTES: Debugging function that shows the session
// vars.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function showSession()
{
	echo '<pre>';
	print_r($_SESSION);
	echo '</pre>';
}

// NOTES:	Echos current STRING LIMITED journal.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function echoCurrentJournal($num,$limit) 
{
    global $Link;
    global $DB_Journal;
    global $DB_Users;
    global $sxLang;
	global $sxThemeConfig;
    
    if(!$num)
        $num = 1;
    
    $query = "SELECT * FROM $DB_Journal ORDER BY timestamp DESC LIMIT 0,$num"; 
    $result = mysql_query($query, $Link) or queryError("103", mysql_error());
    
    if(mysql_num_rows($result))
    {
        while($ROW = mysql_fetch_object($result))
        {
            $query2 = "SELECT * FROM $DB_Users WHERE id='$ROW->userid'"; 
            $result2 = mysql_query($query2, $Link) or queryError("190", mysql_error());        
            $ROW2 = mysql_fetch_object($result2);
            
            if($ROW->title)
            echo '<span class="journalTitle">' . $ROW->title . '</span>'."\n"; 
            echo '<br /><span class="journalBy">' . $sxLang['PostedBy'] . ': <a href="admin/profile_view.php?user=' . $ROW2->username . '">';
            echo $ROW2->firstname . ' ' . $ROW2->lastname . '</a></span> - <span class="sxSmallText">' . fetchDate($ROW->timestamp, 1, 1) . '</span>'."\n"; 
			
			if($sxThemeConfig['HomepageJournalStripTags'] == 1)
            	echo '<div class="journalEntry">'.nl2br(limitString(strip_tags($ROW->entry), $limit)).'</div>';
			else
            	echo '<div class="journalEntry">'.limitString($ROW->entry, $limit).'</div>';
            
			echo '<div class="journalReadmore"><a  href="journal.php?sxEntryID=' . $ROW->id . '">' . $sxLang['ReadMore'] . '</a></div><br/>'."\n";
        }
    }
    else
    {
        echo '<em>' . $sxLang['NoEntries'] . '</em>'."\n"; 
    }
}	

// NOTES:	Determines poll value's parent poll
// 			and if that is active.
// RETURNS: true | false
//--------------------------------------------------
function votedForCurrentPoll($poll_value_id)
{
	global $Link;
	global $DB_Polls_Values;
	global $DB_Polls;
	
	$query = "SELECT * FROM $DB_Polls_Values, $DB_Polls
	          WHERE $DB_Polls_Values.id='$poll_value_id' AND 
			        $DB_Polls_Values.pollid=$DB_Polls.id AND 
					$DB_Polls.currentpoll='1'";
	$result = mysql_query($query) or queryError("123", mysql_error());
	
	if(mysql_num_rows($result))
		return true;
	else
		return false;
}

// NOTES:	Echos current poll.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function echoCurrentPoll($vote,$view)
{
	global $Link;
	global $DB_Polls;
	global $DB_Polls_Values;
	global $sxLang;
		
	$query = "SELECT * FROM $DB_Polls WHERE currentpoll='1' AND active='1'";
	$result = mysql_query($query) or queryError("104", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if (mysql_num_rows($result) > 0)
	{
		// If viewing poll, voting, or already voted
		if (($view) OR ($vote) OR (votedForCurrentPoll($_COOKIE['voted'])))
		{
			// If user submitted a new vote
			if (($vote) AND (votedForCurrentPoll($_COOKIE['voted']) == FALSE))
			{
				$query2 = "SELECT * FROM $DB_Polls_Values WHERE id='$vote'";
				$result2 = mysql_query($query2) or queryError("104", mysql_error());
				$ROW2 = mysql_fetch_object($result2);
				$newVotes = $ROW2->votes + 1;
				
				$query2 = "UPDATE $DB_Polls_Values SET votes='$newVotes' WHERE id='$vote'";
				$result2 = mysql_query($query2) or queryError("104", mysql_error());
			}
			
			echo '<div class="sxPollName">' . $ROW->name . '</div>'."\n";
		
			// Calculate total votes
			$totalVotes = 0;
			$query2 = "SELECT * FROM $DB_Polls_Values WHERE pollid='$ROW->id'";
			$result2 = mysql_query($query2) or queryError("104", mysql_error());
			while ($ROW2 = mysql_fetch_object($result2))
				$totalVotes = $totalVotes + $ROW2->votes;
			
			if ($totalVotes == 0)
				$totalVotes = 0.1;
		
			/* Printout values with bar graphs */
			$query2 = "SELECT * FROM $DB_Polls_Values WHERE pollid='$ROW->id' ORDER BY id";
			$result2 = mysql_query($query2) or queryError("104", mysql_error());
			while ($ROW2 = mysql_fetch_object($result2))
			{
				$voteWidth = 120 * ($ROW2->votes/$totalVotes);
				$percentage = intval(($ROW2->votes/$totalVotes)*100);
				echo "<span class='sxPollPercent'><br>$ROW2->value ($ROW2->votes)<br />".'<img src="images/px_black.gif" border="1" style="border-color:#FFFFFF;" height="10" width="' . $voteWidth . '" /> '. $percentage . '%</span>';			}
			
			$totalVotes = intval($totalVotes);
			echo '<br />' . $sxLang['PollsTotalVotes'] . ': ' . $totalVotes . '<br /><a href="polls.php">' . $sxLang['PollsPast'] . '</a>';
		} // End if
	
		// If user has not voted or is in view mode
		else
		{
			$query = "SELECT * FROM $DB_Polls WHERE currentpoll='1'";
			$result = mysql_query($query) or queryError("104", mysql_error());
			$ROW = mysql_fetch_object($result);
			
			echo '<span class="sxPollName">' . $ROW->name . '</span>'."\n";
			
			$query2 = "SELECT * FROM $DB_Polls_Values WHERE pollid='$ROW->id' ORDER BY id";
			$result2 = mysql_query($query2) or queryError("104", mysql_error());
			while ($ROW2 = mysql_fetch_object($result2))                
				echo "<br /><input type=\"radio\" name=\"vote\" onclick=\"window.location='$PHP_SELF?vote=$ROW2->id'\" />$ROW2->value";
			
			echo '<br /><br /><a href="' . $PHP_SELF . '?viewPoll=true">' . $sxLang['PollsViewResults'] . '</a><br /><a href="polls.php">' . $sxLang['PollsPast'] . '</a>';
		}
	}
}

// NOTES:	Echos navigation.
// RETURNS: NULL ! ECHOS
//--------------------------------------------------
function echoNavigation($a)
{
	global $Link;
	global $sxSetup;
	global $DB_Navigation;
	global $DB_Pages;
	
	switch($a)
	{
		case 'vert' :
		
			$first = true;
			$query = "SELECT * FROM $DB_Navigation ORDER BY position ASC";
			$result = mysql_query($query, $Link) or queryError("104", mysql_error());
			while($ROW = mysql_fetch_object($result))
			{
				$page = false;
				$query2 = "SELECT * FROM $DB_Pages";
				$result2 = mysql_query($query2, $Link) or queryError("105", mysql_error());
				while($ROW2 = mysql_fetch_object($result2))
				{
					if($ROW->url == ('page.php?page='.str_replace(" ", "_", $ROW2->name)))
					{
						$page = true;
						$page_id = $ROW2->id;
					}
				}
				if($page)
				{
					if(protectPrivatePage($page_id))
					{
						if(!$first)
							echo '<br />';
						if(substr($ROW->url, 0, 4) == 'http')
							echo '<a class="navigation" href="' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
						else
							echo '<a class="navigation" href="' . $sxSetup['Url'] . '/' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
						$first = false;
					}
				}
				else
				{
					if(!$first)
						echo '<br />';
					if(substr($ROW->url, 0, 4) == 'http')
						echo '<a class="navigation" href="' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
					else
						echo '<a class="navigation" href="' . $sxSetup['Url'] . '/' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
					$first = false;
				}
			}
			break;
		
		case 'horiz' :
		
			$first = true;
			$query = "SELECT * FROM $DB_Navigation ORDER BY position ASC";
			$result = mysql_query($query, $Link) or queryError("106", mysql_error());
			while($ROW = mysql_fetch_object($result))
			{
				$page = false;
				$query2 = "SELECT * FROM $DB_Pages";
				$result2 = mysql_query($query2, $Link) or queryError("107", mysql_error());
				while($ROW2 = mysql_fetch_object($result2))
				{
					if($ROW->url == ('page.php?page='.str_replace(" ", "_", $ROW2->name)))
					{
						$page = true;
						$page_id = $ROW2->id;
					}
				}
				if($page)
				{
					if(protectPrivatePage($page_id))
					{
						if(!$first)
							echo '&nbsp;&nbsp;&nbsp;';
						if(substr($ROW->url, 0, 4) == 'http')
							echo '<a class="navigation" href="' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
						else
							echo '<a class="navigation" href="' . $sxSetup['Url'] . '/' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
						$first = false;
					}
				}
				else
				{
					if(!$first)
						echo '&nbsp;&nbsp;&nbsp;';
					if(substr($ROW->url, 0, 4) == 'http')
						echo '<a class="navigation" href="' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
					else
						echo '<a class="navigation" href="' . $sxSetup['Url'] . '/' . $ROW->url . '" target="'. $ROW->target .'">' . $ROW->name . '</a>';
					$first = false;
				}
			}
			break;
	}
}

// NOTES:	Protects site from use when not setup.
// RETURNS: ! REDIRECTS on condition
//--------------------------------------------------
function verifySetup()
{
	global $HOST;
	global $USER;
	global $PASS;
	global $DATABASE;
	global $DB_PREFIX;
	
	foreach(fetchTables() as $value)
	{
		$new_name = "DB".$value;
		$$new_name = $DB_PREFIX.$value;
	}
	
	// BUG: Maybe this redirect should change!
	if(($USER == "")OR($DATABASE == ""))
	{
		header("Location:setup/setup.php");
		die();
	}
	
	$Link = @mysql_connect($HOST, $USER, $PASS) or queryError("108", mysql_error());
	@mysql_select_db($DATABASE, $Link) or queryError("109", mysql_error());
	
	$query = "SELECT * FROM $DB_Setup WHERE setup_key='setup_complete'";
	$result = @mysql_query($query, $Link);
	
	$query2 = "SELECT * FROM $DB_Setup WHERE setup_key='SetupComplete'";
	$result2 = @mysql_query($query2, $Link);
	
	if(mysql_num_rows($result))
	{
		$ROW = @mysql_fetch_object($result);
		if($ROW->setup_value == 0)
		{
			header("Location:setup/setup.php");
			die();
		}
	}
	elseif(mysql_num_rows($result2))
	{
		$ROW = @mysql_fetch_object($result2);
		if($ROW->setup_value == 0)
		{
			header("Location:setup/setup.php");
			die();
		}
	}
	else
	{
		header("Location:setup/setup.php");
		die();
	}
}

// NOTES:	Protects an inactive component page.
// RETURNS: ! REDIRECTS on condition
//--------------------------------------------------
function protectComponentPage($n)
{
	global $Link;
	global $DB_Components;
	global $sxThemeConfig;
	
	$query = "SELECT * FROM $DB_Components WHERE id='$n'";
	$result = mysql_query($query, $Link) or queryError("110", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(!$ROW->active)
	{
		header("Location:".$sxThemeConfig['Homepage']);
		die();
	}
}

// NOTES:	Fetches component's activity
// RETURNS:	true if active, false otherwise
//--------------------------------------------------
function componentActive($n){

	global $Link;
	global $DB_Components;
	
	$query = "SELECT * FROM $DB_Components WHERE id='$n'";
	$result = mysql_query($query, $Link) or queryError("111", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if($ROW->active) return true;
	else return false;
}

// NOTES:	Fetches component name
// RETURNS:	component name
//--------------------------------------------------
function getComponentName($n){
	
	global $Link;
	global $DB_Components;
	global $DB_Components_Rename;
	
	$query = "SELECT * FROM $DB_Components, $DB_Components_Rename WHERE $DB_Components.id=$DB_Components_Rename.compid AND $DB_Components.id='$n'";
	$result = mysql_query($query, $Link) or queryError("112", mysql_error());
	$ROW = mysql_fetch_object($result);
	return $ROW->new_name;
}

// NOTES:	Prints page turn navigation.
// RETURNS:	0 on not needed
//--------------------------------------------------
function pageTurns($url, $total, $page, $numberPerPage)
{
	global $sxLang;
	$max_pages = 15;
	
	if($total <= $numberPerPage)
		return 0;	// Return out of function if no need for page turn
	
	echo $sxLang['Pages'] . ': ';
	
	if($page > 1)
		echo '<a href="' . $url . 'page=1"><<</a> <a href="' . $url . 'page=' . ($page - 1) . '"><</a> ';
	
	$totalPages = (int) ($total/$numberPerPage);
	
	if($total%$numberPerPage > 0)
		$totalPages = $totalPages + 1;
	
	if($page > (int)($max_pages/2) + 1)
	{
		echo ' ...';
		$start = ($page - (int)($max_pages/2)) + 1;
	}
	else
		$start = 1;
	
	if(($max_pages + $start) < $totalPages)
		$end = ($max_pages + $start)-1;
	else
		$end = $totalPages;
	
	for($i = $start; $i <= $end; $i++)
	{
		if($page == $i) 
			echo "[$i] ";
		else
			echo '<a href="' . $url . 'page=' . $i . '">' . $i . '</a> ';
	}
	
	if($end < $totalPages)
		echo '... ';
	
	if(($page + 1) <= $totalPages)
		echo '<a href="' . $url . 'page=' . ($page + 1) . '">></a> <a href="' . $url . 'page=' . $totalPages . '">>></a>';
}

// NOTES:	Prints page turn navigation special.
// RETURNS:	0 on not needed
//--------------------------------------------------
function pageTurnsSpecial($url, $total, $numberPerPage){
	
	$max_pages = 4;
		
	if($total > $numberPerPage){
		echo '&nbsp;&nbsp;&nbsp;Page: ';
	}else return 0;
	
	$totalPages = (int) ($total/$numberPerPage);
	if($total%$numberPerPage > 0) $totalPages = $totalPages + 1;
		
	if($max_pages < $totalPages) $end = $max_pages;
	else $end = $totalPages;
	
	if($end < $totalPages) $e = $end-1;
	else $e = $end;
	
	for($i = 1; $i <= $e; $i++){
		if($page == $i) echo "[$i] ";
		else echo '<a href="' . $url . 'page=' . $i . '">' . $i . '</a> ';
	}
	
	if($end < $totalPages){
		echo '... ';
		echo '<a href="' . $url . 'page=' . $totalPages . '">' . $totalPages . '</a> ';
	}
}

// NOTES:	Fetch page hits.
// RETURNS:	number of hits
//--------------------------------------------------
function getNumHits($page){
	
	global $Link;
	global $sxSetup;
	global $DB_Hit_Counters;
	
	$extend = str_replace("http://", "", $sxSetup['Url']);
	$extend = str_replace($_SERVER["SERVER_NAME"], "", $extend);
	
	$tmp = substr($extend, (strlen($extend)-1), strlen($extend));
	if($tmp == '/') $extend = substr($extend, 0, (strlen($extend)-1));
	$page = $extend . "/" . $page;
	
	$query = "SELECT * FROM $DB_Hit_Counters WHERE page='$page'";
	$result = mysql_query($query, $Link) or queryError("113", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->hits;
}

// NOTES:	Gets width of title picture.
// RETURNS:	picture name
//--------------------------------------------------
function getTitleWidth($file){
	
	global $Link;
	global $DB_Themes;
	global $DB_Title_Pictures;
		
	$query = "SELECT * FROM $DB_Themes WHERE selected='1'";
	$result = mysql_query($query, $Link) or queryError("114", mysql_error());
	$ROW = mysql_fetch_object($result);
	$theme_width = $ROW->title_width;
		
	$query = "SELECT * FROM $DB_Title_Pictures WHERE filename='$file'";
	$result = mysql_query($query, $Link) or queryError("114", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if($ROW->width > 0) return $ROW->width;
	else 				return $theme_width;
}

// NOTES:	Gets height of title picture.
// RETURNS:	picture name
//--------------------------------------------------
function getTitleHeight($file){
	
	global $Link;
	global $DB_Themes;
	global $DB_Title_Pictures;
	
	$query = "SELECT * FROM $DB_Themes WHERE selected='1'";
	$result = mysql_query($query, $Link) or queryError("114", mysql_error());
	$ROW = mysql_fetch_object($result);
	$theme_height = $ROW->title_height;
		
	$query = "SELECT * FROM $DB_Title_Pictures WHERE filename='$file'";
	$result = mysql_query($query, $Link) or queryError("114", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if($ROW->height > 0) return $ROW->height;
	else 				 return $theme_height;
}

// NOTES:	Gets name of title picture.
// RETURNS:	picture name
//--------------------------------------------------
function getTitleName($filename){
	
	global $Link;
	global $DB_Title_Pictures;
		
	$query = "SELECT * FROM $DB_Title_Pictures WHERE filename='$filename'";
	$result = mysql_query($query, $Link) or queryError("116", mysql_error());
	$ROW = mysql_fetch_object($result);
	return $ROW->name;
}

// NOTES:	Randomly selects an active title picture.
// RETURNS:	file name
//--------------------------------------------------
function getTitlePicture(){
	
	global $Link;
	global $THEME;
	global $DB_Title_Pictures;
	
	$query = "SELECT * FROM $DB_Title_Pictures WHERE active='1' AND themeid='$THEME' ORDER BY rand()";
	$result = mysql_query($query, $Link) or queryError("117", mysql_error());
	$ROW = mysql_fetch_object($result);
	return $ROW->filename;
}

// NOTES:	Dies with error message.
// RETURNS:	DIES!
//--------------------------------------------------
function queryError($num, $error){
	global $sxLang;
	die("<br /><br /><strong>" . $sxLang['QueryError1'] . " #$num " . $sxLang['QueryError2'] . " :</strong> ".$error);
}

// NOTES:	Logs page hit to database.
// RETURNS:	NULL
//--------------------------------------------------
function countPageHit($location){
	
	global $Link;
	global $DB_Hit_Counters;
	
	$location = addslashes($location);
	
	$query = "SELECT * FROM $DB_Hit_Counters WHERE page='$location'";
	$result = mysql_query($query, $Link) or queryError("118", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	// Setup new page if page not in DB
	if(!mysql_num_rows($result)){
		$query = "INSERT INTO $DB_Hit_Counters (page, hits) VALUES ('$location', '1')";
		$result = mysql_query($query, $Link) or queryError("119", mysql_error());
	}
	// Increment counter if page exists
	else{
		$hits = $ROW->hits + 1;
		$query = "UPDATE $DB_Hit_Counters SET hits='$hits' WHERE page='$location'";
		$result = mysql_query($query, $Link) or queryError("120", mysql_error());
	}
}

// NOTES:	Checks for acceptable file extentions.
// RETURNS:	Boolean (1) if extension is acceptable
//--------------------------------------------------
function checkFileType($filename){

	$filename = strtolower($filename);	// Lowercase file name
	
	str_replace("%body%", "black", "<body text='%body%'>");
	
	// Make sure file is an acceptable file type (jpg, gif, png, txt, doc, ppt, xls, mpp, pdf, html, wps)
	if (eregi ("(.)+\\.(jp(e){0,1}g$|gif$|png$|txt$|rtf$|doc$|ppt$|xls$|mpp$|pdf$|html$|wps$)",$filename)) return 1;
	else return 0;

}

// NOTES:	Checks for acceptable image types.
// RETURNS:	Boolean (1) if acceptable
//--------------------------------------------------
function checkImageType($filename)
{
	$filename = strtolower($filename);	// Lowercase image name
	
	// Check to make sure file is an acceptable image type (jpg, gif, png)
	if (eregi ("(.)+\\.(jp(e){0,1}g$|gif$|png$)",$filename))
		return 1;
	else
		return 0;
}

// NOTES:	Gathers information on an image file.
// RETURNS:	File info array - 
//				['Filesize']
//				['Width']
//				['Height']
//				['Type']
//--------------------------------------------------
function sxGetImageInfo($file)
{
	$fileinfo = array();
	$file = strtolower($file);	// Lowercase image name
	
	$iminfo = getimagesize($file);

	$fileinfo['Filesize'] = filesize($file);
	$fileinfo['Width']	= $iminfo[0];
	$fileinfo['Height']	= $iminfo[1];
	$fileinfo['Type']	= $iminfo[2];
	
	return $fileinfo;
}

// NOTES:	Formats name.
// RETURNS:	Formatted name
//--------------------------------------------------
function formatName($n)
{
	// Format usernames
	//$n = ereg_replace("[^[:alnum:]|[:space:]|[.]]", "", $n);
	$n = ereg_replace (" ", "_", $n);
	return $n;
}

// NOTES:	Scavenges all directories in root of 
//			site and returns total file size.		
// RETURNS:	File size
//--------------------------------------------------
function getdirSize($dir)
{
	$totalSize = 1;
	
	if($current_dir = @opendir($dir))
	{
		while($entryname = @readdir($current_dir))
		{
			if(@is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
			{
				$totalSize += getdirSize("${dir}/${entryname}");
			}
			elseif($entryname != "." and $entryname!="..")
			{
				$totalSize += @filesize("${dir}/${entryname}");
			}
		}
		@closedir($current_dir);
		return $totalSize;
	}
}

// NOTES:	Scavenges all directories in content/
// 			in order to setup directory with
//			current dir image.  New dirs are added,
//			unknown dirs are left alone.
// RETURNS:	
//--------------------------------------------------
function sxUpdateContentDirectories()
{
	global $sxContentDir;
	
	if(sxContentWriteable() == TRUE)
	{
		foreach($sxContentDir as $dir)
		{
			$dir = "../".substr($dir,0,strlen($dir)-1);
			if(!@opendir($dir))
				@mkdir($dir, 0757);
		}
	}
}

// NOTES:	Tests write access on content/ root.
// RETURNS:	
//--------------------------------------------------
function sxContentWriteable()
{
	return sxFolderWriteable('content/');
}

// NOTES:	Tests write access on themes/ root.
// RETURNS:	
//--------------------------------------------------
function sxThemesWriteable()
{
	return sxFolderWriteable('themes/');
}

// NOTES:	Tests write access on folder.
//			$pathFromRoot contains 'folder/'
// RETURNS:	
//--------------------------------------------------
function sxFolderWriteable($pathFromRoot)
{
	$write = TRUE;

	if(!is_writable(sxPathToRoot().$pathFromRoot))	
		$write = FALSE;
	
	return $write;
}

// NOTES:	Clears a standard file directory of 
//			all contents and removes dir.		
// RETURNS:	NULL
//--------------------------------------------------
function sxDirDelete($path)
{
	$path = sxPathToRoot().$path;
	
	if(empty($path))
		return;

	if(file_exists($path))
	{
		$dir = dir($path);
		while($file = $dir->read())
		{
			if($file != '.' && $file != '..')
			{
				if(is_dir($path.'/'.$file))
					sxDirDelete($path.'/'.$file);
				else
					@unlink($path.'/'.$file);
			}
		}
		@rmdir($path.'/'.$file);
	}
}

// NOTES:	Generates a random string.		
// RETURNS: Random string
//--------------------------------------------------
function randomstring($len)
{
	srand(date("s"));
	while($i < $len)
	{
		$str .= chr((rand()%26)+97);
		$i++;
	}
	$str = $str.substr(uniqid (""),0,22);
	return $str;
}

// NOTES:	Checks for username.		
// RETURNS: Boolean (1) if NOT found
//--------------------------------------------------
function usernameNotFound($u)
{
	global $Link;
	global $DB_Users;
	
	$query = "SELECT id FROM $DB_Users WHERE username='$u'";
	$result = mysql_query($query, $Link) or queryError("121", mysql_error());
	
	if(!mysql_num_rows($result))
		return 1;
	else
		return 0;
}

// NOTES:	Determines if image does NOT exist		
// RETURNS:	Boolean (1) if does NOT exist
//--------------------------------------------------
function imageNotFound($name, $directory)
{
	$name = strtolower($name);
    if($fp = fopen("$directory/$name",w))
	{
		fclose($fp);
		return 0;
	}
	else
		return 1;
}

// NOTES:	Relocates user to homepage with error.
// RETURNS: NULL > DIES
//--------------------------------------------------
function loginError($error)
{
	global $sxSetup;
	$error = str_replace(' ', '_', $error);
	header("Location:".$sxSetup['Url']."/login.php?error=$error");
	die();
}

// NOTES:	Determines if userid session var is set.
// RETURNS: TRUE/FALSE
//--------------------------------------------------
function loggedIn()
{	
	global $Link;
	global $DB_Users;
	
	if((session_is_registered('userid'))AND(session_is_registered('username'))AND(session_is_registered('password')))
	{
		$uid = $_SESSION['userid'];
		$this_username = $_SESSION['username'];
		$this_password = $_SESSION['password'];
		
		$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
		$result = mysql_query($query, $Link) or queryError("122", mysql_error());
		$ROW = mysql_fetch_object($result);
		
		if(md5($ROW->password) == $this_password){
			return true;
		}
		else
			logOut();
	}
	else
		return false;
}

// NOTES:	Checks authentication of user and sets up
//		session if user info is correct
// RETURNS: NULL
//--------------------------------------------------
function authenticate($u, $p)
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	global $NOW;
	global $sxSetup;
	
	// Protect login from SQL injection
	$u = htmlspecialchars($u);
	$p = htmlspecialchars($p);
	
	$query = "SELECT * FROM $DB_Users WHERE username='$u'";
	$result = mysql_query($query, $Link) or queryError("123", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	// Check if user exists
	if (!mysql_num_rows($result))
	{
		header("Location:".$sxSetup['Url']."/login.php?sxAuthError=MessageUserAuthErrorUsername");
		die();
	}
	
	// Check password
	else if($p == $ROW->password)
	{
		// Check activity of account
		if($ROW->active == 0)
		{
			header("Location:".$sxSetup['Url']."/login.php?sxAuthError=MessageUserAuthErrorDeactivated");
			die();
		}
		// Check validity
		if($ROW->validated == 0)
		{
			header("Location:".$sxSetup['Url']."/login.php?sxAuthError=MessageUserAuthErrorValidated");
			die();
		}
		// Setup session if active
		else
		{
			// Initialize session variables
			session_register('userid');
			$_SESSION['userid'] = $ROW->id;
			session_register('username');
			$_SESSION['username'] = $ROW->username;
			session_register('password');
			$_SESSION['password'] = md5($ROW->password);
			session_register('firstname');
			$_SESSION['firstname'] = $ROW->firstname;
			session_register('lastname');
			$_SESSION['lastname'] = $ROW->lastname;
			session_register('email');
			$_SESSION['email'] = $ROW->email;
			session_register('website');
			$_SESSION['website'] = $ROW->website;
			
			// Log last login value
			$query2 = "UPDATE $DB_Users SET lastlogin='$NOW' WHERE id='$ROW->id'";
			$result2 = mysql_query($query2, $Link) or queryError("405", mysql_error());
		}
	}
	else
	{
		header("Location:".$sxSetup['Url']."/login.php?sxAuthError=MessageUserAuthErrorUserPass");
		die();
	}
}

// NOTES:	Clears httpd headers in order to force
//		a page refresh of content.
// RETURNS: NULL
//--------------------------------------------------
function clearCache()
{
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
}

// NOTES:	Expires user's session to log out user.
// SEE: clearCache()
// RETURNS: NULL > DIES
//--------------------------------------------------
function logOut()
{
	global $sxThemeConfig;
	session_unset();
	session_destroy();
	clearCache();
	header("Location:".$sxThemeConfig['Homepage']);
	die();
}

// NOTES:	Fetches user id.
// RETURNS: User id from users database
//--------------------------------------------------
function getUID($u)
{
	global $Link;
	global $DB_Users;
	
	$query = "SELECT * FROM $DB_Users WHERE username='$u'";
	$result = mysql_query($query, $Link) or queryError("125", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->id;
}

// NOTES:	Fetches user id.
// RETURNS: User id from users database
//--------------------------------------------------
function get_THIS_USER()
{
	global $Link;
	global $DB_Users;
	
	$uid = $_SESSION['userid'];
	$this_username = $_SESSION['username'];
	$this_password = $_SESSION['password'];
	
	$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
	$result = mysql_query($query, $Link) or queryError("126", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(md5($ROW->password) == $this_password)
		return $ROW->id;
	else
		return 0;
}

function userAdmin()
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	
	$uid = $_SESSION['userid'];
	$this_username = $_SESSION['username'];
	$this_password = $_SESSION['password'];
	
	$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
	$result = mysql_query($query, $Link) or queryError("127", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(md5($ROW->password) == $this_password)
	{
		$query2 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$uid' AND typeid='1'";
		$result2 = mysql_query($query2, $Link) or queryError("128", mysql_error());
		
		if(mysql_num_rows($result2))
			return true;
		else
			return false;
	}
	else
		return false;
}

function userEditor()
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	
	$uid = $_SESSION['userid'];
	$this_username = $_SESSION['username'];
	$this_password = $_SESSION['password'];
	
	$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
	$result = mysql_query($query, $Link) or queryError("127", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(md5($ROW->password) == $this_password)
	{
		$query2 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$uid' AND typeid='4'";
		$result2 = mysql_query($query2, $Link) or queryError("128", mysql_error());
		
		if(mysql_num_rows($result2))
			return true;
		else
			return false;
	}
	else
		return false;
}

function userForumManager()
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	
	$uid = $_SESSION['userid'];
	$this_username = $_SESSION['username'];
	$this_password = $_SESSION['password'];
	
	$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
	$result = mysql_query($query, $Link) or queryError("129", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(md5($ROW->password) == $this_password)
	{
		$query2 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$uid' AND typeid='5'";
		$result2 = mysql_query($query2, $Link) or queryError("130", mysql_error());
		
		if(mysql_num_rows($result2))
			return true;
		else
			return false;
	}
	else
		return false;
	
}

function userModerator()
{
	global $Link;
	global $DB_Users;
	global $DB_Users_Assoc;
	
	$uid = $_SESSION['userid'];
	$this_username = $_SESSION['username'];
	$this_password = $_SESSION['password'];
	
	$query = "SELECT * FROM $DB_Users WHERE id='$uid' AND username='$this_username'";
	$result = mysql_query($query, $Link) or queryError("129", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if(md5($ROW->password) == $this_password)
	{
		$query2 = "SELECT * FROM $DB_Users_Assoc WHERE userid='$uid' AND typeid='3'";
		$result2 = mysql_query($query2, $Link) or queryError("130", mysql_error());
		
		if(mysql_num_rows($result2))
			return true;
		else
			return false;
	}
	else
		return false;

}

// RETURNS: Username based on user id
//--------------------------------------------------
function getUsername($userid)
{
	global $Link;
	global $DB_Users;	
	
	$query = "SELECT * FROM $DB_Users WHERE id='$userid'";
	$result = mysql_query($query, $Link) or queryError("131", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->username;
}

// RETURNS: First and last name based on user id
//--------------------------------------------------
function getUserFullName($userid)
{
	global $Link;
	global $DB_Users;
		
	$query = "SELECT * FROM $DB_Users WHERE id='$userid'";
	$result = mysql_query($query, $Link) or queryError("131", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->firstname . ' ' . $ROW->lastname;
}

// NOTES: Reports hack attempts to database.
//		  NOT USED IN SITEX CORE ANY MORE!!!!!!!!!!!
// RETURNS: NULL > FUNCTION DIES
//--------------------------------------------------
function reportHackAttempt($page, $attempt, $message)
{
	global $Link;
	global $NOW;
	global $username;
	
	$userid = getUID($username);
	$message = addslashes($message);
		
	$query = "INSERT INTO hacks (userid, page, attempt, timestamp, message) VALUES ('$userid', '$page', '$attempt', '$NOW', '$message')";
	$result = mysql_query($query, $Link) or queryError("132", mysql_error());
	
	$query = "SELECT * FROM hacks WHERE userid='$userid'";
	$result = mysql_query($query, $Link) or queryError("133", mysql_error());
	if(mysql_num_rows($result) > 2)
	{
		$query = "UPDATE $DB_Users SET active='0' WHERE id='$userid'";
		$result = mysql_query($query, $Link) or queryError("134", mysql_error());
	}
	die("Please note that we have detected, reported, and stopped your hack attempt.<br /><br />Further attemps will suspend your computer name, IP, and network signature from the use of our software and servers.");
}

function randLookup($num)
{
	switch($num)
	{
		case "1":  $rand_value = "a"; break;
		case "2":  $rand_value = "b"; break;
		case "3":  $rand_value = "c"; break;
		case "4":  $rand_value = "d"; break;
		case "5":  $rand_value = "e"; break;
		case "6":  $rand_value = "f"; break;
		case "7":  $rand_value = "g"; break;
		case "8":  $rand_value = "h"; break;
		case "9":  $rand_value = "i"; break;
		case "10": $rand_value = "j"; break;
		case "11": $rand_value = "k"; break;
		case "12": $rand_value = "l"; break;
		case "13": $rand_value = "m"; break;
		case "14": $rand_value = "n"; break;
		case "15": $rand_value = "o"; break;
		case "16": $rand_value = "p"; break;
		case "17": $rand_value = "q"; break;
		case "18": $rand_value = "r"; break;
		case "19": $rand_value = "s"; break;
		case "20": $rand_value = "t"; break;
		case "21": $rand_value = "u"; break;
		case "22": $rand_value = "v"; break;
		case "23": $rand_value = "w"; break;
		case "24": $rand_value = "x"; break;
		case "25": $rand_value = "y"; break;
		case "26": $rand_value = "z"; break;
		case "27": $rand_value = "0"; break;
		case "28": $rand_value = "1"; break;
		case "29": $rand_value = "2"; break;
		case "30": $rand_value = "3"; break;
		case "31": $rand_value = "4"; break;
		case "32": $rand_value = "5"; break;
		case "33": $rand_value = "6"; break;
		case "34": $rand_value = "7"; break;
		case "35": $rand_value = "8"; break;
		case "36": $rand_value = "9"; break;
	}
	return $rand_value;
}

function getRand($length)
{
	$rand = "";
	if($length > 0)
	{ 
		for($i = 1; $i <= $length; $i++)
		{
			mt_srand((double)microtime() * 1000000);
			$num = mt_rand(1,36);
			$rand .= randLookup($num);
		}
	}
	return $rand;
}

function userValidation($key)
{
	global $Link;
	global $DB_Users;
	global $sxSetup;
	global $sxLang;
	
	$query = "SELECT * FROM $DB_Users WHERE validation_code='$key'";
	$result = mysql_query($query, $Link) or queryError("1002", mysql_error());
	
	if(mysql_num_rows($result))
	{
		$ROW = mysql_fetch_object($result);
		$query2 = "UPDATE $DB_Users SET validation_code='', validated='1' WHERE id='$ROW->id'";
		$result2 = mysql_query($query2, $Link) or queryError("1001", mysql_error());

		if(($sxSetup['UserApproval'])AND($ROW->active == 0))
			$extra = " ".$sxLang['MessageUserLoginAfterApproval'];
		else
			$extra = " ".$sxLang['MessageUserLogin'];
		
		header("Location:login.php?error=".str_replace(" ","_",$sxLang['MessageUserValidated'].$extra));
		die();
	}
	else
	{
		header("Location:login.php?error=".str_replace(" ","_",$sxLang['MessageUserValidationKeyInvalid']));
		die();
	}
}

function sxCreateSecurityImage()
{
	global $sxContentDir;
	global $Link;
	global $NOW;
	global $DB_Security_Image;
	global $sxThemeConfig;
		
	// Security options
	$image_width = 230;
	$image_height = 40;
	$code_length = 7;
	$ttf_file = "includes/elephant.ttf";
	$font_size = 20;
	$text_angle_minimum = -20;
	$text_angle_maximum = 20;
	$text_x_start = 9;
	$text_minimum_distance = 30;
	$text_maximum_distance = 33;
	$image_bg_color = array("red" => hexdec(substr($sxThemeConfig['SecurityImageColorBackground'],1,2)), "green" => hexdec(substr($sxThemeConfig['SecurityImageColorBackground'],3,2)), "blue" => hexdec(substr($sxThemeConfig['SecurityImageColorBackground'],5,2)));
	$text_color = array("red" => hexdec(substr($sxThemeConfig['SecurityImageColorText'],1,2)), "green" => hexdec(substr($sxThemeConfig['SecurityImageColorText'],3,2)), "blue" => hexdec(substr($sxThemeConfig['SecurityImageColorText'],5,2)));
	$line_color = array("red" => hexdec(substr($sxThemeConfig['SecurityImageColorLine'],1,2)), "green" => hexdec(substr($sxThemeConfig['SecurityImageColorLine'],3,2)), "blue" => hexdec(substr($sxThemeConfig['SecurityImageColorLine'],5,2)));
	$shadow_text = false;
	$use_transparent_text = TRUE;
	$text_transparency_percentage = 15;
	$draw_lines = TRUE;
	$line_distance = 6;
	$draw_angled_lines = TRUE;
	$draw_lines_over_text = TRUE;
	
	// Construct image
	if((imageCompatibility() == "truecolor")AND($use_transparent_text == true || $this->bgimg != ""))
	{
		$image = imagecreatetruecolor($image_width, $image_height);
		$bgcolor = imagecolorallocate($image, $image_bg_color['red'], $image_bg_color['green'], $image_bg_color['blue']);
		imagefilledrectangle($image, 0, 0, imagesx($image), imagesy($image), $bgcolor);
	}
	elseif(imageCompatibility() == "normal")
	{
		$image = imagecreate($image_width, $image_height);
		$bgcolor = imagecolorallocate($image, $image_bg_color['red'], $image_bg_color['green'], $image_bg_color['blue']);
	}
	
	// If desired, form background
	if($bgimg != "")
	{
		$dat = @getimagesize($bgimg);
		switch($dat[2])
		{
			case 1: $newim = @imagecreatefromgif($this->bgimg); break;
			case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
			case 3: $newim = @imagecreatefrompng($this->bgimg); break;
			case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
			case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
			default: return;
		}
		imagecopy($image, $newim, 0, 0, 0, 0, $image_width, $image_height);
	}
	
	// Formulate security code
	$code = "";
	for($i = 1; $i <= $code_length; ++$i)
		$code .= chr(rand(65, 90));
	
	// Draw obsuring lines
	if (!$draw_lines_over_text && $draw_lines)
	{
		$linecolor = imagecolorallocate($image, $line_color['red'], $line_color['green'], $line_color['blue']);
		
		// Vertical lines
		for($x = 1; $x < $image_width; $x += $line_distance)
			imageline($image, $x, 0, $x, $image_height, $linecolor);
		
		// Horizontal lines
		for($y = 11; $y < $image_height; $y += $line_distance)
			imageline($image, 0, $y, $this->image_width, $y, $linecolor);
		
		// Angled lines
		if ($draw_angled_lines == TRUE)
		{
			for ($x = -($image_height); $x < $image_width; $x += $line_distance)
				imageline($image, $x, 0, $x + $image_height, $image_height, $linecolor);
			
			for ($x = $image_width + $image_height; $x > 0; $x -= $line_distance)
				imageline($image, $x, 0, $x - $image_height, $image_height, $linecolor);
		}
	}
	
	// Draw text on image
	if(use_transparent_text == true)
	{
		$alpha = floor($text_transparency_percentage / 100 * 127);
		$font_color = imagecolorallocatealpha($image, $text_color['red'], $text_color['green'], $text_color['blue'], $alpha);
	}
	else
		$font_color = imagecolorallocate($image, $text_color['red'], $text_color['green'], $text_color['blue']);
	
	$x = $text_x_start;
	$strlen = strlen($code);
	$y_min = ($image_height / 2) + (($font_size+rand(-5,5)) / 2) - 2;
	$y_max = ($image_height / 2) + (($font_size+rand(-5,5)) / 2) + 2;
	
	for($i = 0; $i < $strlen; ++$i)
	{
		$angle = rand($text_angle_minimum, $text_angle_maximum);
		$y = rand($y_min, $y_max);
		
		imagettftext($image, ($font_size+rand(-5,5)), $angle, $x, $y, $font_color, $ttf_file, $code{$i});
		
		if($shadow_text == true)
			imagettftext($image, ($font_size+rand(-5,5)), $angle, $x + 2, $y + 2, $font_color, $ttf_file, $code{$i});
		
		$x += rand($text_minimum_distance, $text_maximum_distance);
	}
	
	// Draw final covering lines
	if ($draw_lines_over_text && $draw_lines)
	{
		$linecolor = imagecolorallocate($image, $line_color['red'], $line_color['green'], $line_color['blue']);
		
		// Vertical lines
		for($x = 1; $x < $image_width; $x += ($line_distance+rand(0,10)) )
			imageline($image, $x, 0, $x, $image_height, $linecolor);
		
		// Horizontal lines
		for($y = 11; $y < $image_height; $y += ($line_distance+rand(0,10)) )
			imageline($image, 0, $y, $image_width, $y, $linecolor);
		
		// Angled lines
		if ($draw_angled_lines == TRUE)
		{
			for ($x = -($image_height); $x < $image_width; $x += ($line_distance+rand(0,10)) )
				imageline($image, $x, 0, $x + $image_height, $image_height, $linecolor);
			
			for ($x = $image_width + $image_height; $x > 0; $x -= ($line_distance+rand(0,10)) )
				imageline($image, $x, 0, $x - $image_height, $image_height, $linecolor);
		}
	}
	
	// Formulate secure filename
	$filename = "";
	for($i = 1; $i <= 15; ++$i)
		$filename .= chr(rand(65, 90));
	$filename = md5(md5($filename)).".jpg";
	$filelocation = $sxContentDir['Security'].$filename;
	
	// Final output
	imagejpeg($image, $filelocation, 70);
	imagedestroy($image);
	
	// Record in DB
	$query = "INSERT INTO $DB_Security_Image (code, filename, timestamp) VALUES ('$code', '$filename', '$NOW')";
	$result = mysql_query($query, $Link) or queryError("10100", mysql_error());

	$query = "SELECT * FROM $DB_Security_Image WHERE code='$code' AND filename='$filename' AND timestamp='$NOW'";
	$result = mysql_query($query, $Link) or queryError("10101", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	// Return image information
	$image_info = array();
	$image_info['url'] = $filelocation;		// URL to image
	$image_info['codeid'] = $ROW->id;	// ID of code row in db
	
	return $image_info;

} //end function

function validateSecurityCode($code, $id)
{
	global $Link;
	global $DB_Security_Image;
	
	//echo "Code entered: ".$code."<br />";
	//echo "Image ID: ".$id."<br />";
	
	if(is_numeric($id) == FALSE)
	{
		//echo "ERROR - ID is non-numeric!<br />";
		return false;
	}
	
	if ((strlen($code) < 1) OR (strlen($id) < 1))
	{
		//echo "ERROR - length of code or id is less than 1!<br />";
		return false;
	}
	
	$query = "SELECT * FROM $DB_Security_Image WHERE id='$id'";
	$result = mysql_query($query, $Link) or queryError("10101", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	// Check code in non-case-sensitive mode
	if(strtolower($ROW->code) == strtolower($code))
		return true;
	else
	{
		//echo "ERROR - ".strtolower($ROW->code)."!=".strtolower($code)."<br />";
		return false;
	}
	//die();
}

function sxNonOperatingWord($word)
{
	switch(substr($word,0,1))
	{
		case '-' :
			return false;
			break;
		default :
			return true;
			break;
	}
}

function sxMineElement($phrase, $keywords)
{
	$mine = TRUE;
	
	foreach($keywords as $word)
	{
		$word = strtolower($word);
		if(sxNonOperatingWord($word))
		{
			if(strpos($phrase, $word) == FALSE)
				$mine = FALSE;
		}
		else
		{
			// - word
			if(strpos($phrase, substr($word,1)))
				$mine = FALSE;
		}
	}
	return $mine;
}

function sxExtractKeywords($search)
{
	$search = $search;
	
	// Make char array of keywords
	$search_char = array();
	for ($i = 0; $i < strlen($search); $i++)
		$search_char[$i] = substr($search,$i,1);
	
	// Join words with " operators ("join text" -> "join_text")
	$join_mode = 0;
	foreach($search_char as $key => $value)
	{
		// Flag join mode with XOR logic
		if($value == '"')
			$join_mode = $join_mode^1;
			
		// To join word(s) underscore spaces
		if(($join_mode == 1)AND($value == ' '))
			$search_char[$key] = "_";
	}
	
	// Pull string back together
	for ($i = 0; $i < count($search_char); $i++)
		$search_joined .= $search_char[$i];
	
	// Split string into array of keywords by space char
	$keywords = explode(" ", $search_joined);
	
	// Convert underscores in joined keywords to space
	$keywords = str_replace("_", " ", $keywords);
	
	// Remove quotes ("text" -> text)
	$keywords = str_replace('"', '', $keywords);
	
	// Final cleaning of input for SQLi or XSS
	foreach ($keywords as $key => $value)
		$keywords[$key] = htmlspecialchars($value);

	// $keywords is now array of keywords
	return $keywords;
}

function sxHighlightText($text,$keywords)
{
	if (count($keywords) < 1)
		return $text;
		
	$pre_code 	= '<span class="sxTextHighlight">';
	$post_code 	= '</span>';
	
	foreach($keywords as $keyword)
	{
		$continue 	= TRUE;
		$offset 	= 0;
		
		while($continue == TRUE)
		{
			$position = strpos(strtolower($text),strtolower($keyword),$offset);
			
			if(is_bool($position) == FALSE)
			{
				$text = substr($text, 0, $position) . $pre_code . substr($text, $position, strlen($keyword)) . $post_code . substr($text, $position+strlen($keyword));
				$offset = $position + strlen($keyword) + strlen($pre_code) + strlen($post_code);
			}
			else
				$continue = FALSE;
		}
	}
	return $text;
}

function sxEventsSearchResults($search)
{
	global $Link;
	global $THIS_USER;
	global $DB_Events;
	global $DB_Events_Private;
	global $DB_Users_Assoc;
	
	if (strlen($search) < 1)
		return false;
	
	$SearchQuery = "";
	$SearchResults = array();
	$keywords = sxExtractKeywords($search);
	foreach ($keywords as $word)
	{
		if (sxNonOperatingWord($word))
		{
			$SearchQuery .= "OR longname LIKE '%$word%' ";
			$SearchQuery .= "OR description LIKE '%$word%' ";
		}
	}
	$SearchQuery = substr($SearchQuery, 3);
	
	$query = "SELECT * FROM $DB_Events WHERE ($SearchQuery) ORDER BY end_timestamp DESC";
	$result = mysql_query($query, $Link) or queryError("221", mysql_error());
	while ($ROW = mysql_fetch_object($result))
	{
		// Make a master key phrase of all keywords
		$MineElement = true;
		$KeyPhrase = " ";
		$KeyPhrase .= $ROW->longname;
		$KeyPhrase .= $ROW->description;
		$KeyPhrase = strtolower(strip_tags($KeyPhrase));
		
		// Figure out if item should be mined
		if (sxMineElement($KeyPhrase, $keywords))
		{
			// Determine if user has access to this item
			$protect = false;
			$query3 = "SELECT * FROM $DB_Events_Private WHERE eventid='$ROW->id'";
			$result3 = mysql_query($query3, $Link) or queryError("220", mysql_error());
			if (mysql_num_rows($result3))
			{
				$query3 = "SELECT * FROM $DB_Events_Private, $DB_Users_Assoc
						   WHERE $DB_Events_Private.typeid=$DB_Users_Assoc.typeid AND
								 $DB_Users_Assoc.userid='$THIS_USER' AND
								 $DB_Events_Private.eventid='$ROW->id'";
				$result3 = mysql_query($query3, $Link) or queryError("222", mysql_error());
				if (!mysql_num_rows($result3))
					$protect = true;
			}
			
			// Ensure user has access
			if (!$protect)
				array_push($SearchResults, $ROW->id);
		}
	}
	return $SearchResults;
}

function sxPageSearchResults($search)
{
	global $Link;
	global $THIS_USER;
	global $DB_Pages;
	global $DB_Pages_Private;
	global $DB_Users_Assoc;
	
	if(strlen($search) < 1) return false;
	
	$SearchQuery = "";
	$SearchResults = array();
	$keywords = sxExtractKeywords($search);
	foreach($keywords as $word)
	{
		if(sxNonOperatingWord($word))
		{
			$SearchQuery .= "OR name LIKE '%$word%' ";
			$SearchQuery .= "OR content LIKE '%$word%' ";
		}
	}
	$SearchQuery = substr($SearchQuery, 3);
	
	$query = "SELECT * FROM $DB_Pages WHERE ($SearchQuery) ORDER BY name DESC";
	$result = mysql_query($query, $Link) or queryError("221", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		// Make a master key phrase of all keywords
		$MineElement = true;
		$KeyPhrase = " ";
		$KeyPhrase .= $ROW->name;
		$KeyPhrase .= $ROW->content;
		$KeyPhrase = strtolower(strip_tags($KeyPhrase));
		
		// Figure out if item should be mined
		if(sxMineElement($KeyPhrase, $keywords))
		{
			// Determine if user has access to this item
			$protect = false;
			$query3 = "SELECT * FROM $DB_Pages_Private WHERE pageid='$ROW->id'";
			$result3 = mysql_query($query3, $Link) or queryError("220", mysql_error());
			if(mysql_num_rows($result3))
			{
				$query3 = "SELECT * FROM $DB_Pages_Private, $DB_Users_Assoc
						   WHERE $DB_Pages_Private.typeid=$DB_Users_Assoc.typeid AND
								 $DB_Users_Assoc.userid='$THIS_USER' AND
								 $DB_Pages_Private.pageid='$ROW->id'";
				$result3 = mysql_query($query3, $Link) or queryError("222", mysql_error());
				if(!mysql_num_rows($result3))
					$protect = true;
			}
			
			// Ensure user has access
			if(!$protect)
				array_push($SearchResults, $ROW->id);
		}
	}
	return $SearchResults;
}

function sxJournalSearchResults($search)
{
	global $Link;
	global $THIS_USER;
	global $DB_Journal;
	
	if(strlen($search) < 1) return false;
	
	$SearchQuery = "";
	$SearchResults = array();
	$keywords = sxExtractKeywords($search);
	foreach($keywords as $word)
	{
		if(sxNonOperatingWord($word))
		{
			$SearchQuery .= "OR title LIKE '%$word%' ";
			$SearchQuery .= "OR entry LIKE '%$word%' ";
		}
	}
	$SearchQuery = substr($SearchQuery, 3);
	
	$query = "SELECT * FROM $DB_Journal WHERE ($SearchQuery) ORDER BY timestamp DESC";
	$result = mysql_query($query, $Link) or queryError("221", mysql_error());
	while ($ROW = mysql_fetch_object($result))
	{
		// Make a master key phrase of all keywords
		$MineElement = true;
		$KeyPhrase = " ";
		$KeyPhrase .= $ROW->title;
		$KeyPhrase .= $ROW->entry;
		$KeyPhrase = strtolower($KeyPhrase);
		
		if(sxMineElement($KeyPhrase, $keywords) == TRUE)
			array_push($SearchResults, $ROW->id);
	}
	return $SearchResults;
}

function sxForumSearchResults($search)
{
	global $Link;
	global $THIS_USER;
	global $DB_Forums_Posts;
	global $DB_Forums_Private;
	global $DB_Users_Assoc;
	
	if(strlen($search) < 1)
		return false;
	
	$SearchQuery = "";
	$SearchResults = array();
	$keywords = sxExtractKeywords($search);
	foreach($keywords as $word)
	{
		if(sxNonOperatingWord($word))
		{
			$SearchQuery .= "OR content LIKE '%$word%' ";
			$SearchQuery .= "OR topic LIKE '%$word%' ";
		}
	}
	$SearchQuery = substr($SearchQuery, 3);
	
	$query = "SELECT * FROM $DB_Forums_Posts WHERE ($SearchQuery) ORDER BY updated DESC";
	$result = mysql_query($query, $Link) or queryError("221", mysql_error());
	while($ROW = mysql_fetch_object($result))
	{
		// Make a master key phrase of all keywords
		$MineElement = true;
		$KeyPhrase = " ";
		$KeyPhrase .= $ROW->topic;
		$KeyPhrase .= $ROW->content;
		$KeyPhrase = strtolower($KeyPhrase);
		
		// Figure out if topic should be mined
		if(sxMineElement($KeyPhrase, $keywords))
		{
			// Determine if user has access to this post
			$protect = false;
			$query3 = "SELECT * FROM $DB_Forums_Private WHERE forumid='$ROW->forumid'";
			$result3 = mysql_query($query3, $Link) or queryError("220", mysql_error());
			if(mysql_num_rows($result3))
			{
				$query3 = "SELECT * FROM $DB_Forums_Private, $DB_Users_Assoc
						   WHERE $DB_Forums_Private.typeid=$DB_Users_Assoc.typeid AND
								 $DB_Users_Assoc.userid='$THIS_USER' AND
								 $DB_Forums_Private.forumid='$ROW->forumid'";
				$result3 = mysql_query($query3, $Link) or queryError("222", mysql_error());
				if(!mysql_num_rows($result3))
					$protect = true;
			}
			
			// Ensure user has access
			if(!$protect)
			{
				if($ROW->replyto == 0)
					$add_id = $ROW->id;
				else
					$add_id = $ROW->replyto;
				
				if($searchPostResults)
				{
					if(!in_array($add_id, $SearchResults))
						array_push($SearchResults, $add_id);
				}
				else
				{
					if(!in_array($add_id, $SearchResults))
						array_push($SearchResults, $add_id);
				}
			}
		}
	}

	return $SearchResults;
}

function sxPhotoSearchResults($search)
{
	global $Link;
	global $DB_Photos;
	global $DB_Photos_Keywords;
	global $DB_Photos_Assoc;
	global $DB_Photos_Albums_Private;
	global $DB_Users_Assoc;
	global $THIS_USER;
	
	$SearchQuery = "";
	$SearchQuery2 = "";
	
	$SearchResults = array();
	$InitialList = array();
	
	$keywords = sxExtractKeywords($search);
	
	foreach($keywords as $word)
	{
		if(sxNonOperatingWord($word))
		{
			$SearchQuery .= "OR $DB_Photos_Keywords.keyword LIKE '%$word%' ";
			$SearchQuery .= "OR $DB_Photos.name LIKE '%$word%' ";
			$SearchQuery .= "OR $DB_Photos.description LIKE '%$word%' ";
			
			$SearchQuery2 .= "OR name LIKE '%$word%' ";
			$SearchQuery .= "OR description LIKE '%$word%' "; 
		}
	}
	$SearchQuery = substr($SearchQuery, 3);
	$SearchQuery2 = substr($SearchQuery2, 3);
	
	// Get all somewhat relevant photos with keywords
	$query = "SELECT DISTINCT $DB_Photos.id FROM $DB_Photos, $DB_Photos_Keywords
			  WHERE $DB_Photos.id=$DB_Photos_Keywords.photoid AND ($SearchQuery)
			  ORDER BY $DB_Photos.filename";
	$result = mysql_query($query, $Link) or queryError("1", mysql_error());
	while($sxPhotoID = mysql_fetch_object($result))
		array_push($InitialList, $sxPhotoID->id);
	
	// Get all somewhat relevant photos regardless of keywords
	$query = "SELECT DISTINCT id FROM $DB_Photos WHERE ($SearchQuery2) ORDER BY filename";
	$result = mysql_query($query, $Link) or queryError("124121", mysql_error());
	while($sxPhotoID = mysql_fetch_object($result))
	{
		// Make sure this is a new entry
		if(array_search($sxPhotoID->id, $InitialList) == FALSE)
			array_push($InitialList, $sxPhotoID->id);
	}
	
	foreach($InitialList as $photoid)
	{
		// Make a master key phrase of all keywords for this photo
		$MinePhoto = true;
		$KeyPhrase = " ";
		
		// Gather keywords
		$query2 = "SELECT keyword FROM $DB_Photos_Keywords WHERE photoid='$photoid'";
		$result2 = mysql_query($query2, $Link) or queryError("1", mysql_error());
		while($ROW2 = mysql_fetch_object($result2))
			$KeyPhrase .= $ROW2->keyword . " ";
		
		// Gather name and description
		$query2 = "SELECT name, description FROM $DB_Photos WHERE id='$photoid'";
		$result2 = mysql_query($query2, $Link) or queryError("1", mysql_error());
		$ROW2 = mysql_fetch_object($result2);
		
		$KeyPhrase .= $ROW2->name;
		$KeyPhrase .= $ROW2->description;
		$KeyPhrase = strtolower($KeyPhrase);
		
		// Figure out if photo should be mined
		if(sxMineElement($KeyPhrase, $keywords))
		{
			if(sxPhotoUserAccess($photoid, $THIS_USER) == TRUE)
				array_push($SearchResults, $photoid);
		}
	}
	return $SearchResults;	
}

function sxPhotoUserAccess($photoid, $userid)
{
	global $Link;
	global $DB_Photos_Assoc;
	global $DB_Photos_Albums_Private;
	global $DB_Users_Assoc;
	
	$sxPhotoAccess = FALSE;
	
	// Determine if photo is protected
	$query = "SELECT $DB_Photos_Assoc.id
	
	            FROM $DB_Photos_Assoc,
				     $DB_Photos_Albums_Private
					  
			   WHERE $DB_Photos_Albums_Private.albumid=$DB_Photos_Assoc.albumid AND
					 $DB_Photos_Assoc.photoid='$photoid'";
					 
	$result = mysql_query($query, $Link) or queryError("12522", mysql_error());
	
	// Photo is protected
	if(mysql_num_rows($result))
	{
		// Photo is protected in at least one album, but is it in at least one
		// public album?
		
		$sxInPublicAlbum = FALSE;
		
		$query = "SELECT albumid FROM $DB_Photos_Assoc WHERE photoid='$photoid'";
		$result = mysql_query($query, $Link) or queryError("135324", mysql_error());
		while($sxAlbum = mysql_fetch_object($result))
		{
			$query2 = "SELECT id FROM $DB_Photos_Albums_Private WHERE albumid='$sxAlbum->albumid'";
			$result2 = mysql_query($query2, $Link) or queryError("13874", mysql_error());
			if (mysql_num_rows($result2) == 0)
				$sxInPublicAlbum = TRUE;
		}	
		
		// Not in public album... continue checking out user
		if($sxInPublicAlbum == FALSE)
		{
			// Determine if user has access
			$query2 = "SELECT $DB_Photos_Assoc.id 
			
					  FROM $DB_Photos_Assoc,
						   $DB_Photos_Albums_Private,
						   $DB_Users_Assoc
								
					  WHERE $DB_Photos_Albums_Private.albumid=$DB_Photos_Assoc.albumid AND
							$DB_Users_Assoc.typeid=$DB_Photos_Albums_Private.typeid AND
							$DB_Photos_Assoc.photoid='$photoid' AND
							$DB_Users_Assoc.userid='$userid'";
							
			$result2 = mysql_query($query2, $Link) or queryError("3456876", mysql_error());
			
			// User has correct permissions, access granted
			if(mysql_num_rows($result2))
				$sxPhotoAccess = TRUE;
		}
		
		// Photo is in a public album, access granted
		else
			$sxPhotoAccess = TRUE;
	}
	
	// Photo is not protected, access granted
	else
		$sxPhotoAccess = TRUE;
		
	return $sxPhotoAccess;
}

function sxAlbumUserAccess($albumid, $userid)
{
	global $Link;
	global $DB_Photos_Albums_Private;
	global $DB_Users_Assoc;
	
	$sxAlbumAccess = FALSE;
	
	// Determine if album is protected
	$query = "SELECT albumid FROM $DB_Photos_Albums_Private WHERE albumid='$albumid'";
	$result = mysql_query($query, $Link) or queryError("12522", mysql_error());
	
	if(mysql_num_rows($result) > 0)
	{
		$query = "SELECT $DB_Photos_Albums_Private.id 
				
						  FROM $DB_Photos_Albums_Private,
							   $DB_Users_Assoc
									
						  WHERE $DB_Users_Assoc.typeid=$DB_Photos_Albums_Private.typeid AND
								$DB_Users_Assoc.userid='$userid' AND
								$DB_Photos_Albums_Private.albumid='$albumid'";
								
		$result = mysql_query($query, $Link) or queryError("12522", mysql_error());
		
		if(mysql_num_rows($result) > 0)
			$sxAlbumAccess = TRUE;
	}
	else
		$sxAlbumAccess = TRUE;
	
	return $sxAlbumAccess;
}

function sxForumSubscription($type, $id)
{
	global $THIS_USER;
	global $Link;
	global $DB_Forums_Notify;
	
	$query = "SELECT * FROM $DB_Forums_Notify WHERE userid='$THIS_USER' AND id_type='$type' AND id_num='$id'";
	$result = mysql_query($query, $Link) or queryError("2", mysql_error());
	if(mysql_num_rows($result))
		return true;
	else
		return false;
}

function sxForumSubscriptionNotify($topicid)
{
	global $Link;
	global $DB_Forums_Notify;
	global $DB_Forums_Posts;
	global $DB_Users;
	global $sxLangMail;
	global $sxSetup;
	global $THIS_USER;
	
	$query = "SELECT forumid FROM $DB_Forums_Posts WHERE id='$topicid'";
	$result = mysql_query($query, $Link) or queryError("2", mysql_error());
	$ROW = mysql_fetch_object($result);
	$forumid = $ROW->forumid;
	
	// Check post-specific notifications
	$query = "SELECT * FROM $DB_Forums_Notify WHERE id_type='topic' AND id_num='$topicid' AND notified='0'";
	$result = mysql_query($query, $Link) or queryError("2", mysql_error());
	if(mysql_num_rows($result))
	{
		while($ROW = mysql_fetch_object($result))
		{
			if ($ROW->userid != $THIS_USER)
			{
				$query2 = "SELECT * FROM $DB_Users WHERE id='$ROW->userid'";
				$result2 = mysql_query($query2, $Link) or queryError("2", mysql_error());
				$ROW2 = mysql_fetch_object($result2);
				
				$userEmail = $ROW2->email;
				
				$forumURL = $sxSetup['Url'].'/forums_topic.php?topicid='.$topicid;
				$message = str_replace('[LINK]', $forumURL, $sxLangMail['NewPost']);
				
				if(strlen($userEmail) > 0)
					@mail($userEmail, $sxLangMail['SubjectNewPost'], $message, "From: ".$sxSetup['AdminEmail']);
				
				$query2 = "UPDATE $DB_Forums_Notify 
						   SET notified='1'
						   WHERE id_type='topic' AND id_num='$topicid' AND userid='$ROW->userid'";
				$result2 = mysql_query($query2, $Link) or queryError("2", mysql_error());
			}
		}
	}
	
	// Check forum-specific notifications
	$query = "SELECT * FROM $DB_Forums_Notify WHERE id_type='forum' AND id_num='$forumid' AND notified='0'";
	$result = mysql_query($query, $Link) or queryError("2", mysql_error());
	if(mysql_num_rows($result))
	{
		while($ROW = mysql_fetch_object($result))
		{
			if ($ROW->userid != $THIS_USER)
			{
				$query2 = "SELECT * FROM $DB_Users WHERE id='$ROW->userid'";
				$result2 = mysql_query($query2, $Link) or queryError("2", mysql_error());
				$ROW2 = mysql_fetch_object($result2);
				$userEmail = $ROW2->email;
				
				$forumURL = $sxSetup['Url'].'/forums_view.php?forumid='.$forumid;
				$message = str_replace('[LINK]', $forumURL, $sxLangMail['NewPost']);
				
				if(strlen($userEmail) > 0)
					mail($userEmail, $sxLangMail['SubjectNewPost'], $message, "From: ".$sxSetup['AdminEmail']);
				
				$query2 = "UPDATE $DB_Forums_Notify 
						   SET notified='1'
						   WHERE id_type='forum' AND id_num='$forumid' AND userid='$ROW->userid'";
				$result2 = mysql_query($query2, $Link) or queryError("2", mysql_error());
			}
		}
	}
}

// NOTES:	Protects a private collection.
// RETURNS: ! REDIRECTS on condition
//--------------------------------------------------
function sxProtectCollection($cid)
{
	global $Link;
	global $DB_Collections_Private;	
	global $DB_Collections;	
	
	// Protect based on active flag
	$query = "SELECT active FROM $DB_Collections WHERE id='$cid' LIMIT 0,1";
	$result = mysql_query($query, $Link) or queryError("34517", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	if($ROW->active != 1)
	{
		header("Location:".$sxThemeConfig['Homepage']);
		die();
	}
	
	// Protect based on user permissions
	$types = array();
	
	$query = "SELECT usertype FROM $DB_Collections_Private WHERE collectionid='$cid'";
	$result = mysql_query($query, $Link) or queryError("110", mysql_error());
	
	// Collection is private
	if (mysql_num_rows($result) > 0)
	{
		// Form type array
		while ($ROW = mysql_fetch_object($result))
			array_push($types, $ROW->usertype);
		
		// Verify user against types
		if (sxVerifyUserType($THIS_USER, $types) == FALSE)
		{
			header("Location:".$sxThemeConfig['Homepage']);
			die();
		}
	}
}

// NOTES:	Returns name of collection.
// RETURNS: collection name (String)
//--------------------------------------------------
function sxFetchCollectionName($cid)
{
	global $Link;
	global $DB_Collections;	

	$query = "SELECT name FROM $DB_Collections WHERE id='$cid' LIMIT 0,1";
	$result = mysql_query($query, $Link) or queryError("34517", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->name;
}

// NOTES:	Determines if a user is of a certain 
//			type.  Accepts $typeid as an array of
//			types.
// RETURNS: TRUE if user belongs to any group from
//			$typeid array.
//--------------------------------------------------
function sxVerifyUserType($uid, $typeid)
{
	global $Link;
	global $DB_User_Assoc;
	
	$verify = FALSE;
	
	if (is_array($typeid))
	{
		foreach ($typeid as $key => $value)
		{
			$query = "SELECT id FROM $DB_User_Assoc WHERE userid='$uid' AND typeid='$value'";
			$result = mysql_query($query, $Link) or queryError("15626", mysql_error());
			
			if (mysql_num_rows($result) > 0)
				$verify = TRUE;
		}
	}
	else
	{
		$query = "SELECT id FROM $DB_User_Assoc WHERE userid='$uid' AND typeid='$typeid'";
		$result = mysql_query($query, $Link) or queryError("15626", mysql_error());
		
		if (mysql_num_rows($result) > 0)
			$verify = TRUE;
	}
	return $verify;
}

function sxCollectionItemOrder($cid)
{
	global $Link;
	global $DB_Collections;
	
	$sxQuery = "SELECT * FROM $DB_Collections WHERE id='".$cid."' LIMIT 0,1";
	$sxResult = mysql_query($sxQuery, $Link) or queryError("1938", mysql_error());
	$sxCollection = mysql_fetch_object($sxResult);

	$sxItemOrder = " ORDER BY ";
	
	switch($sxCollection->listorder)
	{
		case 'custom' :
			$sxItemOrder .= "position ASC";
			break;
			
		case 'name_asc' :
			$sxItemOrder .= "name ASC";
			break;
			
		case 'name_desc' :
			$sxItemOrder .= "name DESC";
			break;
			
		case 'id_asc' :
			$sxItemOrder .= "id ASC";
			break;
			
		case 'id_desc' :
			$sxItemOrder .= "id DESC";
			break;
			
		case 'date_asc' :
			$sxItemOrder .= "displaydate ASC";
			break;
			
		case 'date_desc' :
			$sxItemOrder .= "displaydate ASC";
			break;
			
		case 'timestamp_asc' :
			$sxItemOrder .= "timestamp ASC";
			break;
			
		case 'timestamp_desc' :
			$sxItemOrder .= "timestamp DESC";
			break;
			
		case 'username_asc' :
			$sxItemOrder .= "";
			break;
			
		case 'author_asc' :
			$sxItemOrder .= "author ASC";
			break;
			
		default :
			$sxItemOrder .= "name ASC";
			break;
	}
	return $sxItemOrder;
}

function echoCollectionItemList($cid, $root_cid)
{
	global $Link;
	global $DB_Collections;
	global $DB_Collections_Items;
	
	// Get collection info
	$sxQuery = "SELECT * FROM $DB_Collections WHERE id='".$cid."' LIMIT 0,1";
	$sxResult = mysql_query($sxQuery, $Link) or queryError("11513", mysql_error());
	$sxCollection = mysql_fetch_object($sxResult);
	
	if (($sxCollection->subcollection != 0) AND ($root_cid != $sxCollection->id))
	{
		echo '	<div class="sxSubCollection">'."\n";
		echo '		<div class="sxSubCollectionName"><a href="collection.php?cid=' . $sxCollection->id . '">' . $sxCollection->name . '</a></div>'."\n";
	}
	else
	{
		echo '<div class="sxCollection">'."\n";
		echo '	<div class="sxCollectionName">' . $sxCollection->name . '</div>'."\n";
	}
	
	// Echo subcollections
	$sxQuery2 = "SELECT * FROM $DB_Collections WHERE subcollection='".$cid."' ORDER BY name ASC";
	$sxResult2 = mysql_query($sxQuery2, $Link) or queryError("154345", mysql_error());
	while($sxSubcollection = mysql_fetch_object($sxResult2))
	{
		echoCollectionItemList($sxSubcollection->id, $root_cid);
	}
	
	// Form extra query parameters
	$sxItemLimit = "";
	$sxItemQueryAdd = sxCollectionItemOrder($cid) . $sxItemLimit;
	
	// Echo items from collection
	$sxQuery = "SELECT * FROM $DB_Collections_Items WHERE collectionid='".$cid."' AND active='1' $sxItemQueryAdd";
	$sxResult = mysql_query($sxQuery, $Link) or queryError("12465", mysql_error());
	while($sxItem = mysql_fetch_object($sxResult))
	{
		echo '		<div class="sxCollectionListItem">'."\n";
		echo '			<div class="sxCollectionListItemName"><a href="collection_item.php?itemid=' . $sxItem->id . '">' . $sxItem->name . '</a></div>'."\n";
		
		if($sxCollection->show_user == 1)
			echo '			<div class="sxCollectionListItemUser"><a href="admin/profile_view.php?user=' . getUsername($sxItem->userid) . '">' . getUsername($sxItem->userid) . '</a></div>'."\n";
		
		if($sxCollection->show_author == 1)
			echo '			<div class="sxCollectionListItemAuthor">' . $sxItem->author . '</div>'."\n";
		
		if($sxCollection->show_timestamp == 1)
			echo '			<div class="sxCollectionListItemTimestamp">' . fetchDate($sxItem->timestamp, 1, 0) . '</div>'."\n";
		
		if($sxCollection->show_date == 1)
			echo '			<div class="sxCollectionListItemDate">' . fetchDate($sxItem->displaydate, 2, 0) . '</div>'."\n";
		
		echo '			<div class="sxCollectionListItemText">' . $sxItem->itemtext . '</div>'."\n";
		
		if($sxCollection->show_additional == 1)
			echo '			<div class="sxCollectionListItemAdditional">' . $sxItem->additional . '</div>'."\n";
		
		echo '		</div>'."\n";
	}
	echo '</div>'."\n";
}

function sxFetchCollectionHeading($cid)
{
	$heading = sxFetchCollectionHeadingPre($cid);
	if(strlen($heading) > 0)
		$heading .= sxFetchCollectionName($cid);
	return $heading;
}

function sxFetchCollectionHeadingPre($cid)
{
	$path = array();
	$path = sxFetchCollectionPath($cid, $path);
	array_push($path, $cid);
	
	$heading = '';
	if (count($path) > 1)
	{
		for ($i = 0; $i < count($path)-1; $i++)
			$heading .= '<a href="collection.php?cid=' . $path[$i] . '">' . sxFetchCollectionName($path[$i]) . '</a> > ';
	}
	return $heading;
}


function sxFetchCollectionPath($cid, $path)
{
	$parent = sxFetchParentCollection($cid);	
	if($parent != 0)
	{
		$path = sxFetchCollectionPath($parent, $path);
		array_push($path, $parent);
	}
	return $path;
}

function sxFetchParentCollection($cid)
{
	global $Link;
	global $DB_Collections;	

	$query = "SELECT subcollection FROM $DB_Collections WHERE id='$cid' LIMIT 0,1";
	$result = mysql_query($query, $Link) or queryError("34517", mysql_error());
	$ROW = mysql_fetch_object($result);
	
	return $ROW->subcollection;
}

function sxEchoRecentComments($num)
{
	global $Link;
	global $DB_Comments;
	global $THIS_USER;
	global $sxLang;
	global $sxThemeConfig;

	$comment_array = sxFetchLatestComments($num);
	
	if($comment_array)
	{
		echo '<ul>'."\n";
		
		foreach($comment_array as $comment_id_value)
		{
			$query = "SELECT * FROM $DB_Comments WHERE id='$comment_id_value'";
			$result = mysql_query($query, $Link) or queryError("245", mysql_error());
			while($ROW = mysql_fetch_object($result))
			{
				echo '<li>';
				
				switch($ROW->sectionid)
				{
					// Journal entry
					case 1 :
						echo '<a href="journal.php?sxEntryID=' . $ROW->rowid . '&comments=' . $ROW->rowid . '#' . $ROW->rowid . '" title="' . getComponentName(1) . ' - ' . $ROW->name;
						break;
					
					// Photo	
					case 2 :
						echo '<a href="photo.php?photoid=' . $ROW->rowid . '&comments=' . $ROW->rowid . '#comments" title="' . getComponentName(2) . ' - ' . $ROW->name;
						break;
				}
				
				echo'">' . fetchDate($ROW->timestamp, 2, 0);
				echo ' - ' . limitStringForce($ROW->comments, $sxThemeConfig['HomepageCommentsStringLimit']) . '</a>'."\n";
				echo ' </li>'."\n";
			}
		}
		echo '</ul>'."\n";
	}
}

function sxFetchLatestComments($num)
{
	global $Link;
	global $DB_Comments;
	global $DB_Photos_Albums_Private;
	global $DB_Photos_Assoc;
	global $DB_Users_Assoc;
	global $THIS_USER;
	global $NOW;
	global $sxSetup;
	
	if (!$num)
		$num = 5;

	$sxComments = array();
	
	// Get event id's the user can access
	$query = "SELECT * FROM $DB_Comments ORDER BY timestamp DESC LIMIT 0, $num";
	$result = mysql_query($query, $Link) or queryError("240", mysql_error());
	while ($sxComment = mysql_fetch_object($result))
	{
		$add_comment = TRUE;
		
		// Private filter
		switch($sxComment->sectionid)
		{
			// Photos
			case '2' :
				if(sxPhotoUserAccess($sxComment->rowid, $THIS_USER) == FALSE)
					$add_comment = FALSE;
				break;
		}
		
		// Approval filter
		if (($sxSetup['CommentsApproval'] == 1) AND ($sxComment->approved != 1))
			$add_comment = FALSE;

		if ($add_comment == TRUE)
			array_push($sxComments, $sxComment->id);
	}
	
	if(count($sxComments) == 0)
		$sxComments = 0;
		
	return $sxComments;
}
function sxShowHomepageComponent($component)
{
	global $Link;
	global $DB_Polls;
	global $DB_Polls_Values;
	global $sxSetup;

	$show = TRUE;
	
	switch ($component)
	{
		// Polls
		case 'Polls' :
		
			if($sxSetup['HomepageCurrentPoll'] != 1)
				$show = FALSE;
				
			if(componentActive(4) == FALSE)
				$show = FALSE;
				
			$query = "SELECT id FROM $DB_Polls WHERE currentpoll='1' AND active='1'";
			$result = mysql_query($query) or queryError("7252", mysql_error());
			
			if (mysql_num_rows($result) == 0)
				$show = FALSE;
				
			break;
			
		// Forum topics
		case 'Forums' :
		
			if($sxSetup['HomepageRecentTopics'] != 1)
				$show = FALSE;
				
			if(componentActive(6) == FALSE)
				$show = FALSE;
				
			if(getRecentTopics(5) == 0)
				$show = FALSE;
				
			break;
			
		// Events
		case 'Events' :
		
			if($sxSetup['HomepageUpcomingEvents'] != 1)
				$show = FALSE;
				
			if(componentActive(8) == FALSE)
				$show = FALSE;
				
			if(getUpcomingEvents(5) == 0)
				$show = FALSE;
				
			break;
			
		// Comments
		case 'Comments' :
		
			if($sxSetup['HomepageRecentComments'] != 1)
				$show = FALSE;
				
			if($sxSetup['CommentsEnabled'] != 1)
				$show = FALSE;
				
			if(sxFetchLatestComments(5) == 0)
				$show = FALSE;
				
			break;
			
		// Event Calendar
		case 'Calendar' :
		
			if($sxSetup['HomepageMiniCalendar'] != 1)
				$show = FALSE;
				
			if(componentActive(8) == FALSE)
				$show = FALSE;
				
			break;
			
		// Random Photos
		case 'Photos' :
			
			if($sxSetup['HomepageRandomPhotos'] != 1)
				$show = FALSE;
				
			if(componentActive(2) == FALSE)
				$show = FALSE;
				
			if(getRandomPhotos() == 0)
				$show = FALSE;
				
			break;
	}
	return $show;
}

function sxDirCopy($srcdir, $dstdir)
{
	$error = FALSE;
	
	// Create dir if not there
	if(@is_dir($dstdir) == FALSE)
		@mkdir($dstdir);
	
	// Open dir
	if($curdir = @opendir($srcdir))
	{
		// Traverse files
		while($file = @readdir($curdir))
		{
			if($file != '.' && $file != '..')
			{
				$srcfile = $srcdir . '\\' . $file;
				$dstfile = $dstdir . '\\' . $file;
				
				// File
				if(@is_file($srcfile))
				{
					if(@is_file($dstfile))
						$ow = @filemtime($srcfile) - @filemtime($dstfile);
					else
						$ow = 1;
						
					if($ow > 0)
					{
						if(@copy($srcfile, $dstfile))
							@touch($dstfile, @filemtime($srcfile));
						else
							$error = TRUE;
					}                  
				}
				
				// Dir
				elseif(@is_dir($srcfile))
					$error = sxDirCopy($srcfile, $dstfile, $verbose);
			}
		}
		@closedir($curdir);
	}
	return $error;
}

function sxCheckVersion()
{
	$handle = @fopen("http://sitex.bjsintay.com/version.txt", "r");
	
	if($handle)
	{
		$current_version = @fread($handle, 200);
		@fclose($handle);
		return trim($current_version);
	}
	else
		return FALSE;
}

function sxFetchPanelWarnings()
{
	global $sxLang;
	$warnings = array($sxLang['WarningTitle']);
	// Setup files warning
	if(sxSetupFilesExist() == TRUE)
		array_push($warnings, $sxLang['WarningSetupFiles']);
		
	// Version warning	
//	if (sxCheckVersion() != $sxSetup['Version'])
//	array_push($warnings, sxCheckVersion());	

	// PHP Safe Mode = On
	if(ini_get('safe_mode') == TRUE)
		array_push($warnings, $sxLang['WarningSafeModeON']);
	
	if(count($warnings) > 1)	
		return $warnings;
	else
		return FALSE;
		
}

function sxSetupFilesExist()
{
	$files = array('setup/setup.php',
	               'setup/upgrade.php');
	$results = array();
	$exists = FALSE;
	
	// Attempt to open files in list, form boolean array of results
	foreach($files as $key => $filename)
	{
		$open_result = @fopen(sxPathToRoot().$filename, 'r');
		if( (is_bool($open_result) == TRUE) AND ($open_result == FALSE) )
			$results[$key] = FALSE;
		else
		{
			$results[$key] = TRUE;
			$exists = TRUE;
		}
	}		
	
	return $exists;
}

function sxDebugPrintR($mixed)
{
	echo '<pre>';
	print_r($mixed);
	echo '</pre>';
}

// NOTES:	Fixes old navigation ordering problems.
// RETURNS: null
//--------------------------------------------------
function sxSyncPositionsNavigation()
{
	global $Link;
	global $DB_Navigation;
	
	$counter = 1;	//Initialize counter to starting value
	
	$query = "SELECT * FROM $DB_Navigation ORDER BY position";
	$result = mysql_query($query, $Link) or queryError("7254", mysql_error());
	
	while($ROW = mysql_fetch_object($result))
	{
		//Check to see if the position is the same as the counter
		if($ROW->position != $counter)
		{
			$query2 = "UPDATE $DB_Navigation SET position='$counter' WHERE id='$ROW->id'";	
			$result2 = mysql_query($query2, $Link) or queryError("7253", mysql_error());
		}
		$counter = $counter + 1;
	}
}

// Clears contents of a directory
function cleardir($dir)
{
	if(is_dir($dir))
	{
		$dir = (substr($dir, -1) != "/")? $dir."/":$dir;
		$opendir = opendir($dir);
		while($file = readdir($opendir))
		{
			if(!in_array($file, array(".", "..")))
			{
				if(!is_dir($dir.$file))
					unlink($dir.$file);
				else
					deletedir($dir.$file);
			}
		}
		closedir($opendir);
	}
}

// Clears contents of directory, then removes directory
function deletedir($dir)
{
	if(is_dir($dir))
	{
		$dir = (substr($dir, -1) != "/")? $dir."/":$dir;
		$opendir = opendir($dir);
		while($file = readdir($opendir))
		{
			if(!in_array($file, array(".", "..")))
			{
				if(!is_dir($dir.$file))
					unlink($dir.$file);
				else
					deletedir($dir.$file);
			}
		}
		closedir($opendir);
		rmdir($dir);
	}
}

//checks to see if google analytics field is set, and if so prints the GA code
function sxGoogleAnalytics(){
	global $sxSetup;
	if(!($sxSetup['GoogleAnalytics'] == NULL))
	{
		echo "<script type=\"text/javascript\">\n";
		echo "var _gaq = _gaq || [];\n";
		echo "_gaq.push(['_setAccount', '" . $sxSetup['GoogleAnalytics'] . "']);\n";
		echo "']);\n";
		echo "_gaq.push(['_trackPageview']);\n";
		echo "(function() {\n";
		echo "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n";
		echo "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n";
		echo "(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);\n";
		echo "})();\n";
		echo "</script>\n";
	}
}

//checks to see if gallery lightbox is enabled, if so prints JS
function sxAlbumUseLightbox(){
	global $sxSetup;
	if(($sxSetup['AlbumUseLightbox'] == 1))
	{
	echo "<!-- jQuery lightBox plugin -->\n";
    echo "<script type=\"text/javascript\" src=\"includes/lightbox/jquery.js\"></script>\n";
    echo "<script type=\"text/javascript\" src=\"includes/lightbox/jquery.lightbox-0.5.js\"></script>\n";
    echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"includes/lightbox/css/jquery.lightbox-0.5.css\" media=\"screen\" />\n";
	echo "<script type=\"text/javascript\">\n";
	echo "$(function() {\n";
	echo "$('a[@rel*=lightbox]').lightBox();\n"; // Select all links that contain lightbox in the attribute rel
	echo "});\n";
	echo "</script>\n";
	echo "<!-- end jQuery lightBox plugin -->\n";
	}
}
//loads batch uploader
function sxBatchUploader(){
	$currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = $parts[count($parts) - 1];
	if ( $currentFile == "photo_batch_up.php" ) {
	echo "<!-- code for batch uploader -->\n";
	echo "<script type=\"text/javascript\" src=\"../includes/uploadify/jquery-1.3.2.min.js\"></script>\n";
	echo "<script type=\"text/javascript\" src=\"../includes/uploadify/swfobject.js\"></script>\n";
	echo "<script type=\"text/javascript\" src=\"../includes/uploadify/jquery.uploadify.v2.1.0.min.js\"></script>\n";
	echo "<script type=\"text/javascript\" src=\"../includes/uploadify/uploadcfg.js\"></script>\n";
	echo "<!-- end batch uploader -->\n";
	}
}
?>
Return current item: SiteX