<?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
	 *
	 * ==============================================================================
	 */
require_once 'KLogger.php';
require_once('functions.php');

	$log = new KLogger("log.txt" , KLogger::OFF);

	$myIP = $_SERVER['HTTP_HOST'];

  $type = @$_GET['type'];
  if (is_null($type) || $type == '')
    $type = 'category';

  $category = @$_GET['category'];
  if (is_null($category) || $category == '')
    $category = 'main';

  $search = @$_GET['search'];
  if (is_null($search) || $search == '')
    $search = '';

  $submenuLev = @$_GET['submenuLev'];
  if (is_null($submenuLev) || $submenuLev == '')
    $submenuLev = 1;

  $submenu = @$_GET['submenu'];
  if (is_null($submenu) || $submenu == '')
    $submenu = 0;

	$titleCategory = '';
	$categorySearch = '';

	foreach ($categoriesArr['main']["subcategory"] as $i => $value) {
		if ($value != '' && $value == $category) {
			$titleCategory .= $categoriesArr['main']["categories"][$i];
			$categorySearch = $categoriesArr['main']["categories"][$i];
			break;
		}
	}

	$log->LogDebug("search_items: titleCategory: '$titleCategory'");

	foreach ($categoriesArr[$category]["search"] as $i => $value) {
		if ($value != '' && $value == $search) {
			if ($titleCategory != '')
				$titleCategory .= ', ' . $categoriesArr[$category]["categories"][$i];
			else
				$titleCategory .= $categoriesArr[$category]["categories"][$i];
			break;
		}
	}

	$log->LogDebug("search_items: $type: '$type'  $search: '$search'  titleCategory: '$titleCategory'");

  if ($type == 'all') {
  	$search = 'all';
  	$titleCategory = 'All';
  }

  $log->LogDebug("search_items: type: '$type' categorySearch: '$categorySearch' search: '$search'");

	echo '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <!-- ---------------------------------------------------------  -->
  <!-- RSS DEBUG RSS FUNCTION WILL WRITE ENTRY IN debug.txt FILE  -->
  <!-- syntax: txt = "string to write"; executeScript("log");     -->
  <log>
  	write = 1;
  	if (write == "1") {
    	old = readStringFromFile("/tmp/usbmounts/sda1/debug.txt");
    	new = old + "&#x0A;" + date("%d.%m.%Y %H:%M:%S") + ": " + txt;
    	writeStringToFile("/tmp/usbmounts/sda1/debug.txt", new);
    }
  </log>
  <!-- ---------------------------------------------------------  -->

<onEnter>
	SwitchViewer(0);
	itemSize = 0;
	titleCategory = "<?= $titleCategory ?>";
	txt = "titleCategory " + titleCategory; executeScript("log");

	txt = "categorySearch '<?= $categorySearch ?>' | search '<?= $search ?>'"; executeScript("log");
	if ("<?= $categorySearch ?>" != "" &amp;&amp; "<?= $search ?>" != "") {
		txt = "search1"; executeScript("log");
		xmlUrl = "http://<?= $myIP ?>/media/sda1/scripts/BBC-iPlayer/search_items.php?type=<?= $type ?>&amp;search=<?php echo urlencode($categorySearch .','. $search); ?>";
		txt = "xmlUrl1 '" + xmlUrl + "'"; executeScript("log");
		dlOk = loadXMLFile(xmlUrl);
		if (dlOk != null) {
	  	itemSize = getXMLElementCount("items", "item");
		}
	} else if ("<?= $search ?>" != "") {
		txt = "search2"; executeScript("log");
		xmlUrl = "http://<?= $myIP ?>/media/sda1/scripts/BBC-iPlayer/search_items.php?type=<?= $type ?>&amp;search=<?php echo urlencode($search); ?>";
		txt = "xmlUrl2 '" + xmlUrl + "'"; executeScript("log");
		dlOk = loadXMLFile(xmlUrl);
		if (dlOk != null) {
	  	itemSize = getXMLElementCount("items", "item");
		}
	} else {
		txt = "no search done"; executeScript("log");
	}

