<?php

define('IN_COPPERMINE', true);
define('INDEX_PHP', true);
require('include/init.inc.php');


// Get the starting category
if (!$_GET['cat']):
	$cat = 0;
else:
	$cat = (int) $_GET['cat'];
endif;

// Functions
// Sorting by name
function sort_name($a,$b) {
	if ($a["name"] == $b["name"])
		return 0;
	return ($a["name"] < $b["name"]) ? -1 : 1;
}

// Sorting by position
function sort_pos($a,$b) {
	if ($a["pos"] == $b["pos"])
		return 0;
	return ($a["pos"] < $b["pos"]) ? -1 : 1;
}

// Sorting by level
function sort_level($a,$b) {
	if ($a["level"] == $b["level"])
		return 0;
	return ($a["level"] > $b["level"]) ? -1 : 1;
}

// Sorting by order
function sort_order($a,$b) {
	if ($a["count"] == $b["count"])
		return 0;
	return ($a["count"] < $b["count"]) ? -1 : 1;
}

// Building the main tables $cpg_categories and $cpg_albums
function catlist() {
	global $CONFIG, $HIDE_USER_CAT, $FORBIDDEN_SET, $cpg_show_private_album;
	global $gallery,$count,$cpg_categories,$cpg_albums,$cat,$lang_list_categories;

	// Création des filtres
	if (!empty($FORBIDDEN_SET) && !$cpg_show_private_album) {
		$album_filter = ' and ' . str_replace('p.', 'a.', $FORBIDDEN_SET);
		$unaliased_album_filter = ' WHERE ' . str_replace('p.', '', $FORBIDDEN_SET);
		$pic_filter = ' and ' . str_replace('p.', $CONFIG['TABLE_PICTURES'] . '.', $FORBIDDEN_SET);
	}

	// Listing categories
	$sql = "SELECT cid,name,description,pos,parent,thumb,theme FROM {$CONFIG['TABLE_CATEGORIES']}";
	$result = cpg_db_query($sql);
	$tmp = cpg_db_fetch_rowset($result);

	$cpg_categories[0] = array("name" => $lang_list_categories['home']);

	foreach($tmp as $tmp2) {
		$cpg_categories[$tmp2["cid"]]["name"] = $tmp2["name"];
		if ($tmp2["description"]!=null):
			$cpg_categories[$tmp2["cid"]]["description"] = $tmp2["description"];
		endif;
		$cpg_categories[$tmp2["cid"]]["parent"] = $tmp2["parent"];
		$cpg_categories[$tmp2["cid"]]["thumb"] = $tmp2["thumb"];
		$cpg_categories[$tmp2["cid"]]["theme"] = $tmp2["theme"];
		$cpg_categories[$tmp2["parent"]]["subcat"][]= array("cid" => $tmp2["cid"],"pos" => $tmp2["pos"],"name" => $tmp2["name"]);
	}

	// Listing users with a personal gallery
	$sql = "SELECT category FROM {$CONFIG['TABLE_ALBUMS']} as a WHERE category>=" . FIRST_USER_CAT . $album_filter ." GROUP BY category";
	$sql2 = "SELECT user_id, user_name FROM {$CONFIG['TABLE_USERS']} ORDER BY user_name ASC";
	$result = cpg_db_query($sql);
	$result2 = cpg_db_query($sql2);
	$tmp= cpg_db_fetch_rowset($result);
	foreach($tmp as $tmp2) {
		$cpg_categories[$tmp2["category"]]["parent"] = USER_GAL_CAT;
	}

	$tmp= cpg_db_fetch_rowset($result2);
	foreach($tmp as $tmp2) {
		if (isset($cpg_categories[FIRST_USER_CAT + (int) $tmp2['user_id']])):
			$cpg_categories[FIRST_USER_CAT + (int) $tmp2['user_id']]["name"] = $tmp2['user_name'];
			$cpg_categories[USER_GAL_CAT]["subcat"][]["cid"] = FIRST_USER_CAT + (int) $tmp2['user_id'];
		endif;
	}

	// Listing albums
	$sql = "SELECT aid,title,description,pos,category,thumb,last_pid,last_addition,file_count FROM {$CONFIG['TABLE_ALBUMS']}". $unaliased_album_filter;
	$result = cpg_db_query($sql);
	$tmp = cpg_db_fetch_rowset($result);

	foreach($tmp as $tmp2) {
		$cpg_albums[$tmp2["aid"]]["title"] = $tmp2["title"];
		if ($tmp2["description"]!=null):
			$cpg_albums[$tmp2["aid"]]["description"] = $tmp2["description"];
		endif;
		$cpg_albums[$tmp2["aid"]]["parent"] = $tmp2["category"];
		$cpg_albums[$tmp2["aid"]]["thumb"] = $tmp2["thumb"];
		$cpg_albums[$tmp2["aid"]]["last_pid"] = $tmp2["last_pid"];
		$cpg_albums[$tmp2["aid"]]["last_addition"] = $tmp2["last_addition"];
		$cpg_albums[$tmp2["aid"]]["file_count"] = $tmp2["file_count"];
		$cpg_categories[$tmp2["category"]]["albums"][$tmp2["pos"]] = $tmp2["aid"];
	}

	reset($cpg_categories);
	while (list($key, $val) = each($cpg_categories)):
		ksort($cpg_categories[$key]["albums"]);
	endwhile;

}

