<?php
	/*
	 * ==============================================================================
	 * BBC iPlayer for Xtreamer Media Player & Streamer
	 * ==============================================================================
	 *
	 * This project allows to watch content brom BBC iPlayer, which is supported
	 * on Linux by get_iplayer PERL script.
	 *
	 * Licence: GNU General Public License v2
	 * http://www.gnu.org/licenses/gpl.html
	 *
	 * Do not remove or change any header comments! Respect our work!
	 *
	 * If you are satisfied with my work you can support it with small donation                                                                                                                               
	 *   https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=SB8WDDAWY5YZE&lc=SI&item_name=xJukebox&item_number=ak5349jgdr&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted	 *
	 *
	 * Author: vpeter/misek
	 *
	 * ==============================================================================
	 */
	 
$categoriesArr = array(
	"main" => array(
		"categories" =>  array("", "Children's", "Comedy", "Drama & Soaps", "Entertainment", "Factual", "Films", "Learning", "Lifestyle & Leisure", "Music", "News & Current Affairs", "Religion & Ethics", "Sport", "All"),
		"subcategory" => array("", "childrens",  "comedy", "drama",         "entertainment", "factual", "",      "learning", "lifestyle",           "music", "",                       "",                  "sport", ""),
		"search" => 		 array("", "",           "",       "",              "",              "",        "Films", "",         "",                    "",      "News",                   "Religion,Ethics", "",      "")
	),
	"childrens" => array(
		"categories" => array("Children's", "Activities", "Animation", "Drama", "Entertainment & Comedy", "Factual", "Games & Quizzes", "Music"),
		"search" => 		array("Children's", "Activities", "Animation", "Drama", "Entertainment,Comedy",   "Factual", "Games,Quizzes",   "Music"),
	),
	"comedy" => array(
		"categories" => array("Comedy", "Character", "Satire", "Sitcoms", "Sketch", "Standup", "Stunt"),
		"search" => 		array("Comedy", "Character", "Satire", "Sitcoms", "Sketch", "Standup", "Stunt")
	),
	"drama" => array(
		"categories" => array("Drama & Soaps", "Action & Adventure", "Biographical", "Crime", "Medical", "Relationships & Romance", "SciFi & Fantasy", "Soaps"),
		"search" => 		array("Drama,Soaps", "Action,Adventure", "Biographical", "Crime", "Medical", "Relationships,Romance", "SciFi,Fantasy", "Soaps")
	),
	"entertainment" => array(
		"categories" => array("Entertainment", "Discussion & Talk Shows", "Games & Quizzes", "Makeovers", "Reality", "Review Shows", "Talent Shows"),
		"search" => 		array("Entertainment", "Discussion,Talk Shows", "Games,Quizzes", "Makeovers", "Reality", "Review", "Talent")
	),
	"factual" => array(
		"categories" => array("Factual", "Arts, Culture & the Media", "Cars & Motors", "Consumer", "Crime & Justice", "Disability", "Families & Relationships", "History", "Life Stories", "Money", "Politics", "Science & Nature"),
		"search" => 		array("Factual", "Arts, Culture,Media", "Cars,Motors", "Consumer", "Crime,Justice", "Disability", "Families,Relationships", "History", "Life,Stories", "Money", "Politics", "Science,Nature")
	),
	"learning" => array(
		"categories" => array("Learning", "Adult", "Pre-School", "Secondary"),
		"search" => 		array("Learning", "Adult", "Pre-School", "Secondary")
	),
	"lifestyle" => array(
		"categories" => array("Lifestyle & Leisure", "Antiques", "Beauty & Style", "Food & Drink", "Health & Wellbeing", "Homes & Gardens", "Pets & Animals", "Travel"),
		"search" => 		array("Lifestyle,Leisure", "Antiques", "Beauty,Style", "Food,Drink", "Health,Wellbeing", "Homes,Gardens", "Pets,Animals", "Travel")
	),
	"music" => array(
		"categories" => array("Music", "Classic Pop & Rock", "Country", "Folk", "Pop & Chart", "Rock & Indie"),
		"search" => 		array("Music", "Classic,Pop,Rock", "Country", "Folk", "Pop,Chart", "Rock,Indie")
	),
	"sport" => array(
		"categories" => array("Sport", "Commonwealth Games", "Football", "Formula One", "Gymnastics", "Motorsport", "Rugby League", "Rugby Union"),
		"search" => 		array("Sport", "Commonwealth,Games", "Football", "Formula,One", "Gymnastics", "Motorsport", "Rugby,League", "Rugby,Union")
	)
);

