<?php
/**
 *  Copyright (C) 2007 Ben Leto <undertoe@chemlab.org>
 * 
 *  Description: Apple Trailer Grabber for mythtv
 * 
 *  Version 0.4.3
 * 
 *  Apple Trailer Grabber is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 * 
 *  Apple Trailer Grabber is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  Usage: read the INSTALL file
 *  	Setup as a cron script to run as frequently as you want
 *
 *
 */

/************************************************************************/
// CONFIGURATION

// command to use when streaming content from the internet - cache 50% before displaying and use 32MB of memory
$STREAMING_EXEC_CMD		= 'loading.sh &amp;&amp; mplayer-wrapper.pl -fs -zoom -really-quiet -user-agent "QuickTime/7.6.2" -cache 16000';
$APPLE_FEED = 'http://www.apple.com/trailers/home/xml/current.xml';
/************************************************************************/
// Shouldn't Need To modify anything beyond here


define("PLAYERCMD", $STREAMING_EXEC_CMD);
define("XMLFEED", $APPLE_FEED);

/************************************************************************/

init_main();

// Function:  returns null | init_main () 
// Description: Outputs Apple Trailer XML feed to watchable movie urls in MythTV menu XML format
function init_main()
{

	print "<mythmenu name=\"TRAILERS\">\n";
	
	if(valid_url(XMLFEED)){
		
		// Gather Array of Current Movie Trailers  
		//XML Data
		$xml_data = url_to_string(XMLFEED);
		//Creating Instance of the Class
		$xmlObj    = new XmlToArray($xml_data);
		$arrayData = $xmlObj->createArray();
				
		foreach($arrayData['records']['movieinfo'] as $Row){
			
			$MovieTitle = $Row['info'][0]['title'];
			$MovieLink = $Row['preview'][0]['large'];
			$VideoPlayCMD = PLAYERCMD . ' ' . $MovieLink;
			
			if(!valid_url($MovieLink)){
				$MovieTitle = $MovieTitle . '*VIDEO ERROR*';
				$VideoPlayCMD = '';			
			}
			
			print "\t<button>\n";
			print "\t\t<type>VIDEO_BROWSER</type>\n";
			$MovieTitle = preg_replace('/ & /', ' &amp; ', $MovieTitle);
			print "\t\t<text>$MovieTitle</text>\n";
			print "\t\t<action>EXEC $VideoPlayCMD</action>\n";
			print "\t</button>\n\n";		
			
		}
	}else{
			print "\t<button>\n";
			print "\t\t<type>VIDEO_BROWSER</type>\n";
			print "\t\t<text>Error Grabbing XML Feed</text>\n";
			print "\t\t<action></action>\n";
			print "\t</button>\n\n";				
	}
	
	print "</mythmenu>\n";
	

	
}


// Function:  returns boolean | valid_url ( var | url to check) 
// Description: Checks to see if a url is a valid page    
function valid_url($str)
{
	if(@fopen($str, "r")) {
		return true;
	} else {
		return false;
	}
}

// Function:  returns string | all elements of XML ( var | url to feed) 
// Description: Converts each element in an XML feed to single line string
// Notes: must have 'allow_url_fopen = On' in php.ini 
function url_to_string($url){
	$lines = file($url);
	foreach ($lines as $line) {
		$lineR = trim($line);
	}
	$lineR = eregi_replace("<" . "large" . "[^>]*>", "<large>", $lineR); //hack for apple goofy xml
	return $lineR;
}

// Class:  returns (~) x array | elements of XML ( var | XML in string) 
// Description: Converts each element in an XML feed to an Array
class XmlToArray
{
   
    var $xml='';
   
    /**
    * Default Constructor
    * @param $xml = xml data
    * @return none
    */
   
    function XmlToArray($xml)
    {
       $this->xml = $xml;   
    }
   
    /**
    * _struct_to_array($values, &$i)
    *
    * This is adds the contents of the return xml into the array for easier processing.
    * Recursive, Static
    *
    * @access    private
    * @param    array  $values this is the xml data in an array
    * @param    int    $i  this is the current location in the array
    * @return    Array
    */
   
    function _struct_to_array($values, &$i)
    {
        $child = array();
        if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
       
        while ($i++ < count($values)) {
            switch ($values[$i]['type']) {
                case 'cdata':
                array_push($child, $values[$i]['value']);
                break;
               
                case 'complete':
                    $name = $values[$i]['tag'];
                    if(!empty($name)){
                    $child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
                    if(isset($values[$i]['attributes'])) {                   
                        $child[$name] = $values[$i]['attributes'];
                    }
                }   
              break;
               
                case 'open':
                    $name = $values[$i]['tag'];
                    $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
                    $child[$name][$size] = $this->_struct_to_array($values, $i);
                break;
               
                case 'close':
                return $child;
                break;
            }
        }
        return $child;
    }//_struct_to_array
   
    /**
    * createArray($data)
    *
    * This is adds the contents of the return xml into the array for easier processing.
    *
    * @access    public
    * @param    string    $data this is the string of the xml data
    * @return    Array
    */
    function createArray()
    {
        $xml    = $this->xml;
        $values = array();
        $index  = array();
        $array  = array();
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parse_into_struct($parser, $xml, $values, $index);
        xml_parser_free($parser);
        $i = 0;
        $name = $values[$i]['tag'];
        $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
        $array[$name] = $this->_struct_to_array($values, $i);
        return $array;
    }
   
   
}

?>