<?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	= (int) $_GET['action'];
$page	= (int) $_GET['page'];
$filter = '';
$filters = array('broken', 'restricted', 'unchecked', 'localhost', 'featured', 'category', 'source', 'mostviewed', 'access');
$filter_value = '';

if(in_array(strtolower($_GET['filter']), $filters) !== false)
{
	$filter = strtolower($_GET['filter']);
	$filter_value = $_GET['fv'];

	if (($filter == 'source' || $filter == 'category') && $filter_value == '')
	{
		$filter = '';
	}
}

if($page == 0)
	$page = 1;

$limit = 30;		//	videos per page
$from = $page * $limit - ($limit);

$categories = a_list_cats_simple();

if($filter != "")
{
	switch($filter)
	{
		case 'broken':
			
			$total_videos = count_entries('pm_videos', 'status', VS_BROKEN);
			
		break;
		
		case 'restricted':
			
			$total_videos = count_entries('pm_videos', 'status', VS_RESTRICTED);
			
		break;
		
		case 'unchecked':
			
			$total_videos = count_entries('pm_videos', 'status', VS_UNCHECKED);
			
		break;
		
		case 'localhost':
			
			$total_videos = count_entries('pm_videos', 'source_id', '1');
			
		break;
		
		case 'featured':
			
			$total_videos = count_entries('pm_videos', 'featured', '1');
			
		break;
		
		case 'category':
			
			$filter_value = (int) $filter_value;
			if ($filter_value > 0)
			{
				$total_videos = $categories[$filter_value]['total_videos'];
			}
			else
			{
				$total_videos = 0;
				unset($filter_value);
			}
			
		break;
		
		case 'source':
			
			$filter_value = (int) $filter_value;
			$total_videos = count_entries('pm_videos', 'source_id', $filter_value);
			
		break;
		
		case 'mostviewed':
			
			$total_videos = count_entries('pm_videos', '', '');
			
		break;
		
		case 'access': // @since 1.6.5
			
			$filter_value = '1';
			$total_videos = count_entries('pm_videos', 'restricted', $filter_value);
			
		break;
	}
}
else
{
	$total_videos = count_entries('pm_videos', '', '');
}

if(!empty($_POST['submit']) && $_POST['submit'] == 'Search') 
{
	$search_query = secure_sql(trim($_POST['keywords']));
	$search_type = $_POST['search_type'];

	$videos = a_list_videos($search_query, $search_type, $from, $limit, $page);
	$total_videos = preg_match_all("/<\/tr>/", $videos, $matches);
} 
else 
{
	if($total_videos - $from == 1)
		$page--;
		
	$videos = a_list_videos('', '', $from, $limit, $page, $filter, $filter_value); 
	
	if($total_videos - $from == 1)
		$page++;	
}

// generate smart pagination
$filename = 'videos.php';
$pagination = '';

if(!isset($_POST['submit'])) 
	$pagination = a_generate_smart_pagination($page, $total_videos, $limit, 5, $filename, '&filter='. $filter .'&fv='. $filter_value);

?>
<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 manager</h2>
<div id="more_v_details">
You have <a href="approve.php"><?php echo count_entries('pm_temp', '', ''); ?> videos</a> pending approval and <a href="reports.php"><?php echo count_entries('pm_reports', '', ''); ?> videos</a> that have been reported by the users.
</div>
<br />
<?php

if ($_GET['action'] == 'deleted') 
{
	echo "<div class=\"info_msg_ok\">The item has been deleted.</div>";
}

// Fix for IE
if ($_POST['Submit_restrict_x'] != '' && $_POST['Submit_restrict_y'] != '')
{
	$_POST['Submit'] = 'Restrict access';
}
if ($_POST['Submit_derestrict_x'] != '' && $_POST['Submit_derestrict_y'] != '')
{
	$_POST['Submit'] = 'Derestrict access';
}

