<?PHP
ini_set('max_execution_time', 0);
ini_set('error_reporting', E_ALL);
/*

 20.05 08/04/2012

 code by BlackHawk <docbollore@gmail.com>
 Special thanks to ZeroCalcare.iT, all developers from MobileRead.com
 and labionda for the support;
 
 CHANGELOG:
 
 v0.3
 
 - fixed some forgotten ;
 - added ability to define costum functions to work on file after download_img
 - added questionablecontent.php recipe
 
 v0.2
 
 - fixed bug while sorting dir content
 - fixed some minor things
 - added site crawler for comics
 - added 2 recipes
 
 v0.1
 
 - added support for .txt files with list of images
 - rewrote some code
 - added changelog & greetings
 - fixed order problem with unix based systems
 
 v0.0
 
 - initial release
 - support dirs, .mngl & .cbz files
 
 */


echo "


+------------------------------------------------------+
|                                                      |
|                       KGCMRC                         |
|                                                      |
| Kindle Gallery  Comics / Mangle Renamer / Converter  |
|                                                      |
+------------------------------------------------------+

                by BlackHawk / mr.w0lf

";
$usage = "
To crawl an entire comic site saving the images call build a
recipe and place it in the 'recipes' folder (edit the 2 attached
to see what to do), then call the crawler like this:

--- +++ ---
php $argv[0] crawl
--- +++ ---

And follow the provided instructions.

To convert a (working) .mngl file made with Mangle:

--- +++ ---
php $argv[0] filename.mngl
--- +++ ---

that will make a new dir named with the book title,
automatically copying images into it already renamed.
You can use even a normal TXT file with the path of an image
for each line. You parse it in the same way:

--- +++ ---
php $argv[0] filename.txt
--- +++ ---


If you have a comic file (.cbz) use the same command as above,
file will be extracted and names will be fixed.

--- +++ ---
php $argv[0] filename.cbz
--- +++ ---

To mass rename an entire dir files:

--- +++ ---
php $argv[0] ./dir/to/rename/
--- +++ ---
";

function order_directory($dir)
{
	$handle = opendir ($dir);
	$i=0;
	while (($filename = readdir ($handle)) !== false)
	{
		if ($filename != '..' && $filename != '.')
		{
			$ord_file[] = $filename;
		}
	}
	sort($ord_file, SORT_NUMERIC);
	foreach ($ord_file as $fn)
	{
		rename("$dir/$fn", "$dir/$i.".end(explode('.', $fn)));
		$i++;
	}
}

function download_img($page)
{
	global $next_page, $detect_img, $counter, $title, $before_next, $before_img, $after_func;
	echo "Started $page\r\n";
	$html = file_get_contents($page);
	preg_match("/$detect_img/ims", $html, $result);
	$new_name = "$title/$counter.".end(explode('.', $result[1]));
	file_put_contents($new_name, file_get_contents(str_replace(' ', '%20', $before_img.$result[1])));
	if (isset($after_func))
	{
		$after_func($new_name);
	}
	$counter++;
	preg_match("/$next_page/ims", $html, $next);
	if ($next[1] == '') exit;
	download_img($before_next.$next[1]);
}

if ($argv[1] == 'crawl')
{
	echo 'Type the recipe name (es: jesuschristgun.php): ';
	$recipe = trim(fgets(STDIN));
	if (is_file('./recipes/'.$recipe))
	{
		include './recipes/'.$recipe;
		mkdir($title);
		download_img($start_page);
	}
	else
	{
		die("\r\nSorry, no such file");
	}
	
}
elseif (is_file($argv[1]))
{
	$boom = explode('.', $argv[1]);
	switch(end($boom))
	{
		case 'mngl':
			$mangle = file($argv[1]);
			preg_match('/title="(.+?)"/i', $mangle[0], $title);
			mkdir($title[1]);
			for ($i=1;$i<count($mangle)-1;$i++)
			{
				$filename = str_replace(array('    <image filename="', "\"/>\r\n"), '', $mangle[$i]);
				copy($filename, $title[1].'/'.($i-1).'.'.end(explode('.', $filename)));
			}
		break;
		
		case 'txt':
			echo 'Insert Book name: ';
			$title = trim(fgets(STDIN));
			$txt = file($argv[1]);
			mkdir($title);
			for ($i=0;$i<=count($txt);$i++)
			{
				$filename = str_replace(array('    <image filename="', "\"/>\r\n"), '', $mangle[$i]);
				copy($txt[$i], $title.'/'.$i.'.'.end(explode('.', $txt[$i])));
			}
		break;
		
		case 'cbz':
			$files = new zipfile();
			$content = $files->read_zip($argv[1]);
			$dir = substr($files->name,0,-4);
			mkdir($dir);
			foreach ($content as $file)
			{
				file_put_contents($dir.'/'.$file['name'],$file['data']);
			}
			order_directory($dir);
		break;
		
		default:
			die($usage.'-- Sorry, I support .mngl, .txt & .cbz files only ( for now.. )--');
		break;
	}
}
elseif (is_dir($argv[1]))
{
	order_directory($argv[1]);
}
else
{
	die($usage);
}
?>