<?php

$args = getopt( 'u:p:f:s:h:' );

$sizelimit = 2*1024*1024; // 2MB

if( empty( $args ) ) {
	echo<<<END
This script requires the following options:
 -u: Username
 -p: Password
 -f: File to upload
 -s: Size of the chunks to upload (1-$sizelimit)
 -h: The host to upload to

END;
	exit;
}

if ( ! file_exists( $args['f'] ) ) {
	echo "Filename doesn't exist.\n";
	exit;
}

$args['s'] = (int) $args['s'];
if( $args['s'] < 1 || $args['s'] > $sizelimit ) {
	echo "Size must be between 1 and $sizelimit\n";
	exit;
}

$filesize = filesize( $args['f'] );

$values = array(
			0 => 0,
			1 => $args['u'],
			2 => $args['p'],
			3 => array(
						'name' => basename( $args['f'] ),
						'type' => mime_content_type( $args['f'] ),
						'filesize' => $filesize,
						'resume' => true
			)
		);

$handle = fopen( $args['f'], 'r' );

for( $ii = 0; $ii <= $filesize; $ii += $args['s'] ) {
	$values[3]['bits'] = base64_encode( fread( $handle, $args['s'] ) );
	$values[3]['location'] = $ii;

	$xml = xmlrpc_encode_request( 'wp.uploadFile', $values );
	
	echo $response = do_post_request( $args['h'], $xml );
	$data = xmlrpc_decode( $response );
	//var_dump( $data );
	$values['3']['path'] = $data['path'];
	$values['3']['url'] = $data['url'];
}

function do_post_request($url, $data, $optional_headers = null)
{
	$params = array('http' => array(
					'method' => 'POST',
					'content' => $data
		));
	if ($optional_headers !== null) {
		$params['http']['header'] = $optional_headers;
	}
	$ctx = stream_context_create($params);
	$fp = @fopen($url, 'rb', false, $ctx);
	if (!$fp) {
		throw new Exception("Problem with $url, $php_errormsg");
	}
	$response = @stream_get_contents($fp);
	if ($response === false) {
		throw new Exception("Problem reading data from $url, $php_errormsg");
	}
	return $response;
}
?>