<?php
	if ($submenuLev >= 3 && $submenu > 0)
		echo "  setFocusMenuIndex($submenu);"
?>
</onEnter>

  <mediaDisplay name=threePartsView
sideColorLeft="0:0:0"
sideLeftWidthPC="18"
sideRightWidthPC="10"
sideColorRight="0:0:0"
headerXPC="14"
headerYPC="3"
headerWidthPC="95"
itemImageXPC="23"
itemImageYPC="18"
itemImageWidthPC="10"
itemImageHeightPC="10"

itemXPC="34"
itemYPC="16"
itemWidthPC="48"
itemHeightPC="14"

menuXPC="5"
menuWidthPC="15"
menuHeightPC="6"
capXPC="82"
capYPC="17"

capHeightPC="10"
headerCapXPC="90"
headerCapYPC="10"
headerCapWidthPC="0"
showDefaultInfo=yes
backgroundColor="0:0:0"

infoYPC="85"

popupXPC="100"
popupYPC="0"
popupWidthPC="0"
popupHeightPC="0"

popupBorderColor="0:0:0"
idleImageXPC=45
idleImageYPC=42
idleImageWidthPC=10
idleImageHeightPC=16

unFocusBorderColor="127:127:127"
itemPerPage="5"

showHeader="no"
parentFocusFontColor="28:134:238"
itemBorderColor="110:0:0"
popupBackgroundColor="22:22:22"
imageFocus="/tmp/usbmounts/sda1/scripts/BBC-iPlayer/selection.bmp"
imageParentFocus="/tmp/usbmounts/sda1/scripts/BBC-iPlayer/selection.bmp"
forceFocusOnItem="yes"
selectMenuOnRight="yes"
>

