<?php
/**
 * project:     GooTube FLV Retriever
 * file:        function.general.php
 * desc:        general funtions
 * author:      Kej<kejjang@gmail.com>
 *
 * last update: 2006/8/17 10:44
 */

function parseUrl($url){
	if(!function_exists('get_headers')){
		function get_headers($url, $flag=1){
			$url_info=parse_url($url);
			if(isset($url_info['scheme']) && $url_info['scheme'] == 'https'){
				$port = 443;
				@$fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 10);
			}else{
				$port = isset($url_info['port']) ? $url_info['port'] : 80;
				@$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 10);
			}
			if($fp){
				stream_set_timeout($fp, 10);
				$head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
				$head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
				fputs($fp, $head);
				while(!feof($fp)){
					if($header=trim(fgets($fp, 1024))) {
						$sc_pos = strpos( $header, ':' );
						if( $sc_pos === false ) {
							$headers['status'] = $header;
						} else {
							$label = substr( $header, 0, $sc_pos );
							$value = substr( $header, $sc_pos+1 );
							//$headers[strtolower($label)] = trim($value);
							$headers[$label] = trim($value);
						}
					}
				}
				return $headers;
			}else{
				return false;
			}
		}
	}

	$url=trim($url); 
	if(preg_match('/http:\/\/video\.google\.com\/videoplay/',$url)){
		$ff=file_get_contents($url);
		preg_match('/googleplayer\.swf\?(.*?)videoUrl.u003d(.*?)\&autoPlay/',$ff,$matches);
		$vurl=urldecode($matches[2]);
	}elseif(preg_match('/http:\/\/(www\.)?youtube.com/',$url)){
		if(preg_match('/[\?&]v=/',$url) || preg_match('/p\.swf\?video_id=/',$url) || preg_match('/\/v\//',$url)){
			$ff=file_get_contents($url);
			preg_match('/\"\/player2\.swf\?(.*?)\"/',$ff,$matches);
			$qstr=$matches[1];
			parse_str($qstr,$qary);
			if(strlen($qary['video_id'])>0 && strlen($qary['t'])>0){
				$vurl='http://www.youtube.com/get_video.php?video_id='.$qary['video_id'].'&t='.$qary['t'];
			}else{
				if(strpos($url,'p.swf?video_id')!==false){
					parse_str(substr($url,strpos($url,'?')+1),$qry_data);
				}else{
					if(strpos($url,'com/v/')!==false){
						$url_new='http://www.youtube.com/watch_video?v='.substr($url,strpos($url,'com/v/')+6);
					}else{
						$url_new=$url;
					}
					$url_new=str_replace('watch?v=','watch_video?v=',$url_new);
					$url_new=str_replace('watch?search=','watch_video?search=',$url_new);
					$url_new_headers=get_headers($url_new);
					parse_str(substr($url_new_headers['Location'],strpos($url_new_headers['Location'],'?')+1),$qry_data);
				}
				if(strlen($qry_data['video_id'])>0 && strlen($qry_data['t'])>0){
					$vurl='http://www.youtube.com/get_video.php?video_id='.$qry_data['video_id'].'&t='.$qry_data['t'];
				}
			}
			$vurl=get_headers($vurl,1);
			$vurl=$vurl['Location'];
		}
	}
	return $vurl;
}
?>