<?php
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)
{
    global $CONFIG;
    $blockdirs=array('.','..','CVS',str_replace('/','',$CONFIG['userpics']),'edit','_vti_cnf');
	if ($dir = opendir($path))
	{
		$thisdir = array();
		while (false !== ($file = readdir($dir)))
		{
			if  (!in_array($file,$blockdirs))
			{
				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) {
				if ( (strncmp($file,$CONFIG['thumb_pfx'],strlen($CONFIG['thumb_pfx'])) != 0 ) && ( strncmp($file,$CONFIG['normal_pfx'],strlen($CONFIG['normal_pfx'])) != 0) ) {
					$filelist["$path/$name/$file"] = $aid;
				}
			}
		}
	}
}

function cleanupfilelist() {
	global $filelist, $CONFIG;

	$sql = "SELECT aid, CONCAT('./" . addslashes($CONFIG['fullpath']) . "',filepath,filename) As filepath FROM {$CONFIG['TABLE_PICTURES']} ORDER BY filepath";
    $result = db_query($sql);
	while($row = mysql_fetch_row($result)) {
		$arr[$row[1]] = $row[0];
	}
	flush();

	echo count($filelist) . " Pictures Found<br />";
	echo count($arr) . " Pictures in the database<br />";
	if (is_array($arr)) {
	   $filelist = array_diff_assoc($filelist,$arr);
	}
	echo "After filtering " . count($filelist) . " pictures will be added<br />";
}

function populatealbums()
{
	global $filelist, $counter;
	
	$lim = $_POST['hardlimit'] > 0 ? $_POST['hardlimit'] : getrandmax();
		
	foreach ($filelist as $filename => $aid)
	{
		if ($counter < $lim)
		{
			set_time_limit(180);
			//echo "$filename - $aid<br />";
			addpic($aid, $filename);
			$filelist = array_diff_assoc($filelist, array($filename => $aid));
			usleep($_POST['sleep'] * 1000);
			$counter++;
		}
	}
}

function createcategory($parent, $name)
{
	global $CONFIG;

	$sql = "SELECT cid " . "FROM {$CONFIG['TABLE_CATEGORIES']} " . "WHERE name='" . addslashes($name) . "' AND parent=" . (INT)$parent . " LIMIT 1";
    $result = db_query($sql);

    if (mysql_num_rows($result)) {
		echo "category already exists : $name<br />";
		$row = mysql_fetch_row($result);
		$cid = $row[0];
	} else {
		db_query("INSERT INTO {$CONFIG['TABLE_CATEGORIES']} (pos, parent, name) VALUES ('10000', '$parent', '" . addslashes($name) . "')");
		echo "created category $name<br/>";
		$cid = mysql_insert_id();
	}
	flush();

	return $cid;
}

function createalbum($category, $title)
{
	global $CONFIG;
	
	$sql = "SELECT aid " . "FROM {$CONFIG['TABLE_ALBUMS']} " . "WHERE title='" . addslashes($title) . "' AND category=" . (INT)$category . " LIMIT 1";
    $result = db_query($sql);

    if (mysql_num_rows($result)) {
		echo "album already exists : $title<br />";
		$row = mysql_fetch_row($result);
		$aid = $row[0];
	} else {
		db_query("INSERT INTO {$CONFIG['TABLE_ALBUMS']} (category, title, pos) VALUES ('".(INT)$category."', '" . addslashes($title) . "', '10000')");
		echo "created album $title<br/>";
		$aid = mysql_insert_id();
	}
	flush();

	return $aid;
}

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);

	if ( (strncmp($file_name,$CONFIG['thumb_pfx'],strlen($CONFIG['thumb_pfx'])) != 0 ) && ( strncmp($file_name,$CONFIG['normal_pfx'],strlen($CONFIG['normal_pfx'])) != 0) ) {

		$sane_name = str_replace('%20', '_', $file_name);
		$sane_name = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $sane_name);
		$sane_name = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $sane_name);
		while ( strpos($sane_name,'__') !== FALSE ) {
			$sane_name = str_replace('__', '_', $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();
	} else {
		echo "Skipping thumb or normale pics<br />";
	}
}

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'] : '';
	$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']);

	if (!$_POST['directory']) {
        echo 'Using root Category<br />';
        $parent=0;
    } else {
        $sql = "SELECT cid " . "FROM {$CONFIG['TABLE_CATEGORIES']} " . "WHERE parent='0' AND name='" . $_POST['directory'] . "' " . "LIMIT 1";
    	$result = db_query($sql);
        if (mysql_num_rows($result)) {
			echo "Root category already exists : " . $_POST['directory'] . "<br />";
			$row = mysql_fetch_row($result);
			$cid = $row[0];
		} else {
			db_query("INSERT INTO {$CONFIG['TABLE_CATEGORIES']} (pos, parent, name) VALUES ('10000', '0', '{$_POST['directory']}')");
			echo 'Created root category<br />';
			$cid = mysql_insert_id();
		}
	}
	flush();
				
	createstructure($data, $cid, './albums/' . $_POST['directory']);

	cleanupfilelist();

} else {
	echo <<< EOT
	
<form method="POST" action="timer.php">
	SubDirectory (under albums) or blank: <input type="text" name="directory" value=""><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;
}
