<?php
// +------------------------------------------------------------------------+
// | PHP Melody version 1.6.7 ( www.phpsugar.com )
// +------------------------------------------------------------------------+
// | PHP Melody IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than www.phpsugar.com or if you have received
// | this software from someone who is not a representative of
// | phpSugar, you are involved in an illegal activity.
// | ---
// | In such case, please contact: support@phpsugar.com.
// +------------------------------------------------------------------------+
// | Developed by: phpSugar (www.phpsugar.com) / support@phpsugar.com
// | Copyright: (c) 2004-2011 PhpSugar.com. All rights reserved.
// +------------------------------------------------------------------------+

$showm	= '2';
include('header.php');

$action	 = $_GET['a'];
$id 	 = (int) $_GET['vid'];
$page	 = (int) $_GET['page'];

if($_POST['Submit'] != '')
{
	if($_POST['Submit'] == 'Delete checked')
		$action = 'delvids';
}

if($page == '' || !is_numeric($page))
   $page = 1;
$limit	 = 20;	//	videos per page
$from 	 = $page * $limit - ($limit);


switch($action)
{
	case 'deleted':
		$info_msg = "<div class=\"info_msg_err\">The item has been deleted.</div>";
	break;
	
	case 'approve':
		if($id == '')	break;
		
		define('PHPMELODY', true);

		$video_details = array(	'uniq_id' => '',	
								'artist' => '',	
								'video_title' => '',	
								'description' => '',	
								'yt_id' => '',	
								'yt_length' => '',	
								'category' => '',	
								'submitted' => '',	
								'source_id' => '',	
								'language' => '',	
								'age_verification' => '',
								'url_flv' => '',	
								'yt_thumb' => '',
								'mp4' => '',	
								'direct' => '',	
								'tags' => '',
								'restricted' => 0 
								);		
		$sources = a_fetch_video_sources();

		$temp	= array();
		$query = mysql_query("SELECT * FROM pm_temp WHERE id = '".$id."'");
		$input = mysql_fetch_assoc($query);
		mysql_free_result($query);


		$video_details['artist'] 		= 	$input['artist'];
		$video_details['video_title']	=	$input['video_title'];
		$video_details['description']	=	$input['description'];
		$video_details['submitted']		=	$input['username'];
		$video_details['direct']		=	$input['url'];
		$video_details['category']		=	$input['category'];
		$video_details['submitted']		=	$input['username'];
		$video_details['source_id']		=	$input['source_id'];
		$video_details['language']		=	$input['language'];
		$video_details['tags']			=	$input['tags'];

		//	generate unique id;
		$found = 0;
		$uniq_id = '';
		$i = 0;
		do
		{
			$found = 0;
			if(function_exists('microtime'))
				$str = microtime();
			else
				$str = time();
			$str = md5($str);
			$uniq_id = substr($str, 0, 9);
			if(count_entries('pm_videos', 'uniq_id', $uniq_id) > 0)
				$found = 1;
		} while($found === 1);
		
		
		//	fetch information about this video
		if ($input['source_id'] != $sources['localhost']['source_id'])
		{
			switch ($sources[ $video_details['source_id'] ]['source_name'])
			{
				case 'divx':
				case 'windows media player':
				case 'quicktime':
				case 'mp3':
					$video_details['source_id'] = $sources['other']['source_id'];
				break;
			}
			
			require_once( "./src/" . $sources[ $video_details['source_id'] ]['source_name'] . ".php");
			do_main($temp, $video_details['direct'], false);
			
			if($temp['yt_id'] == '')
			{
				$video_details['yt_id'] = substr( md5( time() ), 2, 9);
			}
			else
			{
				$video_details['yt_id'] = $temp['yt_id'];
			}
			
			if ($video_details['source_id'] == $sources['other']['source_id'])
			{
				$video_details['url_flv']	=	$input['url'];
			}
			else
			{
				$video_details['url_flv']	=	$temp['url_flv'];
			}
			
			$video_details['mp4']		=	$temp['mp4'];
			$video_details['yt_length']	=	$temp['yt_length'];
			$video_details['yt_thumb']	=	$temp['yt_thumb'];
		}
		else // user uploaded video
		{
			$video_details['url_flv'] = $input['url'];
			$video_details['direct'] = $input['url'];
			$video_details['yt_length'] = 0;
			
			if ($input['thumbnail'] != '')
			{
				$ext = strtolower(array_pop(explode('.', $input['thumbnail'])));
				if (rename(_THUMBS_DIR_PATH . $input['thumbnail'], _THUMBS_DIR_PATH . $uniq_id . '-1.'. $ext))
				{
					$input['thumbnail'] =  $uniq_id . '-1.'. $ext;
				}
				
				$video_details['yt_thumb'] = _THUMBS_DIR . $input['thumbnail'];	
			}
			else
			{
				$video_details['yt_thumb'] = '';
			}
		}

		$video_details['uniq_id'] = $uniq_id;

		//	download thumbnail
		if ('' != $video_details['yt_thumb'] && $video_details['source_id'] != $sources['localhost']['source_id'])
		{
			$img = download_thumb($video_details['yt_thumb'], _THUMBS_DIR_PATH, $uniq_id);
		}
		
		foreach($video_details as $k => $v)
		{
			$video_details[$k] = str_replace("&amp;", "&", $v);
		}
		
		//	Ok, let's add this video to our database
		$new_video = insert_new_video($video_details);
		
		if($new_video !== true)
		{
			$info_msg = '<div class="info_msg_err"><em>A problem occurred! Could not insert new video in your database;</em><br /><strong>MySQL Reported:</strong> ".$new_video[0]."<br /><strong>Error Number:</strong> '.$new_video[1].'</div>';				
		}
		else
		{
			if($video_details['tags'] != '')
			{
				$tags = explode(",", $video_details['tags']);
				foreach($tags as $k => $tag)
				{
					$tags[$k] = stripslashes(trim($tag));
				}
				//	remove duplicates and 'empty' tags
				$temp = array();
				for($i = 0; $i < count($tags); $i++)
				{
					if($tags[$i] != '')
						if($i <= (count($tags)-1))
						{
							$found = 0;
							for($j = $i + 1; $j < count($tags); $j++)
							{
								if(strcmp($tags[$i], $tags[$j]) == 0)
									$found++;
							}
							if($found == 0)
								$temp[] = $tags[$i];
						}
				}
				$tags = $temp;
				//	insert tags
				if(count($tags) > 0)
					insert_tags($uniq_id, $tags);
			}
			$info_msg = '<div class="info_msg_ok">Video has been approved!<br />Would you like to <a href="modify.php?vid='.$uniq_id.'">edit</a> this video?</div>'; 
		}

		//	remove the suggested video from 'pm_temp'
		@mysql_query("DELETE FROM pm_temp WHERE id = '".$id."'");
	break;
	
	case 'delall':
		
		$files = array();
		$sql = "SELECT url FROM pm_temp WHERE source_id = '1'";
		$result = mysql_query($sql);
		
		if (mysql_num_rows($result) > 0)
		{
			while ($row = mysql_fetch_assoc($result))
			{
				$files[] = $row['url'];
			}
			mysql_free_result($result);
		}
		
		if (count($files) > 0)
		{
			foreach ($files as $k => $filename)
			{
				if (file_exists(_VIDEOS_DIR_PATH . $filename) && strlen($filename) > 0)
				{
					unlink(_VIDEOS_DIR_PATH . $filename);
				}
			}
		}
		
		mysql_query("TRUNCATE TABLE pm_temp");
		$info_msg = '<div class="info_msg_ok">All videos pending approval have been removed.</div>';
	break;
	
	case 'delvid':
		
		$sql = "SELECT url, source_id, thumbnail FROM pm_temp WHERE id = '". $id ."'";
		$result = mysql_query($sql);
		$video = mysql_fetch_assoc($result);
		mysql_free_result($result);
		
		if ($video['source_id'] == 1)
		{
			if (file_exists(_VIDEOS_DIR_PATH . $video['url']) && strlen($video['url']) > 0)
			{
				unlink(_VIDEOS_DIR_PATH . $video['url']);
			}
			if ($video['thumbnail'] != '')
			{
				unlink(_THUMBS_DIR_PATH . $video['thumbnail']);
			}
		}

		@mysql_query("DELETE FROM pm_temp WHERE id = '".$id."'");
	
		echo '<meta http-equiv="refresh" content="0;URL=approve.php?a=deleted&page='. $page .'" />';
		exit();
	break;
	case 'delvids':
		if($_POST['Submit'] == 'Delete checked')
		{
			$video_ids = array();
			$video_ids = $_POST['video_ids'];
			
			$total_ids = count($video_ids);
			if($total_ids > 0)
			{
				$in_arr = '';
				for($i = 0; $i < $total_ids; $i++)
				{
					$in_arr .= "'" . $video_ids[ $i ] . "', ";
				}
				$in_arr = substr($in_arr, 0, -2);
				if(strlen($in_arr) > 0)
				{
					$videos = array();
					$sql = "SELECT url, source_id, thumbnail FROM pm_temp WHERE id IN (". $in_arr .") AND source_id = '1'";
					$result = mysql_query($sql);
					
					while ($row = mysql_fetch_assoc($result))
					{
						$videos[] = $row;
					}
					mysql_free_result($result);
					
					$sql = "DELETE FROM pm_temp WHERE id IN (" . $in_arr . ")";
					$result = @mysql_query($sql);
					if(!$result)
						$info_msg = '<div class="info_msg_errimg">There was an error while updating your database.<br />MySQL returned: '.mysql_error().'</div>';
					else
						$info_msg = '<div class="info_msg_ok">The selected items have been deleted.</div>';
					
					if (count($videos) > 0)
					{
						foreach ($videos as $k => $video)
						{
							if (file_exists(_VIDEOS_DIR_PATH . $video['url']))
							{
								unlink(_VIDEOS_DIR_PATH . $video['url']);
							}
							if ($video['thumbnail'] != '')
							{
								unlink(_THUMBS_DIR_PATH . $video['thumbnail']);
							}
						}
					}
				}
			}
		}	
	break;
} //	end switch

