#!/usr/bin/php
<?php 

require __DIR__.'/../../../vendor/autoload.php';

$url = $argv[1];

$folder = isset($argv[2]) ? rtrim($argv[2], '/') : '.';

if(! is_dir($folder)) {
	mkdir($folder);
}

if(count($argv) == 1) {
	exit("You need to specify the Url\n");
}

$page = file_get_contents($url);

$dom = new DOMDocument;

libxml_use_internal_errors(true);
$dom->loadHTML($page);
libxml_clear_errors();

foreach ($dom->getElementsByTagName('img') as $node)
{
	$localfile = $folder . '/' . uniqid() . '.jpg';

	$toDownload = (substr($node->getAttribute('src'), 0, 4) == 'http')
				 ? $node->getAttribute('src') 
				 : 'http://' . $node->getAttribute('src');

	if(copy($toDownload, $localfile)) {
		echo 'Downloading file ' . $node->getAttribute('src') . " to $localfile\n";
	}

}

