#!/usr/bin/perl 
#######################################
# ZCom Bulletin Board - Copyright (C) #
#      http://zcom.speckz.com/        #
#=====================================#
#       Created by Frank Oyer         #
#######################################
print "Content-type: text/html\n\n";

eval {
	($0 =~ m,(.*)/[^/]+,)   and unshift(@INC,$1);
	($0 =~ m,(.*)\\[^\\]+,) and unshift(@INC,$1);

	require "routine.cgi";
	require "variables.dat";
	require "thread_create.cgi";
	require "stat.cgi";
	require "board_leaders.cgi";
	require "lang/$language";
};

if ($@) {
	print "Error with a required file(s): $@"; exit;
}

use CGI::Carp "fatalsToBrowser";
use CGI;
$obj = new CGI;
@names = $obj->param();
%form = map {$_ => $obj->param($_)} $obj->param();

if ($form{'action'} eq 'currentversion') {
		print $version; exit();
}

opencolors();
CheckBoardStatus();
get_cookie();
CheckExists($cookie{user});

if ($exists eq 'yes') {
	$log = qq(<font size=2 face=$fontface><b><a href="$cgiurl/index.cgi?action=logout">$text{index_log_out}</a></b></font>);
	$membername = $cookie{user};
} else {
	$log = qq(<input type="text" name="username" value="username" size=10> <input type="password" name="password" value="password" size=10> <input type="submit" value="Login!">);
	$membername = 'guest';
}

$name = $membername;
DeleteOldPrivate();

if ($form{'action'} eq 'board' || $form{'categoryid'} || !@names) {
	WhosOnline($name,'Forum index page');

	$zcomstats = ShowZBBStats() if $statistics eq 'on';
	$privatemessage = PrivateMessages() if $private eq 'yes';
	$onlineusers = ActiveUsers() if $online eq 'on';

	intro();
	GetForumLine();
	introbot();
}

if ($form{'action'} eq 'register') {
 	WhosOnline($name,'Registering');

 	if ($allowusers eq 'on') {
   		register();
 	} else {
   		ErrorHTML("Sorry, but new registrations have been turned off.");
 	}
}

if ($form{'action'} eq 'inlog') {
	if ((!$form{'username'}) || (!$form{'password'})) {
  		ErrorHTML("You did not complete the form. Please go back and fill in the feilds.");
  		exit;
	}

	CheckExists($form{'username'});
	CurrentDate();

	if ($exists eq 'yes') {
    		@memberfeilds = &OpenMember($form{'username'});
    		if ($form{'password'} eq "$memberfeilds[2]") {
        		print qq(<html><body><script>
			document.cookie="user=$form{'username'}; expires=$exp_date_lastvisit;";
			document.cookie="pass=$form{'password'}; expires=$exp_date_lastvisit;";
			</script></body></html>);

       			MoveHTML("$cgiurl/index.cgi", "You have been loged in successfully and are being fowarded to the Forum Summary page.");
    		} else {
       			ErrorHTML("Sorry, but the password you typed in was incorrect.");
       			exit;
    		}
	} else {
  		ErrorHTML("Sorry but we could not find a record for the username you entered. If you haven't already <a href=\"$cgiurl/index.cgi?action=register\">registered</a> please do so.");
  		exit;
	} 
}

if ($ENV{'QUERY_STRING'} eq 'zcode') {
	$top_data = "<a href=\"$cgiurl/index.cgi\">$ZBBName</a>" . $spacer . "ZCode Explained";
	GlobalVariables();
	print OpenTemplates('',$zcodetemplate,$top_data,'','yes');
}

if ($ENV{'QUERY_STRING'} eq 'smilies') {
	@smilies = OpenFile("$cgipath/smilies.dat");

	$SmiliesLegend = '';
	foreach (@smilies) {
		chomp $_;
		($face,$url,$id) = split(/=/,$_);

		$url =~ s/\$noncgiurl/$noncgiurl/isg;

		$SmiliesLegend .= qq(<tr bgcolor="$altcolor2"><td><font size=1 face=verdana><b>$face</b></font></td><td><img src="$url"></td></tr>);
	}

	$top_data = "<a href=\"$cgiurl/index.cgi\">$ZBBName</a>" . $spacer . "Smilie Legend";
	GlobalVariables();
	print OpenTemplates('',$smiliestemplate,$top_data,'','yes');
}

if ($form{'action'} eq 'logout') {
	WhosOnline($name,'Loging out');
	logout();
}

