<?php
/*
 **************************************************************************************************
 *    Copyright (c) 2010-2012 Just Another Video script
 *
 * 	  This file is part of Just Another Video Script.
 *    Version 1.4.3
 *    info@justanothervideoscript.com
 **************************************************************************************************
 *    Come to website for support or buying additional plugins/modules.
 *    http://justanothervideoscript.com/
 **************************************************************************************************
 *    By using this software you agree that you have read and acknowledged our End-User License
 *    Agreement available at http://justanothervideoscript.com/license and can be bound by it.
 **********************************************************************************
 */
global $db,$sitepath,$loggedIn,$templateimagepath ;
function datediff($str_start, $str_end) {
	$defdate = $str_start ;
	$str_start = strtotime($str_start) ;
	$str_end = strtotime($str_end) ;
	$nseconds = $str_end - $str_start ;
	$ndays = floor($nseconds / 86400) ;
	$nseconds = $nseconds % 86400 ;
	$nhours = floor($nseconds / 3600) ;
	$nseconds = $nseconds % 3600 ;
	$nminutes = floor($nseconds / 60) ;
	$nseconds = $nseconds % 60 ;
	$retString = "" ;
	if ($ndays > 0) {
		$retString .= $defdate ;
		return "@ ".$retString ;
	}
	if ($nhours > 0) {
		$retString .= " ".$nhours." hour" ;
		if ($nhours > 1)
		$retString .= "s" ;
	}
	if ($nminutes > 0) {
		$retString .= " ".$nminutes." minute" ;
		if ($nminutes > 1)
		$retString .= "s" ;
	}
	if (strcmp($retString, "") == 0)
	$retString = "< 1 minute" ;
	return $retString." ago" ;
}
if (isset($_GET['user'])) {
	$db->query("SELECT * FROM member WHERE username = '".quote_smart($_GET['user'])."'") ;
	$idres = $db->fetch() ;
	$profileid = $idres['id'] ;
	$avatarname = $idres['avatar'] ;
	$avatargender = $idres['gender'] > 0 ? 'female' : 'male' ;
}
$db->query("SELECT * FROM member WHERE username = '".$_SESSION['session_username']."'") ;
$userres = $db->fetch() ;
$userid = $userres['id'] ;
$fromID = $userid ;
$toID = $profileid ;
$avatarpath = $templateimagepath."default_".$avatargender."_avatar.png" ;
if (@file_exists("uploads/avatars/".$avatarname) && ($avatarname != "")) {
	$avatarpath = "uploads/avatars/".$avatarname ;
	$avatarpath = $sitepath.str_replace(" ", "%20", $avatarpath) ;
}
$userandavatar = '<a href="'.$sitepath.'profile/'.quote_smart($_GET['user']).'"><img src="'.$avatarpath.'" border=0 height=22px width=22px>'.quote_smart($_GET['user']).'&nbsp;</a>' ;
//send message
if (isset($_POST['submit']) && ($_POST['type'] == 'sendmessage') && (canMessage() == '') && ($loggedIn)) {
	$messagebody = quote_smart($_POST['msgbody']) ;
	$db->query("INSERT INTO message (fromid, toid, body, sentdate, msgread) VALUES (".quote_smart($_POST['from']).",".quote_smart($_POST['to']).",'".$messagebody."',".time().",0)") ;
	$message = "Thank you, your message has been sent to <a href=\"".$sitepath."profile/".quote_smart($_GET['user'])."\">".quote_smart($_GET['user'])."</a>" ;
	
	 			//send mail to receiving user				
	 				if (getSetting("mail_friend_pm", $db) == '1') {
	 					$db->query("SELECT username FROM member WHERE id = '".quote_smart($_POST['from'])."'") ;
						$sendmember = $db->fetch() ;
						$msg = getEmailformat("email_friend_pm") ;
						$msg = str_replace(array('[POSTER]', '[SITEURL]'), array($sendmember['username'], $sitepath), $msg);
						$db->query("SELECT username FROM member WHERE id = '".quote_smart($_POST['to'])."'") ;
						$recmember = $db->fetch() ;
						$db->query("SELECT email, username FROM member WHERE USERNAME = '".$recmember['username']."' LIMIT 1") ;
						$mailinfo = $db->fetch() ;
						sendmail(array(array("email"=>$mailinfo['email'], "name"=>$mailinfo['username'])), 'You have a new message from '.$username, $msg, 'no') ;
						echo '<h3>Message has been send</h3>';
				}
}
if (($loggedIn) && ($profileid != 0) && ($userid != 0)) {
	$action = quote_smart($_GET['act']) ;
	//arr - Accept request from profile member
	if ($action == 'arr') {
		//update friend record where userid = loggedinuser and friendid = profileuser to approved = 0, removed = 0
		$db->query('UPDATE friend SET friend_approved = 1 WHERE userid='.$userid.' AND friendid='.$profileid) ;
		$db->query('UPDATE friend SET friend_removed = 0 WHERE userid='.$userid.' AND friendid='.$profileid) ;
	}
	//rfa - Profile member removed you - click here to ask again
	if ($action == 'rfa') {
		//delete old friend record where userid = loggedinuser and friendid = profileuser
		$db->query('DELETE FROM friend WHERE userid='.$userid.' AND friendid='.$profileid) ;
		//insert new friend record with userid = profileuser, friendid = loggedinuser, approved = 0, removed = 0
		$db->query('INSERT INTO friend (userid,friendid,friend_approved,friend_removed) VALUES ('.$profileid.','.$userid.',0,0)') ;
	}
	//csr - Your sent request is pending - cancel the request
	if ($action == 'csr') {
		//delete friend record where userid = profileuser and friendid = loggedinuser
		$db->query('DELETE FROM friend WHERE userid='.$profileid.' AND friendid='.$userid) ;
	}
	//rmaf - You have removed this friend request - this just removes the remove! Makes it a live request again
	if ($action == 'rmaf') {
		//update where userid = profileuser and friendid = loggedinuser set removed = 0
		$db->query('UPDATE friend SET friend_removed = 0 WHERE userid='.$profileid.' AND friendid='.$userid) ;
	}
	//af - Send a request to profile user
	if ($action == 'af') {
		//check there isn't already a record
		$db->query('SELECT * FROM friend WHERE userid='.$profileid.' AND friendid='.$userid) ;
		if ($db->numRows() < 1) {
			$db->query('INSERT INTO friend (userid,friendid,friend_approved,friend_removed) VALUES ('.$profileid.','.$userid.',0,0)') ;
			//send mail to the receiving user to notify him
			if (getSetting("mail_friend_request", $db) == '1') {
				$db->query("SELECT username FROM member WHERE id = '".$userid."' LIMIT 1") ;
				$memberid = $db->fetch() ;

				$msg = getEmailformat("email_request_friend") ;
				$msg = str_replace(array('[FRIENDREQUEST]', '[SITEURL]'), array($memberid['username'], $sitepath), $msg);

				$db->query("SELECT email, username FROM member WHERE id = '".$profileid."' LIMIT 1") ;
				$mailinfo = $db->fetch() ;

				sendmail(array(array("email"=>$mailinfo['email'], "name"=>$mailinfo['username'])), $memberid['username'].' requested to be friend', $msg) ;
			}
			
			
		}
		else {
			//if already sent, just update it
			$db->query('UPDATE friend SET friend_removed = 0 WHERE userid='.$profileid.' AND friendid='.$userid) ;
		}
	}
	//afr - Remove approved friend
	if ($action == 'afr') {
		//Remove: check if i am the original requester
		$db->query('SELECT * FROM friend WHERE userid='.$profileid.' AND friendid='.$userid) ;
		if ($db->numRows() > 0) {
			//if i am, just make it 'removed = 1 approved = 0' goes back to a request, but removed
			$db->query('UPDATE friend SET friend_removed = 1 WHERE userid='.$profileid.' AND friendid='.$userid) ;
			$db->query('UPDATE friend SET friend_approved = 0 WHERE userid='.$profileid.' AND friendid='.$userid) ;
		}
		else {
			//if i'm not, need to reverse (delete and insert) the request, removed =1 approved = 0
			$db->query('DELETE FROM friend WHERE userid='.$userid.' AND friendid='.$profileid) ;
			$db->query('INSERT INTO friend (userid,friendid,friend_approved,friend_removed) VALUES ('.$profileid.','.$userid.',0,1)') ;
		}
	}

	if ($action == 'bl') {
		$db->query('SELECT * FROM blocked WHERE blocker_id='.$userid.' AND blockee_id='.$profileid) ;
		if ($db->numRows() < 1) {
			$db->query('INSERT INTO blocked (blocker_id,blockee_id) VALUES ('.$userid.','.$profileid.')') ;
		}
	}
	if ($action == 'sb') {
		$db->query('SELECT * FROM subscription WHERE userid='.$userid.' AND subscribedtoid='.$profileid) ;
		if ($db->numRows() < 1) {
			$db->query('INSERT INTO subscription (userid,subscribedtoid) VALUES ('.$userid.','.$profileid.')') ;
		}
	}
	if ($action == 'ub') {
		$db->query('DELETE FROM blocked WHERE blocker_id='.$userid.' AND blockee_id='.$profileid) ;
	}
	if ($action == 'us') {
		$db->query('DELETE FROM subscription WHERE userid='.$userid.' AND subscribedtoid='.$profileid) ;
	}
}
function echotable($ulget, $res, $page, $url) {
	global $db,$sitepath,$templateimagepath ;
	$getuser = quote_smart($_GET['user']);
		$vidcount = 0 ;
		foreach ($res as $key=>$value) {
			if ($value['added'] < time()) {
				$visible = true ;
				if ($visible) {
					$vidcount++ ;
				}
			}
		}
		switch ($ulget) {
			case '1':
				$perpage = getSetting("mp_friend", $db) ;
			break ;
			case '2':
				$perpage = getSetting("mp_fav", $db) ;
			break ;
			case '3':
				$perpage = getSetting("mp_media", $db) ;
			break ;
			case '4':
				$perpage = getSetting("mp_sub", $db) ;
			break ;		
		}
		$size = sizeof($res) ;
		$pages = ceil($vidcount / $perpage) ;
		$pageLinks = "<div align=left>Pages: " ;
		$pp = $page - 1 ;
		switch ($ulget) {
			case '1':
				$pageoption = 'doFriend' ;
			break ;
			case '2':
				$pageoption = 'doFav' ;
			break ;
			case '3':
				$pageoption = 'doMedia' ;
			break ;
			case '4':
				$pageoption = 'doSub' ;
			break ;		
		}
		if ($pp >= 1) {
			$pageLinks .= '<a class="prevp" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$pp.'\');">Previous Page </a>' ;
		}
		if ($pages > 10 && $page > 6) {
			if (!$nomr) {
				$pageLinks .= '<a title="1" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\'1\');">1</a> ... ' ;
			}
			else {
				$pageLinks .= '<a title="1" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\'1\');">1</a> ... ' ;
			}
		}
		$p = 1 ;
		$stopat = ($pages <= 10) ? $pages : 10 ;
		if ($pages > 10 && $page > 5) {
			$p = $page - 5 ;
			$stopat = $page + 5 ;
			if ($stopat > $pages)
				$stopat = $pages ;
		}
		for ($p; $p <= $stopat; $p++) {
			if (!$nomr) {
				if ($p == $page)
					$pageLinks .= "$p " ;
				else
					$pageLinks .= '<a title="'.$p.'" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$p.'\');">'.$p.'</a> ' ;
			}
			else {
				if ($p == $page)
					$pageLinks .= "$p " ;
				else
					$pageLinks .= '<a title="'.$p.'" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$p.'\');">'.$p.'</a> ' ;
			}
		}
		if ($pages > 10) {
			if (!$nomr) {
				$pageLinks .= '... <a title="'.$pages.'" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$pages.'\');">'.$pages.'</a>' ;
			}
			else {
				$pageLinks .= '... <a title="'.$pages.'" style="cursor: hand; cursor: pointer;" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$pages.'\');">'.$pages.'</a>' ;
			}
		}
		$np = $page + 1 ;
		if ($np <= $pages) {
			$pageLinks .= '<a class="nextp" style="cursor: hand; cursor: pointer;" title="'.$np.'" onClick="'.$pageoption.'(\''.$getuser.'\',\''.$np.'\');"> Next Page</a>' ;
		}
		$pageLinks .= "</div>" ;
		$output = '<div class="tab-cont"><ul class="related-video-thumbs-list">' ;
		$count = 0 ;
		$page-- ;
		//Clear previous page results
		for ($i = 0; $i < $perpage * $page; $i++)
		unset($res[$i]) ;
		$colcount = 0 ;

		switch ($ulget) {
			case '1':
				foreach ($res as $key=>$value) {
					if ($value['activationkey'] == 0) {
						$count++ ;
						$avatargender = $value['gender'] > 0 ? 'female' : 'male' ;
						$avatar = $templateimagepath."default_".$avatargender."_avatar.png" ;
						if (@file_exists("uploads/avatars/".$value['avatar']) && ($value['avatar'] != "")) {
							$avatar = $sitepath."uploads/avatars/".$value['avatar'] ;
						}
						$avatar = str_replace(" ", "%20", $avatar) ;
						$id = $value['id'] ;
						$username = $value['username'] ;
						$db->query("SELECT id FROM media WHERE status='true' AND poster ='".$username."' ORDER BY allviews DESC") ;
						$mediacount = $db->numRows() ;
						$rres = $db->fetch() ;
						$db->query("SELECT * FROM member LEFT JOIN friend ON (member.id = friend.friendid OR member.id = friend.userid) WHERE (friend.userid =".$id." OR friend.friendid =".$id.") AND (username!='".$username."') AND friend.friend_removed=0 AND friend.friend_approved=1 GROUP BY member.id") ;
						$friendcount = $db->numRows() ;
						$value['username'] = force_length($value['username'], 25) ;
						$output .= "<li>" ;
						$output .= '<div class="related-col-pic"><a href="'.$sitepath.'profile/'.$username.'"><img class="thumb" src="'.$avatar.'" /></a></div>' ;																		
						$output .= '<div class="related-col-body"><a href="'.$sitepath.'profile/'.$username.'">'.$value['username'].'</a><br />Friends: '.$friendcount.'<br />Media: '.$mediacount.'<br /></div>' ;
						$output .= "</li>" ;
						$colcount++ ;
						if ($count == $perpage)
						break ;
					}
				}
			break;
			case '2':
			case '3':
				foreach ($res as $key=>$value) {
					if ($value['added'] < time()) {
						$visible = true ;
						if ($visible) {
							$count++ ;
							$thumb = $sitepath."uploads/thumbs/".$value['fileid']."/".$value['mainthumb'].".jpg" ;
								if ($thumb == '') {
									$thumb = $templateimagepath."default_video_thumb.jpg" ;
								}
							$thumb = str_replace(" ", "%20", $thumb) ;		
									
							$db->query("SELECT * FROM rating WHERE id = ".$value['id']) ;
							$resR = $db->fetch() ;
							$title = url_encode($value['title']) ;
							$value['title'] = force_length($value['title'], 55) ;
							$viewstring = $value['allviews'] ;
							
			      $output .= "<li>" ;
			      
			      if ($value['mediatype'] == 'video') {
			     		$output .= '<div class="related-col-pic"><a href="'.$sitepath.'play/'.$title.'"><img class="thumb" src="'.$thumb.'" alt="'.$title.'" title="'.$title.'" id="rotate_'.$value['fileid'].'_'.getSetting("thumbsnumber", $db).'_viewed" /></a></div>' ;
			      } else {
			      		$output .= '<div class="related-col-pic"><a href="'.$sitepath.'play/'.$title.'"><img class="thumb" src="'.$thumb.'" alt="'.$title.'" title="'.$title.'" /></a></div>' ;
			      }
				if ($value['hd'] == '1') {
					$output .= "<img class='hd' width='20px' height='15px' src='".$templateimagepath."hd_logo.png' />" ;
				}
			      $output .= '<div class="related-col-body"><a href="'.$sitepath.'play/'.$title.'">'.str_replace("-", " ", $title).'<br /><div class="thumbholder">Duration: '.$value['duration'].'<br />views: '.$viewstring.'<br />'.show_rating($value['id']).'</div></a></div>';
							$output .= "</li>" ;
							if ($count == $perpage)
								break ;
						}
					}
				}
			break;
			case '4':
				foreach ($res as $key=>$value) {
					if ($value['activationkey'] == 0) {
						$count++ ;
						$avatargender = $value['gender'] > 0 ? 'female' : 'male' ;
						$avatar = $templateimagepath."default_".$avatargender."_avatar.png" ;
						if (@file_exists("uploads/avatars/".$value['avatar']) && ($value['avatar'] != "")) {
							$avatar = $sitepath."uploads/avatars/".$value['avatar'] ;
						}
						$avatar = str_replace(" ", "%20", $avatar) ;
						$id = $value['id'] ;
						$username = $value['username'] ;
						$db->query("SELECT id FROM media WHERE status='true' AND poster ='".$username."' ORDER BY allviews DESC") ;
						$mediacount = $db->numRows() ;
						$rres = $db->fetch() ;
						$db->query("SELECT * FROM member LEFT JOIN friend ON (member.id = friend.friendid OR member.id = friend.userid) WHERE (friend.userid =".$id." OR friend.friendid =".$id.") AND (username!='".$username."') AND friend.friend_removed=0 AND friend.friend_approved=1 GROUP BY member.id") ;
						$friendcount = $db->numRows() ;
						$value['username'] = force_length($value['username'], 25) ;
						$output .= "<li>" ;
						$output .= '<div class="related-col-pic"><a href="'.$sitepath.'profile/'.$username.'"><img class="thumb" src="'.$avatar.'" /></a></div>' ;								
						$output .= '<div class="related-col-body"><a href="'.$sitepath.'profile/'.$username.'">'.$value['username'].'</a><br />Friends: '.$friendcount.'<br />Media: '.$mediacount.'<br /></div>' ;
						$output .= "</li>" ;					
						$colcount++ ;
						if ($count == $perpage)
							break ;
					}
				}
			break;
		}

$output .= "</ul></div>" ;
if ($pages > 0)
$output .= $pageLinks ;
return $output ;




}

