<?php

class youTube{

//---------------------------------------------------------------------------------------
// FUNÇÃO SUBSTITUTA FILE_GET_CONTENTS PARA HOSTS COM URL FILE-ACESS DISABLED
//---------------------------------------------------------------------------------------
    function curlURL($url) {
		$ch = curl_init();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_HEADER, 0);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);		
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
		$conteudo = curl_exec($ch);
		curl_close($ch);
		return $conteudo;
    }
//---------------------------------------------------------------------------------------
// FUNÇÃO SUBSTITUTA GET_HEADERS PARA HOSTS COM URL FILE-ACESS DISABLED
//---------------------------------------------------------------------------------------
   function _get_headers($url,$format=0, $user='', $pass='', $referer='') {
        if (!empty($user)) {
            $authentification = base64_encode($user.':'.$pass);
            $authline = "Authorization: Basic $authentification\r\n";
        }

        if (!empty($referer)) {
            $refererline = "Referer: $referer\r\n";
        }

        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";
            if (!empty($url_info['port'])) {
                $head .= "Host: ".@$url_info['host'].":".$url_info['port']."\r\n";
            } else {
                $head .= "Host: ".@$url_info['host']."\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n";
            $head .= $refererline;
            $head .= $authline;
            $head .= "\r\n";

            fputs($fp, $head);      
            while(!feof($fp) or ($eoheader==true)) {
                if($header=fgets($fp, 1024)) {
                    if ($header == "\r\n") {
                        $eoheader = true;
                        break;
                    } else {
                        $header = trim($header);
                    }

                    if($format == 1) {
                    $key = array_shift(explode(':',$header));
                        if($key == $header) {
                            $headers[] = $header;
                        } else {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                    unset($key);
                    } else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;

        } else {
            return false;
        }
    }
	
	function get_flv($v_id, $fmt=5){
		// Verifica se aceita url file acess
		// Senão usa curl
    	if (ini_get('allow_url_fopen')){
			$conteudo = file_get_contents("http://youtube.com/get_video_info?video_id=".$v_id);
		} else {
			$conteudo = $this->curlURL("http://youtube.com/get_video_info?video_id=".$v_id);
		}
				
		parse_str($conteudo, $inf);	
		// Verificado e retornando os itags de qualidade do vídeo disponivel			
		preg_match_all('/&itag=(.+?)&ipbits/', $inf['fmt_url_map'], $itags);
		// Verifico se a qualidade passada pelo usuário está presenta nas disponíveis no array
		// Se não estiver, defino a qualide padrão disponivel em todas fmt=5
		if (in_array($fmt, $itags[1])){
			$fmt = $fmt;			
		} else {
			$fmt = 5;
		}		
		// url para gerar a url para o video flv,mp4,etc
		$url = "http://www.youtube.com/get_video.php?video_id=". $v_id ."&vq=".$inf['vq']."&fmt=".$fmt."&t=" . $inf['token'];
		
		// headers com informações da url
		$cabecalhos = $this->_get_headers($url,1);
		if(!is_array($cabecalhos['Location'])) {
			$url = $cabecalhos['Location'];
		} else {
			foreach($cabecalhos['Location'] as $h){
				if(strpos($h,"googlevideo.com")!=false){
					$url = $h;
					break;
				}
			}
		}
		return $url;
	}
	
}

$FLV = new youTube;

$loc = $FLV->get_flv($_GET['v'], $_GET['fmt']);

header("Location: $loc");
?>