<?php
/**
 * 	This class allows you to get the download links from any youtube video
 */
class Download {
	/**
     * @var array $info - Video data
     */
    private static $info;
	
	/**
     * @var array $links - Links array
     */
    private static $links = array();
	
	/**
     * @var array $formats - Formats of youtube video
     */
    private static $formats = array(
        '5'=>'flv',
        '6'=>'flv',
        '34'=>'flv',
        '35'=>'flv',
        '18'=>'mp4',
        '22'=>'mp4',
        '37'=>'mp4',
        '38'=>'mp4',
        '83'=>'mp4',
        '82'=>'mp4',
        '85'=>'mp4',
        '84'=>'mp4',
        '43'=>'webm',
        '44'=>'webm',
        '45'=>'webm',
        '46'=>'webm',
        '100'=>'webm',
        '101'=>'webm',
        '102'=>'webm',
        '13'=>'3gp',
        '17'=>'3gp',
        '36'=>'3gp'
    );
	
	/**
     * Method for processing getting information about video
	 *
     * @return array|null
     */
    public static function get_info($id) {
        if(empty($id)) die('Enter video id');
        if(!empty(self::$info)) return self::$info;
        
		# Get video data
        $data = file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id);

        # Parsing data
        parse_str($data, $info);

        # Check the returned status
        if(@$info['status'] == 'ok') {
            self::$info = $info;
            return $info;
        } else {
            return false;
        }
    }
	
	/**
	 * Return the download links
	 * 
	 * @param string The video id
	 * @return array The download links
	 */ 
	function getDownloadLinks($id) {
		if(!empty(self::$links)) return self::$links;
        if(empty(self::$info)) self::get_info($id);
        $links_map = explode(',',self::$info['url_encoded_fmt_stream_map']);
        $fmt_list = explode(',',self::$info['fmt_list']);
        if(empty($links_map) || (sizeof($links_map) == 1 && empty($links_map[0]))) return false;
        foreach($links_map as $key => $link){
            parse_str($link,$parts);
            //$link = $parts['url'].='&signature='.$parts['sig'];
			$link = $parts['url'];
            $fmt_parts = explode('/', $fmt_list[$key],3);
            # Create array of information of video
            self::$links[self::$formats[$parts['itag']] .'-'. $fmt_parts[1]] = array(self::$formats[$parts['itag']], $fmt_parts[1], $link);
        }
        return self::$links;
	}
}