<?php

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$images = array();


function scan_dir($dir) {
	$ignored = array('.', '..', '.svn', '.htaccess');

	$files = array();
		foreach (scandir($dir) as $file) {
		if (in_array($file, $ignored)) continue;
		$files[$file] = filemtime($dir . '/' . $file);
	}

	arsort($files);
	$files = array_keys($files);

	return ($files) ? $files : false;
}

function imagelist($dir)
{
	global $images;

	//$stuffs = scandir($dir);

	$stuffs = scan_dir($dir);
	
	for ($i = 0; $i < sizeof($stuffs); $i++)
	{
		$farr = explode('.', $stuffs[$i]);
		if ($stuffs[$i] != '.' && $stuffs[$i] != '..' && $farr[0] != 'thumb')
			if (is_dir($stuffs[$i]))
				imagelist($dir.'/'.$stuffs[$i]);
			elseif (in_array(end($farr), array('gif', 'png', 'jpg', 'jpeg')))
			{
				// PATHS
				$outdir = '/data/'.ltrim($dir, './').'/';
				$img	= $dir.'/'.$stuffs[$i];
				$thumb	= $dir.'/thumb.'.$stuffs[$i];

				// THUMBNAIL
				if (!file_exists($thumb))
				{
					$cthumb = new Imagick($img);
					$cthumb->cropThumbnailImage(260, 260);
					$cthumb->writeImage($thumb);
					$cthumb->destroy(); 
				}

				// ADD TO LIST
				array_push($images, array(
					'image'		=> $outdir.rawurlencode($stuffs[$i]),
					'thumb'		=> $outdir.'thumb.'.$stuffs[$i],
					'folder'	=> ltrim($dir, './')
				));
			}
	}
}

imagelist('./uploads');
foreach(glob('./uploads/*', GLOB_ONLYDIR) as $dir)
    imagelist($dir);

echo str_replace('\/', '/', json_encode($images));