function add_submenu($name, $url) {
  echo <<<SUBMENU
<submenu name="$name">
	<onClick>
		<script>
			url = $url;
		</script>
	</onClick>

</submenu>

SUBMENU;
}

function add_item($title, $thumb, $pid, $channel, $time, $series, $webinfo) {
  echo <<<ITEM
  <item>
    <title>$title</title>
    <thumb>$thumb</thumb>
    <pid>$pid</pid>
    <channel>$channel</channel>
    <time>$time</time>
    <series>$series</series>
    <webinfo>$webinfo</webinfo>
  </item>

ITEM;
}

function add_item_file($fp, $title, $thumb, $pid, $channel, $time, $series, $webinfo) {
	$item ="<item>
	    <title>$title</title>
	    <thumb>$thumb</thumb>
	    <pid>$pid</pid>
	    <channel>$channel</channel>
	    <time>$time</time>
	    <series>$series</series>
	    <webinfo>$webinfo</webinfo>
	  </item>
	";
	fwrite($fp, $item);
}

function getStringBetween($string, $start, $end) {
	//$string = trim($string, " \r\n\t");
	$string = " ". $string;
	$ini = strpos($string, $start);
	if ($ini == 0)
		return "";
	$ini += strlen($start);
	$len = strpos($string, $end, $ini) - $ini;
	$ret = substr($string, $ini, $len);
	$ret = str_replace('<br /><br />', '', $ret);
	return trim($ret, " \r\n\t");
}

function getStringBetween_1($string, $start, $end, $cnt=0) {
	//$string = trim($string, " \r\n\t");
	$string = " ". $string;
	$ini = strpos($string, $start);
	if ($ini == 0)
		return "";
	
	//if ($cnt > 0) {
	for (; $cnt > 0; $cnt--) {
		$string = substr($string, $ini+1);
		$ini = strpos($string, $start);
		if ($ini == 0)
			return "";
	}	
	//}
		
	$ini += strlen($start);
	$len = strpos($string, $end, $ini) - $ini;
	$ret = substr($string, $ini, $len);
	$ret = str_replace('<br /><br />', '', $ret);
	return trim($ret, " \r\n\t");
}

function getLinks($data) {
	preg_match_all('/(href|src)\=(\"|\')[^\"\'\>]+/i',$data,$media);
	unset($data);
	$data=preg_replace('/(href|src)(\"|\'|\=\"|\=\')(.*)/i',"$3",$media[0]);
	return $data;
}

/*
http://w-shadow.com/blog/2009/10/20/how-to-extract-html-tags-and-their-attributes-with-php/
*/
/**
 * extract_tags()
 * Extract specific HTML tags and their attributes from a string.
 *
 * You can either specify one tag, an array of tag names, or a regular expression that matches the tag name(s). 
 * If multiple tags are specified you must also set the $selfclosing parameter and it must be the same for 
 * all specified tags (so you can't extract both normal and self-closing tags in one go).
 * 
 * The function returns a numerically indexed array of extracted tags. Each entry is an associative array
 * with these keys :
 * 	tag_name	- the name of the extracted tag, e.g. "a" or "img".
 *	offset		- the numberic offset of the first character of the tag within the HTML source.
 *	contents	- the inner HTML of the tag. This is always empty for self-closing tags.
 *	attributes	- a name -> value array of the tag's attributes, or an empty array if the tag has none.
 *	full_tag	- the entire matched tag, e.g. '<a href="http://example.com">example.com</a>'. This key 
 *		          will only be present if you set $return_the_entire_tag to true.	   
 *
 * @param string $html The HTML code to search for tags.
 * @param string|array $tag The tag(s) to extract.							 
 * @param bool $selfclosing	Whether the tag is self-closing or not. Setting it to null will force the script to try and make an educated guess. 
 * @param bool $return_the_entire_tag Return the entire matched tag in 'full_tag' key of the results array.  
 * @param string $charset The character set of the HTML code. Defaults to ISO-8859-1.
 *
 * @return array An array of extracted tags, or an empty array if no matching tags were found. 
 */
