<?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 = trim($_GET['action']);

$post_n_get = 0;
$post_n_get = count($_POST) + count($_GET);

/*
 ** Define Local Functions Here **
 */
function get_micro_time()
{
	list($microsec, $sec) = explode(" ", microtime());
	return ((float)$microsec + (float)$sec);
}

function get_exec_time($end, $start)
{
	return round($end - $start, 2);
}

function startElement($parser, $name, $attrs) 
{
	global $youtube, $youtube_array_counter, $youtube_index;

	switch($name) 
	{
		case 'ENTRY':
			$youtube_index = "";
			break;
		case 'YT:DURATION':
			$youtube_index = $name;
			$youtube[$youtube_array_counter][$youtube_index] = $attrs['SECONDS'];
			break;
		case 'MEDIA:RESTRICTION':
			$youtube_index = $name;
			$youtube[$youtube_array_counter][$youtube_index] = array('TYPE' => $attrs['TYPE'],
																	 'RELATIONSHIP' => $attrs['RELATIONSHIP'],
																	 'LIST' => ''
																	);
			break;
		case 'YT:STATE':
			$youtube_index = $name;
			$youtube[$youtube_array_counter][$youtube_index] = array('NAME' => $attrs['NAME'],
																	 'REASONCODE' => $attrs['REASONCODE'],
																	 'REASON' => ''
																	);
			break;
		case 'MEDIA:CONTENT':
			$youtube_index = $name;
			$youtube[$youtube_array_counter][$youtube_index][$attrs['YT:FORMAT']] = array('URL' => $attrs['URL'],
																						 'TYPE' => $attrs['TYPE']
																						);
		break;
		default:
			$youtube_index = $name;
			$youtube[$youtube_array_counter][$youtube_index] = "";
			break;
	}
}

function endElement($parser, $name) 
{
	global $youtube, $youtube_index, $youtube_array_counter;
	switch($name) 
	{
		case "ENTRY":
			$youtube_array_counter++;
			break;
	}
	$youtube_index = "";
}

function characterData($parser, $data) 
{
	global $youtube, $youtube_array_counter, $youtube_index;
	if ($youtube_index != "")
	{
		if ($youtube_index == 'MEDIA:RESTRICTION')
		{
			$youtube[$youtube_array_counter][$youtube_index]['LIST'] .= trim($data);
		}
		else if ($youtube_index == 'YT:STATE')
		{
			$youtube[$youtube_array_counter][$youtube_index]['REASON'] .= trim($data);
		}
		else
		{
			$youtube[$youtube_array_counter][$youtube_index] .= trim($data);
		}
	}
}
function grab_and_parse_xml($file)
{
	global $action;
	
	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	$error = 0;
	
	if ( function_exists('curl_init') ) 
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $file);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
		
		$data = curl_exec($ch);
		curl_close($ch);
		
		if ( !xml_parse($xml_parser, $data, TRUE) ) 
		{
			if ($action == 'favorites' && strlen($data) > 0)
			{
				die(sprintf('<div class="info_msg_err">%s</div>', htmlentities($data)));
			}
			else
			{
				die(sprintf('<div class="info_msg_err">XML error: %s at line %d</div>',
			       xml_error_string(xml_get_error_code($xml_parser)),
			       xml_get_current_line_number($xml_parser)));
			}
		}
	}
	else if ( ini_get('allow_url_fopen') == 1 ) 
	{
	   if ( $fp = @fopen($file, "r") ) 
	   {
	      while ($data = fread($fp, 4096)) 
	      {
	        if ( !xml_parse($xml_parser, $data, feof($fp)) ) 
	        {
	        	if ($action == 'favorites' && strlen($data) > 0)
				{
					die(sprintf('<div class="info_msg_err">%s</div>', htmlentities($data)));
				}
				else
				{
					die(sprintf('<div class="info_msg_err">XML error: %s at line %d</div>',
							xml_error_string(xml_get_error_code($xml_parser)),
							xml_get_current_line_number($xml_parser)));
				}
	         }
	      }
	   }
	   else 
	   {
	      $error = 1;
	   }
	   @fclose($fp);
	}
	else 
	{
		$error = 1;
	}

	if( $error == 1 )
	{
	   // fopen failed, cURL failed, there's nothing else to do but quit   
	   die( '<div class="info_msg_err">
	   			Unable to connect to retrieve data. This can mean either the username you\'ve entered is invalid or your hosting account has <em>allow_url_fopen</em> or <em>cURL</em> disabled.<br />
				<br />
				<b>Please try again in a few moments.</b>
				<br />
				<b><a href="sys_phpinfo.php">See if your hosting account has <em>allow_url_fopen</em> or <em>cURL</em> enabled</a></b></div>' );
	}
	xml_parser_free($xml_parser);
}