// COUNT VIDEOS IN DB
$total_videos = count_entries('pm_temp', '', '');

if($total_videos - $from == 1)
	$page--;
	
$videos = a_list_temp('', '', $from, $limit, $page); 

if($total_videos - $from == 1)
	$page++;

// generate smart pagination
$filename = ('' != $_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF']) : 'approve.php';
$pagination = '';

$pagination = a_generate_smart_pagination($page, $total_videos, $limit, 1, $filename, '');

?>
<div id="sub_menu">
<li><a href="addvideo.php">Add new video</a></li>
<li><a href="embedvideo.php">Embed new video</a></li>
<li><a href="import.php">Import from Youtube</a></li>
<li><a href="import_user.php">Import from Youtube User</a></li>
<li><a href="reports.php">Reported Videos</a></li>
<li><a href="approve.php">Approve Videos</a></li>
</div>
<div id="content">
<h2>Videos pending approval</h2>
<?php echo $info_msg; ?>

<form name="approve_videos_checkboxes" action="approve.php?page=<?php echo $page;?>" method="post">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
  <tr>
    <td valign="top"><img src="images/remove.png" alt="delete" width="16" height="16" align="top" /> <a href="#" class="b_delete" onClick="del_alltemp()">Delete all</a></td>
    <td width="220" valign="top"><div class="totals">Total videos: <?php echo $total_videos; ?></div></td>
  </tr>
</table>
<table class="tablesorter" cellspacing="1">
 <thead>
  <tr> 
	<th align="center" width="20"><input type="checkbox" class="checkbox" name="checkall" onclick="checkUncheckAll(this);"/></th>
	<th width="15">&nbsp;</th>
    <th>Video Title</th>
    <th>Description</th>
	<th>Tags</th>
    <th>Submitted</th>
	<th>Added by</th>
    <th>Category</th>
    <th align="center">Action</th>
  </tr>
 </thead>
 <tbody>
	<?php echo $videos; ?>
 </tbody>
</table>
<?php
if($total_videos != 0) {
?>
 <table width="100%">
  <tr>
	<td align="left"><input type="submit" name="Submit" value="Delete checked" class="deletebutton"></td>
  </tr>
 </table>
<?php
}
?>
</form>

<div align="center"><?php echo $pagination; ?></div>

</div>

<script type="text/javascript">
	$(document).ready(function() {
		$('a[id^="show-more-"]').click(function(){
			var id = $(this).attr('id').match(/\d+$/);
			$(this).hide();
			$('#excerpt-'+id).hide();
			$('#full-text-'+id).show();
			$('#show-less-'+id).show();
			return false;
		});
		$('a[id^="show-less-"]').click(function(){
			var id = $(this).attr('id').match(/\d+$/);
			$(this).hide();
			$('#full-text-'+id).hide();
			$('#show-more-'+id).show();
			$('#excerpt-'+id).show();
			return false;
		});
	});
</script>

<?php
include('footer.php');
?>