function extract_tags( $html, $tag, $selfclosing = null, $return_the_entire_tag = false, $charset = 'ISO-8859-1' ){
 
	if ( is_array($tag) ){
		$tag = implode('|', $tag);
	}
 
	//If the user didn't specify if $tag is a self-closing tag we try to auto-detect it
	//by checking against a list of known self-closing tags.
	$selfclosing_tags = array( 'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta', 'col', 'param' );
	if ( is_null($selfclosing) ){
		$selfclosing = in_array( $tag, $selfclosing_tags );
	}
 
	//The regexp is different for normal and self-closing tags because I can't figure out 
	//how to make a sufficiently robust unified one.
	if ( $selfclosing ){
		$tag_pattern = 
			'@<(?P<tag>'.$tag.')			# <tag
			(?P<attributes>\s[^>]+)?		# attributes, if any
			\s*/?>					# /> or just >, being lenient here 
			@xsi';
	} else {
		$tag_pattern = 
			'@<(?P<tag>'.$tag.')			# <tag
			(?P<attributes>\s[^>]+)?		# attributes, if any
			\s*>					# >
			(?P<contents>.*?)			# tag contents
			</(?P=tag)>				# the closing </tag>
			@xsi';
	}
 
	$attribute_pattern = 
		'@
		(?P<name>\w+)							# attribute name
		\s*=\s*
		(
			(?P<quote>[\"\'])(?P<value_quoted>.*?)(?P=quote)	# a quoted value
			|							# or
			(?P<value_unquoted>[^\s"\']+?)(?:\s+|$)			# an unquoted value (terminated by whitespace or EOF) 
		)
		@xsi';
 
	//Find all tags 
	if ( !preg_match_all($tag_pattern, $html, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ) ){
		//Return an empty array if we didn't find anything
		return array();
	}
 
	$tags = array();
	foreach ($matches as $match){
 
		//Parse tag attributes, if any
		$attributes = array();
		if ( !empty($match['attributes'][0]) ){ 
 
			if ( preg_match_all( $attribute_pattern, $match['attributes'][0], $attribute_data, PREG_SET_ORDER ) ){
				//Turn the attribute data into a name->value array
				foreach($attribute_data as $attr){
					if( !empty($attr['value_quoted']) ){
						$value = $attr['value_quoted'];
					} else if( !empty($attr['value_unquoted']) ){
						$value = $attr['value_unquoted'];
					} else {
						$value = '';
					}
 
					//Passing the value through html_entity_decode is handy when you want
					//to extract link URLs or something like that. You might want to remove
					//or modify this call if it doesn't fit your situation.
					$value = html_entity_decode( $value, ENT_QUOTES, $charset );
 
					$attributes[$attr['name']] = $value;
				}
			}
 
		}
 
		$tag = array(
			'tag_name' => $match['tag'][0],
			'offset' => $match[0][1], 
			'contents' => !empty($match['contents'])?$match['contents'][0]:'', //empty for self-closing tags
			'attributes' => $attributes, 
		);
		if ( $return_the_entire_tag ){
			$tag['full_tag'] = $match[0][0]; 			
		}
 
		$tags[] = $tag;
	}
 
	return $tags;
}

?>