/*
 ** Finish defining Local Functions **
 */

?>
<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>Import from Youtube User</h2>
<?php echo $info_msg; ?>
<?php
if(empty($_GET['action'])) {
?>
<div class="info_msg">
Enter any valid YouTube.com username and you will be able to import the user's playlists, favorites and uploaded videos.<br /> Please note that some playlists may be private and you will see them as being empty.
</div>
<?php } ?>
<br />
<form name="search_username" action="import_user.php?action=search" method="post">
<input name="username" type="text" onclick='value=""' value="<?php if($_POST['username'] != '') echo $_POST['username']; elseif($_GET['username'] != '') echo $_GET['username']; else echo 'Youtube username';?>" size="30" maxlength="30" />
<select name="results">
  <option value="10" <?php if($_POST['results'] == 10 || $_GET['results'] == 10) echo 'selected="selected"'; ?>>10 results</option>
  <option value="20" <?php if(($_POST['results'] == 20 || $_GET['results'] == 20) || ($_POST['results'] == '' && $_GET['results'] == '')) echo 'selected="selected"'; ?>>20 results</option>
  <option value="30" <?php if($_POST['results'] == 30 || $_GET['results'] == 30) echo 'selected="selected"'; ?>>30 results</option>
  <option value="50" <?php if($_POST['results'] == 50 || $_GET['results'] == 50) echo 'selected="selected"'; ?>>50 results</option>
</select>
<input name="submit" type="submit" value="Find" class="inputbutton" />
<br /><small>Note: The greater the number of results is the longer it takes to load the results.</small>
 <div id="instructions">
 <h2 class="">Options</h2>
 <input type="checkbox" name="autofilling" id="autofilling" value="1" <?php if($_POST['autofilling'] == "1" || $_GET['autofilling'] == "1" || $post_n_get == 0) echo 'checked="checked"'; ?> />
 <label for="autofilling">Auto-populate 'Artist name' & 'Video Title'</label>
 <br />
 <input type="checkbox" name="autodata" id="autodata" value="1" <?php if($_POST['autodata'] == "1" || $_GET['autodata'] == "1" || $post_n_get == 0) echo 'checked="checked"'; ?> />
 <label for="autodata">Auto-populate 'Tags' & 'Description' from Youtube</label>
 <br />
 <label>Auto-populate for this category</label>
   <?php
	
	$form_select_cats = '';
	
	$selected_categories = array();
	if (is_array($_POST['use_this_category']))
	{
		$selected_categories = $_POST['use_this_category'];
	}
	if ($_GET['utc'] != '')
	{
		$selected_categories = (array) explode(',', $_GET['utc']);
	}
	
	$categories_dropdown_options = array(
									'attr_name' => 'use_this_category[]',
									'attr_id' => 'main_select_category',
									'select_all_option' => false,
									'spacer' => '&mdash;',
									'selected' => $selected_categories,
									'other_attr' => 'multiple="multiple" size="3"',
									'option_attr_id' => 'check_ignore'
									);
	echo categories_dropdown($categories_dropdown_options);

  ?>
</div>
</form>
<br />
<?php

$autodata = 0;
$autofilling = 0;
$overwrite_category = array();

