<?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.
 **********************************************************************************
 */
require_once( "../functions.php" );
session_start();
if (!Beveiliging()){
    header ( "location: ../index.php" );
} else {
	include_once("adminfunctions.inc");



if($_GET['page']) {
	$page=$_GET['page'];
	$pagename=$_GET['PageName'];
	$output = '';
	$sort = '';
	if($_GET['Pnum']) {
		$numpages = $_GET['Pnum'];
	} else {
		$numpages = 25;
	}
	$startpage = ($page-1)*$numpages;

	if (($_GET['PageName'] == 'allvideos') || ($_GET['PageName'] == 'newuploads') || ($_GET['PageName'] == 'dbclean')) {

		switch($pagename) {
			case "allvideos":
				$query = "SELECT * FROM media WHERE status = 'true'" ;
			break;
			case "newuploads":
				$query = "SELECT * FROM media WHERE status = 'false'" ;
			break;
			case "dbclean":
				$query = "SELECT * FROM media WHERE (status <> 'true' AND status <> 'false')" ;
			break;
		}

		if ((isset($_GET['stitle'])) && ($_GET['stitle'] !== "")) {
				$sort .= " AND (title LIKE '%".$_GET['stitle']."%')" ;
		}
		if ((isset($_GET['sdesc'])) && ($_GET['sdesc'] !== "")) {
				$sort .= " AND (description LIKE '%".$_GET['sdesc']."%')" ;
		}
		if ((isset($_GET['spos'])) && ($_GET['spos'] !== "")) {
				$sort .= " AND (poster = '".$_GET['spos']."')" ;
		}
		if ((isset($_GET['scat'])) && ($_GET['scat'] !== "")) {
				$sort .= " AND (category = '".$_GET['scat']."')" ;
		}
		if ((isset($_GET['viem'])) && ($_GET['viem'] !== "")) {
			$sort .= " AND (mediatype = '".$_GET['viem']."')" ;
		}

		if ((isset($_GET['hdmo'])) && ($_GET['hdmo'] !== "")) {
			$sort .= " AND (".$_GET['hdmo']." = '1')" ;
		}


		if ((isset($_GET['soby'])) && ($_GET['soby'] !== "")) {
			$orderby = " ORDER BY ".$_GET['soby'] ;
		}
		if ((isset($_GET['order'])) && ($_GET['order'] !== "")) {
			$order = " ".$_GET['order'] ;
		}
		if ($orderby == "") {
			$orderby = " ORDER BY id DESC" ;
		}


		$db->query($query.$sort.$orderby.$order) ;
		$maxpages = $db->numRows();



		$limit = ' LIMIT '.$startpage.','.$numpages ;
		$db->query($query.$sort.$orderby.$order.$limit) ;

		$pages = ceil($maxpages/$numpages);

		$output .= '<table><tr><td>Number of results: '.$maxpages.'</td><td><ul id="pagination">';


		for($i=1; $i<=$pages; $i++) {
				if ($page == $i){
					$output .= '<li id="'.$i.'"><em id="'.$i.'">'.$i.'</em></li>';
				} else {
					$output .= '<li id="'.$i.'">'.$i.'</li>';
				}
		}
		$output .= '</ul></td></tr></table>';



 	$output .= '<form method="post" action="">
	<table class="allvideostable" cellspacing="0">

	<tr>
		<select id="massvideofunc">
			<option value="deleteall" selected>Delete selected</option>';

			if (($pagename == 'allvideos') || ($pagename == 'newuploads')) {
				$output .= '<option value="genthumb">reGenerate thumb</option>
				<option value="gendur">reGenerate Duration</option>';
			}
			if ($pagename == 'newuploads') {
				$output .= '<option SELECTED value="approveall">Approve selected</option>';
			}


		$output .= '</select>
		<input type="submit" id="submitmassvideofunc" value="Apply">
	</tr>

	<tr class="allvideomenu">
	<td><input type="checkbox" id="paradigm_all" />Select All</td>
	</tr>';




	$res = $db->fetchAll() ;
	foreach ($res as $value) {

		$thumb = $sitepath."uploads/thumbs/".$value['fileid']."/".$value['mainthumb'].".jpg" ;
		$db->query("SELECT name FROM category WHERE id = '".$value['category']."'") ;
		$cat = $db->fetch() ;
		$category = $cat['name'];

		if ($value['mobile'] == '1') {
			$show_hd = '<img src="images/green.png" width="16" height="16">';
		} else {
			$show_hd = '<img src="images/red.png" width="16" height="16">';
		}
		if ($value['hd'] == '1') {
			$show_mobile = '<img src="images/green.png" width="16" height="16">';
		} else {
			$show_mobile = '<img src="images/red.png" width="16" height="16">';
		}
		if ($value['flagged'] == '1') {
			$show_flag = '<img src="images/green.png" width="16" height="16">';
		} else {
			$show_flag = '<img src="images/red.png" width="16" height="16">';
		}
		if ($value['vidad'] == '') {
			$show_vidad = '<img src="images/red.png" width="16" height="16">';
		} else {
			$show_vidad = '<img src="images/green.png" width="16" height="16">';
		}


		if ($pagename == 'dbclean') {
			$displaystatus = " status: (".$value['status'].")" ;
		}


		$output .= '
		<table id="listingtableheader'.$value['id'].'" class="listingtableheader" cellspacing="0">
		<tr>
			<th class="title"><input type="checkbox" id="paradigm'.$value['id'].'" /> '.$value['title'].' ('.$value['id'].') '.$displaystatus.'</th>
			<th class="actions">';

				if (($pagename == 'allvideos') || ($pagename == 'newuploads')) {
					$output .= '<input type="submit" class="preview" id="preview'.$value['id'].'" title="Preview video" value="">
						<input type="submit" class="edit" id="editvideo'.$value['id'].'" title="Edit video" value="">
						<input type="submit" class="delete" id="deletevideo'.$value['id'].'" title="Delete video" value="">
						<input type="submit" class="thumbgen" id="reGenthumb'.$value['id'].'" title="ReGenerate Thumbs" value="">
						<input type="submit" class="durgen" id="reGenDur'.$value['id'].'" title="ReGenerate Duration" value="">';
				}
				if ($pagename == 'newuploads') {
					$output .= '<input type="submit" class="approve" id="approvevideo'.$value['id'].'" title="Approve video" value="">';

				}
				if ($pagename == 'dbclean') {
					$output .= '<input type="submit" class="delete" id="deletevideo'.$value['id'].'" title="Delete video" value="">';
				}


		$output .= '</th>
		</tr>
		</table>
		<table id="listingtabletext'.$value['id'].'" class="listingtabletext">
		<tr>
			<td class="thumb"><div id="thumbholder'.$value['id'].'"><img src="'.$thumb.'" width="103" height="80"></div></td>
			<td class="text1"><b>Title:</b> '.$value['title'].'<br><b>Description:</b> '.$value['description'].'<br><b>Category:</b> '.$category.'<br><b>Tags:</b> '.$value['tags'].'</td>
			<td class="text2"><b>Poster:</b> '.$value['poster'].'<br><b>Added:</b> '.date("m/d/Y h:i:s a", $value['added']).'<br><b>Mediatype:</b> '.$value['mediatype'].'<br><div id="duration'.$value['id'].'"><b>Duration:</b> '.$value['duration'].'</div></td>
			<td class="text3"><b>Video AD:</b> '.$show_vidad.'<br><b>HD:</b> '.$show_hd.'<br><b>Mobile:</b> '.$show_mobile.'<br><b>Flagged:</b> '.$show_flag.'</td>
			<td class="text4"><b>All Views:</b> '.$value['allviews'].'<br><b>Today Views:</b> '.$value['dayviews'].'<br><b>Weekly Views:</b> '.$value['weekviews'].'<br><b>Monthly Views:</b> '.$value['monthviews'].'<br></td>
		</tr>
		</table>';
		}

		$output .= '</table></form>';
		echo $output ;
	}




	if ($_GET['PageName'] == 'userlist') {

		$query = "SELECT * FROM member WHERE created <> ''" ;


		//make sort with $_GET

		if ((isset($_GET['username'])) && ($_GET['username'] !== "")) {
				$sort .= " AND (username LIKE '%".$_GET['username']."%')" ;
		}
		if ((isset($_GET['email'])) && ($_GET['email'] !== "")) {
				$sort .= " AND (email LIKE '%".$_GET['email']."%')" ;
		}
		if ((isset($_GET['country'])) && ($_GET['country'] !== "")) {
				$sort .= " AND (location LIKE '%".$_GET['country']."%')" ;
		}
		if ((isset($_GET['usergender'])) && ($_GET['usergender'] !== "")) {
				$sort .= " AND (gender = '".$_GET['usergender']."')" ;
		}

		if ((isset($_GET['userorderby'])) && ($_GET['userorderby'] !== "")) {
			$orderby = " ORDER BY ".$_GET['userorderby'] ;
		}
		if ((isset($_GET['userorder'])) && ($_GET['userorder'] !== "")) {
			$order = " ".$_GET['userorder'] ;
		}



		$db->query($query.$sort.$orderby.$order) ;
		$maxpages = $db->numRows();

		$limit = ' LIMIT '.$startpage.','.$numpages ;


		$db->query($query.$sort.$orderby.$order.$limit) ;

		$pages = ceil($maxpages/$numpages);

		$output .= '<table><tr><td>Number of results: '.$maxpages.'</td><td><ul id="pagination">';

		for($i=1; $i<=$pages; $i++) {
				if ($page == $i){
					$output .= '<li id="'.$i.'"><em id="'.$i.'">'.$i.'</em></li>';
				} else {
					$output .= '<li id="'.$i.'">'.$i.'</li>';
				}
		}
		$output .= '</ul></td></tr></table>';


		$output .= '<form method="post" action="">
		<table class="allvideostable" cellspacing="0">
		<tr>
			<select id="massuserfunc">
				<option value="approveall" selected>Approve Users</option>
				<option value="deleteall">Delete Users</option>
				<option value="banall">Ban Users</option>
				<option value="unbanall">Unban Users</option>
			</select>
			<input type="submit" id="submitmassuserfunc" value="Apply">
		</tr>

		<tr class="allvideomenu">
		<td><input type="checkbox" id="paradigm_all" />Select All</td>
		</tr>';


	$res = $db->fetchAll() ;
	foreach ($res as $value) {
		if ($value['activationkey'] == "0")  {
			$displaystatus = "Yes" ;
		} else {
			$displaystatus = "No" ;
		}
		$joined = date("m/d/Y h:i:s a", $value['created']);
		$lastlogin =  date("m/d/Y h:i:s a", $value['lastlogin']);
		if ($value['avatar'] == '') {
			$thumb = "No avatar";
		} else {
			$thumb = "<img src='".$sitepath."uploads/avatars/".$value['avatar']."' width='103px' height='80px'>" ;
		}
		if ($value['gender'] == "1")  {
			$gender = "Female" ;
		} else {
			$gender = "male" ;
		}
		if ($value['banned'] == "0")  {
			$banned = "no" ;
		} else {
			$banned = "yes" ;
		}

			$output .= '
			<table id="listingtableheader'.$value['id'].'" class="listingtableheader" cellspacing="0">
			<tr>
				<th class="title"><input type="checkbox" id="paradigm'.$value['id'].'" /> '.$value['username'].' ('.$value['id'].') '.$displaystatus.'</th>
				<th class="actions">';
					if ($value['banned'] == "0")  {
						$output .= '<input type="submit" class="ban" id="banuser'.$value['id'].'" title="Ban User" value="">';
					} else {
						$output .= '<input type="submit" class="unban" id="unbanuser'.$value['id'].'" title="Unban User" value="">';
					}

					if ($value['activationkey'] != "0")  {
						$output .= '<input type="submit" class="approve" id="approveuser'.$value['id'].'" title="Activated User" value="">';
					}
					$output .= '<input type="submit" class="delete" id="deleteuser'.$value['id'].'" title="Delete User" value="">';

					$output .= '</th></tr></table>';


			$output .= '
			<table id="listingtabletext'.$value['id'].'" class="listingtabletext">
			<tr>
				<td class="thumb"><div id="thumbholder'.$value['id'].'">'.$thumb.'</div></td>
				<td class="text7"><b>Username:</b> '.$value['username'].'<br><b>Email:</b> '.$value['email'].'<br><b>Gender:</b> '.$gender.'<br><b>Country:</b> '.$value['location'].'</td>
				<td class="text5"><b>Joined:</b> '.$joined.'<br><b>Last Login:</b> '.$lastlogin.'<br><b>Last Ip:</b> '.$value['ip'].'<br><b>Profile Views:</b> '.$value['profileviews'].'</td>
				<td class="text6"><b>Age:</b> '.$value['age'].'<br><div id="banned'.$value['id'].'"><b>Banned:</b> '.$banned.'</div><div id="activated'.$value['id'].'"><b>Activated :</b> '.$displaystatus.'</div></td>
			</tr>
			</table>';

	}

		echo $output ;
	}



}

if($_GET['plugfunc']) {
	$plugfunc = $_GET['plugfunc'] ;
	$plugname = $_GET['plugname'] ;

	if ($plugfunc == "load") {
	//update the menu
		$db->query("UPDATE plugin_menu SET `loaded` = '1' WHERE `menuclass` = '".$plugname."'") ;
	//check if install want to execute stuff

		require_once("../plugins/".$plugname."/settings.inc");
		if (isset($plug_table_names)) {
			$tablearr = explode('|', $plug_table_names);

			foreach($tablearr as $value) {
				$sqlcode = ${'plug_execsql_'.$value};
				plug_install($value, $sqlcode);
			}
		}
	}
	if ($plugfunc == "unload") {
		$db->query("UPDATE plugin_menu SET `loaded` = '0' WHERE `menuclass` = '".$plugname."'") ;
	}
}

if($_GET['userfunc']) {
	$userid = $_GET['userid'] ;
	if ($_GET['userfunc'] == 'banuser') {
		$db->query("UPDATE member SET `banned` = '1' WHERE `id` = '".$userid."'") ;
	}
	if ($_GET['userfunc'] == 'unbanuser') {
		$db->query("UPDATE member SET `banned` = '0' WHERE `id` = '".$userid."'") ;
	}
	if ($_GET['userfunc'] == 'approveuser') {
		$db->query("UPDATE member SET `activationkey` = '0' WHERE `id` = '".$userid."'") ;
	}
	if ($_GET['userfunc'] == 'deleteuser') {
		$db->query("DELETE FROM member WHERE id = '".$userid."' ") ;
	}
}
if($_GET['usermassfunc']) {
	$userfunc = $_GET['usermassfunc'] ;
	$useridarray = $_GET['array'];
	$pieces = explode(",", $useridarray);

	if ($userfunc == "approveall") {
		foreach($pieces as $value) {
			$db->query("UPDATE member SET `activationkey` = '0' WHERE `id` = '".$value."'") ;
		}
	}
	if ($userfunc == "deleteall") {
		foreach($pieces as $value) {
			$db->query("DELETE FROM member WHERE id = '".$value."' ") ;
		}
	}
	if ($userfunc == "banall") {
		foreach($pieces as $value) {
			$db->query("UPDATE member SET `banned` = '1' WHERE `id` = '".$value."'") ;
		}
	}
	if ($userfunc == "unbanall") {
		foreach($pieces as $value) {
			$db->query("UPDATE member SET `banned` = '0' WHERE `id` = '".$value."'") ;
		}
	}
}


if($_GET['videofunc']) {
	if ($_GET['videofunc'] == 'funcdel') {
		$delid = $_GET['delid'];
		$db->query("SELECT * from `media` WHERE id = '".$delid."'") ;
		$res = $db->fetch() ;
		$fileid = $res['fileid'] ;

			//send mail to poster video is rejected before deleting all video info
			if (getSetting("mail_video_rejected", $db) == '1') {
				$msg = getEmailformat("email_rejected") ;

				$db->query("SELECT title, poster FROM media WHERE id = '".$delid."' LIMIT 1") ;
				$mediainfo = $db->fetch() ;
				$db->query("SELECT email FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
				$mailinfo = $db->fetch() ;
				$msg = str_replace(array('[TITLE]', '[POSTER]', '[SITEURL]', '[SITENAME]'), array($mediainfo['title'], $mediainfo['poster'], $sitepath, getSetting("sitename", $db)), $msg);
				sendmail(array(array("email"=>$mailinfo['email'], "name"=>$mediainfo['poster'])), 'Video Rejected', $msg) ;
			}
			//if sitemap auto is on we update the sitemap so the deleted videos are removed
			if (getSetting("autositemap", $db) == '1') {
					$db->query("SELECT id,name FROM category") ;
					$rowCAT = $db->fetchAll() ;
					$numrows = $db->numrows() ;
					$siteoutput = '<?xml version="1.0" encoding="UTF-8"?>' ;
					$siteoutput .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ;
					$datelast = gmdate("Y-m-d", time())."T".gmdate("H:i:s", time())."+01:00"  ;
					foreach ($rowCAT as $key=>$value) {
						$db->query("SELECT * FROM media WHERE category = '".$value['id']."' AND status = 'true' ORDER BY id DESC") ;
						$rowmedia = $db->fetchAll() ;
						$catname = $value['name'] ;
						if ($rowmedia) {
							sitemapper($rowmedia, $catname) ;
							$siteoutput .= '<sitemap><loc>'.$sitepath.'sitemap/'.str_replace(" ", "_", trim($catname)).'.xml</loc><lastmod>'.$datelast.'</lastmod></sitemap>' ;
						}

					}
					$siteoutput .= '</sitemapindex>' ;
					if ($siteoutput) {
						$file = $rootpath.'sitemap/sitemap.xml' ;
						$fp = fopen($file, "w");
						fwrite($fp, $siteoutput);
						fclose($fp);
					}
			}

		if ($res['mediatype'] == 'video') {
				if (($res['status'] == 'true') || ($res['status'] == 'false')) {
					if ($res['hd'] == "1") {
						unlink($rootpath."uploads/vids/".$fileid."/".$fileid.".mp4") ;
					}
					if ($res['mobile'] == "1") {
						unlink($rootpath."uploads/vids/".$fileid."/mob_".$fileid.".mp4") ;
					}
					unlink($rootpath."uploads/vids/".$fileid."/".$fileid.".flv") ;
					rmdir($rootpath."uploads/vids/".$fileid."/") ;
					$thumbdir = $rootpath."uploads/thumbs/".$res['fileid']."/" ;
					if (file_exists($thumbdir)) {
						foreach(glob($thumbdir.'*.*') as $v){
							unlink($v);
						}
					}
					rmdir($thumbdir) ;
					$db->query("DELETE FROM media WHERE id = '".$delid."' ") ;
				} else {
					unlink($rootpath."uploads/encode/".$fileid) ;
					$db->query("DELETE FROM media WHERE id = '".$delid."' ") ;
				}
		}
		if ($res['mediatype'] == 'embed') {
				$thumbdir = $rootpath."uploads/thumbs/".$res['fileid']."/" ;
				if (file_exists($thumbdir)) {
					foreach(glob($thumbdir.'*.*') as $v){
							unlink($v);
					}
				}
				rmdir($thumbdir) ;
				$db->query("DELETE FROM media WHERE id = '".$delid."' ") ;
		}
	}
	if ($_GET['videofunc'] == 'funcapp') {
		$appid = $_GET['appid'];
		$db->query("UPDATE media SET `status` = 'true' WHERE `id` = '".$appid."'") ;
			//send mail to the poster, subscripber and friends
			if (getSetting("mail_video_approved", $db) == '1') {
				$msg = getEmailformat("email_approved") ;
				$db->query("SELECT title, poster FROM media WHERE id = '".$appid."' LIMIT 1") ;
				$mediainfo = $db->fetch() ;
				$db->query("SELECT email FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
				$mailinfo = $db->fetch() ;
				$msg = str_replace(array('[TITLE]', '[POSTER]', '[MEDIALINK]', '[SITEURL]', '[SITENAME]'), array($mediainfo['title'], $mediainfo['poster'], $sitepath."play/".url_encode($mediainfo['title']),$sitepath, getSetting("sitename", $db)), $msg);
				sendmail(array(array("email"=>$mailinfo['email'], "name"=>$mediainfo['poster'])), 'Video Approved', $msg) ;
			}
			if (getSetting("mail_friend_subscribed", $db) == '1') {
						$db->query("SELECT title, poster FROM media WHERE id = '".$appid."' LIMIT 1") ;
						$mediainfo = $db->fetch() ;
						$db->query("SELECT id, email FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
						$mailinfo = $db->fetch() ;
						$msg = getEmailformat("email_approved_subscriber") ;
						$msg = str_replace(array('[TITLE]', '[SITENAME]', '[MEDIALINK]', '[SITEURL]', '[POSTER]'), array($mediainfo['title'], getSetting("sitename", $db), $sitepath."play/".url_encode($mediainfo['title']), $sitepath, $mediainfo['poster']), $msg);

						$db->query("SELECT userid FROM subscription WHERE subscribedtoid = '".$mailinfo['id']."'");
						$subscripids = $db->fetchAll() ;
						$subarray = array() ;

							foreach($subscripids as $subvalue) {
								$db->query("SELECT email, username FROM member WHERE id = '".$subvalue['userid']."' LIMIT 1") ;
								$subinfo = $db->fetch() ;
								array_push($subarray, array("email"=>$subinfo['email'], "name"=>$subinfo['username']));
							}
				sendmail($subarray, $mediainfo['poster'].' Uploaded a new video', $msg) ;
			}
			if (getSetting("mail_video_friends", $db) == '1') {
						$db->query("SELECT title, poster FROM media WHERE id = '".$appid."' LIMIT 1") ;
						$mediainfo = $db->fetch() ;
						$db->query("SELECT id FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
						$memberid = $db->fetch() ;
						$msg = getEmailformat("email_approved_friend") ;
						$msg = str_replace(array('[TITLE]', '[SITENAME]', '[MEDIALINK]', '[SITEURL]', '[POSTER]'), array($mediainfo['title'], getSetting("sitename", $db), $sitepath."play/".url_encode($mediainfo['title']), $sitepath, $mediainfo['poster']), $msg);

						$db->query("SELECT * FROM friend WHERE (userid = '".$memberid['id']."' OR friendid = '".$memberid['id']."') AND friend_approved = '1'");
						$friendids = $db->fetchAll() ;

						$friarray = array() ;
							foreach($friendids as $frivalue) {
								if ($memberid['id'] != $frivalue['userid']) {
									$db->query("SELECT email, username, friendmail_privacy FROM member WHERE id = '".$frivalue['userid']."' LIMIT 1") ;
									$friinfo = $db->fetch() ;
									if ($friinfo['friendmail_privacy'] != '0') {
										array_push($friarray, array("email"=>$friinfo['email'], "name"=>$friinfo['username']));
									}
								}

								if ($memberid['id'] != $frivalue['friendid']) {
									$db->query("SELECT email, username, friendmail_privacy FROM member WHERE id = '".$frivalue['friendid']."' LIMIT 1") ;
									$friinfo = $db->fetch() ;
									if ($friinfo['friendmail_privacy'] != '0') {
										array_push($friarray, array("email"=>$friinfo['email'], "name"=>$friinfo['username']));
									}
								}
							}
				sendmail($friarray, $mediainfo['poster'].' Uploaded a new video', $msg) ;
			}
			//if sitemap auto is on we update the sitemap so the deleted videos are removed
			if (getSetting("autositemap", $db) == '1') {
					$db->query("SELECT id,name FROM category") ;
					$rowCAT = $db->fetchAll() ;
					$numrows = $db->numrows() ;
					$siteoutput = '<?xml version="1.0" encoding="UTF-8"?>' ;
					$siteoutput .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ;
					$datelast = gmdate("Y-m-d", time())."T".gmdate("H:i:s", time())."+01:00"  ;
					foreach ($rowCAT as $key=>$value) {
						$db->query("SELECT * FROM media WHERE category = '".$value['id']."' AND status = 'true' ORDER BY id DESC") ;
						$rowmedia = $db->fetchAll() ;
						$catname = $value['name'] ;
						if ($rowmedia) {
							sitemapper($rowmedia, $catname) ;
							$siteoutput .= '<sitemap><loc>'.$sitepath.'sitemap/'.str_replace(" ", "_", trim($catname)).'.xml</loc><lastmod>'.$datelast.'</lastmod></sitemap>' ;
						}

					}
					$siteoutput .= '</sitemapindex>' ;
					if ($siteoutput) {
						$file = $rootpath.'sitemap/sitemap.xml' ;
						$fp = fopen($file, "w");
						fwrite($fp, $siteoutput);
						fclose($fp);
					}
			}
	}
	if ($_GET['videofunc'] == 'functhumb') {
		$genid = $_GET['genid'];
		$db->query("SELECT * from `media` WHERE id = '".$genid."'") ;
		$res = $db->fetch() ;
		if ($res['mediatype'] == 'video') {
			$thumbdir = $rootpath."uploads/thumbs/".$res['fileid']."/" ;
				if (file_exists($thumbdir)) {
					foreach(glob($thumbdir.'*.*') as $v){
						unlink($v);
					}
				}
				if (!file_exists($thumbdir)) {
					mkdir($rootpath."uploads/thumbs/".$res['fileid'], 0755);
				}
			makethumbs($rootpath."uploads/vids/".$res['fileid']."/".$res['fileid'].".flv", $rootpath."uploads/thumbs/".$res['fileid']."/");
			echo $sitepath."uploads/thumbs/".$res['fileid']."/".$res['mainthumb'].".jpg" ;
		}
	}
	if ($_GET['videofunc'] == 'funcdur') {
		$durid = $_GET['durid'];
		$db->query("SELECT * from `media` WHERE id = '".$durid."'") ;
		$res = $db->fetch() ;
		if ($res['mediatype'] == 'video') {
			//get new duration
			$newduration = getduration($rootpath."uploads/vids/".$res['fileid']."/".$res['fileid'].".flv", 'site');
			//update it in DB
			$db->query("UPDATE media SET `duration` = '".$newduration."' WHERE `id` = '".$res['id']."'") ;
			echo $newduration ;
		}
	}




}


if($_GET['videomassfunc']) {
	$videofunc = $_GET['videomassfunc'] ;
	$videoidarray = $_GET['array'];
	$pieces = explode(",", $videoidarray);
	if ($videofunc == "deleteall") {
		foreach($pieces as $value) {
			$db->query("SELECT * from `media` WHERE id = '".$value."'") ;
			$res = $db->fetch() ;

			$fileid = $res['fileid'] ;
			if ($res['mediatype'] == 'video') {
				if (($res['status'] == 'true') || ($res['status'] == 'false')) {
					if ($res['hd'] == "1") {
						unlink($rootpath."uploads/vids/".$fileid."/".$fileid.".mp4") ;
					}
					if ($res['mobile'] == "1") {
						unlink($rootpath."uploads/vids/".$fileid."/mob_".$fileid.".mp4") ;
					}
					unlink($rootpath."uploads/vids/".$fileid."/".$fileid.".flv") ;
					rmdir($rootpath."uploads/vids/".$fileid."/") ;
					$thumbdir = $rootpath."uploads/thumbs/".$fileid."/" ;
					if (file_exists($thumbdir)) {
						foreach(glob($thumbdir.'*.*') as $v){
							unlink($v);
						}
					}
					rmdir($thumbdir) ;
					$db->query("DELETE FROM media WHERE id = '".$res['id']."' ") ;
				} else {
					unlink($rootpath."uploads/encode/".$fileid) ;
					$db->query("DELETE FROM media WHERE id = '".$res['id']."' ") ;
				}
			}
			if ($res['mediatype'] == 'embed') {
					$thumbdir = $rootpath."uploads/thumbs/".$fileid."/" ;
					if (file_exists($thumbdir)) {
						foreach(glob($thumbdir.'*.*') as $v){
								unlink($v);
						}
					}
					rmdir($thumbdir) ;
					$db->query("DELETE FROM media WHERE id = '".$res['id']."' ") ;
			}

			//send mail to poster video is rejected before deleting all video info
			if (getSetting("mail_video_rejected", $db) == '1') {
				$msg = getEmailformat("email_rejected") ;
				$db->query("SELECT email FROM member WHERE username = '".$res['poster']."' LIMIT 1") ;
				$mailinfo = $db->fetch() ;
				$msg = str_replace(array('[TITLE]', '[POSTER]', '[SITEURL]', '[SITENAME]'), array($res['title'], $res['poster'], $sitepath, getSetting("sitename", $db)), $msg);
				sendmail(array(array("email"=>$mailinfo['email'], "name"=>$res['poster'])), 'Video Rejected', $msg) ;
			}



		}
		//if sitemap auto is on we update the sitemap so the deleted videos are removed
			if (getSetting("autositemap", $db) == '1') {
					$db->query("SELECT id,name FROM category") ;
					$rowCAT = $db->fetchAll() ;
					$numrows = $db->numrows() ;
					$siteoutput = '<?xml version="1.0" encoding="UTF-8"?>' ;
					$siteoutput .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ;
					$datelast = gmdate("Y-m-d", time())."T".gmdate("H:i:s", time())."+01:00"  ;
					foreach ($rowCAT as $key=>$value) {
						$db->query("SELECT * FROM media WHERE category = '".$value['id']."' AND status = 'true' ORDER BY id DESC") ;
						$rowmedia = $db->fetchAll() ;
						$catname = $value['name'] ;
						if ($rowmedia) {
							sitemapper($rowmedia, $catname) ;
							$siteoutput .= '<sitemap><loc>'.$sitepath.'sitemap/'.str_replace(" ", "_", trim($catname)).'.xml</loc><lastmod>'.$datelast.'</lastmod></sitemap>' ;
						}

					}
					$siteoutput .= '</sitemapindex>' ;
					if ($siteoutput) {
						$file = $rootpath.'sitemap/sitemap.xml' ;
						$fp = fopen($file, "w");
						fwrite($fp, $siteoutput);
						fclose($fp);
					}
			}

	}
	if ($videofunc == "approveall") {
		foreach($pieces as $value) {
			$db->query("UPDATE media SET `status` = 'true' WHERE `id` = '".$value."'") ;

			//send mail to the poster, subscripber and friends
			if (getSetting("mail_video_approved", $db) == '1') {
				$msg = getEmailformat("email_approved") ;
				$db->query("SELECT title, poster FROM media WHERE id = '".$value."' LIMIT 1") ;
				$mediainfo = $db->fetch() ;
				$db->query("SELECT email FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
				$mailinfo = $db->fetch() ;
				$msg = str_replace(array('[TITLE]', '[POSTER]', '[MEDIALINK]', '[SITEURL]', '[SITENAME]'), array($mediainfo['title'], $mediainfo['poster'], $sitepath."play/".url_encode($mediainfo['title']),$sitepath, getSetting("sitename", $db)), $msg);
				sendmail(array(array("email"=>$mailinfo['email'], "name"=>$mediainfo['poster'])), 'Video Approved', $msg) ;
			}



			if (getSetting("mail_friend_subscribed", $db) == '1') {
						$db->query("SELECT title, poster FROM media WHERE id = '".$value."' LIMIT 1") ;
						$mediainfo = $db->fetch() ;
						$db->query("SELECT id, email FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
						$mailinfo = $db->fetch() ;
						$msg = getEmailformat("email_approved_subscriber") ;
						$msg = str_replace(array('[TITLE]', '[SITENAME]', '[MEDIALINK]', '[SITEURL]', '[POSTER]'), array($mediainfo['title'], getSetting("sitename", $db), $sitepath."play/".url_encode($mediainfo['title']), $sitepath, $mediainfo['poster']), $msg);

						$db->query("SELECT userid FROM subscription WHERE subscribedtoid = '".$mailinfo['id']."'");
						$subscripids = $db->fetchAll() ;
						$subarray = array() ;

							foreach($subscripids as $subvalue) {
								$db->query("SELECT email, username FROM member WHERE id = '".$subvalue['userid']."' LIMIT 1") ;
								$subinfo = $db->fetch() ;
								array_push($subarray, array("email"=>$subinfo['email'], "name"=>$subinfo['username']));
							}
				sendmail($subarray, $mediainfo['poster'].' Uploaded a new video', $msg) ;
			}
			if (getSetting("mail_video_friends", $db) == '1') {
						$db->query("SELECT title, poster FROM media WHERE id = '".$value."' LIMIT 1") ;
						$mediainfo = $db->fetch() ;
						$db->query("SELECT id FROM member WHERE username = '".$mediainfo['poster']."' LIMIT 1") ;
						$memberid = $db->fetch() ;
						$msg = getEmailformat("email_approved_friend") ;
						$msg = str_replace(array('[TITLE]', '[SITENAME]', '[MEDIALINK]', '[SITEURL]', '[POSTER]'), array($mediainfo['title'], getSetting("sitename", $db), $sitepath."play/".url_encode($mediainfo['title']), $sitepath, $mediainfo['poster']), $msg);

						$db->query("SELECT * FROM friend WHERE (userid = '".$memberid['id']."' OR friendid = '".$memberid['id']."') AND friend_approved = '1'");
						$friendids = $db->fetchAll() ;

						$friarray = array() ;
							foreach($friendids as $frivalue) {
								if ($memberid['id'] != $frivalue['userid']) {
									$db->query("SELECT email, username, friendmail_privacy FROM member WHERE id = '".$frivalue['userid']."' LIMIT 1") ;
									$friinfo = $db->fetch() ;
									if ($friinfo['friendmail_privacy'] != '0') {
										array_push($friarray, array("email"=>$friinfo['email'], "name"=>$friinfo['username']));
									}
								}

								if ($memberid['id'] != $frivalue['friendid']) {
									$db->query("SELECT email, username, friendmail_privacy FROM member WHERE id = '".$frivalue['friendid']."' LIMIT 1") ;
									$friinfo = $db->fetch() ;
									if ($friinfo['friendmail_privacy'] != '0') {
										array_push($friarray, array("email"=>$friinfo['email'], "name"=>$friinfo['username']));
									}
								}
							}
				sendmail($friarray, $mediainfo['poster'].' Uploaded a new video', $msg) ;
			}

		}
		//if sitemap auto is on we update the sitemap so the deleted videos are removed
			if (getSetting("autositemap", $db) == '1') {
					$db->query("SELECT id,name FROM category") ;
					$rowCAT = $db->fetchAll() ;
					$numrows = $db->numrows() ;
					$siteoutput = '<?xml version="1.0" encoding="UTF-8"?>' ;
					$siteoutput .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ;
					$datelast = gmdate("Y-m-d", time())."T".gmdate("H:i:s", time())."+01:00"  ;
					foreach ($rowCAT as $key=>$value) {
						$db->query("SELECT * FROM media WHERE category = '".$value['id']."' AND status = 'true' ORDER BY id DESC") ;
						$rowmedia = $db->fetchAll() ;
						$catname = $value['name'] ;
						if ($rowmedia) {
							sitemapper($rowmedia, $catname) ;
							$siteoutput .= '<sitemap><loc>'.$sitepath.'sitemap/'.str_replace(" ", "_", trim($catname)).'.xml</loc><lastmod>'.$datelast.'</lastmod></sitemap>' ;
						}

					}
					$siteoutput .= '</sitemapindex>' ;
					if ($siteoutput) {
						$file = $rootpath.'sitemap/sitemap.xml' ;
						$fp = fopen($file, "w");
						fwrite($fp, $siteoutput);
						fclose($fp);
					}
			}
	}



	if ($videofunc == "genthumb") {
		$replay = '';
		foreach($pieces as $value) {
			//generate new thumbs
				//get info from id
				$db->query("SELECT * from `media` WHERE id = '".$value."'") ;
				$res = $db->fetch() ;
				if ($res['mediatype'] == 'video') {
					//first delete old ones
					$thumbdir = $rootpath."uploads/thumbs/".$res['fileid']."/" ;
						if (file_exists($thumbdir)) {
							foreach(glob($thumbdir.'*.*') as $v){
								unlink($v);
							}
						}
					//get new ones
							if (!file_exists($thumbdir)) {
								mkdir($rootpath."uploads/thumbs/".$res['fileid'], 0755);
							}
					makethumbs($rootpath."uploads/vids/".$res['fileid']."/".$res['fileid'].".flv", $rootpath."uploads/thumbs/".$res['fileid']."/");
					$replay .= $res['id']."^".$sitepath."uploads/thumbs/".$res['fileid']."/".$res['mainthumb'].".jpg," ;
				}
		}
		echo $replay ;
	}
	if ($videofunc == "gendur") {
		$replay = '';
		foreach($pieces as $value) {
			//generate new duration
				//get info from id
				$db->query("SELECT * from `media` WHERE id = '".$value."'") ;
				$res = $db->fetch() ;

				if ($res['mediatype'] == 'video') {
					//get new duration
					$newduration = getduration($rootpath."uploads/vids/".$res['fileid']."/".$res['fileid'].".flv", 'site');
					//update it in DB
					$db->query("UPDATE media SET `duration` = '".$newduration."' WHERE `id` = '".$res['id']."'") ;
					$replay .= $res['id']."^".$newduration."," ;
				}
		}

		echo $replay ;


	}

}
//replay the video to watch in admin panel
if($_GET['previewid']) {
	$previewid = $_GET['previewid'];
	$replay = '';
	$db->query("SELECT * from `media` WHERE id = '".$previewid."'") ;
	$res = $db->fetch() ;


	$replay .= '<h2>Title Video</h2><h5>'.$res['title'].'</h5>
	<div class="settings">
	<fieldset>
	<form action="" method="post" enctype="multipart/form-data">
	<table>';


	if ($res['mediatype'] == 'video') {
		if ($res['hd'] == "1") {
			$hd = '&plugins=hd-1&hd.file='.$sitepath.'uploads/vids/'.$res['fileid'].'/'.$res['fileid'].'.mp4' ;
		} else {
			$hd = '' ;
		}
		$replay .= '<div id="player">This will be replaced with video</div>
				<script type="text/javascript">
				var so = new SWFObject("js/player.swf","mpl","600","480","9");
				so.addParam("allowscriptacces","always");
				so.addParam("allowfullscreen","true");
				so.addParam("wmode","opaque");
				so.addParam("flashvars","file='.$sitepath.'uploads/vids/'.$res['fileid'].'/'.$res['fileid'].'.flv'.$hd.'&amp;provider=http&amp;stretching=false");
				so.write("player");
				</script>';
	}
	if ($res['mediatype'] == 'embed') {

		$replay .= stripslashes($res['embed']) ;

	}


	$replay .= '<tr><td><input class="submitbutton" id="edit_close'.$res['id'].'" type="submit" value="Close" /></td></tr></table></form></fieldset></div>';



echo $replay;
}
//replay the greybox with edit form
if($_GET['editid']) {
	$replay = '';
	$editid = $_GET['editid'];
	$db->query("SELECT * from `media` WHERE id = '".$editid."'") ;
	$res = $db->fetch() ;
	$db->query("SELECT * FROM `category` ORDER BY name") ;
	$cat = $db->fetchAll() ;

 	$replay .= '
 	<h2>Edit Video ID '.$editid.'</h2>
 	<h5>You can edit everything even stuff users cant so watch out you only use the allowed characters</h5>
	<h5>Title: only use a-zA-Z0-9</h5>
	<h5>Description: Everything</h5>
	<h5>Tags: a-zA-Z0-9 and - </h5>

 	<div class="settings">
	<fieldset>
		<form action="" method="post" enctype="multipart/form-data">
		<table>

			<tr>
				<td>Title:</td>
				<td><input type="text" size="110" id="edit_title" value="'.$res['title'].'"></td>
			</tr>
			<tr>
				<td>Description:</td>
				<td><input type="text" size="110" id="edit_description" value="'.$res['description'].'"></td>
			</tr>
			<tr>
				<td>Tags:</td>
				<td><input type="text" size="110" id="edit_tags" value="'.$res['tags'].'"></td>
			</tr>

			<tr>
				<td>Category:</td>
				<td><select id="edit_category">
					<option value="">-----</option>';

			foreach($cat as $catvalue) {
				if ($res['category'] == $catvalue['id']) {
					$sel = ' selected';
				}

				$replay .= '<option'.$sel.' value="'.$catvalue['id'].'">'.$catvalue['name'].'</option>' ;
				unset($sel);
			}

		$replay .= '</select></td></tr>
			<tr>
				<td>Video AD:</td>
				<td><textarea type="text" id="edit_vidad" >'.$res['vidad'].'</textarea></td>
			</tr>';


		if ($res['mediatype'] == 'embed') {
			$replay .='<tr>
				<td>Embed code:</td>
				<td><textarea type="text" id="edit_embed" >'.$res['embed'].'</textarea></td>
			</tr>';
		}




		if ($res['mediatype'] == 'video') {
			$numthumbs = getSetting("thumbsnumber", $db);

			//show all thumbs
			$replay .='<tr><td>Thumbs:</td><td id="thumbrotator">';
				for ($x = 1; $x <= $numthumbs; $x++) {
					$replay .= '<img src="'.$sitepath.'uploads/thumbs/'.$res['fileid'].'/'.$x.'.jpg" width="80" height="60">';
					if (strlen($x / 6) == '1') {
						$replay .= '<br>';
					}
				}
			//make a dropdown box to see which thumbnail to use
			$replay .='</td></tr><tr>
				<td>Thumbnail:</td>
				<td><select id="edit_thumbnail">';
					for ($a = 1; $a <= $numthumbs; $a++) {
						if ($a == $res['mainthumb']) {
							$sel2 = ' selected';
						}

						$replay .= '<option'.$sel2.' value="'.$a.'">'.$a.'</option>' ;
						unset($sel2);
					}
			$replay .='</select></td></tr>';
		}


		$replay .='<input type="hidden" id="edit_id" value="'.$res['id'].'">
			<tr>
				<td><input class="submitbutton" id="edit_submit" type="submit" value="Submit" /></td>
				<td><input class="submitbutton" id="edit_close'.$res['id'].'" type="submit" value="Close" /></td>
			</tr>



		</table>
		</form>
	</fieldset></div>';




echo $replay;
}

//update the settings from edit video form
if($_GET['edit_id']) {
	if($_GET['edit_ti']) {
		$db->query("UPDATE media SET `title` = '".$_GET['edit_ti']."' WHERE `id` = '".$_GET['edit_id']."'") ;
	}
	if($_GET['edit_de']) {
		$db->query("UPDATE media SET `description` = '".addslashes($_GET['edit_de'])."' WHERE `id` = '".$_GET['edit_id']."'") ;
	}
	if($_GET['edit_ta']) {
		$db->query("UPDATE media SET `tags` = '".$_GET['edit_ta']."' WHERE `id` = '".$_GET['edit_id']."'") ;
	}
	if($_GET['edit_ca']) {
		$db->query("UPDATE media SET `category` = '".$_GET['edit_ca']."' WHERE `id` = '".$_GET['edit_id']."'") ;
	}
	if($_GET['edit_ad']) {
		$db->query("UPDATE media SET `vidad` = '".addslashes($_GET['edit_ad'])."' WHERE `id` = '".$_GET['edit_id']."'") ;
	}
	if($_GET['edit_em']) {
		if ($_GET['edit_em'] != 'undefined') {
			$db->query("UPDATE media SET `embed` = '".addslashes($_GET['edit_em'])."' WHERE `id` = '".$_GET['edit_id']."'") ;
		}
	}
	if($_GET['edit_th']) {
		if ($_GET['edit_th'] != 'undefined') {
		 $db->query("UPDATE media SET `mainthumb` = '".addslashes($_GET['edit_th'])."' WHERE `id` = '".$_GET['edit_id']."'") ;
		}
	}
			//if sitemap auto is on we update the sitemap so the deleted videos are removed
			if (getSetting("autositemap", $db) == '1') {
					$db->query("SELECT id,name FROM category") ;
					$rowCAT = $db->fetchAll() ;
					$numrows = $db->numrows() ;
					$siteoutput = '<?xml version="1.0" encoding="UTF-8"?>' ;
					$siteoutput .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ;
					$datelast = gmdate("Y-m-d", time())."T".gmdate("H:i:s", time())."+01:00"  ;
					foreach ($rowCAT as $key=>$value) {
						$db->query("SELECT * FROM media WHERE category = '".$value['id']."' AND status = 'true' ORDER BY id DESC") ;
						$rowmedia = $db->fetchAll() ;
						$catname = $value['name'] ;
						if ($rowmedia) {
							sitemapper($rowmedia, $catname) ;
							$siteoutput .= '<sitemap><loc>'.$sitepath.'sitemap/'.str_replace(" ", "_", trim($catname)).'.xml</loc><lastmod>'.$datelast.'</lastmod></sitemap>' ;
						}

					}
					$siteoutput .= '</sitemapindex>' ;
					if ($siteoutput) {
						$file = $rootpath.'sitemap/sitemap.xml' ;
						$fp = fopen($file, "w");
						fwrite($fp, $siteoutput);
						fclose($fp);
					}
			}
}

//comment delete and edit
//return grey box
if($_GET['commentedit']) {
	$replay = '';
	$editid = $_GET['commentedit'];
	$db->query("SELECT * from `media_comment` WHERE id = '".$editid."'") ;
	$res = $db->fetch() ;

 	$replay .= '
 	<h2>Edit comment ID '.$editid.'</h2>
 	<h5>You can edit everything even stuff users cant so watch out you only use the allowed characters</h5>
	<h5>Only use a-zA-Z0-9</h5>

	<div class="settings">
	<fieldset>
		<form action="" method="post" enctype="multipart/form-data">
			<table>
				<tr>
					<td>Comment Text:</td>
					<td><input type="text" size="110" id="com_edit_text" value="'.$res['text'].'"></td>
				</tr>

				<input type="hidden" id="com_edit_id" value="'.$res['id'].'">
				<tr>
					<td><input class="submitbutton" id="edit_com_submit" type="submit" value="Submit" /></td>
					<td><input class="submitbutton" id="edit_com_close'.$res['id'].'" type="submit" value="Close" /></td>
				</tr>
		</table>
		</form>
	</fieldset></div>';

	echo $replay ;
}
//update or delete the database
if($_GET['commentfunc']) {
	if ($_GET['commentfunc'] == 'funcdel') {
		//comment verwijderen
		$db->query("DELETE FROM media_comment WHERE id = '".$_GET['delid']."' ") ;
	}
	if ($_GET['commentfunc'] == 'funcedit') {
		if($_GET['com_edit_id']) {
			$db->query("UPDATE media_comment SET `text` = '".$_GET['com_edit_text']."' WHERE `id` = '".$_GET['com_edit_id']."'") ;
		}
	}
}



//Flag delete edit preview

//update or delete the database
if($_GET['flagfunc']) {
	if ($_GET['flagfunc'] == 'funcunflag') {
		//flagged video default 0
			$db->query("UPDATE `media` SET `flagged` = '0' WHERE id = '".$_GET['flagid']."'") ;
	}
}

if($_GET['previewflag']) {
	$replay = '';
	$previewid = $_GET['previewflag'];
	$db->query("SELECT * from `media` WHERE id = '".$previewid."'") ;
	$res = $db->fetch() ;


	$replay .= '<h2>Title Video</h2><h5>'.$res['title'].'</h5>
	<div class="settings">
	<fieldset>
	<form action="" method="post" enctype="multipart/form-data">
	<table>';


	if ($res['mediatype'] == 'video') {
		if ($res['hd'] == "1") {
			$hd = '&plugins=hd-1&hd.file='.$sitepath.'uploads/vids/'.$res['fileid'].'/'.$res['fileid'].'.mp4' ;
		} else {
			$hd = '' ;
		}
		$replay .= '<div id="player">This will be replaced with video</div>
				<script type="text/javascript">
				var so = new SWFObject("js/player.swf","mpl","600","480","9");
				so.addParam("allowscriptacces","always");
				so.addParam("allowfullscreen","true");
				so.addParam("wmode","opaque");
				so.addParam("flashvars","file='.$sitepath.'uploads/vids/'.$res['fileid'].'/'.$res['fileid'].'.flv'.$hd.'&amp;provider=http&amp;stretching=false");
				so.write("player");
				</script>';
	}
	if ($res['mediatype'] == 'embed') {
		$replay .= stripslashes($res['embed']) ;
	}
	$replay .= '<tr><td><input class="submitbutton" id="edit_com_close'.$res['id'].'" type="submit" value="Close" /></td></tr></table></form></fieldset></div>';


	echo $replay;
}

//category edit delete add

if($_GET['catadd']) {
	$replay = '';
	 $replay .= '
 	<h2>Add New category</h2>
 	<h5>You can add everything so watch out you only use the allowed characters</h5>
 	<h5>Only use a-zA-Z0-9</h5>
 	<h5>You can leave ID empty but if you deleted a category and want to add it again with the same id you can fill it in.</h5>
 	<h5>You can add a thumb after you add a category</h5>

	<div class="settings">
	<fieldset>
		<form action="" method="post" enctype="multipart/form-data">
			<table>
				<tr>
					<td>Category ID:</td>
					<td><input type="text" size="110" id="cat_add_id" ></td>
				</tr>
				<tr>
					<td>Category Name:</td>
					<td><input type="text" size="110" id="cat_add_name" ></td>
				</tr>
				<tr><div id="caterrormsg"></div></tr>
				<tr>
					<td><input class="submitbutton" id="edit_add_submit" type="submit" value="Submit" /></td>
					<td><input class="submitbutton" id="cat_add_close1" type="submit" value="Close" /></td>
				</tr>
		</table>
		</form>
	</fieldset></div>';
	echo $replay ;
}








if($_GET['categoryfunc']) {
	if ($_GET['categoryfunc'] == 'funcdel') {
		//delete category
		$db->query("DELETE FROM category WHERE id = '".$_GET['delid']."' ") ;
		//if category is deleted but has video it needs the main category
		$db->query("UPDATE `media` SET `category` = '1' WHERE category = '".$_GET['delid']."'") ;
	}
	if ($_GET['categoryfunc'] == 'funcedit') {
		if($_GET['cat_edit_catid']) {
				$db->query("SELECT * from `category` WHERE id = '".$_GET['cat_edit_catid']."'") ;
				$res = $db->fetch() ;

				$oldcatname = str_replace(" ", "-", trim($res['name'])).".jpg" ;
				$namecatname = str_replace(" ", "-", trim($_GET['cat_edit_catname'])).".jpg" ;

				if (file_exists($rootpath."uploads/category/".$oldcatname)) {
					rename($rootpath."uploads/category/".$oldcatname, $rootpath."uploads/category/".$namecatname);
				}
				//update DB
				$db->query("UPDATE `category` SET `name` = '".$_GET['cat_edit_catname']."' WHERE id = '".$_GET['cat_edit_catid']."'") ;


		}
	}
	if ($_GET['categoryfunc'] == 'funcadd') {
		if ($_GET['cat_add_name'] != '') {

			  if ( ($_GET['cat_add_id'] == '') || (is_numeric($_GET['cat_add_id'])) ) {

				$db->query("SELECT * from `category` WHERE id = '".$_GET['cat_add_id']."'") ;
				if ($db->numRows() == 1) {
					echo '4';
				} else {
					$db->query("SELECT * from `category` WHERE name = '".$_GET['cat_add_name']."'") ;
					if ($db->numRows() == 1) {
						echo '5';
					} else {
						if ($_GET['cat_add_id'] == '') {
							$db->query("INSERT INTO `category` (name) VALUES ('".$_GET['cat_add_name']."')") ;
						} else {
							$db->query("INSERT INTO `category` (id,name) VALUES ('".$_GET['cat_add_id']."','".$_GET['cat_add_name']."')") ;
						}

						echo '1';
					}
				}
			} else {
				echo '3';
			}
		} else {
			echo '2';
		}
	}
}
if($_GET['catedit']) {
	$replay = '';
	$editid = $_GET['catedit'];
	$db->query("SELECT * from `category` WHERE id = '".$editid."'") ;
	$res = $db->fetch() ;

	 $replay .= '
 	<h2>Edit category ID '.$editid.'</h2>
 	<h5>You can edit everything so watch out you only use the allowed characters</h5>
 	<h5>Only use a-zA-Z0-9</h5>

	<div class="settings">
	<fieldset>
		<form action="" method="post" enctype="multipart/form-data">
			<table>
				<tr>
					<td>Category Name:</td>
					<td><input type="text" size="110" id="cat_edit_catname" value="'.$res['name'].'"></td>
				</tr>
				<input type="hidden" id="cat_edit_catid" value="'.$res['id'].'">
				<tr>
					<td><input class="submitbutton" id="edit_cat_submit" type="submit" value="Submit" /></td>
					<td><input class="submitbutton" id="edit_cat_close'.$res['id'].'" type="submit" value="Close" /></td>
				</tr>
		</table>
		</form>
	</fieldset></div>';

	echo $replay ;
}



if($_GET['categorythumb']) {
	$replay = '';
	$editid = $_GET['categorythumb'];
	$db->query("SELECT * from `category` WHERE id = '".$editid."'") ;
	$res = $db->fetch() ;

	$catname = str_replace(' ', '-', $res['name']);

	if (file_exists($rootpath.'uploads/category/'.$catname.'.jpg')) {
		$thumb = "<img src='".$sitepath."uploads/category/".$catname.".jpg' width='80px' height='113px'>" ;
	} else {
		$thumb = "<img src='".$templateimagepath."defaultcat.jpg' width='80px' height='113px'>" ;
	}
 	$replay .= '
 	<h2>Upload thumb for category '.$editid.'</h2>

	<div class="settings">
	<fieldset>
		<form id="catimageform" action="./modules/ajaximage.php" method="post" enctype="multipart/form-data">
			<table>
				<div id="preview">'.$thumb.'</div>
				<tr>
					<td>Upload Thumb:</td>
					<td><input type="file" size="30" name="cat_edit_thumb" id="cat_edit_thumb"></td>
				</tr>
				<input type="hidden" name="cat_edit_name" value="'.$res['name'].'">
				<tr>
					<td><input class="submitbutton" id="edit_cat_close'.$res['id'].'" type="submit" value="Close" /></td>
				</tr>
		</table>
		</form>
	</fieldset></div>';

	echo $replay ;
}









//advertise settings edit, delete and preview
if($_GET['adfunc']) {
	if ($_GET['adfunc'] == 'funcdel') {
		//set ad to default
		$db->query("UPDATE `sitead` SET `adtext` = '' WHERE adid = '".$_GET['siteadid']."'") ;
	}
	if ($_GET['adfunc'] == 'funcedit') {
		if($_GET['ad_edit_id']) {
			$db->query("UPDATE sitead SET `adtext` = '".$_GET['ad_edit_text']."' WHERE `adid` = '".$_GET['ad_edit_id']."'") ;
			$db->query("UPDATE sitead SET `adsize` = '".$_GET['ad_edit_size']."' WHERE `adid` = '".$_GET['ad_edit_id']."'") ;
		}
	}
	if ($_GET['adfunc'] == 'funcpre') {
		if($_GET['ad_pre_id']) {
			$preid = $_GET['ad_pre_id'] ;
					$db->query("SELECT * from `sitead` WHERE adid = '".$preid."'") ;
					$res = $db->fetch() ;
					$replay = '<h2>Preview AD '.$preid.'</h2>
					<div class="settings"><fieldset><form action="" method="post" enctype="multipart/form-data"><table>
					<tr><td>Ad Place:</td><td>'.$res['adspace'].'</td></tr>
					<tr><td>Ad Size:</td><td>'.$res['adsize'].'</td></tr>
					<tr>'.$res['adtext'].'</tr>
					<tr><td><input class="submitbutton" id="ad_edit_close'.$res['id'].'" type="submit" value="Close" /></td></tr>
					</table></form></fieldset></div>';

		echo $replay;
		}
	}
}
if($_GET['siteadedit']) {

	$editid = $_GET['siteadedit'];
	$db->query("SELECT * from `sitead` WHERE adid = '".$editid."'") ;
	$res = $db->fetch() ;

 	$replay = '<h2>Edit advertisement ID '.$editid.'</h2>
 	<h5>You can edit everything so watch out you only use the allowed characters</h5>
	<div class="settings">
	<fieldset><form action="" method="post" enctype="multipart/form-data"><table>
				<tr>
					<td>AD text:</td>
					<td><textarea type="text" id="ad_edit_text" >'.$res['adtext'].'</textarea></td>
				</tr>
				<tr>
					<td>Ad size:</td>
					<td><select id="ad_edit_size">
							<option SELECTED value="'.$res['adsize'].'">'.$res['adsize'].'</option>
							<option value="300x250">300x250</option>
							<option value="468x60">468x60</option>
							<option value="728x90">728x90</option>
							<option value="160x600">160x600</option>
						</select>
					</td>
				</tr>
				<input type="hidden" id="ad_edit_id" value="'.$res['adid'].'">
				<tr>
					<td><input class="submitbutton" id="ad_edit_submit" type="submit" value="Submit" /></td>
					<td><input class="submitbutton" id="ad_edit_close'.$res['id'].'" type="submit" value="Close" /></td>
				</tr>
		</table>
		</form>
	</fieldset></div>';

	echo $replay ;
}

}
?>

