<?
define('IN_COPPERMINE', true);
define('ADDPIC_PHP', true);

require('include/init.inc.php');
require('include/picmgmt.inc.php');

if (!GALLERY_ADMIN_MODE) die('Access denied');

ob_end_flush();

register_shutdown_function('reload');

function dir_parse($path)
{
	if ($dir = opendir($path))
	{
		$thisdir = array();
		while (false !== ($file = readdir($dir)))
		{
			if  ($file != '.' && $file != '..')
			{
				if (is_dir("$path/$file"))
				{
					$thisdir[$file] = dir_parse("$path/$file");
				} else {
					$thisdir[] = $file;
				}
			}
		}
		return $thisdir;
	}
}

function createstructure($data, $parent, $path)
{
	global $CONFIG, $filelist;
	
	$i = 0;
	
	$names = array_keys($data);

	$cat_names = array();

	foreach ($data as $set)
	{
		if (is_array($set)) $cat_names[] = $names[$i];
		$i++;
	}

	$i = 0;
	
	foreach ($cat_names as $name)
	{
		unset($aid);
		
		$base = true;

		foreach ($data[$name] as $lower)
		{
			if (is_array($lower)){
				$base = false;
				break;
			}
		}
		
		if ($base){
			$directory = $name;
		} else {
			$parent2 = createcategory($parent, $name);
			$directory = $data[$name];
		}
		
		if (is_array($directory))
		{
			createstructure($directory, $parent2, "$path/$name");
		} else {
			if (!isset($aid)) $aid = createalbum($parent, $name);
			$contents = dir_parse("$path/$name");
			
			foreach ($contents as $file)
				$filelist["$path/$name/$file"] = $aid;
		}
	}
}

function populatealbums()
{
	global $filelist, $counter;
	
	$lim = $_POST['hardlimit'] > 0 ? $_POST['hardlimit'] : getrandmax();
		
	foreach ($filelist as $filename => $aid)
	{
		if ($counter < $lim)
		{
			addpic($aid, $filename);
			$filelist = array_diff_assoc($filelist, array($filename => $aid));
			usleep($_POST['sleep'] * 1000);
			$counter++;
		}
	}
}

function createcategory($parent, $name)
{
	global $CONFIG;
	
	db_query("INSERT INTO {$CONFIG['TABLE_CATEGORIES']} (pos, parent, name) VALUES ('10000', '$parent', '$name')");
	echo "created category $name<br/>";
	
	return mysql_insert_id();
}

function createalbum($category, $title)
{
	global $CONFIG;
	
	db_query("INSERT INTO {$CONFIG['TABLE_ALBUMS']} (category, title, pos) VALUES ('$category', '$title', '10000')");
	echo "created album $title<br/>";
	
	return mysql_insert_id();
}

function addpic($aid, $pic_file)
{
	global $CONFIG;
	
	$pic_file = str_replace('./' . $CONFIG['fullpath'], '', $pic_file);
	
	$dir_name = dirname($pic_file) . "/";
	$file_name = basename($pic_file);

	$sane_name = str_replace('%20', '_', $file_name);
	$sane_name = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $sane_name);
	$c = 0;
	$sane_name2 = $sane_name;
	
		$sql = "SELECT pid " . "FROM {$CONFIG['TABLE_PICTURES']} " . "WHERE filepath='" . addslashes($dir_name) . "' AND filename='" . addslashes($sane_name) . "' " . "LIMIT 1";
	$result = db_query($sql);
	
	$extra = strstr($pic_file, $sane_name) ? '' : " (as $sane_name)";
	if (mysql_num_rows($result)) {
		echo "Picture '$pic_file' already added$extra<br />";
	} else {
		while (($sane_name != $file_name) && file_exists("./" . $CONFIG['fullpath'] . $dir_name . $sane_name))
		{
			$c++;
			$sane_name = $c . '_' . $sane_name2;
		}
	
		$source = "./" . $CONFIG['fullpath'] . $dir_name . $file_name;
		rename($source, "./" . $CONFIG['fullpath'] . $dir_name . $sane_name);
	
		if (add_picture($aid, $dir_name, $sane_name, $file_name)) {
			echo "Picture '$pic_file' added$extra<br />"; 
		} else {
			echo "Picture '$pic_file' failed$extra<br />"; 
		}
	}
	flush();
	ob_end_flush();
}

function reload()
{
	global $filelist, $counter;
	
	if (count($_POST) == 0) exit();
	
	$remaining = countup($filelist);
	
	$filelist = base64_encode(serialize($filelist));
	$auto = (isset($_POST['auto']) && $_POST['auto']) ? 'checked = "checked"' : '';
	$js = ($_POST['auto'] && $remaining) ? '<script type="text/javascript"> onload = document.form.submit();</script>' : ''; 
	$counter = $counter ? "$counter files added" : "structure created";
	$directory = isset($_POST['directory'])  ? $_POST['directory'] : 'albums/your_dir';
	$sleep = isset($_POST['sleep'])  ? $_POST['sleep'] : '1000';
	$hardlimit = isset($_POST['hardlimit'])  ? $_POST['hardlimit'] : '0';
	
	if (!connection_aborted()) echo <<< EOT
	
	$counter, $remaining files to add.<br />
	<form name="form" method="POST" action="timer.php">
		<input name="filelist" type="hidden" value="$filelist">
		<input type="hidden" name="directory" value="$directory">	
		Sleep: <input type="text" name="sleep" value="$sleep">
		Limit: <input type="text" name="hardlimit" value="$hardlimit">
		<input type="submit" value="continue">
		Autorun: <input type="checkbox" name="auto" value="1" $auto>
	</form>
	$js
EOT;
}
	
function countup($array)
{
	$result = 0;

	foreach ($array as $a)
		$result += is_array($a) ? countup($a) : count($a);

	return $result;
}


if (isset($_POST['filelist'])){

	$filelist = unserialize(base64_decode($_POST['filelist']));
	$counter = 0;
	
	populatealbums();

} elseif (isset($_POST['start'])) {

	$data = dir_parse('./albums/' . $_POST['directory']);
	
	db_query("INSERT INTO {$CONFIG['TABLE_CATEGORIES']} (pos, parent, name) VALUES ('10000', '0', '{$_POST['directory']}')");
	echo 'Created root category<br />';

	createstructure($data, mysql_insert_id(), './albums/' . $_POST['directory']);

} else {
	
	echo <<< EOT
	
<form method="POST" action="timer.php">
	SubDirectory (under albums): <input type="text" name="directory" value="your_directory"><br /><br />
	Sleep between additions (ms): <input type="text" name="sleep" value="1000"><br /><br />
	Run unattended: <input type="checkbox" name="auto" value="1"><br /><br />
	Limit additions per refresh<input type="text" name="hardlimit" value="0"><br /><br />
	<input type="submit" name="start" value="Begin">
</form>
	
EOT;
}