if(isset($_POST['submit']) && !empty($_POST['username']) && ($action == 'search'))
{
	$username = trim($_POST['username']);
	$import_results = $_POST['results'];
	$autofilling = ($_POST['autofilling'] == '1') ? 1 : 0;
	$autodata = ($_POST['autodata'] == '1') ? 1 : 0;
	
	if (is_array($_POST['use_this_category']))
	{
		$overwrite_category = $_POST['use_this_category'];
	}
	
}
elseif($action != '')
{
	$username = trim($_GET['username']);
	$import_results = ($_GET['results'] != '') ? $_GET['results'] : 20;
	$autofilling = ($_GET['autofilling'] == 1) ? 1 : 0;
	$autodata = ($_GET['autodata'] == 1) ? 1 : 0;
	
	if($_GET['oc'] == 1)	//	oc = overwrite_category
	{
		$overwrite_category = (array) explode(',', $_GET['utc']);	//	utc = use_this_cateogory
	}
}

if(($action == 'search' || $action == 'favorites' || $action == 'playlists') && ($username != ''))
{
	$exec_start = get_micro_time();
	
	//	don't allow any white spaces in the username;
	$username = str_replace(" ", "", $username);
	
	if($action == 'playlists')
	{
		define('PHPMELODY', true);
		require_once('./src/youtube.php');
	}

	//	Step 1 - grab user's playlist
	$file = "http://gdata.youtube.com/feeds/api/users/".$username."/playlists?start-index=1&max-results=".$import_results;
	$youtube = array();
	$youtube_index = "";
	$youtube_array_counter = 0;
	grab_and_parse_xml($file);
	
	$total_results = count($youtube);
?>
	<h2>Results from: <em><?php echo $username; ?></em></h2>
  <div id="import_user">
	<p class="msg_head"><img src="images/ico_v_playlist.png" alt="Playlists" align="absmiddle" width="16" height="16" /> Available Playlists</p>
    <?php
	if($youtube[0]['OPENSEARCH:TOTALRESULTS'] != 0)
	{
		echo '<div class="msg_body">';
		echo '<ul>';
		$buff_link = '';
		for($i = 0; $i < $total_results; $i++) 
		{
			$temp 		 = explode('/', $youtube[$i]['ID']);
			$playlist_id = $temp[ count($temp)-1 ];
			$buff_link = '<li><a href="import_user.php?action=playlists&username='.$username.'&playlistid='.$playlist_id.'&title='.$youtube[$i]['TITLE'];
			$buff_link .= '&autofilling='.$autofilling.'&autodata='.$autodata.'&oc=1&utc='. implode(',', $overwrite_category);
			$buff_link .= '">'.$youtube[$i]['TITLE'].'</a></li>';
			echo $buff_link;
		}
		echo '</ul>';
		echo '</div>';
	}
	else
	{
		echo $username . ' doesn\'t have any playlists.';
	}

	unset($youtube, $youtube_index, $youtube_array_counter);

	//	Step 2 - generate favorites link
?>
	<p class="msg_head"><img src="images/ico_v_fav.png" alt="Favorites" align="absmiddle" width="16" height="16" /> <a href="import_user.php?action=favorites&username=<?php echo $username. '&autofilling='.$autofilling.'&autodata='.$autodata.'&oc=1&utc='. implode(',', $overwrite_category); ?>">Show <em><?php echo ucfirst($username); ?></em>'s favorite videos</a></p>
<?php
	if($action != 'search')
	{
?>
	<p class="msg_head"><img src="images/ico_v_uploaded.png" alt="Uploaded" align="absmiddle" width="16" height="16" /> <a href="import_user.php?action=search&username=<?php echo $username; ?>">Show videos uploaded by <em><?php echo ucfirst($username); ?></em></a></p>
	</div>
	<br /><br />
<?php
	}
	//	Step 3
	$page = (int) $_GET['page'];

	if(empty($page))
		$page = 1;
		
	$start_from = ($page * $import_results) - $import_results + 1;

	switch($action)
	{
		case 'search':
			$file = "http://gdata.youtube.com/feeds/api/users/".$username."/uploads?start-index=".$start_from."&max-results=".$import_results;
			echo "<h2><em>".ucfirst($username)."'s</em> Uploaded Videos</h2>";
		break;
		case 'favorites':
			$file = "http://gdata.youtube.com/feeds/api/users/".$username."/favorites?start-index=".$start_from."&max-results=".$import_results;
			echo "<h2><em>".ucfirst($username)."'s</em> Favorite Videos</h2>";
		break;
		case 'playlists':
			$play_id = trim($_GET['playlistid']);
			$title  = urldecode($_GET['title']);
			
			$file = "http://gdata.youtube.com/feeds/api/playlists/".$play_id."?start-index=".$start_from."&max-results=".$import_results."&v=2";
			echo "<h2><em>".ucfirst($username)."</em>'s Playlist: ".$title."</h2>"; 
		break;
	}

	$youtube = array();
	$youtube_index = "";
	$youtube_array_counter = 0;
	grab_and_parse_xml($file);
   ?>
	<br />
   <form name="import_videos" action="import.php?action=import" method="post">
	<table width="100%" border="0" cellspacing="2" cellpadding="10">
	  <tr class="table_head">
	    <td width="30%">Youtube Title / Thumbnails</td>
	    <td>Import</td>
	    <td width="2%" align="center"><input type="checkbox" name="checkall" onclick="checkUncheckAll(this);"/></td>
	    <td width="2%" align="center"><a href="#import_button" class="anchorLink"><img src="images/ico_arr_down.gif" border="0" width="11" height="11" /></a></td>
	  </tr>
	<?php
	
	// begin formatting
	$total_results = count($youtube);
	$alt 	 	= 0;
	$counter 	= 1;
	$duplicates = 0;
	$total_search_results = $youtube[0]['OPENSEARCH:TOTALRESULTS'];
	
	$youtube_mirror = array();
	$youtube_mirror = $youtube;
	
	if($youtube_mirror[0]['OPENSEARCH:TOTALRESULTS'] != 0)
	{
		for($i = 0; $i < $total_results; $i++) 
		{
			$count_vids	= 0;
			$pieces		= array();
			
			if($action == 'playlists')
			{
				$yt_id 		 = $youtube[$i]['YT:VIDEOID'];
			}
			else
			{
				$pieces		 = explode("/", $youtube[$i]["ID"]);
				$yt_id 		 = $pieces[count($pieces) - 1];
			}
			
			$count_vids	 = count_entries('pm_videos', 'yt_id', $yt_id);
			if($count_vids == 0)
			{
				$title		 = $youtube[$i]['MEDIA:TITLE'];
				$url		 = 'http://www.youtube.com/watch?v='. $yt_id;
				$description = $youtube[$i]['MEDIA:DESCRIPTION'];
				$tags		 = $youtube[$i]['MEDIA:KEYWORDS'];
				if($action == 'playlists')
				{
					$autofill 	 = array( 
									0 => $youtube[$i]["NAME"], 
									1 => $title);
				}
				$restriction = $youtube[$i]['MEDIA:RESTRICTION'];
				$no_embed	 = 0;
				if(array_key_exists('YT:NOEMBED', $youtube[$i]))
				{
					$no_embed = 1;
				}

				$private	 = 0;
				if(array_key_exists('YT:NOEMBED', $youtube[$i]))
				{
					$private = 1;
				}
				$col = ($alt % 2) ? 'table_row1' : 'table_row2';
				$col2 = '';
				$alt++;	
				
		?>
			  <tr class="<?php echo $col; ?>">
				<td valign="top">
				<h3><a href="http://www.youtube.com/v/<?php echo $yt_id; ?>&autoplay=1&v=<?php echo $yt_id; ?>" rel="prettyPop[flash]" title="<?php echo $title; ?>" class="<?php echo $h3class; ?>"><?php echo $title; ?></a></h3>
				 
				 <ul class="thumbs_ul">
				  <li class="thumbs_li_selected"><img src="http://img.youtube.com/vi/<?php echo $yt_id; ?>/1.jpg" alt="Thumb 1" width="100" height="76" border="0" name="video_thumbnail" videoid="<?php echo $yt_id; ?>" /></li>
				  <li class="thumbs_li_default"><img src="http://img.youtube.com/vi/<?php echo $yt_id; ?>/2.jpg" alt="Thumb 2" width="100" height="76" border="0" name="video_thumbnail" videoid="<?php echo $yt_id; ?>" /></li>
				  <li class="thumbs_li_default"><img src="http://img.youtube.com/vi/<?php echo $yt_id; ?>/3.jpg" alt="Thumb 3" width="100" height="76" border="0" name="video_thumbnail" videoid="<?php echo $yt_id; ?>" /></li>
				 </ul>
				<br />
				<a href="http://www.youtube.com/v/<?php echo $yt_id; ?>&autoplay=1&v=<?php echo $yt_id; ?>" rel="prettyPop[flash]" title="<?php echo $title; ?>"><img src="images/ico_preview.gif" width="72" height="18" alt="Preview This Video" border="0" /></a>
				 <input type="hidden" name="thumb_url[<?php echo $counter;?>]" value="http://img.youtube.com/vi/<?php echo $yt_id; ?>/1.jpg" />
				 
				 <?php
				 	if($no_embed == 1 || $private == 1)
					{
						$col2 = 'table_row_unembed';
						?>
						<br />
						<div class="css_yellow_warn"><span onMouseover="showhint('This video will not work since the owner decided to disable embedding.', this, event, '350px')">YouTube disabled embedding for this video.</span></div>
						<?php 
					}
					
					if(is_array($restriction))
					{
						$col2 = 'table_row_unembed';
						?>
						 <!--<div class="css_yellow_warn"><span onMouseover="showhint('<strong>Geo-restricted</strong> videos work only in certain countries. Please check this video before adding it.', this, event, '350px')">This video is geo-restricted.</span></div>-->
						 <div class="css_yellow_warn"><span onMouseover="showhint('Access <b><?php echo ($restriction['RELATIONSHIP'] == 'deny') ? 'denied' : 'granted';?></b> in the following countries: <?php echo $restriction['LIST'];?>.', this, event, '350px')">This video is geo-restricted.</span></div>
						<?php
					}
					
				  ?>
				</td>
				<td class="<?php echo $col2; ?>">
				 <table width="100%" border="0" cellspacing="5" cellpadding="0">
                   <tr>
                     <td width="15%">
						<small>Artist name (<em>required</em>):</small><br />
						<input name="artist[<?php echo $counter; ?>]" type="text" value="<?php if ($autofilling) echo ucfirst($username); ?>" size="20" class="required_field" /> 
					 </td>
                     <td width="15%">
						<small>Video title (<em>required</em>):</small><br />
						<input name="video_title[<?php echo $counter; ?>]" type="text" value="<?php if ($autofilling) echo $title; ?>" size="20" class="required_field" />
					 </td>
                     <td width="70%">
					 <small>Category: (<em>required</em>):</small><br />
						<?php
						$categories_dropdown_options = array(
									'attr_name' => 'genre['. $counter .'][]',
									'attr_id' => 'select_category-'. $counter,
									'select_all_option' => false,
									'spacer' => '&mdash;',
									'selected' => $overwrite_category,
									'other_attr' => 'multiple="multiple" size="3"',
									'option_attr_id' => 'check_ignore'
									);
						echo categories_dropdown($categories_dropdown_options);
						?>
					 </td>
                   </tr>
                   <tr>
                     <td colspan="3">
						 <small>Tags:</small><br />
						 <input name="tags[<?php echo $counter; ?>]" type="text" value="<?php if($autodata) echo $tags; ?>" style="width: 50%" />
					 </td>
                   </tr>
                   <tr>
                     <td colspan="3">
						 <small>Description:</small><br />
						 <textarea name="description[<?php echo $counter; ?>]" id="description[<?php echo $counter; ?>]" style="width:60%; height:50px"><?php if ($autodata) echo $description;?></textarea>
					 </td>
                   </tr>
				   <tr>
                     <td colspan="3">
						 <label>
						  <input type="checkbox" name="featured[<?php echo $counter;?>]" id="check_ignore" value="1" /> Mark video as <span class="b_featured">featured</span>
						</label>
					 </td>
                   </tr>
                 </table>
			</td>
				<td align="center">
				 <input name="video_ids[<?php echo $counter; ?>]" type="checkbox" value="<?php echo $url; ?>"/>
				</td>
				<td align="center">
					<a href="#import_button" class="anchorLink"><img src="images/ico_arr_down.gif" border="0" width="11" height="11" /></a>
				</td>
			  </tr>
		<?php
				$counter++;
			}
			else
			{
				$duplicates++;
			}
		}	//	end for()
		$exec_end = get_micro_time();
	}	//	end if()
	else
	{
		?>
		<tr>
		<td colspan="3" align="center">
		Sorry, no videos found! <br /><br />Please remember that some videos may be private and that is why they will not appear in the results!
		</td>
		</tr>
		<?php
	}
	if($duplicates == $total_results)
	{
		//	All videos found 
		?>
		<tr>
		<td colspan="3" align="center">
		You already have these videos on your site.<br />
		Please try again by selecting more than <?php echo $import_results; ?> results or by using different keywords.
		</td>
		</tr>
		<?php
	}
?>
	</table>
	<br />
	<div align="right">
	<input name="yt_username" type="hidden" value="<?php echo $username; ?>"/>
	<?php
		
		// generate pagination
		if($total_search_results > 0)
		{
		 if($total_search_results > 1000)
		 {
			$total_search_results = 999 - $import_results;
		 }
		?>
		<?php if($duplicates != $total_results) : ?>
		<a name="import_button" id="import_button"></a>
		<div align="right"><input type="submit" name="submit" value="Import" class="approvebutton"></div>
		<?php endif; ?>
		<div align="center">
		 <div class="pagination">
		  <?php
		  	// generate smart pagination
			$filename = 'import_user.php';
			$ext = 'action='.$action.'&username='.$username.'&results='.$import_results.'&page='.$page;
			$ext.= '&autofilling='.$autofilling.'&autodata='.$autodata;
			
			$ext .= (count($overwrite_category) > 0) ? '&oc=1&utc='. implode(',', $overwrite_category) : '&oc=0&utc=';
			
			if ($action == 'playlists')
			{
				$ext .= '&playlistid='. $_GET['playlistid'] .'&title='. $_GET['title'];
			}
			
			$pagination = '';
			$pagination = a_generate_smart_pagination($page, $total_search_results, $import_results, 1, $filename, $ext);
			echo $pagination;
			
		  ?>
		 </div>
		</div>
		<?php
		} // end if($youtube[0]['OPENSEARCH:TOTALRESULTS'] > 0)
		?>
	<!-- search form information -->
	<input type="hidden" name="username" value="<?php echo htmlentities($username, ENT_COMPAT); ?>" />
	<input type="hidden" name="results" value="<?php echo $import_results; ?>" />
	<input type="hidden" name="autofilling" value="<?php echo $autofilling; ?>" />
	<input type="hidden" name="autodata" value="<?php echo $autodata; ?>" />
	<input type="hidden" name="overwrite_category" value="<?php echo ($_GET['oc'] == 1 || is_array($_POST['use_this_category'])) ? '1' : '0'; ?>" />
	<input type="hidden" name="use_this_category" value="<?php echo implode(',', $overwrite_category); ?>" />

   </form>
  </div>
<?php
}
elseif($username == '' && $action != '')
{
	echo "Invalid username";
}
echo '</div></div>';
include('footer.php');
?>