// Building the gallery structure
function cat_data($cat_,$level) {
	global $CONFIG, $gallery,$count,$cpg_categories,$cpg_albums,$cat;
	$cat_tmp = $cpg_categories[$cat_]["subcat"];
	if ($cat_ == USER_GAL_CAT):
		;
	elseif ($CONFIG['categories_alpha_sort'] == 1):
		uasort($cat_tmp, "sort_name");
	else:
		uasort($cat_tmp, "sort_pos");
	endif;
	foreach($cat_tmp as $cat_tmp2) {
		$level_tmp = $level;
		$level++;
		$count++;
		$gallery[$cat_tmp2["cid"]] = array("type" => "CAT", "id" => $cat_tmp2["cid"], "name" => $cpg_categories[$cat_tmp2["cid"]]["name"], "description" => $cpg_categories[$cat_tmp2["cid"]]["description"], "level" => $level, "count" => $count, "cat_count" => count($cpg_categories[$cat_tmp2["cid"]]["subcat"]), "alb_count" => count($cpg_categories[$cat_tmp2["cid"]]["albums"]), "parent" => $cpg_categories[$cat_tmp2["cid"]]["parent"], "thumb" => $cpg_categories[$cat_tmp2["cid"]]["thumb"]);
		$alb_tmp = $cpg_categories[$cat_tmp2["cid"]]["albums"];
		cat_data($cat_tmp2["cid"],$level);
		foreach ($alb_tmp as $alb_tmp2) {
			$count++;
			$gallery["a".$alb_tmp2] = array("type" => "ALB", "id" => $alb_tmp2, "name" => $cpg_albums[$alb_tmp2]["title"], "description" => $cpg_albums[$alb_tmp2]["description"], "level" => $level+1, "count" => $count, "file_count" => $cpg_albums[$alb_tmp2]["file_count"], "parent" => $cpg_albums[$alb_tmp2]["parent"], "thumb" => $cpg_albums[$alb_tmp2]["thumb"]);
		}
		$level = $level_tmp;
	}
	$alb_tmp = $cpg_categories[$cat_]["albums"];
	foreach ($alb_tmp as $alb_tmp2) {
		$count++;
		$gallery["a".$alb_tmp2] = array("type" => "ALB", "id" => $alb_tmp2, "name" => $cpg_albums[$alb_tmp2]["title"], "description" => $cpg_albums[$alb_tmp2]["description"], "level" => $level+1, "count" => $count, "file_count" => $cpg_albums[$alb_tmp2]["file_count"], "parent" => $cpg_albums[$alb_tmp2]["parent"], "thumb" => $cpg_albums[$alb_tmp2]["thumb"]);
	}
}

