#!/usr/bin/perl --
###############################################################################
# YaBB.pl                                                                     #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2                                                    #
# Packaged:       November 8, 2007                                            #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2007 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

### Version Info ###
$YaBBversion = 'YaBB 2.2';
$YaBBplver = 'YaBB 2.2 $Revision: 1.21 $';

if ($action eq 'detailedversion') { return 1; }

# Make sure the module path is present
# Some servers need all the subdirs in @INC too.
push(@INC, "./Modules");
push(@INC, "./Modules/Upload");
push(@INC, "./Modules/Digest");

if ($ENV{'SERVER_SOFTWARE'} =~ /IIS/) {
	$yyIIS = 1;
	$0 =~ m~(.*)(\\|/)~;
	$yypath = $1;
	$yypath =~ s~\\~/~g;
	chdir($yypath);
	push(@INC, $yypath);
}

# Check for Time::HiRes
#eval { require Time::HiRes; import Time::HiRes qw(time); };
#if ($@) { $START_TIME = 0; }
#else { $START_TIME = time; }

$START_TIME = 0;

### Requirements and Errors ###
$script_root = $ENV{'SCRIPT_FILENAME'};
$script_root =~ s/\/YaBB\.(pl|cgi)//ig;

$low_disk_alert = 100000; 	# in bytes (default 100 Kb) put forum on maintenance if quota goes below this value

if (-e "Paths.pl") { require "Paths.pl"; }
elsif (-e "$script_root/Paths.pl") { require "$script_root/Paths.pl"; }

require "$vardir/Settings.pl";
require "$vardir/advsettings.txt";
require "$vardir/secsettings.txt";
require "$vardir/membergroups.txt";
require "$vardir/Smilies.txt";
require "$sourcedir/Subs.pl";
require "$sourcedir/DateTime.pl";

## check if hard drive has enough space to safely operate the board.
if($enable_freespace_check) {
	&freespace;
	if ($FreeBytesAvailableToCaller && $FreeBytesAvailableToCaller < $low_disk_alert) {
		&automaintenance('on','low_disk');
	} elsif ($FreeBytesAvailableToCaller && $FreeBytesAvailableToCaller >= $low_disk_alert) {
		&automaintenance('off');
	}
}

# Auto Maintenance Hook
if (-e "$vardir/maintenance.lock"){ $maintenance = 1; }

require "$sourcedir/Load.pl";

# Those who write software only for pay should go hurt some other field.
# - Erik Naggum

&LoadCookie;          # Load the user's cookie (or set to guest)
&LoadUserSettings;    # Load user settings
&WhatTemplate;        # Figure out which template to be using.
&WhatLanguage;        # Figure out which language file we should be using! :D

use lib "../acControl";
require "AccessControl.pm";

if (-e "$vardir/gmodsettings.txt" && $iamgmod) { require "$vardir/gmodsettings.txt"; }
if (!$masterkey || $masterkey eq '') {
	if ($iamadmin || ($iamgmod && $allow_gmod_admin eq 'on' && $gmod_access{"newsettings\;page\=security"} eq 'on')) {
		$yyadmin_alert = $reg_txt{'no_masterkey'};
	}
	$masterkey = $mbname;
}

$yyfreespace = qq~<div>$maintxt{'freespace'} $yyfreespace</div>~ if $enable_freespace_check;

$formsession = &cloak("$mbname$username");

## check for valid form session id ## (reintroduced after someone ripping it out) ##
# Check for any POST requests, except for the admin center ones, and the login/register/reminder ones.
if(lc $ENV{REQUEST_METHOD} eq 'post' && $action ne "login2" && $action ne "reminder2" && $action ne "register2"){
	$receiveformsession = &decloak($FORM{'formsession'});
	if ($receiveformsession ne "$mbname$username") {&fatal_error("form_spoofing","$user_ip"); }
}

require "$sourcedir/Guardian.pl";
&guard;

# Check if the action is allowed from an external domain
if ($referersecurity) { &referer_check; }

my $inactsize = -s "$memberdir/memberlist.inactive";
if ((-e "$memberdir/memberlist.inactive") && $inactsize > 2 && ($regtype == 1 || $regtype == 2)) {
	&RegApprovalCheck;
	require "$sourcedir/Register.pl";
	&activation_check;
}

my $aprsize = -s "$memberdir/memberlist.approve";
if ((-e "$memberdir/memberlist.approve") && $aprsize > 2 && ($regtype == 1 || $regtype == 2) && $yyadmin_alert eq "") {
	&RegApprovalCheck;
}

require "$boardsdir/forum.master";
require "$sourcedir/Security.pl";

&banning;     # Check for banned people
&LoadIMs;     # Load IM's

if ($is_perm && $accept_permalink){
	if ($permtopicfound == 0 && $permtitle ne "") {&fatal_error("no_topic_found","$permtitle|C:$permachecktime|T:$threadpermatime"); }
	if ($permboardfound == 0) {&fatal_error("no_board_found","$permboard|C:$permachecktime|T:$threadpermatime"); }
}

$action = $INFO{'action'};
$SIG{__WARN__} = sub { &fatal_error("error_occurred","@_"); };
eval { &yymain; };
if ($@) { &fatal_error("untrapped",":<br />$@"); }

sub yymain {
	# Choose what to do based on the form action
	if ($maintenance == 1) {
		if ($action eq 'login2') { require "$sourcedir/LogInOut.pl"; &Login2; }

		# Allow password reminders in case admins (or just Corey)
		# forgets their admin password...
		if ($action eq 'reminder') {
			require "$sourcedir/LogInOut.pl";
			&Reminder;
		}
		if ($action eq 'validate') {
			require "$sourcedir/Decoder.pl";
			&convert;
		}
		if ($action eq 'reminder2') {
			require "$sourcedir/LogInOut.pl";
			&Reminder2;
		}
		if ($action eq 'resetpass') {
			require "$sourcedir/LogInOut.pl";
			&Reminder3;
		}

		if (!$iamadmin) { require "$sourcedir/Maintenance.pl"; &InMaintenance; }
	}

	# Guest can do the very few following actions.
	if ($iamguest && $guestaccess == 0) {
		if (!(($action eq 'login') || ($action eq 'login2') || ($action eq 'register') || ($action eq 'register2') || ($action eq 'reminder') || ($action eq 'reminder2') || ($action eq 'validate') || ($action eq 'activate') || ($action eq 'resetpass'))) {
			&KickGuest;
		}
	}

	# Write to the log here so kicked guests aren't added.
	&WriteLog;    # Write to the log

	if ($action ne "") {
		if ($action eq $randaction) {require "$sourcedir/Decoder.pl"; &convert; exit; }
		require "$sourcedir/SubList.pl";
		if ($director{$action}) {
			@act = split(/&/, $director{$action});
			$aa = $act[1];
			require "$sourcedir/$act[0]";
			&$aa;
		} else {
			require "$sourcedir/BoardIndex.pl";
			&BoardIndex;
		}
	} elsif ($INFO{'num'} ne "") {
		require "$sourcedir/Display.pl";
		&Display;
	} elsif ($currentboard eq "") {
		require "$sourcedir/BoardIndex.pl";
		&BoardIndex;
	} else {
		require "$sourcedir/MessageIndex.pl";
		&MessageIndex;
	}

	exit;
}