//	Batch Delete
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)
		{
			$categories = array();
			$sql = "SELECT uniq_id, category, url_flv, source_id FROM pm_videos WHERE uniq_id IN (" . $in_arr . ")";
			$result = mysql_query($sql);
			while ($row = mysql_fetch_assoc($result))
			{
				$categories[] = $row;
			}
			mysql_free_result($result);

			$sql = "DELETE FROM pm_videos WHERE uniq_id IN (" . $in_arr . ")";
			$result = mysql_query($sql);
			
			if(!$result)
			{
				echo '<div class="info_msg_errimg">There was an error while updating your database.<br />MySQL returned: '.mysql_error().'</div>';
			}
			else
			{
				mysql_query("DELETE FROM pm_comments WHERE uniq_id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_ratings WHERE id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_reports WHERE entry_id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_videos_urls WHERE uniq_id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_favorites WHERE uniq_id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_chart WHERE uniq_id IN (" . $in_arr . ")");
				mysql_query("DELETE FROM pm_tags WHERE uniq_id IN (" . $in_arr . ")");
				echo '<div class="info_msg_ok">The selected videos have been deleted.</div>';
			}
			
			// update video count for each category
			$video_count = array();
			foreach ($categories as $k => $row)
			{
				// delete hosted files
				if ($row['source_id'] == 1)
				{
					if (file_exists(_VIDEOS_DIR_PATH . $row['url_flv']) && strlen($row['url_flv']) > 0)
					{
						unlink(_VIDEOS_DIR_PATH . $row['url_flv']);
					}
				}
				
				if (file_exists(_THUMBS_DIR_PATH . $row['uniq_id'] .'-1.jpg'))
				{
					unlink(_THUMBS_DIR_PATH . $row['uniq_id'] .'-1.jpg');
				}
				
				$ids = $row['category'];				
				
				$buffer = explode(',', $ids);
				foreach ($buffer as $k => $id)
				{
					$video_count[$id]++;
				}
			}
			
			if (count($video_count) > 0)
			foreach ($video_count as $cid => $count)
			{
				if ('' != $cid)
				{
					$sql = "UPDATE pm_categories SET total_videos=total_videos-". $count ." 
							WHERE id = '". $cid ."'";
					mysql_query($sql);
				}
			}
			
		}
		update_config('total_videos', $config['total_videos'] - $total_ids);
		
		$videos = a_list_videos('', '', $from, $limit, $page, $filter); 
	}
	else
	{
		echo '<div class="info_msg">No items were selected!</div>';
	}
}
//	Mark video(s) as featured/regular video
else if ($_POST['Submit'] == 'Mark as featured' || $_POST['Submit'] == 'Mark as regular')
{
	$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)
		{
			$sql = "UPDATE pm_videos ";
			if ($_POST['Submit'] == 'Mark as featured')
			{
				$sql .= "SET featured = '1' ";
			}
			else
			{
				$sql .= "SET featured = '0' ";
			}
			$sql .=	" WHERE uniq_id IN (" . $in_arr . ")";
			$result = mysql_query($sql);
			
			if(!$result)
			{
				echo '<div class="info_msg_errimg">There was an error while updating your database.<br />MySQL returned: '.mysql_error().'</div>';
			}
			else
			{
				echo '<div class="info_msg_ok">The selected videos have been updated.</div>';
			}
		}
		$videos = a_list_videos('', '', $from, $limit, $page, $filter); 
	}
	else
	{	
		echo '<div class="info_msg">No items were selected!</div>';
	}
}
else if ($_POST['Submit'] == 'Move')
{
	$video_ids = array();
	$video_ids = $_POST['video_ids'];
	$new_cid   = (int) $_POST['move_to_category'];
	
	$total_ids = count($video_ids);
	
	if ($new_cid == '' || !array_key_exists($new_cid, $categories))
	{
		echo '<div class="info_msg">Please select a category first!</div>';
	}
	else
	{
		if($total_ids == 0)
		{
			echo '<div class="info_msg">No items were selected!</div>';	
		}
		else
		{
			$in_arr = '';
			for($i = 0; $i < $total_ids; $i++)
			{
				$in_arr .= "'" . $video_ids[ $i ] . "', ";
			}
			$in_arr = substr($in_arr, 0, -2);
			
			$sql = "SELECT category 
					FROM pm_videos 
					WHERE uniq_id IN (". $in_arr .")";
			$result = mysql_query($sql);
			if ( !$result)
			{
				echo '<div class="info_msg_err">Mysql Error: '.mysql_error().'</div>';
			}
			else
			{				
				$add = $total_ids;
				$deduct = array();
				
				while ($row = mysql_fetch_assoc($result))
				{
					if (strpos($row['category'], ','))
					{
						$buff = explode(',', $row['category']);
						foreach ($buff as $k => $v)
						{
							$deduct[ (int) $v ]++;
						}
					}
					else
					{
						$deduct[ (int) $row['category'] ]++;
					}
				}
				
				mysql_free_result($result);
				
				// update pm_videos
				$sql = "UPDATE pm_videos 
						SET category = '". $new_cid ."' 
						WHERE uniq_id IN (". $in_arr .")";
				$result = mysql_query($sql);
				if ( !$result)
				{
					echo '<div class="info_msg_err">This operation failed for some reason. <br />Mysql Error: '.mysql_error().'</div>';
				}
				
				// update pm_categories (deduct video count)
				foreach ($deduct as $cid => $count)
				{
					$sql = "UPDATE pm_categories 
							SET total_videos=total_videos-". $count ." 
							WHERE id = '". $cid ."'";
					mysql_query($sql);
				}
				
				// update pm_categories (add video count)
				$sql = "UPDATE pm_categories 
						SET total_videos=total_videos+". $add ."
						WHERE id = '". $new_cid ."'";
				
				$result = mysql_query($sql);
				
				echo '<div class="info_msg_ok">The selected videos were moved to <strong>'. $categories[$new_cid]['name'].'</strong>.</div>';
				
				// update table
				$videos = a_list_videos('', '', $from, $limit, $page, $filter); 
			}
		}
	}
}
else if ($_POST['Submit'] == 'Restrict access' || $_POST['Submit'] == 'Derestrict access')
{
	$video_ids = array();
	$video_ids = $_POST['video_ids'];
	$total_ids = count($video_ids);
	
	if ($total_ids > 0)
	{
		$access = ($_POST['Submit'] == 'Restrict access') ? '1' : '0';
		
		$in_arr = '';
		for($i = 0; $i < $total_ids; $i++)
		{
			$in_arr .= "'" . $video_ids[ $i ] . "', ";
		}
		$in_arr = substr($in_arr, 0, -2);
		
		$sql = "UPDATE pm_videos 
				SET restricted = '". $access ."'
				WHERE uniq_id IN (". $in_arr .")";
		$result = mysql_query($sql);
			
		if ( ! $result)
		{
			echo '<div class="info_msg_errimg">There was an error while updating your database.<br />MySQL returned: '.mysql_error().'</div>';
		}
		else
		{
			echo '<div class="info_msg_ok">The selected videos have been updated.</div>';
			$videos = a_list_videos('', '', $from, $limit, $page, $filter, $filter_value); 
		}
	}
	else
	{
		echo '<div class="info_msg">No items were selected!</div>';	
	}
}