// Building breadcrumb
function breadcr($category) {
	global $breadcrumb,$BREADCRUMB_TEXT,$cpg_categories,$cat_theme;
	if (isset($breadcrumb)):
		$breadcrumb = "<a href=\"?cat={$category}\">{$cpg_categories[$category]["name"]}</a> > {$breadcrumb}";
		$BREADCRUMB_TEXT = $cpg_categories[$category]["name"]." > ".$BREADCRUMB_TEXT;
	else:
		$breadcrumb = "<a href=\"?cat={$category}\">{$cpg_categories[$category]["name"]}</a>";
		$BREADCRUMB_TEXT = $cpg_categories[$category]["name"];
	endif;
	if (isset($cpg_categories[$category]["theme"]) && !isset($cat_theme)):
		$cat_theme = $cpg_categories[$category]["theme"];
	endif;
	if (isset($cpg_categories[$category]["parent"])):
    		breadcr($cpg_categories[$category]["parent"]);
	endif;
}

catlist();
cat_data($cat);
breadcr($cat);

uasort($gallery, "sort_level");
reset($gallery);

// Recursively updating categories, albums and files counts
while (list($key, $val) = each($gallery)):
	if ($val["level"] > 1):
		$gallery[$val["parent"]]["cat_count"] += $val["cat_count"];
		$gallery[$val["parent"]]["alb_count"] += $val["alb_count"];
		$gallery[$val["parent"]]["file_count"] += $val["file_count"];
	endif;
endwhile;

uasort($gallery, "sort_order");
reset($gallery);


// Displaying the gallery
header("Content-Type: text/html");
if (isset($cat_theme)):
	echo "Theme : " . $cat_theme . "<br />\n";
else:
	echo "Theme : " . $CONFIG['theme'] . "<br />\n";
endif;
echo $breadcrumb."<br />\n";
echo "<table border=\"1\">\n";
echo "<tr><td></td><td colspan=\"".($CONFIG['subcat_level'])."\">Name/Title<br />Description</td><td>Sub-categories</td><td>Albums</td><td>Pictures</td></tr>";
while (list($key, $val) = each($gallery)):
	if ($gallery[$key]["level"] - $gallery[$cat]["level"] <= $CONFIG['subcat_level'] && $gallery[$key]["file_count"] > 0):
		if ((int)$val["thumb"] > O):
			$thumb = "<img align=\"left\" src=\"thumb.php?id={$val["thumb"]}\">";
		elseif ((int)$val["thumb"] == O && $val["type"] == "ALB"):
			$thumb = "<img align=\"left\" src=\"thumb.php?id={$cpg_albums[ltrim($key,"a")]["last_pid"]}\">";
		endif;
		if ($val["cat_count"] == 0):
			$val["cat_count"] = "";
		endif;
		if ($val["alb_count"] == 0):
			$val["alb_count"] = "";
		endif;
		if ($val["type"] == "CAT"):
			echo "<tr><td>".$val["type"]."</td>".str_repeat("<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>",$val["level"]-1)."<td colspan=\"".($CONFIG['subcat_level']-$val["level"]+1)."\">{$thumb}<a href=\"?cat={$key}\">{$val["name"]}</a><br />".preg_replace("/<br.*?>[\r\n]*/i", '<br />', bb_decode($val['description']))."</td><td align=\"center\">{$val["cat_count"]}</td><td align=\"center\">{$val["alb_count"]}</td><td align=\"center\">{$val["file_count"]}</td></tr>\n";
		elseif ($val["type"] == "ALB"):
			echo "<tr><td>".$val["type"]."</td>".str_repeat("<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>",$val["level"]-1)."<td colspan=\"".($CONFIG['subcat_level']-$val["level"]+1)."\">{$thumb}<a href=\"thumbnails.php?album=".ltrim($key,"a")."\">{$val["name"]}</a><br />".preg_replace("/<br.*?>[\r\n]*/i", '<br />', bb_decode($val['description']))."<br /><font size=\"-2\">Last file added : " . $cpg_albums[ltrim($key,"a")]["last_addition"] . "</font></td><td align=\"center\">{$val["cat_count"]}</td><td align=\"center\">{$val["alb_count"]}</td><td align=\"center\">{$val["file_count"]}</td></tr>\n";
		endif;
	endif;
endwhile;
echo "</table>\n";

// Debug info
cpg_debug_output();

?>