sub intro {
	CurrentDate();
	$date = ($thedate . $thetime);
	$currentdate = DateFormat($cookie{Visit});

	$WelcomeMessage = $cookie{user} && $cookie{Visit} ? "$text{index_last_visit_welcome} $cookie{user} $text{index_last_visit_yourlast} $currentdate" : $text{index_please_reg};

	$olddate = $cookie{Visit};

	if ($newpm) {
		$newpmindex = qq(<br>$text{index_newpm});
	}

	$board_data = qq(
	<SCRIPT LANGUAGE=JAVASCRIPT>
	var NewCookie = "$cookie{'IndexVisit'}";
	var Create = "yes";
	if (NewCookie != Create) {
		document.cookie="OldVisit=$olddate; expires=$exp_date_lastvisit;";
		document.cookie="Visit=$date; expires=$exp_date_lastvisit;";
		document.cookie="IndexVisit=yes;";
	}
	</SCRIPT>
	);
	CheckAnnouncements();
}

sub GetForumLine {
	open(FORUM,"$cgipath/boards.cgi") or &ErrorHTML("Couldn't open the boards file $cgipath/boards.cgi: $!");
	@boards = <FORUM>;
	close(FORUM);

	if ($usecategories eq 'yes') {
		open(FORUM,"$cgipath/categories.cgi") or &ErrorHTML("Couldn't open the categories file");
		@categories = <FORUM>;
		close(FORUM);

		foreach $category(@categories) {
 			chomp $category;
 			@cateinfo = split(/\|\=\|/, $category);
  			category();

    			foreach $line(@boards) {
      				chomp $line;
      				@boardinfo = split(/\|/, $line);

         			if (($cateinfo[1] == $boardinfo[0]) && ($boardinfo[3] eq 'on')) {
	  				if (($form{'categoryid'}) && ($form{'categoryid'} == $cateinfo[1])) {
           					TopicsPosts();
           					ForumLine();
	  				} elsif (!$form{'categoryid'}) {
           					TopicsPosts();
           					ForumLine();
	  				}
				}
    			}
		}
	} else {
    		foreach $line(@boards) {
      			chomp $line;
      			@boardinfo = split(/\|/, $line);

	 		if ($boardinfo[3] eq 'on') {
           			TopicsPosts();
           			ForumLine();
	 		}
    		}
	}
}

sub ForumLine {
	$Modvar = 'Board' . $boardinfo[8];
	$Modvar = $$Modvar;

	@forumleaders = split(/\|\=\|/, $Modvar);
	@mods = ();

	foreach $mod(@forumleaders) {
  		if ($mod) {
  			$mods = qq($mod);
  			push @mods, $mods;
  		}
	}

	$moderators = join(', ', @mods);
	$moderators = '&nbsp;' if !$moderators;


	$descriptions = "";
	if ($showdescriptions ne 'no') {
		$descriptions = $boardinfo[2];
	}

	$BoardNameLink = qq(<a href="$cgiurl/boardsum.cgi?action=display&number=$boardinfo[8]">$boardinfo[1]</a>);
	$board_data .= OpenTemplates("",$forumtemplate,"","yes");
}

sub category {
	$use = 'no';

 	foreach $bod(@boards) {
 		chomp $bod;
 		@info = split(/\|/, $bod);
  		$use = "yes" if ($cateinfo[1] == $info[0]);
 	}

	if ($use eq 'yes') {
		$TemplateLink = qq(<a href="$cgiurl/index.cgi?categoryid=$cateinfo[1]"><font color="$categorytext">$cateinfo[0]</font></a>);
		$board_data .= OpenTemplates("",$categorytemplate,"","yes");
	}
}

