#!/usr/local/bin/perl
# gallery.cgi
#$StartTime = time();	#For debugging purposes
# flush the buffers
$|=1;
# find if it is a windows operating system
my($dpath);
my($windows);
if ( ($^O eq 'MSWin32') || defined($ENV{'OS'}) ) {
      # this one for windows
      $windows = "true";
      $dpath= "$ENV{'PATH_TRANSLATED'}";
      $dpath =~ s/\\$GalleryCgi$//g;
      $slash = '\\';
}else{
      # this one for unix type
      $windows = "false";
      $dpath = "$ENV{'SCRIPT_FILENAME'}";
      $dpath =~ s/\/$GalleryCgi$//g;
      $slash = '/';
}
push (@INC, "$dpath");
eval {
	# load required files
	require 'uig.cfg';
	push(@INC, "$ScriptPath");
	require $ScriptPath.$slash."uiglib.cgi";
	require $ScriptPath.$slash."memory.cgi";
	require $ScriptPath.$slash."display.cgi";
};
if ($@) {
	print qq~
	Content-type: text/html\n\n
	Error including the required files:~;
    print "$@\n\n";
	exit;	
}
use CGI;
$cgi = new CGI;
#eval use_named_parameters to work with both old and new versions of CGI.pm
eval '$cgi->use_named_parameters';
#read cookie
$CookieData = $cgi->cookie("$CookieName");
if ($CookieData){
	CrumbleCookie();
}
InitFromParameters();
LoadProfile();
if($cgi->param("func") eq "showlogin") {
	ShowLogin();
} elsif($cgi->param("func") eq "login") {
	my $rval = Login();
	if($rval eq "true") {
		WriteMessage(" $Username, you have been logged in.");
	} elsif($rval eq "false") {
		ShowLogin("You entered an incorrect password.");
	} 
} elsif($cgi->param("func") eq "logout") {
	Logout();
} elsif($cgi->param("func") eq "showregister") {
	ShowRegister();
} elsif($cgi->param("func") eq "register") {
	Register();
} elsif($cgi->param("func") eq "setsort") {
	$SortBy = $cgi->param("sort");
	SetCookie(PrepareCookie());
} elsif($cgi->param("func") eq "showsort") {
	ShowSortOptions();
} elsif($cgi->param("func") eq "search") {
	if($cgi->param("searchterm")) {
		require $ScriptPath.$slash."categories.cgi";
		require $ScriptPath.$slash."media.cgi";
		#initialize media 
		ReadCategories();
		$searchterm = DecodeURL($cgi->param("searchterm"));
		ReadMedia($cgi->param("Category"), $searchterm, $cgi->param("searchfield"));
		if(!@MediaList) {
			
			FatalError(qq~Found 0 Results for '$searchterm'~);
		}
		ShowGallery();
	} else {
		ShowSearchForm();
	}
} elsif($cgi->param("func") eq "showupload") {
	require $ScriptPath.$slash."categories.cgi";
	require $ScriptPath.$slash."media.cgi";
	#initialize media 
	ReadCategories();
	$CategoryPath = $MediaPath.$CategoryList[$CategoryIndex]->{PATH}."imagedata.cgi";
	$CategoryPath = $MediaPath.$CategoryPath;
	$Category = $CategoryList[$CategoryIndex]->{NAME};
	ShowUpload();
} elsif($cgi->param("func") eq "upload") {
	require $ScriptPath.$slash."categories.cgi";
	require $ScriptPath.$slash."media.cgi";
	require $ScriptPath.$slash."plugins.cgi";
	if(!$Username || $Username eq "Guest") {
		Login();
	}
	ReadCategories();
	ReadMedia($CategoryIndex);
	$CategoryPath = $MediaPath.$CategoryPath;
	$Category = $CategoryList[$CategoryIndex]->{NAME};
	LoadPlugins();
	Upload();
}
if($cgi->param("func") eq "show") {
	require $ScriptPath.$slash."categories.cgi";
	require $ScriptPath.$slash."media.cgi";
	ReadCategories();
	$Category = $CategoryList[$CategoryIndex]->{NAME};
	$granted = "false";
	if($CategoryList[$CategoryIndex]->{PROTECTED} eq "true") {
		if(($CategoryList[$CategoryIndex]->{GROUPS} =~ /$UserProfile[16]/ && $UserProfile[16] ne "" && $Username ne "") ||
			($CategoryList[$CategoryIndex]->{USERS} =~ /$Username/ && $Username ne "")) {
			$granted = "true";
		}
	} else {
		$granted = "true";
	}
	if($granted eq "true") {
		ShowMedia();		
	} else {
		if($Username eq "" || $LoggedIn eq "false") {
			ShowLogin("This is a restricted category, please login first.");
		}
		FatalError("You do not have permission to access this category.");
	}
} elsif($CategoryIndex < 0) {
	require $ScriptPath.$slash."categories.cgi";
	ReadCategories();
	ShowCategoryListing();
} else {
	#Category is set and nothing else needs to be done so show gallery
	require $ScriptPath.$slash."categories.cgi";
	require $ScriptPath.$slash."media.cgi";
	#initialize media 
	ReadCategories();
	$Category = $CategoryList[$CategoryIndex]->{NAME};
	$granted = "false";
	if($CategoryList[$CategoryIndex]->{PROTECTED} eq "true") {
		if(($CategoryList[$CategoryIndex]->{GROUPS} =~ /$UserProfile[16]/ && $UserProfile[16] ne "" && $Username ne "") ||
			($CategoryList[$CategoryIndex]->{USERS} =~ /$Username/ && $Username ne "")) {
			$granted = "true";
		}
	} else {
		$granted = "true";
	}
	if($granted eq "true") {
		ReadMedia($CategoryIndex);
		$CategoryPath = $MediaPath.$CategoryPath;
		ShowGallery();
	} else {
		if($Username eq "" || $LoggedIn eq "false") {
			ShowLogin("This is a restricted category, please login first.");
		}
		FatalError("You do not have permission to access this category.
");
	}
}
########################################################################################
sub InitFromParameters
{
	if($SortBy ne "") {
		
	} elsif($cgi->param("selectedsort") ne "") {
		$SortBy = $cgi->param("selectedsort");
	} elsif($cgi->param("sort") ne "") {
		$SortBy = $cgi->param("sort");
	} else {
		$SortBy = $DefaultSort;
	}
	if($cgi->param("Page") ne "") {
		$Page = $cgi->param("Page");
	} else {
		$Page = 1;
	}	
	if($cgi->param("Category") ne "") {
		$CategoryIndex = int($cgi->param("Category"));
		if($CategoryIndex < 0) { $Category = "NONE"; }
	} else {
		$CategoryIndex = -1;
		$Category = "NONE";
	}
}
########################################################################################
sub CategoryTree {
	if($cgi->param("searchterm")) { return; }
	if(!@CatTree) { BuildCatTree($cgi->param("Category")); }
	my($html) = qq~
	
    
      
        
	      
		  $GalleryTitle 
	~;
	for(my($counter) = 0; $counter < @CatTree; $counter++) {
		for(my($index) = 0; $index < $CatTree[$counter]->{DEPTH}; $index++) {
			$html = $html."  ";
		}
		if($CatTree[$counter]->{INDEX} == $cgi->param("Category")) { 
			$html = $html.qq~
		        
			  $CatTree[$counter]->{NAME} 
			~;
		} else {
			$html = $html.qq~
		        
			  $CatTree[$counter]->{NAME} 
			~;
		}
	}
	$html = $html.qq~
		 | 
      
    
	
	~;
	return $html;
}
sub SubCategoryList {
	if($cgi->param("searchterm")) { return; }
	if(!@SubCats) { FindSubCategories(); }
	my($html) = qq~
	
	| 
	Sub Categories: | 
	~;
	for($counter = 0; $counter < @SubCats; $counter++) {
		if($counter % 2 == 0) {
			$html = $html.qq~~;
		}
		if($SubCats[$counter]->{IMAGE} ne "") {
			$catimg = qq~
						
~;
		} else {
			$catimg = "";
		}
		$html = $html.qq~
		
		
		
		| 
		
		$catimg
		
		 | 
		
		
				
		$SubCats[$counter]->{NAME} 
		$SubCats[$counter]->{DESC} ($SubCats[$counter]->{SUBS} Sub-Categories, $SubCats[$counter]->{COUNT} Images)
		 |  
		 
		 | 
		~;
		if($counter == @SubCats - 1 && @SubCats % 2 == 1) {
			$html = $html.qq~  | ~;
		}
		if($counter % 2 == 1) {
			$html = $html.qq~
~;
		}
	}
	$html = $html.qq~
	
	
	~;
	return $html;
}
########################################################################################
sub PageStats {
	if($cgi->param("func") eq "show") { return; }
	if($TotalPages == 0) {
		$PageStats = "$NumPictures entries
Page $Page of 1";
	} else {
		$PageStats = "$NumPictures entries
Page $Page of $TotalPages";
	}
	my($html);
	$html = qq~
	
	
	$PageStats
	
	~;
	return $html;
}
########################################################################################
sub CategoryInline {
	my $filename = shift;
	if($cgi->param("searchterm") ne "") { 
		$SearchDisplay = "Search Results for '".$cgi->param("searchterm")."'";
	} elsif(!@CatInline) { 
		BuildCatInline($cgi->param("Category")); 
	}
	my($html) = qq~
	
	| 
	 Top
	~;
	if($SearchDisplay) {
		$html = $html."> $SearchDisplay";
	} else {
		for(my($counter) = 0; $counter < @CatInline; $counter++) {
			if(($filename eq "" && $CatInline[$counter]->{INDEX} == $cgi->param("Category")) || $CatInline[$counter] eq "Search Results") { 
				$html = $html."> $CatInline[$counter]->{NAME} ";
			} else {
				$html = $html.qq~> $CatInline[$counter]->{NAME} ~;
			}
		}
		if($filename) {
			$html = $html.qq~ > $filename~;
		}
	}
	$html = $html.qq~
	 
	 | 
	
	~;
	return $html;
}
########################################################################################
sub SortDropBox {
	my($html) = qq~~;
	return $html;
}
########################################################################################
sub CategoryDropBox {
	if(!@CategoryList) {
		require $ScriptPath.$slash."categories.cgi";
		ReadCategories();
	}
	my($html) = qq~
~;
	return $html;
}
########################################################################################
sub SearchBox {
	my($html) = qq~
	
	
	
	~;
	return $html;
}
########################################################################################
########################################################################################
sub NavBack {
	my($html) = qq~
	
	
 ~;
	if($cgi->param("searchterm") eq "") {
		$PageNav = $PageNav.qq~ Prev $CategoryName 
		$CategoryList[$prev]->{NAME} |  ~;
		$width = "33%";
	} else {
		$width = "100%";
	}
	$PageNav = $PageNav.qq(Jump To Page: );
	if($Page > 1 && $TotalPages > 1) {
		$PageNav = $PageNav."<< ";
	}
	if($Page < 1) {
		$PageNav = $PageNav."No Pages Exist!";
	}
	for($j = 1; $j <= $TotalPages; $j++) {
		if($j == $Page) {
			$PageNav = $PageNav."[".$j."]";
		} else {
			$PageNav = $PageNav."[".$j."]";
		}
	}
	if($Page < $TotalPages) {
		$PageNav = $PageNav." >>";
	}
	$PageNav = $PageNav." | ";
	if($cgi->param("searchterm") eq "") {
		$PageNav = $PageNav.qq~ Next $CategoryName 
		$CategoryList[$next]->{NAME} | ~;
	}
	$PageNav = $PageNav."
";
	$html = qq~
	
	 ~;
	$PageNav = $PageNav.qq~ Previous 
	$MediaList[$prev][$FILENAME] |  ~;
	$PageNav = $PageNav.qq(
	Thumbnails | );
	$PageNav = $PageNav.qq~ Next 
	$MediaList[$next][$FILENAME] | ~;
	
	$PageNav = $PageNav."
";
	$html = qq~