function getFriends($page) {
	global $db ;
	$getuser = quote_smart($_GET['user']);
	$sitefolder = getSetting("sitefolder", $db) ;
	$path = "http://".$_SERVER['SERVER_NAME'].$sitefolder."profile/".$getuser."/frd" ;
	$db->query("SELECT * FROM member WHERE username = '".$getuser."'") ;
	$idres = $db->fetch() ;
	$userid = $idres['id'] ;
	$db->query("SELECT * FROM member LEFT JOIN friend ON (member.id = friend.friendid OR member.id = friend.userid) WHERE (friend.userid =".$userid." OR friend.friendid =".$userid.") AND (username!='".$getuser."') AND friend.friend_removed=0 AND friend.friend_approved=1 GROUP BY member.id") ;
	$resLV = $db->fetchAll() ;
	if (sizeof($resLV) > 0) {
		$output = "<div align=center><h5>".$getuser."'s friends</h5></div>" ;
		if (isset($page))
			$output .= echotable(1, $resLV, $page, $path) ;
		else
			$output .= echotable(1, $resLV, $page, $path) ;
	}
	else {
		$output .= "<div align=center><h5>".$getuser." has no friends</h5></div>" ;
	}
	return $output ;
}
function getFavorites($page) {
	global $db,$sitepath ;
	$getuser = quote_smart($_GET['user']);
	$db->query("SELECT * FROM member WHERE username = '".$getuser."'") ;
	$idres = $db->fetch() ;
	$userid = $idres['id'] ;
	$query = "SELECT * FROM `media` LEFT JOIN favorite ON favorite.vidid = media.id WHERE (`status` ='true') AND (favorite.userid = ".$userid.") ORDER BY `added` DESC" ;
	$db->query($query) ;
	$resLV = $db->fetchAll() ;
	if (sizeof($resLV) > 0) {
		$output = "<div align=center><h5>".$getuser."'s favorite media</h5></div>" ;
		if (isset($page))
			$output .= echotable(2, $resLV, $page, $sitepath) ;
		else
			$output .= echotable(2, $resLV, $page, $path) ;
	}
	else {
		$output = "<div align=center><h5>".$getuser." has no favorites</h5></div>" ;
	}
	return $output ;
}
function getMedia($page) {
	global $db,$sitepath ;
	$getuser = quote_smart($_GET['user']);
	$path = $sitepath."profile/".$getuser."/med" ;
	$query = "SELECT * FROM `media` WHERE (`status` ='true') AND (poster ='".$getuser."') ORDER BY `added` DESC" ;
	$db->query($query) ;
	$resLV = $db->fetchAll() ;
	if (sizeof($resLV) > 0) {
		$output = "<div align=center><h5>".$getuser."'s uploaded media</h5></div>" ;
		if (isset($page) && (quote_smart($_GET['act']) == 'med'))
			$output .= echotable(3, $resLV, $page, $path) ;
		else
			$output .= echotable(3, $resLV, $page, $path) ;
	}
	else {
		$output = "<div align=center><h5>".$getuser." has not uploaded any media yet</h5></div><br/><br/>" ;
	}
	return $output ;
}
function getSubscriptions($page) {
	global $db,$sitepath ;
	$getuser = quote_smart($_GET['user']);
	$path = $sitepath."profile/".$getuser."/sub" ;
	$db->query("SELECT * FROM member WHERE username = '".$getuser."'") ;
	$idres = $db->fetch() ;
	$userid = $idres['id'] ;
	$db->query("SELECT * FROM member LEFT JOIN subscription ON member.id = subscription.subscribedtoid WHERE subscription.userid = ".$userid) ;
	$resLV = $db->fetchAll() ;
	if (sizeof($resLV) > 0) {
		$output = "<div align=center><h5>".$getuser."'s subscriptions</h5></div>" ;
		if (isset($page))
			$output .= echotable(4, $resLV, $page, $path) ;
		else
			$output .= echotable(4, $resLV, $page, $path) ;
	}
	else {
		$output = "<div align=center><h5>".$getuser." has no subscriptions</h5></div>" ;
	}
	return $output ;
}
function profileTabs() {
	global $db ;
	$getuser = quote_smart($_GET['user']);
	$sitefolder = getSetting("sitefolder", $db) ;
	$sitetemplate = getSetting("sitetemplate", $db) ;
	$rootpath = $_SERVER['DOCUMENT_ROOT'].$sitefolder ;
	$path = "http://".$_SERVER['SERVER_NAME'].$sitefolder ;
	$link = $path.'profile/'.$getuser.'/' ;
	$activetab = quote_smart($_GET['act']) ;
	$medtab = "" ;
	$favtab = "" ;
	$subtab = "" ;
	$frdtab = "" ;
	$grptab = "" ;
	$tabs = '<!-- s:TABS -->

			<ul class="c-tabs">

				<li'.$medtab.'><span><a style="cursor: hand; cursor: pointer;" title="Media" onClick="doMedia(\''.$getuser.'\',\'1\');" >Media</a></span></li>

				<li'.$favtab.'><span><a style="cursor: hand; cursor: pointer;" title="Favorites" onClick="doFav(\''.$getuser.'\',\'1\');">Favorites</a></span></li>

				<li'.$subtab.'><span><a style="cursor: hand; cursor: pointer;" title="Subscriptions" onClick="doSub(\''.$getuser.'\',\'1\');">Subscriptions</a></span></li>

				<li'.$frdtab.'><span><a style="cursor: hand; cursor: pointer;" title="Friends" onClick="doFriend(\''.$getuser.'\',\'1\');">Friends</a></span></li>

			</ul>

			<!-- e:TABS -->' ;
	return $tabs ;
}
function checkMemberExists() {
	global $db,$loggedIn ;
	$getuser = quote_smart($_GET['user']);
	$path = getSetting('sitefolder', $db) ;
	$sitepath = 'http://'.$_SERVER['SERVER_NAME'].$path ;
	$message = "" ;
	if (!isset($getuser)) {
		// NO USER IN URL
		$message = "Sorry - this user does not exist or is no longer registered" ;
	}
	else {
		$username = mysql_real_escape_string($getuser) ;
		$db->query("SELECT * FROM member WHERE username = '".$username."'") ;
		$registeredUser = false ;
		if ($db->numRows() < 1) {
			$message = "Sorry - this user does not exist or is no longer registered" ;
		}
	}
	return $message ;
}
function canMessage() {
	global $db,$loggedIn ;
	$getuser = quote_smart($_GET['user']);
	$path = getSetting('sitefolder', $db) ;
	$sitepath = 'http://'.$_SERVER['SERVER_NAME'].$path ;
	$message = "" ;
	if (!isset($getuser)) {
		// NO USER IN URL
		$message = "Sorry - this user does not exist or is no longer registered" ;
	}
	else {
		$username = mysql_real_escape_string($getuser) ;
		//Check it's a registered user
		$db->query("SELECT * FROM member WHERE username = '".$username."'") ;
		$registeredUser = false ;
		if ($db->numRows() >= 1) {
			$registeredUser = true ;
			$res = $db->fetch() ;
			$profileid = $res['id'] ;
			$profileprivacylevel = $res['profile_privacy'] ;
			// NOW CHECK THAT THIS USER IS ALLOWED TO VIEW THE PROFILE

			
			// IF USER IS LOGGED IN CHECK IF USER IS BLOCKED
			$blocked = false ;
			$userisfriend = false ;
			$userisowner = false ;
			$useridadmin = false ;
			if ($loggedIn) {
				$db->query("SELECT * FROM member WHERE username = '".$_SESSION['session_username']."'") ;
				$res = $db->fetch() ;
				$loggedInid = $res['id'] ;
				$db->query("SELECT * FROM blocked WHERE blocker_id = ".$profileid." AND blockee_id = ".$loggedInid) ;
				$blocked = ($db->numRows() >= 1) ;
				// CHECK IF USER IS THE OWNER OF THIS PROFILE
				$userisowner = ($profileid == $loggedInid) ;
				// CHECK IF USER IS ON THE OWNER'S FRIENDS LIST AND IS APPROVED
				$db->query("SELECT * from friend WHERE ((userid = ".$profileid." AND friendid = ".$loggedInid.") OR  (friendid = ".$profileid." AND userid = ".$loggedInid.")) AND friend_approved = 1") ;
				$userisfriend = ($db->numRows() > 0) ;
			}

				if ($blocked) {
					$message = "<h3>Sorry, this member has chosen not to let you see their profile</h3>" ;
				} else {

					$profileispublic = ($profileprivacylevel == 0) ;
					$registeredonlyandloggedin = (($profileprivacylevel == 1) && ($loggedIn)) ;
					$privateandloggedinandfriendorowner = (($profileprivacylevel == 2) && ($loggedIn) && (($userisfriend) OR ($userisowner))) ;
					$showprofile = $profileispublic || $registeredonlyandloggedin || $privateandloggedinandfriendorowner ;
					if (!$showprofile) {
						if (!$loggedIn) {
							$message = "<h3>You must log in to send messages to ".$username."</h3>" ;
						}
						else {
							if (quote_smart($_GET['act']) == 'af') {
								$message = "<h3>Thank you! Your request to be added to ".quote_smart($_GET['user'])."'s friends list has been submitted</h3>" ;
							}
							else {
								$message = '<h3>You must be on '.quote_smart($getuser).'\'s friends list to send messages - <a href="'.$sitepath.'profile/'.$getuser.'/af">ask '.$getuser.' to add you here</a></h3>' ;
							}
						}
					}
				}
		}
		else {
			// USER NAME IS NOT IN THE DATABASE
			if (!$registeredUser) {
				$message = "Sorry - this user does not exist or is no longer registered" ;
			}
		}
	}
	return $message ;
}
function canMessageForMenu() {
	global $db,$loggedIn ;
	$getuser = quote_smart($_GET['user']);
	$path = getSetting('sitefolder', $db) ;
	$sitepath = 'http://'.$_SERVER['SERVER_NAME'].$path ;
	$message = "" ;
	if (!isset($getuser)) {
		// NO USER IN URL
		$message = "Sorry - this user does not exist or is no longer registered" ;
	}
	else {
		$username = mysql_real_escape_string($getuser) ;
		//Check it's a registered user
		$db->query("SELECT * FROM member WHERE username = '".$username."'") ;
		$registeredUser = false ;
		if ($db->numRows() >= 1) {
			$registeredUser = true ;
			$res = $db->fetch() ;
			$profileid = $res['id'] ;
			$profileprivacylevel = $res['profile_privacy'] ;
			// NOW CHECK THAT THIS USER IS ALLOWED TO VIEW THE PROFILE

			
			// IF USER IS LOGGED IN CHECK IF USER IS BLOCKED
			$blocked = false ;
			$userisfriend = false ;
			$userisowner = false ;
			$useridadmin = false ;
			if ($loggedIn) {
				$db->query("SELECT * FROM member WHERE username = '".$_SESSION['session_username']."'") ;
				$res = $db->fetch() ;
				$loggedInid = $res['id'] ;

				$db->query("SELECT * FROM blocked WHERE blocker_id = ".$profileid." AND blockee_id = ".$loggedInid) ;
				$blocked = ($db->numRows() >= 1) ;
				// CHECK IF USER IS THE OWNER OF THIS PROFILE
				$userisowner = ($profileid == $loggedInid) ;
				// CHECK IF USER IS ON THE OWNER'S FRIENDS LIST AND IS APPROVED
				$db->query("SELECT * from friend WHERE ((userid = ".$profileid." AND friendid = ".$loggedInid.") OR  (friendid = ".$profileid." AND userid = ".$loggedInid.")) AND friend_approved = 1") ;
				$userisfriend = ($db->numRows() > 0) ;

			}
				if ($blocked) {
					//USER IS BLOCKED
					$message = "<h4>$username has chosen not to let you send messages</h4>" ;
				}
				else
				// USER IS NOT BLOCKED
				{
					// NOW CHECK IF THE PROFILE IS VISIBLE - IT WILL BE SHOWN IN ANY OF THESE 3 CASES:
					
					// 1 - PROFILE IS PUBLIC
					
					// 2 - PROFILE IS REGISTERED ONLY AND USER IS LOGGED IN
					
					// 3 - PROFILE IS PRIVATE AND USER IS LOGGED IN AND (USER IS A FRIEND OR THE OWNER OF THIS PROFILE)
					$profileispublic = ($profileprivacylevel == 0) ;
					$registeredonlyandloggedin = (($profileprivacylevel == 1) && ($loggedIn)) ;
					$privateandloggedinandfriendorowner = (($profileprivacylevel == 2) && ($loggedIn) && (($userisfriend) OR ($userisowner))) ;
					$showprofile = $profileispublic || $registeredonlyandloggedin || $privateandloggedinandfriendorowner ;
					if (!$showprofile) {
						if (!$loggedIn) {
							$message = "Log in to send a message to ".$username ;
						}
						else {
							if (quote_smart($_GET['act']) == 'af') {
								$message = "You will be able to send a message to ".$username." when your friend request is approved" ;
							}
							else {
								$message = '<a href="'.$sitepath.'profile/'.$getuser.'/af">Become '.$username.'\'s friend</a> to send a message' ;
							}
						}
					}
				}
		}
		else {
			// USER NAME IS NOT IN THE DATABASE
			if (!$registeredUser) {
				$message = "Sorry - this user does not exist or is no longer registered" ;
			}
		}
	}
	return $message ;
}

