<?php
/*
 *    Copyright (c) 2010 VidiScript
 *
 *    This file is part of VidiScript.
 *
 *    VidiScript is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    VidiScript is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with VidiScript.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    File Name: ajaxfunc.php
 *    Description: Ajax functions
 *    $Date: 2010-02-21 23:16:57 +0000 (Sun, 21 Feb 2010) $
 *    $Revision: 12 $
 */
include_once 'includes/bootstrap.inc' ;
include_once 'includes/common.inc' ;
session_start() ;
function date_diff($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" ;
}
function datez_diff($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" ;
}
function displayRUser($res) {
	global $db,$sitepath,$templateimagepath ;
	$max = getSetting("relateduserpage", $db) ;
	$thumbcount = max(sizeof($res), $max) ;
	$sitefolder = getSetting("sitefolder", $db) ;
	$path = "http://".$_SERVER['SERVER_NAME'].$sitefolder ;
	if ($thumbcount > 0) {
		$output = "" ;
		$count = 0 ;
		$page-- ;
		foreach ($res as $key=>$value) {
			if ($value['added'] < time()) {
				$count++ ;
				$thumbpath = $path.'uploads/thumbs/' ;
				$thumb = '' ;
				if (checkHideThumbnails() && ($value['requires_agreement'] == 1)) {
					$thumb = $templateimagepath."default_mature_thumb.jpg" ;
				}
				else {
					if (@file_exists($thumbpath.$value['thumb'].".small.jpg")) {
						$thumb = $sitepath."uploads/thumbs/".$value['thumb'].".small.jpg" ;
					}
					elseif (@file_exists($thumbpath.$value['mediaurl'].".small.jpg")) {
						$thumb = $sitepath."uploads/thumbs/".$value['mediaurl'].".small.jpg" ;
					}
					elseif (findThumb($value['thumb'], true)) {
						$thumb = findThumb($value['thumb'], true) ;
						$thumb = $sitepath."uploads/thumbs/".$thumb[0] ;
					}
					if ($thumb == '') {
						$thumb = $templateimagepath.getDefaultThumb($value['mediatype']) ;
					}
					$thumb = str_replace(" ", "%20", $thumb) ;
				}
				$kat = getCategoryPath($value['category']) ;
				$db->query("SELECT * FROM rating WHERE id = ".$value['id']) ;
				$resR = $db->fetch() ;
				$title = url_encode($value['title']) ;
				$added = datez_diff(date("Y-m-d H:i:s", $value["added"]), date("Y-m-d H:i:s")) ;
				$output .= "<li><a href=\"".$path."play$kat/$title\"><img class='thumb' src='".$thumb."' /></a>\n" ;
				$short_title = force_length($value['title'], 30) ;
				$output .= "<p><a href=\"".$path."play$kat/$title\">".$short_title."</a><br><b>".$added."</b></p></li>\n" ;
				if ($count >= $max) {
					break ;
				}
			}
		}
	}
	return $output ;
}
global $sitepath,$templateimagepath ;
if ($_GET['id'] == 1) {
	$tags = quote_smart($_GET['tags']) ;
	$poster = quote_smart($_GET['poster']) ;
	$db->query("SELECT * FROM media LEFT JOIN `group` ON (`media`.`groupid` = `group`.`group_id`) WHERE `status`='true' AND  (`privacy`!=1 OR `privacy` IS NULL) AND (`suspended`!=1 OR `suspended` IS NULL) AND MATCH (tags) AGAINST ('".quote_smart(trim($_GET['tags']))."' IN BOOLEAN MODE)") ;
	$res = $db->fetchALL() ;
	echo '
	<ul class="no-format c-tabs">
		<li class="crt">
			<span>
				<a class="rel" style="cursor: hand; cursor: pointer;" onClick="doRelated(\''.$tags.'\',\''.$poster.'\');">Related </a>
			</span>
		</li>
		<li>
			<span>
				<a class="rel" style="cursor: hand; cursor: pointer;" onClick="doUser(\''.$tags.'\',\''.$poster.'\');"> User   </a>
			</span>
		</li>
	</ul>' ;
	echo '<div class="tab-cont"><ul class="no-format horiz-thumbs-list">' ;
	echo displayRUser($res) ;
	echo '</ul></div>' ;
}
if ($_GET['id'] == 2) {
	$tags = quote_smart($_GET['tags']) ;
	$poster = quote_smart($_GET['poster']) ;
	$db->query("SELECT * FROM media WHERE poster = '".quote_smart(trim($_GET['poster']))."' ORDER BY id DESC") ;
	$res = $db->fetchALL() ;
	echo '
	<ul class="no-format c-tabs">
		<li>
			<span>
				<a class="rel" style="cursor: hand; cursor: pointer;" onClick="doRelated(\''.$tags.'\',\''.$poster.'\');">Related </a>
			</span>
		</li>
		<li class="crt">
			<span>
				<a class="rel" style="cursor: hand; cursor: pointer;" onClick="doUser(\''.$tags.'\',\''.$poster.'\');"> User   </a>
			</span>
		</li>
	</ul>' ;
	echo '<div class="tab-cont"><ul class="no-format horiz-thumbs-list">';
	echo displayRUser($res);
	echo '</ul></div>' ;
}
if ($_GET['id'] == 3) {
	$scode2 = quote_smart($_GET['scode2']) ;
	$vidid = quote_smart($_GET['vidid']) ;
	$name = quote_smart($_GET['name']) ;
	$comment = quote_smart($_GET['comment']) ;
	$visitor = quote_smart($_GET['visitor']) ;
	$loggedIn = quote_smart($_GET['loggedIn']) ;
	if ((($_SESSION['security_code'] == $scode2) && (! empty($_SESSION['security_code']))) || ((getSetting("captchaformembers", $db) == 0) && ($loggedIn))) {
		if (! empty($name)) {
			$doComment = true ;
			if (!$loggedIn) {
				$db->query("SELECT id FROM member WHERE LOWER(username) = '".strtolower(quote_smart($name))."'") ;
				if ($db->numRows() != 0) {
					echo 'The name you entered matches the name of a user already registered!' ;
					$doComment = false ;
				}
			}
			if (! empty($comment)) {
				if ($doComment) {
					if (strlen($comment) <= getSetting('comment_length', $db)) {
						$commenttext = quote_smart($comment) ;
						$commenttext = apply_word_censor($commenttext) ;
						if ($visitor == 'visitorposting') {
							$db->query("INSERT INTO `media_comment` (`vid_id`, `leftbyname`, `date`, `text`,`regdposter`) VALUES ('".$vidid."', '".$name."', '".date("Y-m-d H:i:s")."', '".$commenttext."',0);") ;
						}
						else {
							$db->query("INSERT INTO `media_comment` (`vid_id`, `leftbyname`, `date`, `text`,`regdposter`) VALUES ('".$vidid."', '".$_SESSION['username']."', '".date("Y-m-d H:i:s")."', '".$commenttext."',1);") ;
						}
						echo '<b>Your comment was added successfully. Thank you.</b>' ;
						unset($_SESSION['security_code']) ;

						?>
<input
	type="hidden" name="ajax" id="ajax" value="<?=$sitepath?>">
<script type="text/javascript" src="<?=$sitepath?>ajax/play.js">
</script>
<script type="text/javascript">
    RefreshComments();
</script>
						<?
					}
					else {
						echo '<blink><b>Your comment is to long, please make it less then '.getSetting('comment_length', $db).' characters.</b></blink>' ;
					}
				}
			}
			else {
				echo '<blink><b>You have to fill in something in the text box.</b></blink>' ;
			}
		}
		else {
			echo '<blink><b>You have to fill in your name.</b></blink>' ;
		}
	}
	else {
		echo '<blink><b>Please enter the security code on the form</b></blink>' ;
	}
}
if ($_GET['id'] == 4) {
	$pagelink = $_SESSION['pagelink'] ;
	$vidid = $_SESSION['vidid'] ;
	if ((session_is_registered(username)) && ($_SESSION['username'] != "")) {
		$loggedIn = 1 ;
	}
	else {
		$loggedIn = "" ;
	}
	$sql = "SELECT * FROM `media_comment` WHERE `vid_id` = '".$vidid."' ORDER BY id DESC" ;
	$result = mysql_query($sql) or die('Fehler: '.mysql_error()) ;
	$comments = $message ;
	if ($result) {
		$count = 0 ;
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$db->query("SELECT * FROM `member` WHERE `username` = '".quote_smart($row['name'])."'") ;
			$user = $db->fetch() ;
			if (isset($_SESSION['privs']) && $_SESSION['privs'] == 7) {
				$del = '<div align=right><a title="delete this comment" style="cursor: hand; cursor: pointer;" onClick="deleteComment(\''.$row['id'].'\');"> Delete Comment </a></div>' ;
			}
			else {
				$del = '' ;
			}
			$postername = $row['leftbyname'] ;
			if ($row['regdposter'] == 1) {
				$posterString = '<a href="'.$sitepath.'profile/'.htmlentities($row['leftbyname']).'">'.htmlentities($row['leftbyname']).'</a>' ;
				$db->query("SELECT * FROM `member` WHERE `username` = '".quote_smart($row['leftbyname'])."'") ;
				$user = $db->fetch() ;
				if (($user['avatar'] == '') || ($db->numRows() < 1)) {
					$avatargender = $value['gender'] > 0 ? 'female' : 'male' ;
					$avatar_tag = '<img width=30px height=30px class="thumb" src="'.$templateimagepath.'default_'.$avatargender.'_avatar.jpg" alt="" />' ;
				}
				else {
					$avatar_tag = '<a href="'.$sitepath.'profile/'.htmlentities($row['leftbyname']).'"><img width=30px height=30px class="thumb" src="'.$sitepath.'uploads/avatars/'.$user['avatar'].'" alt="" /></a>' ;
				}
			}
			else {
				$posterString = htmlentities($row['leftbyname'])." (visitor)" ;
				$avatar_tag = '<img width=30px height=30px class="thumb" src="'.$templateimagepath.'default_male_avatar.jpg" alt="" />' ;
			}
			$comments .= '<dl class="no-format full-com2"><dt>'.$avatar_tag.'<b>'.$posterString.' </b></dt>' ;
			$comments .= '<dd><p><h3 class="message">'.nl2br(($row['text'])).$del.'</h3></p></dd><h4>'.$row["date"].'</h4></dl>' ;
		}
	}
	$comments .= '<div>' ;
	if (getSetting("restrictpc", $db) == "1" && !$loggedIn) {
		$comments .= '<a href="'.$sitepath.'register">Please login to comment<a/>' ;
	}
	else {
		$comments .= '<h2>Add comment</h2>' ;
		if ($loggedIn == 1) {
			$comments .= '<input type="hidden" id="name" name="name" value="'.$_SESSION['username'].'"/><input type="hidden" id="visitor" name="visitor" value="notguest">' ;
		}
		else {
			$comments .= '<li>
					<label for="name" class="comment">name</label>
						<input type="hidden" id="visitor" name="visitor" value="visitorposting">
					<input id="name" name="name"  />
					</li>' ;
		}
		$comments .= '<div id="message"><textarea id="text" name="text"></textarea></div>' ;
		if ((!$loggedIn) || (getSetting("captchaformembers", $db) == 1)) {
			$comments .= '<p><img src="'.$sitepath.'includes/CaptchaSecurityImages.php" /><br>Enter code above<br>
			<input id="security_code" name="security_code" type="text" size="6"/></p>' ;
		}
		else {
			$comments .= '<input type="hidden" id="security_code" name="security_code" value="" />' ;
		}
		$comments .= '<p><input class="biggerbutton" type="button" onClick="Mcomment(\''.$vidid.'\',\''.$loggedIn.'\');" name="submit" value="Post comment" style="margin-right: 30px;"/></p></form>' ;
		$comments .= '<br />' ;
	}
	$comments .= '<br /></div>' ;
	echo $comments ;
}
if ($_GET['id'] == 5) {
	global $db ;
	$num = $_GET['num'] ;
	if (isset($_SESSION['privs']) && ($_SESSION['privs'] == 7) && ($num > 0)) {
		$db->query("DELETE FROM `media_comment` WHERE `id` = '".$_GET['num']."';") ;
	}
}
?>