<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-1.png </idleImage>
<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-2.png </idleImage>
<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-3.png </idleImage>
<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-4.png </idleImage>
<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-5.png </idleImage>
<idleImage> /tmp/usbmounts/sda1/scripts/BBC-iPlayer/loading/loading-6.png </idleImage>

  <backgroundDisplay>
      <image offsetXPC=0 offsetYPC=0 widthPC=100 heightPC=100>
        /tmp/usbmounts/sda1/scripts/BBC-iPlayer/back.png
      </image>
      <text redraw="yes" tailDots="yes" offsetXPC=30 offsetYPC=5.4 widthPC=100 heightPC=10 fontSize=15 backgroundColor=-1:-1:-1 foregroundColor=255:255:255>
        <script>
					titleCategory;
				</script>
      </text>
  </backgroundDisplay>

  <!-- Method executed when the user presses a button on the remote -->
  <!-- IMPORTANT NOTE: This method needs to be place right after the background display element at end of RSS file -->
  <onUserInput>
		/*txt = "getPageInfo focusItemIndex " + getPageInfo("focusItemIndex"); executeScript("log");
		txt = "getPageInfo itemCount " + getPageInfo("itemCount"); executeScript("log");*/

    userInput = currentUserInput();
    txt = "userInput " + userInput; executeScript("log");
		if (userInput == "ENTR") {
			index = getFocusItemIndex();
			pid = getXMLText("items", "item", index, "pid");

			if (pid != "") {
				showIdle();
				txt = "ENTR onUserInput pid: " + pid; executeScript("log");
				playUrl = "http://<?= $myIP ?>:8100/cgi-bin/BBC-iPlayer.cgi?content=flv&amp;type=tv&amp;what=" + pid;
				txt = "onUserInput playUrl: " + playUrl; executeScript("log");

				playItemUrl(playUrl, 0);
			}
    } else if (userInput == "R") {
    	titleCategorySaved = titleCategory;
  		titleCategory = "";

    	if (itemSize == 0) {
    		/* ignore */
    		"true";
    	} else {
    		showIdle();
				index = getFocusItemIndex();
				thumbUrlSmall = getXMLText("items", "item", index, "thumb");
				webinfo = getXMLText("items", "item", index, "webinfo");

				thumbUrlBig = "http://127.0.0.1/media/sda1/scripts/BBC-iPlayer/dl_details.php?thumburl=" + thumbUrlSmall + "&amp;webinfo=" + webinfo;
				thumbUrlBig = getURL(thumbUrlBig);

    	}
  </onUserInput>

  <!-- itemDisplay will draw widget inside the item area, item area is decided by mediaDisplay attributes -->
  <itemDisplay>
    <text offsetXPC=0 offsetYPC=5 widthPC=100 heightPC=60 fontSize=13 lines="2" backgroundColor=-1:-1:-1 foregroundColor=200:200:200>
      <script>
				index = getQueryItemIndex();
      	tmp = getXMLText("items", "item", index, "title");
      	tmp;
   		</script>
    </text>

  <text offsetXPC=3 offsetYPC=66 widthPC=20 heightPC=30 fontSize=12 backgroundColor=-1:-1:-1 foregroundColor=150:150:150>
    <script>
			index = getQueryItemIndex();
    	tmp = getXMLText("items", "item", index, "channel");
    	tmp;
   	</script>
  </text>

  <text offsetXPC=22 offsetYPC=66 widthPC=32 heightPC=30 fontSize=12 backgroundColor=-1:-1:-1 foregroundColor=150:150:150>
    <script>
			index = getQueryItemIndex();
    	tmp = getXMLText("items", "item", index, "time");
    	tmp;
   	</script>
  </text>

  <text offsetXPC=52 offsetYPC=66 widthPC=50 heightPC=30 fontSize=12 backgroundColor=-1:-1:-1 foregroundColor=150:150:150>
    <script>
			index = getQueryItemIndex();
    	tmp = getXMLText("items", "item", index, "series");
    	tmp;
   	</script>
  </text>
</itemDisplay>

<script>
	showRead = 0;
</script>

<infoDisplay>
  <onEnter>
  	cancelIdle();
  	
  	if (showRead == "0") {
  		setRefreshTime(600);
  	} else
    	setRefreshTime(4000);
  </onEnter>

  <onExit>
  	titleCategory = titleCategorySaved;
    setRefreshTime(-1);
  </onExit>

  <onRefresh>
  	if (showRead == "0") {
			rv = CheckFile("/tmp/bbc_iplayer_show.dat");
			if (rv == "true") {
				showDataArray = null;
				showDataArray = readStringFromFile("/tmp/bbc_iplayer_show.dat");

				show_title        = getStringArrayAt(showDataArray, 0);
				show_synopsis     = getStringArrayAt(showDataArray, 1);
				show_duration     = getStringArrayAt(showDataArray, 2);

				cnt = 3;
				show_category     = "";
				show_category_nr  = getStringArrayAt(showDataArray, cnt);
        while (1) {
          cnt += 1;
          if (cnt &gt; show_category_nr) {
            break;
          }
          tmpStr = getStringArrayAt(showDataArray, cnt);
          show_category = show_category + tmpStr + "&#x0A;";
        }

				show_availability     = "";
				show_availability_nr  = getStringArrayAt(showDataArray, cnt);
        while (1) {
          cnt += 1;
          if (cnt &gt; show_availability_nr) {
            break;
          }
          tmpStr = getStringArrayAt(showDataArray, cnt);
          show_availability = show_availability + tmpStr + "&#x0A;";
        }

				show_credits     = "";
				show_credits_nr  = getStringArrayAt(showDataArray, cnt);
        while (1) {
          cnt += 1;
          if (cnt &gt; show_credits_nr) {
            break;
          }
          tmpStr = getStringArrayAt(showDataArray, cnt);
          show_credits = show_credits + tmpStr + "&#x0A;";
        }

				show_broadcasts     = "";
				show_broadcasts_nr  = getStringArrayAt(showDataArray, cnt);
        while (1) {
          cnt += 1;
          if (cnt &gt; show_broadcasts_nr) {
            break;
          }
          tmpStr = getStringArrayAt(showDataArray, cnt);
          show_broadcasts = show_broadcasts + tmpStr + "&#x0A;";
        }

				showRead = 1;
			}
		}	else {
			setRefreshTime(-1);
			redrawDisplay();
		}
  </onRefresh>

  <image offsetXPC=5 offsetYPC=20 widthPC=40 heightPC=40>
    <script>
    	thumbUrlBig;
    	</script>
  </image>

  <text redraw="yes" tailDots="yes" offsetXPC=20 offsetYPC=5.3 widthPC=100 heightPC=10 fontSize=12 backgroundColor=-1:-1:-1 foregroundColor=255:255:255>
		<script>
			show_title;
		</script>
  </text>
  <text redraw="yes" offsetXPC=50 offsetYPC=20 widthPC=40 heightPC=10 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines=1>
		<script>
			show_duration;
		</script>
  </text>
  <text redraw="yes" offsetXPC=50 offsetYPC=30 widthPC=40 heightPC=15 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines="6" tailDots="yes">
		<script>
			show_synopsis;
		</script>
  </text>
  <text redraw="yes" offsetXPC=50 offsetYPC=50 widthPC=50 heightPC=10 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines=4>
		<script>
			show_category;
		</script>
  </text>
  <text redraw="yes" offsetXPC=5 offsetYPC=65 widthPC=70 heightPC=10 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines=4>
		<script>
			show_availability;
		</script>
  </text>
  <text redraw="yes" offsetXPC=50 offsetYPC=65 widthPC=40 heightPC=10 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines=4>
		<script>
			show_credits;
		</script>
  </text>
  <text redraw="yes" offsetXPC=5 offsetYPC=80 widthPC=70 heightPC=10 fontSize=10 backgroundColor=-1:-1:-1 foregroundColor=255:255:255 lines=3 tailDots="yes">
		<script>
			show_broadcasts;
		</script>
  </text>

</infoDisplay>

</mediaDisplay>

<?php
	if ($submenuLev == 1) {
		add_submenu("All", "\"http://$myIP/media/sda1/scripts/BBC-iPlayer/main_tv.php?type=all&amp;search=all\"");
	}

	$submenuLev++;
	$submenu = 0;
	foreach ($categoriesArr[$category]["categories"] as $i => $value) {
		if ($i == 0)
			continue;

		$subcategory = $categoriesArr[$category]["subcategory"][$i];
		if ($subcategory == "") {
			$search = $categoriesArr[$category]["search"][$i];
			add_submenu($value, "\"http://$myIP/media/sda1/scripts/BBC-iPlayer/main_tv.php?submenuLev=". $submenuLev ."&amp;submenu=". $submenu ."&amp;category=" . urlencode($category) . "&amp;search=" . urlencode($search) . "\"");
		} else {
			add_submenu($value, "\"http://$myIP/media/sda1/scripts/BBC-iPlayer/main_tv.php?submenuLev=". $submenuLev ."&amp;submenu=". $submenu ."&amp;category=" . urlencode($subcategory) . "\"");
		}

		$submenu++;
	}

?>

<item_template>
	<media:thumbnail>
		<script>
      index = getQueryItemIndex();
      thumbUrl = getXMLText("items", "item", index, "thumb");
  		if (thumbUrl != null) {
    		thumbUrl;
  		} else {
				"/tmp/usbmounts/sda1/scripts/BBC-iPlayer/bbc-iplayer.jpg";
  		}
    </script>
	</media:thumbnail>
</item_template>

<channel>
<title>BBC iPlayer</title>
<link>/tmp/usbmounts/sda1/scripts/BBC-iPlayer/main.rss</link>
<media:thumbnail url="/tmp/usbmounts/sda1/scripts/BBC-iPlayer/bbc-iplayer.jpg" width="100" height="90" />

  <itemSize>
     <script>
        itemSize;
     </script>
  </itemSize>

</channel>
</rss>
