<?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.
// +------------------------------------------------------------------------+

if ($_POST['do'] == 'checkurl')
{
	if ($_POST['url'] == '')
	{
		exit();
	}

	session_start();
	require('../config.php');
	include_once(ABSPATH . 'include/user_functions.php');
	include_once(ABSPATH . 'include/islogged.php');
	include(ABSPATH .'admin/functions.php');
	
	if ( ! $logged_in || ( ! is_admin() && ! is_moderator() && ! is_editor()))
	{
		exit();
	}
	if (is_editor() || (is_moderator() && !mod_can('manage_videos')))
	{
		exit();
	}
	
	$msg = '';
	$msg_color = '';
	
	$url = trim($_POST['url']);
	$url = secure_sql($url);
	$uniq_id = '';
	
	if (strpos($url, 'youtube.com'))
	{
		preg_match("/v=([^(\&|$)]*)/", $url, $matches);
		$url = 'http://www.youtube.com/watch?v='. $matches[1];
	}

	$sql = "SELECT uniq_id FROM pm_videos_urls 
			WHERE direct = '". $url ."'";
	$result = @mysql_query($sql);
	if ( ! $result)
	{
		$msg = 'MySQL error';
		$msg_color = 'red';
	}
	if (mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_assoc($result);
		$uniq_id = $row['uniq_id'];
		
		$msg = 'This URL was already added into your database! <a href="modify.php?vid='. $uniq_id. '">Edit</a> video.';
		$msg_color = 'red';
	}
	else
	{
		$msg = '';
		$msg_color = 'green';
	}
	mysql_free_result($result);
	
	if (strlen($msg) > 0)
	{
		echo '<small><i><span style="color: '. $msg_color .';">'. $msg .'</span></i></small>';
	}
	
	exit(); // the end
}


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

define('PHPMELODY', true);

$message = '';
$allowed_ext = array('.flv', '.mp4', '.mov', '.wmv', '.divx', '.avi', '.mkv', '.asf', '.wma', '.mp3', '.m4v', '.m4a', '.3gp', '.3g2');

$step = (int) $_GET['step'];
if($step == '')
	$step = 1;


if($step == 2 && isset($_POST['Submit']))
{
	if(trim($_POST['url']) == '')
	{
		$step = 1;
		$message = 'Invalid URL';	
	}
}