//	Delete all videos
if($action == 9 && is_admin())
{
	//	clear database of all videos
	if(isset($_POST['Submit']))
	{
		if($_POST['Submit'] == 'Yes')
		{
			$files = array();
			$sql = "SELECT url_flv FROM pm_videos WHERE source_id = '1'";
			$result = mysql_query($sql);
			
			if (mysql_num_rows($result) > 0)
			{
				while ($row = mysql_fetch_assoc($result))
				{
					$files[] = $row['url_flv'];
				}
				mysql_free_result($result);
				
				foreach ($files as $k => $filename)
				{
					if (file_exists(_VIDEOS_DIR_PATH . $filename) && strlen($filename) > 0)
					{
						unlink(_VIDEOS_DIR_PATH . $filename);
					}
				}
			}
			
			$sql = "TRUNCATE TABLE pm_videos";
			$result = @mysql_query($sql);
			if(!$result)
			{
				echo '<div class="info_msg_err">Mysql Error: '.mysql_error().'</div>';
			}
			else
			{
			
				update_config('total_videos', 0);
				
				$sql = " UPDATE pm_categories SET total_videos = '0' ";
				@mysql_query($sql);
				
				//	pm_videos extension table
				$sql = "TRUNCATE TABLE pm_videos_urls";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	comments table
				$sql = "TRUNCATE TABLE pm_comments";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	favorites table
				$sql = "TRUNCATE TABLE pm_favorites";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	tags table
				$sql = "TRUNCATE TABLE pm_tags";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	reports table
				$sql = "TRUNCATE TABLE pm_reports";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	ratings table
				$sql = "TRUNCATE TABLE pm_ratings";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
				
				//	chart table
				//	tags table
				$sql = "TRUNCATE TABLE pm_chart";
				$result = @mysql_query($sql);
				if(!$result)
					echo '<div class="info_msg_err">MySQL Error: '.mysql_error().'</div>';
			}
		
			echo '<div class="info_msg_ok">Your database is now clean as a whistle.</div>';
		}
		else
		{
			echo '<meta http-equiv="refresh" content="0;URL=videos.php" />';
			exit();
		}
	}
	else
	{
	?>
		<div class="info_msg_err">
			Are you sure you want to delete all your videos? Clicking 'YES' will remove absolutely all existing videos.
		</div>
		<br />
		<form name="delete" method="post" action="videos.php?action=9">
			<input type="submit" name="Submit" value="Yes" class="inputbutton" style="position:relative"/> <input type="submit" name="Submit" value="Cancel" class="inputbutton" style="position:relative" />
		</form>

	<?php
	include('footer.php');
	exit();
	}
}
else if ($action == 9)
{
	restricted_access();
}
else
{
?>
<table width="100%" border="0" cellspacing="1" cellpadding="3">
  <tr>
    <td valign="top">
	<form name="search" action="videos.php" method="post" onsubmit="return validateSearch('true');">
	<input name="keywords" type="text" value="<?php echo $_POST['keywords']; ?>" size="30" />
	<select name="search_type">
	  <option value="artist" selected="selected">Artist/Band</option>
	  <option value="video_title">Video title</option>
	  <option value="uniq_id">Video Unique ID</option>
	</select>
	<input name="submit" type="submit" value="Search" class="inputbutton" /><br />
	<small>Please make the search as descriptive as possible.</small>
	</form>	</td>
    <td width="220" valign="top"><div class="totals">Total videos: <?php echo $total_videos; ?> </div></td>
  </tr>
</table>
<table width="100%" border="0" cellspacing="1" cellpadding="3">
  <tr>
    <td valign="top">
	<?php
	if($filter == '')
	{
		?>
		 <img src="images/remove.png" alt="delete" width="16" height="16" align="top" /> <a href="videos.php?action=9" class="b_delete">Delete all videos</a>
		<?php
	}
	?>
	</td>
    <td align="right" valign="top">
	<div id="sort_by">
	 <small><strong>Filter: </strong></small>&nbsp;
	 <form name="other_filter" action="videos.php">
	 <select name="URL" onChange="window.parent.location=this.form.URL.options[this.form.URL.selectedIndex].value">
	 	<option value="videos.php">by videos ...</option>
	 	<option value="videos.php?filter=restricted&page=1" <?php if ($filter == 'restricted') echo 'selected="selected"'; ?> >Geo-Restricted Videos</option>
	 	<option value="videos.php?filter=broken&page=1" <?php if ($filter == 'broken') echo 'selected="selected"'; ?>>Dead Videos</option>
	 	<option value="videos.php?filter=featured&page=1" <?php if ($filter == 'featured') echo 'selected="selected"'; ?>>Featured Videos</option>
	 	<option value="videos.php?filter=localhost&page=1" <?php if ($filter == 'localhost') echo 'selected="selected"'; ?>>Hosted locally</option>
	 	<option value="videos.php?page=1&filter=mostviewed" <?php if ($filter == 'mostviewed') echo 'selected="selected"'; ?>>Most viewed</option>
		<option value="videos.php?page=1&filter=access" <?php if ($filter == 'access') echo 'selected="selected"'; ?>>Restricted access</option>
	 </select>
	 </form>
	 <form name="category_filter" action="videos.php" method="get">
	  <input type="hidden" name="filter" value="category" />
	  <?php
	 	 $categories_dropdown_options = array(
											'attr_name' => 'fv',
											'attr_id' => 'select_move_to_category',
											'first_option_text' => 'by category..',
											'first_option_value' => '',
											'selected' => ($filter == 'category') ? $filter_value : '',
											'other_attr' => ' onchange=submit() '
											);
		echo categories_dropdown($categories_dropdown_options);
	  ?>
	 </form>

	 <form name="source_filter" action="videos.php" method="get">
	  <input type="hidden" name="filter" value="source" />
	  <select name="fv" onchange=submit()>
	   <option value="">by video source...</option>
	   <?php
	   $sources = a_fetch_video_sources('source_name');
	   foreach ($sources as $id => $src)
	   {
	   		$option = '';
	   		if (is_int($id) && $id > 1 && $id != 44 && $id != 43)
			{
				$option = '<option value="'. $src['source_id'] .'" ';
				if ($filter_value == $id && $filter == 'source')
				{
					$option .= ' selected="selected" ';
				}
				$option .= '>'. ucfirst($src['source_name']) .'</option>';
				echo $option;
			}
	   }
	   
	   ?>
	  </select>
	 </form>
	 <a href="videos.php" title="Remove filter"><img src="images/ico_filter_remove.gif" alt="Remove filter" width="21" height="15" border="0" align="absmiddle" /></a>
	</div>
	 <br />
	</td>
  </tr>
</table>
<form name="videos_checkboxes" id="videos_checkboxes" action="videos.php?page=<?php echo $page;?>&filter=<?php echo $filter;?>&fv=<?php echo $filter_value;?>" method="post">
 <table id="videosSortTable" class="tablesorter" cellspacing="1">
  <thead>
   <tr>
	<th align="center" width="3%"><input type="checkbox" name="checkall" onclick="checkUncheckAll(this);"/></th>
	<th width="3%">&nbsp;</th>
	<th width="5%">Unique ID</th>
	<th width="12">&nbsp;</th>	
	<th width="12">&nbsp;</th>
    <th>Video title</th>
    <th width="90">Added</th>
	<th width="65">Views</th>
	<th>Category</th>
	<th>Comments</th>
    <th width="90">Action</th>
   </tr>
  </thead>
  <tbody>
	<?php echo $videos; ?>
  </tbody>
 </table>
 
 <table>
    <tr style="background-color: #fff;">
	<td>
	 <input type="submit" name="VideoChecker" id="VideoChecker" value="Check status" class="approvebutton" onclick="javascript: return false;" />
	</td>
	<td align="left">
	 <input type="submit" name="Submit" value="Mark as featured" class="genericbutton" />
	</td>
	<td aligh="left"> 
	 <input type="submit" name="Submit" value="Mark as regular" class="genericbutton" /> 
	</td>
	<td align="left">
	 <input type="submit" name="Submit" value="Delete checked" class="deletebutton" onClick="return confirm_delete_all();" /> 
	</td>
	<td align="left">
	 <input type="image" name="Submit_restrict" value="Restrict access" class="inputbutton" src="images/locked.png" class="hintanchor" onMouseover="showhint('This button will mark the selected video(s) as private; Access to these video(s) will only be available to registred users.', this, event, '250px');" />  
	</td>
	<td align="left">
	 <input type="image" name="Submit_derestrict" value="Derestrict access" class="inputbutton" src="images/unlocked.png" class="hintanchor" onMouseover="showhint('This button will remove any viewing restrictions making the selected video(s) available for everyone. By default, all videos are available to your visitors.', this, event, '250px');" />  
	</td>
	<td align="right" width="100%">
	 <div id="sort_by">
	   <small><strong>Move selected videos to</strong></small>
	   <?php 
			$categories_dropdown_options = array(
										'attr_name' => 'move_to_category',
										'attr_id' => 'select_move_to_category',
										'first_option_text' => 'category...',
										'selected' => ($_POST['move_to_category']) ? $_POST['move_to_category'] : 0
										);
			echo categories_dropdown($categories_dropdown_options);
	   ?>
	  <input type="submit" name="Submit" value="Move" class="genericbutton" onClick="if ($('select[name=move_to_category] option:selected').val() == '' || $('select[name=move_to_category] option:selected').val() == '-1') {alert('Please select a category first.'); return false;}" class="hintanchor" onMouseover="showhint('Selected videos will be moved to the chosen category. If some videos are currently in multiple categories, they will be moved to the chosen category only.', this, event, '250px')" />
	  </div>
	</td>
   </tr>
 </table>
</form>

<div id="video_check_message" class="info_msg"></div>
<br />

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

<br /><br />
<table align="center" width="40%">
 <tr>
  <td width="20%" align="center">
   <img src="<?php echo VS_UNCHECKED_IMG;?>" width="16" height="16" align="absmiddle" />&nbsp;&nbsp;<small>Unchecked</small>
  </td>
  <td width="20%" align="center">
   <img src="<?php echo VS_OK_IMG;?>" width="16" height="16" align="absmiddle" />&nbsp;&nbsp;<small>Video Found</small>
  </td>
  <td width="25%" align="center">
   <img src="<?php echo VS_BROKEN_IMG;?>" width="16" height="16" align="absmiddle" />&nbsp;&nbsp;<small>Video Not Found</small>
  </td>
  <td width="35%" align="center">
   <img src="<?php echo VS_RESTRICTED_IMG;?>" width="16" height="16" align="absmiddle" />&nbsp;&nbsp;<small>Geo-Restricted access</small>
  </td>
 </tr>
</table>
</div>


<?php
}	//	else - if($action == 9)
include('footer.php');
?>