sub TopicsPosts {
	open(THREAD,"$boardspath/Board$boardinfo[8]/topic.threads");
	@latestreply = <THREAD>;
	close(THREAD);

	@threadinfo = split(/\|=\|/,$latestreply[0]);

	$currentdate = DateFormat($threadinfo[8]);

	($readonly,$sortby) = split(/<>/,$boardinfo[10]);

	open(ZBB,"$boardspath/Board$boardinfo[8]/$threadinfo[4].cgi");
	@getlastposter = reverse <ZBB>;
	close(ZBB);

	@getlast = split(/\|\=\|/, $getlastposter[0]);

	$latest = $getlast[1];
	$latest =~ s/ /\&nbsp;/sg;

	$whomaypost = $boardinfo[7];
	($posttopics,$postreplies,$viewboard) = split(/\=/, $whomaypost);

   	$ltopic = length($threadinfo[3]);
   	($TopicTitle) = unpack("A15",$threadinfo[3]);
  	$TopicTitle .= "..." if $ltopic > 15;

	$lasttopic = $viewboard ne 'team' && !$boardinfo[9] && $latestposter eq 'yes' && $threadinfo[8] ? qq(<a href="$cgiurl/viewthread.cgi?board=$boardinfo[8]&thread=$threadinfo[4]">$TopicTitle</a>) : "";

	$lastpostinfo = $viewboard ne 'team' && !$boardinfo[9] && $latestposter eq 'yes' && $threadinfo[8] ? qq($text{index_last_post_by} <a href="$cgiurl/zcomisc.cgi?action=getprofile&name=$getlast[1]">$latest</a>) : "";

	if ($readonly eq 'on') {
		$currentdate = $text{index_readonly};
		$lastpostinfo = '';
	}

	$totaltops = @latestreply;
	$totalposts = 0;

	foreach $post(@latestreply) {
  		chomp($post);
  		@getposts = split(/\|\=\|/, $post);
  		$totalposts = $totalposts + $getposts[5];
	}

	$totalposts = $totalposts + $totaltops;

	$img = ($cookie{Visit} < $threadinfo[8]) ? "<img src=\"$noncgiurl/images/$new\">" : "<img src=\"$noncgiurl/images/$nonew\">" ;
}

sub GetShowVariable {
	my ($board) = @_;

	$used = 0;

	if (-e "$boardspath/Board$board/variables.dat") {
		open(F,"");
		while (<F>) {
			if ($_ =~ /\$showthreadsdefault = qq\((.*?)\);/) {
				$used = $1;	
			}
		}
		close(F);
	}
	return $used;
}

sub introbot {
	$timezonetext = $timezone ? "$text{most_time_zone} $timezone":"&nbsp;";

	$top_data = "<a href=\"$cgiurl/index.cgi\">$ZBBName</a>";
	GlobalVariables();
	print OpenTemplates($board_data,$indextemplate,$top_data);
}

sub logout {
	print "<html><body>", DeleteOldMemCookies(), "</body></html>";
	MoveHTML("$cgiurl/index.cgi",$text{index_logged_out});
}


sub register {
	CheckBannedIP();
	$top_data = "<a href=\"$cgiurl/index.cgi\">$ZBBName</a>" . $spacer . $text{editprofile};
	GlobalVariables();
	print OpenTemplates("",$registeragreetemplate,$top_data);
}

sub CheckAnnouncements {
 	if (-e "$cgipath/annc") {
 		opendir(DIR, "$cgipath/annc"); 
 		@announcements = readdir(DIR);
 		closedir(DIR);

 		@eachfile = grep(/\d{12}.cgi/, @announcements);
 		@announces = sort(@eachfile);
 		@sorted = reverse(@announces);

  		$found = 'no';
  		foreach $file(@sorted) {
   			open(THREAD,"$cgipath/annc/$file") or die "Cannot open announcement: $!";
   			@announceinfo = <THREAD>;
   			close(THREAD);
   			($date,$junk) = split(/\./,$file);

   			@theannoucnedata = split(/\|/, $announceinfo[0]);
   			chomp($theannoucnedata[7]);

    			if (($theannoucnedata[2] eq 'yes') && ($found eq 'no')) {
     				$annoucedate = "$theannoucnedata[6]$theannoucnedata[7]";
     				my ($startyear,$startmon,$startday,$endyear,$endmon,$endday) = unpack('A4 A2 A2 A4 A2 A2', $annoucedate); 

     				$starton = "$startyear$startmon$startday";
     				$endon = "$endyear$endmon$endday";

     				CurrentDate();

     				if (($starton <= $thedate) && ($endon >= $thedate)) {
         				$found = 'yes';
         				$board_data .= qq(<tr bgcolor="$altcolor2">
								<td bgcolor="$altcolor2" colspan=6>
								<table width=100%>
								<tr>
								<td><font size=2 face=$fontface><b>$text{index_news}</b> $theannoucnedata[4]</font></td></tr>
								<tr>
								<td><font size=2 face=$fontface>$theannoucnedata[3]</font></td></tr>
								<td align=right><font size=1 face=$fontface><a href="$cgiurl/announcements.cgi">$text{index_more_announcements}</a></td></tr></table>
								</td></tr>);
     				} else {
      					if ($endon < $thedate) {
       						unlink("$cgipath/annc/$file");
      					}
     				}

    			}
  		}
 	}
}