function add_video_form($video_details = array())
{
	$categories_dropdown_options = array(
									'attr_name' => 'category[]',
									'attr_id' => 'main_select_category',
									'select_all_option' => false,
									'spacer' => '&mdash;',
									'selected' => 0,
									'other_attr' => 'multiple="multiple"'
									);
	$languages = fetch_languages();	

		if($video_details['url_flv'] == '') {
			$video_lookup = '<img src="images/ico_error.png" align="absmiddle" /> <span class="small-warning"><strong>The video was not found. Don\'t continue with this submission. Please go back.</strong></span>';		
		} else {
			$video_lookup = '<img src="images/ico_check.png" /> <span class="small-ok">Video was found please fill in the form below.</span>';
		}

?>
			<form method="post" enctype="multipart/form-data" action="addvideo.php?step=3" name="addvideo_form_step2" onsubmit="return validateFormOnSubmit(this, 'Please fill in the required fields (highlighted) or make sure the URL you entered at STEP 1 is valid.')">
			<table cellpadding="5" cellspacing="0">
			<tr>
			  <td>&nbsp;</td>
			  <td><?php echo $video_lookup; ?></td>
			  </tr>
			<tr class="table_row1">	
				<td><strong>Singer/Band</strong></td> 
				<td><input name="artist" type="text" id="must" value="<?php echo $video_details['artist']; ?>" style="width: 500px;" /></td>
		      </tr>
			<tr class="table_row1">
				<td><strong>Video Title</strong></td>
				<td><input name="video_title" type="text" id="must" value="<?php echo $video_details['video_title']; ?>" style="width: 500px;" /></td>
		      </tr>
			<tr class="table_row1">
				<td><strong>Category</strong></td>
				<td><?php echo categories_dropdown($categories_dropdown_options); ?>
				</td>
		      </tr>
			<tr class="table_row1">
				<td><strong>Featured</strong></td>
				<td>
				 <label>
				  <input type="checkbox" name="featured" value="1" /> Yes, mark as <span class="b_featured">featured</span> 
				 </label>
				</td>
			</tr>
			<tr>
				<td valign="top"><strong>Description</strong></td>
				<td>
				<textarea name="description" id="textarea-WYSIWYG" style="height: 150px; width: 500px;"><?php echo $video_details['description']; ?></textarea>
				<script language="javascript1.2">
					if(navigator.userAgent.toLowerCase().indexOf('chrome/1') == -1)
					{
					// Overwrite WYSIWYG Width and Height
					wysiwygWidth = '100%';
					wysiwygHeight = 150;
					generate_wysiwyg('textarea-WYSIWYG');
					}
				</script>
				<script type="text/javascript">
					//	Editor not loaded?
					if ($("#wysiwygtextarea-WYSIWYG").length == 0)
					{
						// restore textarea
						$("#textarea-WYSIWYG").show();
					}
				</script>
				</td>
		      </tr>
			<tr class="table_row1">
				<td><strong>Tags</strong></td>
				<td><input name="tags" type="text" value="<?php echo $video_details['tags']; ?>" style="width: 500px;" /><br />
				 	<small>(e.g. madonna, justin timberlake, live)</small>				</td>
		      </tr>
			<tr class="table_row1">
				<td><strong>Thumbnail location</strong></td>
				<td><input type="text" name="yt_thumb" id="yt_thumb" value="<?php echo $video_details['yt_thumb']; ?>" style="width: 500px;" /></td>
		      </tr>
			<?php
			if($video_details['source_id'] == 1 || $video_details['source_id'] == 2)
			{
			?>
			<tr class="table_row1">
				<td align="right"><small>...or upload one</small></td>
				<td>
				<input type="file" name="thumb" onChange="javascript: if(this.value!='') yt_thumb.disabled='disabled'; else yt_thumb.disabled=''"/>				</td>
		      </tr>
			<?php
			}
			?>
			<tr>
				<td align="right"><strong>Restrict access</strong></td>
				<td>
					<label><input type="radio" name="restricted" value="1" <?php echo ($video_details['restricted'] == '1') ? 'checked="checked"' : '';?> /> Yes</label> 
					<label><input type="radio" name="restricted" value="0" <?php echo ($video_details['restricted'] != '1') ? 'checked="checked"' : '';?> /> No</label>
				</td>
			</tr>
			<tr>
				<td align="right"></td>
				<td>
				<input type="hidden" name="language" value="1" />
				<input type="hidden" name="yt_id" value="<?php echo $video_details['yt_id']; ?>" />
				<input type="hidden" name="url_flv" value="<?php echo $video_details['url_flv']; ?>" />
				<input type="hidden" name="source_id" value="<?php echo $video_details['source_id']; ?>" />
				<input type="hidden" name="submitted" value="<?php echo $video_details['submitted']; ?>" />
				<input type="hidden" name="mp4" value="<?php echo $video_details['mp4']; ?>" />
				<input type="hidden" name="direct" value="<?php echo $video_details['direct']; ?>" />
				<input type="hidden" name="age_verification" value="0" />
				<input type="submit" name="submit" value="Step 3 &raquo;" class="inputbutton" />				</td>
		      </tr>
			</table>
			<?php
			if($video_details['yt_id'] == '') 
				$video_details['yt_id'] = generate_activation_key(9); 
			?>
			</form>
			<br />
<?php
}

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

?>
<script language="javascript">

function checkFields(Form) {

	var msg;
	if(Form.elements.url.value == "")
		msg = "Please insert a link valid link as instructed below.";
	
	if(msg)
	{
		document.forms["add"].elements.url.style.background = "#FFDDDE";
		alert(msg);
		return false;
	}
	else 
		return true;
}
</script>
<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>Add Video</h2>
<?php echo $message; ?>
<?php