$str_today = date("Y-m-d H:i:s") ;
function profileBox() {
	global $db,$loggedIn,$sitepath,$templateimagepath ;
	$getuser = quote_smart($_GET['user']);
	$sitefolder = getSetting("sitefolder", $db) ;
	$sitetemplate = getSetting("sitetemplate", $db) ;
	$rootpath = $_SERVER['DOCUMENT_ROOT'].$sitefolder ;
	$path = "http://".$_SERVER['SERVER_NAME'].$sitefolder ;
	// GET LOGGED IN USER'S ID
	$db->query("SELECT * FROM member WHERE username = '".$_SESSION['session_username']."'") ;
	$res = $db->fetch() ;
	$loggedInid = $res['id'] ;
	// GET PROFILE DETAILS
	$username = mysql_real_escape_string($getuser) ;
	$db->query("SELECT * FROM member WHERE username = '".$username."'") ;
	$userrow = $db->fetch() ;
	$aboutme = $userrow['aboutmemmmm'] ;
	$age = $userrow['age'] ;
	$gender = $userrow['gender'] ;
	$lookingfor = $userrow['lookingfor'] ;
	$location = $userrow['location'] ;
	$favmovie = $userrow['favmovie'] ;
	$profileid = $userrow['id'] ;
	if (($loggedInid != $profileid) && ($loggedIn)) {
		$db->query("UPDATE member SET profileviews=profileviews+1 WHERE id=".$profileid) ;
		$db->query("SELECT viewerhistory FROM member WHERE id=".$profileid) ;
		$hres = $db->fetch() ;
		$viewerhistory = $hres['viewerhistory'] ;
		$media = array() ;
		$count = 0 ;
		if (strlen($viewerhistory) != 0) {
			$pastviewers = explode(":", $viewerhistory);
			if ($pastviewers[count($pastviewers) - 2] != "") {
				$lastviewer = $pastviewers[count($pastviewers) - 2] ;
			}
			else {
				$lastviewer = -1 ;
			}
		}
		if ($loggedInid != $lastviewer) {
			$viewerhistory .= $loggedInid.":" ;
			$db->query("UPDATE member SET viewerhistory = '".$viewerhistory."' WHERE id=".$profileid) ;
		}
	}
	$avatargender = $userrow['gender'] > 0 ? 'female' : 'male' ;
	$avatar = $templateimagepath."default_".$avatargender."_avatar.png" ;
	if (@file_exists("uploads/avatars/".$userrow['avatar']) && ($userrow['avatar'] != "")) {
		$avatar = $sitepath."uploads/avatars/".$userrow['avatar'] ;
	}
	$avatar = str_replace(" ", "%20", $avatar) ;
	$profileoutput = '	<div id="profile"><img class="thumb" width='.getSetting("avatar_w", $db).'px height='.getSetting("avatar_h", $db).'px class="thumb" src="'.$avatar.'" />
<div id="profile-top-right">
				<h3>About '.$username.'</h3>

				<p> '.$aboutme.'</p>' ;
	if (($age != "") || ($gender != "")) {
		$profileoutput .= '<p>' ;
		if ($age != "") {
			$profileoutput .= '<p>Age - '.$age.'</p>' ;
		}
		if ($gender != "") {
			if ($gender == 1) {
				$profileoutput .= "<p>Gender - female</p>" ;
			}
			else {
				$profileoutput .= "<p>Gender - male</p>" ;
			}
		}
		$username = mysql_real_escape_string($getuser) ;
	}
	if ($location != '') {
		$profileoutput .= '<p>location - '.$location.'</p>' ;
	}
	
	if ($lookingfor != '') {
		switch($lookingfor) {
			case '2':
				$profileoutput .= '<p>Looking for - Female</p>' ;
			break;
			case '1':
				$profileoutput .= '<p>Looking for - Male</p>' ;
			break;
			case '3':
				$profileoutput .= '<p>Looking for - Both</p></div>' ;
			break;
	
		}
	}







	if ($favmovie != '') {
			$profileoutput .= '<p>Favorite Movie - '.$favmovie.'</p>' ;
	}
	$iconpath = $path.'templates/'.$sitetemplate.'/images/' ;
	$userisfriend = false ;
	$userisblocked = false ;
	$userisapproved = false ;
	$requestreceived = false ;
	$requestsent = false ;
	$receivedicanaccept = false ;
	$receivedremovedme = false ;
	$pendingcancancel = false ;
	$iremovedmakerequest = false ;
	$userisfriend = false ;
	$notonlistcanrequest = false ;
	if ($loggedIn) {
		$db->query("SELECT * from friend WHERE (userid = ".$profileid." AND friendid = ".$loggedInid.") OR (userid = ".$loggedInid." AND friendid = ".$profileid.")") ;
		$friendres = $db->fetch() ;
		$useronfriendslist = ($db->numRows() > 0) ;
		if (($useronfriendslist) && ($profileid != $loggedInid)) //don't check friends if user owns profile 
		{
			$requestapproved = ($friendres['friend_approved']) > 0 ;
			$requestremoved = ($friendres['friend_removed']) > 0 ;
			if (!$requestapproved) // user is not friend 
			{
				//now check if the request was sent or received
				if ($friendres['userid'] == $loggedInid) // Received request 
				{
					$requestreceived = true ;
					if (!$requestremoved) 
					{
						$receivedicanaccept = true ;//arr
					}
					else {
						$receivedremovedme = true ;//rfa
					}
				}
				else // It's a sent request 
				{
					$requestsent = true ;
					if (!$requestremoved) 
					{
						$pendingcancancel = true ; //csr
					}
					else {
						$iremovedmakerequest = true ; //rmaf
					}
				}
			}
			else //no friend record 
			{
				$userisfriend = true ; //afr
			}
		}
		else {
			$notonlistcanrequest = true ; //af
		}
		$db->query("SELECT * from blocked WHERE blockee_id = ".$profileid." AND blocker_id = ".$loggedInid) ;
		$userisblocked = ($db->numRows() > 0) ;
		$db->query("SELECT * from subscription WHERE userid=".$loggedInid." AND subscribedtoid=".$profileid) ;
		$userissubscribed = ($db->numRows() > 0) ;
	}
	$proflink = $path.'profile/'.$getuser ;
	$friendaddlink = $proflink.'/af' ;
	$receivedicanacceptlink = $proflink.'/arr' ;
	$receivedremovedmelink = $proflink.'/rfa' ;
	$pendingcancancellink = $proflink.'/csr' ;
	$iremovedmakerequestlink = $proflink.'/rmaf' ;
	$userisfriendlink = $proflink.'/afr' ;
	$notonlistlink = $proflink.'/af' ;
	$blocklink = $path.'profile/'.$getuser.'/bl' ;
	$sublink = $path.'profile/'.$getuser.'/sb' ;
	$unblocklink = $path.'profile/'.$getuser.'/ub' ;
	$unsublink = $path.'profile/'.$getuser.'/us' ;
	$sendmessagelink = $path.'profile/'.$getuser.'/sm' ;
	if ($loggedIn) {
		if ($profileid != $loggedInid) //don't show the links if the user owns the profile 
		{
			if ($receivedicanaccept) {
				$profileoutput .= '<p><b>'.$username.' has sent you a friend request: <a href="'.$receivedicanacceptlink.'">accept the request</a></b></p>' ;
			}
			if ($receivedremovedme) {
				$profileoutput .= '<p><b>'.$username.' removed you from friends list: <a href="'.$receivedremovedmelink.'">request again</a></b></p>' ;
			}
			if ($pendingcancancel) {
				$profileoutput .= '<p><b>'.$username.' has not accepted your request yet: <a href="'.$pendingcancancellink.'">cancel request</a></b></p>' ;
			}
			if ($iremovedmakerequest) {
				$profileoutput .= '<p><b><a href="'.$iremovedmakerequestlink.'">send '.$username.' a friend request</a></b></p>' ;
			}
			if ($userisfriend) {
				$profileoutput .= '<p><b>you are '.$username.'\'s friend <a href="'.$userisfriendlink.'">remove '.$username.' from your friends list</a></b></p>' ;
			}
			if ($notonlistcanrequest) {
				$profileoutput .= '<p><b><a href="'.$notonlistlink.'">send '.$username.' a friend request</a></b></p>' ;
			}
			if (canMessageForMenu() == '') {
				$profileoutput .= '<div class="lnk"><a href="'.$sendmessagelink.'">send '.$username.' a message</a></div>' ;
			}
			else {
				$profileoutput .= '<div class="lnk">'.canMessageForMenu().'</div>' ;
			}
			if (!$userisblocked) {
				$profileoutput .= '<div class="lnk"><a href="'.$blocklink.'">Block '.$username.'</a></div>' ;
			}
			else {
				$profileoutput .= '<div class="lnk">Remove block for '.$username.'</a></div>' ;
			}
			if (!$userissubscribed) {
				$profileoutput .= '<div class="lnk"><a href="'.$sublink.'">subscribe (receive emails when '.$username.' uploads new media)</a></div>' ;
			}
			else {
				$profileoutput .= '<div class="lnk"><a href="'.$unsublink.'">Unsubscribe from '.$username.'</a></div>' ;
			}
		}
	}
	else {
		$profileoutput .= '<p><div class="lnk">log in to send '.$username.' a message</div></p>' ;
	}
	$profileoutput .= "</div>" ;
	return $profileoutput ;
}




?>