<?php

ini_set('user_agent','QuickTime.7.6 (qtver=7.6;os=Windows NT 6.0Service Pack 2)');

function __($s)
	{
	return iconv('utf-8','IBM852',$s);
	}

echo __('Enter URL to a movie trailers page:')."\n  ";
$fp = fopen("php://stdin","r");
$url = trim(fgets($fp, 1024));
$url = rtrim($url,'/').'/';

if ($url == '')
	{exit(__('URL not entered.'));}

// $url = 'http://trailers.apple.com/trailers/independent/scarymovie5/';

$url = $url.'includes/playlists/web.inc';

$page = @file_get_contents($url);

if (!preg_match_all('`(http://trailers\.apple\.com/(?:.*?)1080p\.mov)(?:.*?)\(([0-9]+ MB)\)`i',$page,$res))
	{exit(__('Trailers not found.'));}

$sel = 0;
if (count($res[1])>1)
	{
	echo __('More trainers in highest quality was found. What should I download?')."\n";
	foreach ($res[1] as $n=>$t)
		{
		echo '  '.$n.': '.basename($t).' ('.$res[2][$n].')'. "\n";
		}
	echo 'Selection [0]: ';
	$fp = fopen("php://stdin","r");
	$sel = (int) trim(fgets($fp, 1024));
	if (!isset($res[1][$sel]))
		{$sel = 0;}
	}

$url = $res[1][$sel];

function getRemoteSize($filename)
	{
	fopen($filename,'r');
	$size = false;
	if (count($http_response_header)>0)
		{
		foreach ($http_response_header as $s)
			if (preg_match('`^Content\-Length: ([0-9]+)$`',$s,$x))
				{
				$size = (int) $x[1];
				break;
				}
		}
	return $size;
	}

$total = getRemoteSize($url);
echo 'Size: '.round($total/1024/1024) . ' MB'."\n";

$fn = basename($url);

if (is_file($fn))
	{
	echo __('File already exists ('.round(filesize($fn)/1024/1024).' MB). Redownload? [a/n]: ');
	$fp = fopen("php://stdin","rb");
	$sel = fgetc($fp);
	if (strtolower(trim($sel)) != 'a')
		{exit(__('Aborted.'));}
	}

$wr = 0;
$perc = 0;
$window_width = 79;
$time_last = microtime(true);
$bytes_last = 0;

echo str_pad('',$window_width);

$r = fopen($url,'r');
$w = fopen($fn,'w');
while ($buf = fread($r,1024))
	{
	$wr += strlen($buf);
	fwrite($w,$buf);
    $perc = round(($wr / $total) * 100);

	if (microtime(true)-$time_last>=1)
		{
		for($place = $window_width; $place > 0; $place--) {echo "\x08";}
        echo str_pad(__('Downloaded: '.$perc.' %, current speed: '.round(($wr-$bytes_last) / 1024 / (microtime(true)-$time_last)).' kB/s, '.round(($total-$wr)/1024/1024).' MB remaining'), $window_width);
        exec('title '.$perc.'% '.$fn);
        $time_last = microtime(true);
        $bytes_last = $wr;
		}
	}

fclose($r);
fclose($w);

echo "\n".__('Finished.');
?>