switch($step)
{

	case 1:		//	STEP 1
?>
	<br />
	<div id="add_video_progress">
		<a href="addvideo.php"><img src="images/ico_addvideo.gif" alt="Add video" width="102" height="24" align="absmiddle" border="0" /></a> 
		<span class="steps_selected">1. Choose video</span>
		<span class="steps">2. Add details</span>
		<span class="steps">3. Finish</span>
	</div>
	<br />
	<table width="100%" cellspacing="0" cellpadding="0">
	<tr>
		<td width="50%" valign="top">
		<h2>Direct input</h2>
		<br />
		<form name="add" action="addvideo.php?step=2" method="post" onSubmit="return checkFields(this);">
				<p>
				<input type="text" id="addvideo_direct_input" name="url" value="http://" onFocus="clearText(this)" onBlur="clearText(this)" size="30" style="width: 260px;" /> 
				<input type="submit" id="addvideo_direct_submit" name="Submit" value="Step 2 &raquo;" class="inputbutton" />
				<br /><span id="addvideo_direct_response"></span>
&nbsp;		</p>
		</form>
		<br />
		</td>
	    <td width="50%" valign="top">
		<h2>Upload video</h2>
			<form id="upload_flv" enctype="multipart/form-data" action="upload_file.php" method="post">
			<ul style="padding-left: 0; margin-left: 0;">
			<li id="uploader" style="list-style-type: none; padding: 0; margin: 0;">
				<label for="myFile"> </label>
				<input name="MAX_FILE_SIZE" value="<?php echo $upload_max_filesize; ?>" type="hidden" />
				<input name="myFile" id="myFile" type="file" />
				<input type="submit"  name="submit" id="upload_submit" value="Step 2 &raquo;" class="inputbutton" />
			</li>
			</ul>
		  </form>
	  </td>
	</tr>
	<tr>
	  <td colspan="2">
	  <div id="instructions">
	  <h2>Instructions</h2>
	  <strong>About Direct Input</strong>
	  <br />
	  Direct input allows you to add a video from any location (both local and remote) by simply pasting in the link to the video. <br />
	  <b>Local videos</b><br />
	  In case you want to add a *.flv or a *.mp4 video that you uploaded via FTP, please first make sure the video has been uploaded to /uploads/videos/. If you upload it to another location the video won't be added properly. Once you have the full and correct URL to the video, please post it under '<em>Direct Input</em>' and press the '<em>Step 2</em>' button.
	  <br />
	   <b>Remote videos</b><br />
	   <table width="90%" border="0" cellspacing="1" cellpadding="2">
	     <tr>
	     	<td colspan="2">The remote videos are videos that you add to PHP Melody from other video sites. Thanks to the new PHP Melody, you can  add videos from any of the following video sources:</td>
	     </tr>
		 <?php
			$sources = a_fetch_video_sources();
			$sources = array_reverse($sources);
			$counter = 1;
			
			foreach ($sources as $k => $src)
			{
				if (is_int($k) && $k >= 2): 
				?>
				<tr>
					<td width="10%"><?php echo $counter.'. '. ucfirst($src['source_name']);?></td>
					<td>(e.g. <em><?php echo $src['url_example'];?></em>)</td>
				</tr>
				<?php 
				$counter++;
				endif;
			}
		 ?>
	   </table>
		<br />
		To add/import videos from any of these video sources simply paste in the URL of the video under '<em>Direct Input</em>'. Some video sources provide more information than others and as a result you will sometimes have to enter the video details manually. Please remember that adding videos from remote locations won't actually download the *.flv file to your host. If for any unknown reason any of these video sources stops working please contact the PHPSugar support ASAP.
	  <br />
	  <strong>Uploading a video</strong>
	  <br />
	  Instead of using the FTP to upload *.flv or *.mp4 videos you can use the admin area. The files will be uploaded in the /uploads/videos/ folder.
	  </div>
	  </td>
	</tr>
  </table>
<?php
	break;
	
	case 2:		//	STEP 2
		?>
		<br />
		<div id="add_video_progress">
			<a href="addvideo.php"><img src="images/ico_addvideo.gif" alt="Add video" width="102" height="24" align="absmiddle" border="0" /></a> 
			<span class="steps">1. Choose video</span>
			<span class="steps_selected">2. Add details</span>
			<span class="steps">3. Finish</span>
		</div>
		<br />
		<?php
	
		if(isset($_POST['Submit']) || $_GET['url'] != '' || isset($_POST['filename']))
		{
			if($_POST['url'] != '' || $_GET['url'] != '')
				$url = (isset($_POST['url'])) ? trim($_POST['url']) : trim($_GET['url']);
			
			if($_POST['submitted'] != '' || $_GET['submitted'] != '')
				$submitted = (isset($_POST['submitted'])) ? $_POST['submitted'] : trim($_GET['submitted']);
			else
				$submitted = $userdata['username'];
			/*
				MODE
				1 = Outsource (e.g. youtube)
				2 = Direct URL to video file
				3 = Direct URL/Path/Filename to video hosted locally
			*/
			
			$mode = 0;
			$temp = '';
			
			//	Is this a direct link to a video file?
			if (strpos($url, '?') !== false)
			{
				$temp = explode('?', $url);
				$url = $temp[0];
			}
						
			$ext = '.'. strtolower(array_pop(explode('.', $url)));
			
			if (is_array($temp) && count($temp) > 0)
			{
				$url = '';
				$temp[0] = rtrim($temp[0], '?');
				$temp[0] = $temp[0] .'?';
				foreach ($temp as $k => $v)
				{
					$url .= $v;
				}
			}
			
			if(in_array($ext, $allowed_ext) && (preg_match('/photobucket\.com/', $url) == 0))
			{
				if(!is_url($url))
				{
					$mode = 3;
				}
				else if(strpos($url, _URL) !== false)
				{
					$mode = 3;
				}
				else
				{
					$mode = 2;
				}
			}
			elseif(is_url($url))
			{
				$mode = 1;
			}
			else	//	default;
			{
				$mode = 2;
			}
			if(isset($_POST['filename']) && $_POST['filename'] != '')
				$mode = 3;
			
			//	Build the $video_details array;
			switch($mode)
			{
				case 1: 	//	 Outsource (e.g. youtube); 
					$sources = a_fetch_video_sources();
					$use_this_src = -1;

					if($sources === false || count($sources) == 0)
					{
						$message = "There are no sources available.";
						break;
					}
					
					foreach($sources as $src_id => $source)
					{
						if($use_this_src > -1)
						{
							break;
						}
						else
						{
							if(@preg_match($source['source_rule'], $url))
							{
								$use_this_src = $source['source_id'];
							}
						}
					}

					if($use_this_src > -1)
					{
						if(!file_exists( "./src/" . $sources[ $use_this_src ]['source_name'] . ".php"))
						{
							$message = "File '/src/" . $sources[ $use_this_src ]['source_name'] . ".php'" . " not found.";
							break;
						}
						else
						{
							require_once( "./src/" . $sources[ $use_this_src ]['source_name'] . ".php");
							do_main($video_details, $url);
							
							$video_details['source_id'] = $use_this_src;
						}
					}
					else
					{
						$message = "<strong>This video site is not supported</strong>. For a full list of supported video sites please <a href=\"addvideo.php?step=1\">return to the previous page</a> and read the 'Instructions'.";
					}
				break;
				
				case 2:		//	2 = direct link to .flv/.mp4 (outsource)
					if(!is_url($url))
					{
						$message = '<strong>'.$url.'</strong><br />This doesn\'t look like a valid link. Please <a href="addvideo.php?step=1">return</a> and try again.';
						break;
					}
					$video_details['source_id'] = 2;
					$video_details['url_flv'] = $url;
					$video_details['direct'] = $url;
				break;
				case 3:		//	flv hosted locally or just uploaded
				
					if(isset($_POST['filename']) && $_POST['filename'] != '')
					{
						$contents = get_config('last_video');
						update_config('last_video', '');
						
						//	try the backup file
						if($contents == '')
						{
							$fp = fopen('tmp.pm', 'r');
							$contents = fread($fp, 512);
							fclose($fp);
						}
						
						//	clear file contents anyway
						$fp = fopen('tmp.pm', 'w');
						fwrite($fp, '');
						fclose($fp);
						
						if($contents == '')	
						{
							$message  = 'Could not retreive the name of the uploaded file. ';
							$message .= 'Make sure the "<em>/admin/tmp.pm</em>" file has the required permissions (0777) ';
							$message .= 'and then try uploading the video again.';
						}
						else
						{
							//	get filename
							$content  = explode("/", $contents);
							$filename = $content[ count($content)-1 ];
							
							//	move the new file to the videos directory 
							$oldpath = $contents;
							$newpath = _VIDEOS_DIR_PATH . $filename;
							if(!rename($oldpath, $newpath))
							{
								$message  = 'Could not move uploaded file to the uploads directory. ';
								$message .= 'Make sure the uploads directory is writable (0777).';
								break;
							}
							$video_details['url_flv'] = $filename;
							$video_details['direct'] = $filename;
							
						}				
					}
					else
					{
						//	this means $url is either the path or a direct link to the .flv file whick is hosted locally(!)
						//	we only need the filename
						$temp = explode("/", $url);
						$video_details['url_flv'] = $temp[ count($temp)-1 ];
						unset($temp);
					}
					$sources = a_fetch_video_sources();
					
					$use_this_src = -1;
					foreach($sources as $src_id => $source)
						if($source['source_name'] == 'localhost')
							$use_this_src = $source['source_id'];
						$video_details['source_id'] = ($use_this_src != -1) ? $use_this_src : 1; //	1 = Default for LOCALHOST
				break;
			}
			
			//	Prevent adding the same video twice
			if ($video_details['direct'] != '')
			{
				$sql = "SELECT * FROM pm_videos_urls WHERE direct = '". $video_details['direct'] ."'";
				
				$result = mysql_query($sql);
				if (mysql_num_rows($result) > 0)
				{
					$row = mysql_fetch_assoc($result);
					mysql_free_result($result);
					
					$message .= '<strong>The video you\'re trying to add was found in your database. ';
					//<input name="add_new" type="button" value="&laquo; Return" onClick="location.href=\'addvideo.php?step=1\'" class="inputbutton" />
					//$message .= '<a href="'. _URL .'/musicvideo.php?vid='. $row['uniq_id'] .'" target="_blank">View</a> ';
					//$message .= '<a href="modify.php?vid='. $row['uniq_id'] .'">Edit video &raquo;</a>';
					$message .= '</div><div><br />';
					$message .= '<input name="view_video" type="button" value="View" onClick="location.href=\''. _URL .'/musicvideo.php?vid='. $row['uniq_id'] .'\'" class="inputbutton" />';
					$message .= '<input name="edit_video" type="button" value="Edit video &raquo;" onClick="location.href=\'modify.php?vid='. $row['uniq_id'] .'\'" class="inputbutton" />';
					$message .= '</strong>';
				}
				unset($row, $sql, $result);
			}
			if (strlen($message) == 0 && $video_details['url_flv'] != '')
			{
				$sql = "SELECT * FROM pm_videos WHERE url_flv = '". $video_details['url_flv'] ."'";
				
				$result = mysql_query($sql);
				if (mysql_num_rows($result) > 0)
				{
					$row = mysql_fetch_assoc($result);
					mysql_free_result($result);
					
					$message .= '<strong>The video you\'re trying to add was found in your database. ';
					//<input name="add_new" type="button" value="&laquo; Return" onClick="location.href=\'addvideo.php?step=1\'" class="inputbutton" />
					//$message .= '<a href="'. _URL .'/musicvideo.php?vid='. $row['uniq_id'] .'" target="_blank">View</a> ';
					//$message .= '<a href="modify.php?vid='. $row['uniq_id'] .'">Edit video &raquo;</a>';
					$message .= '</div><div><br />';
					$message .= '<input name="view_video" type="button" value="View" onClick="location.href=\''. _URL .'/musicvideo.php?vid='. $row['uniq_id'] .'\'" class="inputbutton" />';
					$message .= '<input name="edit_video" type="button" value="Edit video &raquo;" onClick="location.href=\'modify.php?vid='. $row['uniq_id'] .'\'" class="inputbutton" />';
					$message .= '</strong>';

				}
				unset($row, $sql, $result);
			}
			
			if($message != '')
			{
				echo "<div class='info_msg'>".$message."</div>";
			}
			else	//	show form
			{
				$video_details['submitted'] = $submitted;
				add_video_form($video_details);
			}
		}	//	endif isset(POST or GET)
		else
		{
			echo "<a href=\"addvideo.php?step=1\">&laquo; Please go to Step 1</a>";
			header("Location: addvideo.php?step=1");
			exit();
		}
	break;
	case 3:		//	STEP 3
	?>
		<br />
		<div id="add_video_progress">
			<a href="addvideo.php"><img src="images/ico_addvideo.gif" alt="Add video" width="102" height="24" align="absmiddle" border="0" /></a> 
			<span class="steps">1. Choose video</span>
			<span class="steps">2. Add details</span>
			<span class="steps_selected">3. Finish</span>
		</div>
		<br />
	<?php
	
		if(isset($_POST['submit']))
		{
			$required_fields = array('artist' => '"Artist" is a required field and cannot be left blank',
									'video_title' => '"Video Title" is a required field and cannot be left blank',
									'url_flv' => 'Link to video file is missing', 
									'category' => 'Please choose at least one category for this video'
									);
			$message = '';
			
			foreach($video_details as $field => $value)
			{
				if ($field == 'category' && is_array($_POST[$field]))
				{
					$_POST[$field] = implode(',', $_POST[$field]);
				}
				$video_details[$field] = trim($_POST[$field]);
				if(trim($_POST[$field]) == '' && array_key_exists($field, $required_fields))
					$message .= $required_fields[$field] . '<br />';
			}

			if($message != '')
			{				
				echo "<div class='info_msg'>".$message."</div>";
				add_video_form($video_details);
				break;
			}
			else
			{
				$message = '';
				//	check if this video already exists
				if(count_entries('pm_videos', 'url_flv', $video_details['url_flv']) > 0)
				{
					$message .= "This video (".$video_details['url_flv'].") is already in your database. Please go back and make the right adjustments.<br />";
				}
				elseif( ($video_details['direct'] != "") && (count_entries('pm_videos_urls', 'direct', $video_details['direct']) > 0))
				{
					$message .= "This direct link <em>'".$video_details['direct']."'</em> already exists in your database. <br />Please go back and make the right adjustments.<br />";
				}
				else
				{
					//	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);
	
					$video_details['uniq_id'] = $uniq_id;
	
					//	upload or download thumbnail picture.
					if($_FILES['thumb']['name'] != '')
					{
						require_once('img.resize.php');
						$img = new resize_img();
						$img->sizelimit_x = THUMB_W_VIDEO;
						$img->sizelimit_y = THUMB_H_VIDEO;
						
						$new_thumb_name = $uniq_id . "-1";
						
						//	resize image and save it
						if($img->resize_image($_FILES['thumb']['tmp_name']) === false)
						{
							$message .= $img->error;
						}
						else
						{
							$img->save_resizedimage(_THUMBS_DIR_PATH, $new_thumb_name);
						}
						$video_details['yt_thumb'] = $new_thumb_name . "." . strtolower($img->output);
					}
					else
					{
						//	download thumbnail
						$sources = a_fetch_video_sources();
						$use_this_src = -1;
						
						foreach($sources as $src_id => $source)
						{
							if($src_id == $video_details['source_id'])
							{
								$use_this_src = $source['source_id'];
								break;
							}
						}
						require_once( "./src/" . $sources[ $use_this_src ]['source_name'] . ".php");

						if ('' != $video_details['yt_thumb'])
							$img = download_thumb($video_details['yt_thumb'], _THUMBS_DIR_PATH, $uniq_id);
						else 
							$img = true;
						
						//if($img === false)
						//	$message .= "An error occurred while downloading the thumbnail!<br />";
					}
				}
				
				if ($img === false)
				{
					echo "<div class='info_msg_err'>An error occurred while downloading the thumbnail!</div>";
				}
				
				if($message != '')
				{
					echo "<div class='info_msg'>".$message."</div>";
					echo '<br /><input name="add_new" type="button" value="&laquo; Return" onClick="location.href=\'addvideo.php?step=1\'" class="inputbutton" />';
				}
				else	//	Everything is good. Now we can add the new video to the database
				{
					if ($_POST['featured'] == '1')
					{
						$video_details['featured'] = 1;
					}
					else
					{
						$video_details['featured'] = 0;
					}
					
					$new_video = insert_new_video($video_details);
					if($new_video !== true)
					{
						$message = "<em>A problem occurred! Couldn't add the new video in your database;</em><br /><strong>MySQL Reports:</strong> ".$new_video[0]."<br /><strong>Error Number:</strong> ".$new_video[1]."<br />";		
					}
					else
					{
						//	tags?
						if(trim($_POST['tags']) != '')
						{
							$tags = explode(",", $_POST['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);
						}
						$message = "<b>SUCCESS!</b> The video has been added to your database.";
					}
					echo "<div class='info_msg_ok'>".$message."</div>";
			
					echo '<br /><input name="add_new" type="button" value="Add / upload new video" onClick="location.href=\'addvideo.php?step=1\'" class="inputbutton" />';
					echo '<input name="import_new" type="button" value="Import from YouTube" onClick="location.href=\'import.php\'" class="inputbutton" />';
				}
			}
		}	//	end if post['submit'];
		else
		{
			if(headers_sent())
			{
				echo '<meta http-equiv="refresh" content="0;URL=addvideo.php?step=1" />';
			}
			else
			{
				header("Location: addvideo.php?step=1");
			}
			exit();
		}
	break;
}
?>
</div>
<?php
include('footer.php');
?>