#!/usr/bin/perl
# index.cgi - e_Board v2.2a
#
# This script runs a message board on your site.
# It was inspired by Matt Wright's WWWBoard.
# This script by Mike Bagneski - copyright 1998.
# Do not redistribute.
#
##################################################
# CONFIGURATION SECTION

#if (serverload() > 1) {
#  print "Content-type: text/html\n\n<html>\n<body>\n<br><br><center><b>Server overload, please try later</b></body></html>";
#  exit;
#}
local $SIG{ALRM} = sub { print "Content-type: text/html\n\n\ntoo long...\n"; die; }; # NB: \n required
alarm 15;
# This is the complete path your eboard directory.

$htmlpath = $ENV{DOCUMENT_ROOT}.'/petrovich/forum';

# This is the URL of your eboard directory.

$htmlurl = 'http://www.rusmoney.com/petrovich/forum';

# This is the URL of the [Exit Board] link.

$exiturl = 'http://www.rusmoney.com';

# This is your admin password.

$password = "Naher";

# END OF CONFIGURATION SECTION
###################################################
# OPTIONS SECTION

# Uncomment one of the following, depending on how you want the
# board to handle HTML.

#$html = 'no';                # if you want all HTML removed from message
#$html = 'show';                # if you want to display the code as text
#$html = 'allow';                # if you're nuts.

# This is the length of each line of quoted text in the reply form.
# You only need to change this if you change your textarea dimensions.

$len = 50;

# The number of seconds that a message is marked new.
# The default is 24 hours.

$newtime = 60*60*48;

# The number of seconds old a topic is before it expires from current messages.
# The default is 30 days.  If you don't want current messages to auto-expire,
# set to 0.

$expiration1 = 60*60*24*30;

# The number of seconds old a topic is before it expires from archived messages.
# The default is 90 days.  If you don't want archived messages to auto-expire,
# set to 0.

$expiration2 = 0;

# Set to 'no' if you want expired current topics to be deleted.
# Set to 'yes' to have them archived.

$x2archive = 'yes';

# This is the HTML of your NEW marker.  This can be an image if you want.

$new = '<font color=red><small><small><b><i> NEW</i></b></small></small></font>';

# This is the term used in the form to denote quoted text.

$wrote = 'говорит, что';

# This is the path to sendmail.  It's usually the default.
# Consult your provider if it isn't.

$sendmail = '/usr/lib/sendmail';

# This is the admin's e-mail address.  The admin will receive
# a copy of each message, incluing IP and REMOTE HOST info.

$sysadmin = 'info@rusmoney.com';

# This is the HTML for reply indentation.  You can substitute
# a transparent image if you want.

$indent = '&nbsp;&nbsp;';

# After initial testing, set this to 'yes'.
# If your server allows file locking, this will reduce errors.

$lockon = 'no';

# The name of your board that inlcuded in e-mail message subjects.

$board_name = 'Petrovich Board:';

# Set to 'yes' to enable creation of separate message windows.

$windows = 'no';

# If $windows is 'yes', this is the width of the message window.

$w_width = '615';

# If $windows is 'yes', this is the height of the message window.

$w_height = '460';

# If $windows is 'yes', this is the horizontal offset of the message window.

$w_horiz = '20';

# If $windows is 'yes', this is the vertical offset of the message window.

$w_vert = '20';

# Set to 'yes' if you wnat the clear buttons to appear on the form for messages.
# These buttons will remove quoted text from the Topic and Message fields.

$buttons = 'yes';

# This is the list of naughty words, and what you want to convert
# them to.

%naughty = (fuck => 'hug', shit => 'pudding', pecker => 'puppy', asshole => 'angel', bitch => 'nice person', cunt => 'stopwatch', ' cock' => ' earlobe', 'cock!' => 'socks!', cocksucker => 'sweetheart', pussy => 'portable wishwasher', ' tit' => ' toe',
            interstock => 'govnuki', '7974445' => 'telefon govnukov',
            '70966433' => 'GOVNUK',
            'FXLibrary' => "Я-ВОР, меня зовут Kler Mihailov (fxlibrary\@mail.ru), мой адрес - " .
            "Leninastreet,15-64 Moscow, NA 113104 RU, я продаю ворованый софт. Это я " .
            "зарегистрировал домен trading-support.com и обычно оставляю контактный " .
            "адрес в этом домене всякий раз, когда публикую свои объявления."
);

# These are the terms for the various modes.

$current = 'Current';
$archived = 'Archived';
$collapse = 'Collapse';
$expand = 'Expand';

# This is the default condition of the main message page.
# Change to 'Expand' if you want all messages displayed by default.

$init_threads = $collapse;

# These are the names and locations of the gifs shown with the lists.

$postimage = "$htmlurl/post.gif";
$replyimage = "$htmlurl/reply.gif";

# These are the names of the various files.  No need to change them
# unless you change the actual file names.

$list_template = 'template/listtmp.txt';
$msg_template = 'template/msgtmp.txt';
$prev_template = 'template/pretmp.txt';
$error_template = 'template/errtmp.txt';
$subscribe_template = 'template/subtmp.txt';
$form_template = 'template/formtmp.txt';
$banlist = 'banlist.txt';
$mlist = 'mlist.txt';
$alist = 'alist.txt';
$countfile = 'counter.txt';

$maxpagenum = 38;

# END OF OPTIONS SECTION
############################################
# Set to flush output

select (STDOUT);
$| = 1;

############################################ Alex
$IP=$ENV{"REMOTE_ADDR"};
$IP=~tr/.//d;
srand(time % 100000 + $IP);
$randomnumber=int rand(10000000);
$bm_ads_dir= '/home/httpd/vhosts/rusmoney.com/httpdocs/ads';
$file = 'petrovich.txt';
$file = join('/', $bm_ads_dir, $file);
$bannercode;
if (open(ADS, "<$file")) {
        @banners = <ADS>;
        close(ADS);
        $topbanner = int rand($#banners + 1);
        $bannercode = $banners[$topbanner];
        chop($bannercode);
}
#$bannercode =<<EOM;
#<script type="text/javascript"><!--
#google_ad_client = "pub-6521134793993961";
#google_ad_width = 468;
#google_ad_height = 60;
#google_ad_format = "468x60_as";
#google_ad_type = "text_image";
#google_ad_channel ="3182679440";
#google_color_border = "336699";
#google_color_bg = "FFFFFF";
#google_color_link = "0000FF";
#google_color_url = "008000";
#google_color_text = "000000";
#//--></script>
#<script type="text/javascript"
#  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
#</script>
#EOM
############################################
############################################
# get form data

read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
if ($ENV{'QUERY_STRING'})
        {$buffer = "$buffer\&$ENV{'QUERY_STRING'}";
}
@pairs = split(/&/,$buffer);
foreach $pair (@pairs){
        ($name,$value) = split(/=/,$pair);
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
        $value =~ s/\*/&ast;/g;
        if (($html eq 'no') or ($name eq 'subject') or ($name =~ /url/)){
                $value =~ s/<.*?>//g;
                $value =~ s/"/&quot;/g;
        }elsif($html eq 'show'){
                $value =~ s/</&lt;/g;
                $value =~ s/>/&gt;/g;
                $value =~ s/"/&quot;/g;
        }

        # Censor Naughty Words
        for(keys(%naughty)){
                $value =~ s/$_/$naughty{$_}/gi;
        }
        $value = '' if(($name eq 'email') and ($value !~ /.*\@.*\..*/));
        $value = '' if(($name =~ /url$/) and ($value !~ /.*tp:.*\..*/));
        $FORM{$name} = $value;
}

$FORM{'threads'} = $init_threads unless $FORM{'threads'};
$FORM{'mode'} = 'Archived';
#$FORM{'mode'} = $current unless $FORM{'mode'};
$FORM{'actionurl'} = $ENV{'SCRIPT_NAME'};

$browser = $ENV{'HTTP_USER_AGENT'};
$windows = 'no' if $browser =~ /Opera/;
$windows = 'no' if $browser =~ /Mozilla\/3/;
$windows = 'no' if $browser =~ /MSIE/ and $browser !~ /4.01/;

if (exists($FORM{'post'})){
        &ban_check;
        if(($FORM{'name'}) and ($FORM{'subject'}) and ($FORM{'body'})){
                &post;
                exit;
        }else{
                &error;
                exit;
        }
}

if (exists($FORM{'preview'})){
        &ban_check;
        if(($FORM{'name'}) and ($FORM{'subject'}) and ($FORM{'body'})){
                &preview;
                exit;
        }else{
                &error;
                exit;
        }
}

if (exists($FORM{'message'})){
        open(MESSAGE, "$htmlpath/messages/$FORM{'message'}.txt");
        @data = <MESSAGE>;
        close(MESSAGE);
        $message = $FORM{'message'};
        print "Content-type: text/html\n\n";
        &view;
        exit;
}

if (exists($FORM{'admin'})){
        &password;
        exit;
}

if (exists($FORM{'password'})){
        if($FORM{'password'} ne $password){
                $FORM{'admin'} = $FORM{'admmessage'};
                &password;
                exit;
        }else{
                if($FORM{'mode'} eq $current) {open(LIST, "$htmlpath/$mlist")}else {open(LIST, "$htmlpath/$alist")}
                flock LIST, 2 if $lockon eq 'yes';
                @list = <LIST>;
                &delete;
        }
}

if (exists($FORM{'subform'})){
        open(SUBSCRIBE, "$htmlpath/$subscribe_template");
        @lines = <SUBSCRIBE>;
        close(SUBSCRIBE);
        chomp(@lines);

        print "Content-type: text/html\n\n";

        foreach $line (@lines){
                $line =~ s/\*boardurl\*/$ENV{'SCRIPT_NAME'}\?threads=$FORM{'threads'}&mode=$FORM{'mode'}/;
                $line =~ s/\*actionurl\*/$FORM{'actionurl'}/;
                print "$line\n" if $line !~ /^<!--.+-->$/ and $line ne '';
        }
        exit;
}

if(exists($FORM{'subscription'})){
        if($FORM{'subaddress'} =~ /@/){
                &subscribe;
        }
}

#####################################################
# View Main Page (default)

if($FORM{'mode'} ne $archived) {
        if(-z "$htmlpath/$mlist") {&restore}
        open(LIST, "$htmlpath/$mlist");
        flock LIST, 2 if $lockon eq 'yes';
        @list = <LIST>;
        &expire1 if $expiration1;
} else {
		$num = 0;
		if(exists($FORM{'pagenum'})) {
			if ($FORM{'pagenum'} > 0 && $FORM{'pagenum'} <= $maxpagenum) {
				$num = $FORM{'pagenum'};
			}
		}
        open(LIST, "$htmlpath/alist.$num.txt");
        flock LIST, 2 if $lockon eq 'yes';
        @list = <LIST>;
        &expire2 if $expiration2;
}

open(TEMPLATE, "$htmlpath/$list_template");
@lines = <TEMPLATE>;
close(TEMPLATE);
chomp(@lines);

$skip = 0;

print "Content-type: text/html\n\n";

foreach $line (@lines){
        if ($line =~ /SKIP BELOW/) {$skip = 1}
        if ($line =~ /SKIP ABOVE/) {$skip = 0}
        next if $FORM{'mode'} eq $archived and $skip;
        next if $FORM{'mode'} eq $archived and $line =~ /#post/;
        if (($line =~ /<\/head>/i) and ($windows eq 'yes')) {
                print "$line\n";
                print "<SCRIPT LANGUAGE=\"Javascript\">\n";
                print "<!--HIDE\n";
                print "function getmyWin(message){ \n";
                print "url = \"$ENV{'SCRIPT_NAME'}?mode=$FORM{'mode'}&message=\" + message\;\n";
                print "myWin = open(url,'myWin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=yes,screenX=$w_horiz,left=$w_horiz,screenY=$w_vert,top=$w_vert,width=$w_width,height=$w_height')\;\n";
                print " } \n";
                print "//STOP HIDING-->\n";
                print "</SCRIPT>\n";
                next;
        }
        next if $line =~ /^<!--.+-->$/ or $line eq '';
        if ($line !~ /\*\w+\*/) {
                print "$line\n";
                next;
        }
        $line =~ s/\*boardurla\*/$ENV{'SCRIPT_NAME'}\?mode=$FORM{'mode'}&threads=\*threads\*/g;
        $line =~ s/\*boardurlb\*/$ENV{'SCRIPT_NAME'}\?mode=\*mode\*&threads=$FORM{'threads'}/g;
        $line =~ s/\*boardurl\*/$ENV{'SCRIPT_NAME'}\?mode=$FORM{'mode'}&threads=$FORM{'threads'}/g;
        $line =~ s/\*htmlurl\*/$htmlurl/g;
        $line =~ s/\*exiturl\*/$exiturl/g;
#################################################################### Alex
        $line =~ s/\*bannercode\*/$bannercode/g;
        $line =~ s/\*randomnumber\*/$randomnumber/g;
        
		require "$ENV{DOCUMENT_ROOT}/c213a7a7c5ad5d8221d62c2b4016427b/SAPE.pm";
		my $sape = new SAPE(
			user => 'c213a7a7c5ad5d8221d62c2b4016427b',
			force_show_code => true
		);
		my $sape = $sape->get_links;
		
		my $o = {};
		$o->{charset} = 'cp1251';
		$o->{force_show_code} = 1;
		$o->{TRUSTLINK_USER} = 'd3a4a914beb8aaa5af8dd3522e9593d0cc2f6722';

		push @INC, "$ENV{DOCUMENT_ROOT}/$o->{TRUSTLINK_USER}";
		eval("use TrustlinkClient;");
		my $trustlink = new TrustlinkClient($o);
		undef($o);
		$sape .= " <!-- Tr -->".$trustlink->build_links();
		
        $line =~ s/\*sape\*/$sape/g;
		
####################################################################
        $line =~ s/\*nowmode\*/$FORM{'mode'}/g;
        if($line =~ /\*mode\*/) {
                if($FORM{'mode'} eq $current){$line =~ s/\*mode\*/$archived/g};
                if($FORM{'mode'} eq $archived){$line =~ s/\*mode\*/$current/g};
        }
        if($line =~ /\*threads\*/){
                if($FORM{'threads'} eq $collapse){$line =~ s/\*threads\*/$expand/g};
                if($FORM{'threads'} eq $expand){$line =~ s/\*threads\*/$collapse/g};
        }
        if($line =~ /\*list\*/){
                if ($windows eq 'yes') {
                         foreach $item (@list){
                                 $item =~ s/&ast;/\*/g;
                                 @items = split(/\t/,$item);
                                 if(($FORM{'threads'} eq $collapse) and ($items[0]) and (time - $items[5] >= $newtime)){next}
                                 $tot_indent = '';
                                 for($i=0;$i<$items[0];$i++){
                                         $tot_indent .= "$indent";
                                 }
                                 print "<script>\n<!--\n document.write('$tot_indent<a href=\"javascript:getmyWin($items[1])\">')\;\n";
                                 if($items[0]){
                                         print " document.write(\"<img src=$replyimage border=0 align=middle alt=''>\")\n";
                                 }else {
                                         print " document.write(\"<img src=$postimage border=0 align=middle alt=''>\")\n";
                                 }
                                 $date = &date($items[4]);
                                 print " document.write(\"$items[2]<\/a><small> - <b>$items[3]<\/b><i> on $date<\/i><\/small>\")";
                                 print "//-->\n</script>\n";
                                 if ((time - $items[5]) < $newtime){print "$new"}
                                 print "<br>\n";
                         }
                         print "<noscript>\n";
                }
                foreach $item (@list){
                        $item =~ s/&ast;/\*/g;
                        @items = split(/\t/,$item);
                        if(($FORM{'threads'} eq $collapse) and ($items[0]) and (time - $items[5] >= $newtime)){next}
                        $tot_indent = '';
                        for($i=0;$i<$items[0];$i++){
                                $tot_indent .= "$indent";
                        }
                        print "$tot_indent<a href=\"$ENV{'SCRIPT_NAME'}?mode=$FORM{'mode'}&message=$items[1]\">\n";
                        if($items[0]) {
                                print "<img src=$replyimage border=0 align=middle alt=\"\">";
                        }else {
                                print "<img src=$postimage border=0 align=middle alt=\"\">";
                        }
                        $date = &date($items[4]);

                        print "$items[2]<\/a><small> - <b>$items[3]<\/b><i> on $date<\/i><\/small>";
                        if ((time - $items[5]) < $newtime){print "$new"}
                        print "<br>\n";
                }
                print "</noscript>\n" if $windows eq 'yes';
				print "<HR>";
				print "<table cellpadding=3 cellspacing=3><tr><td>Страницы:</td><td>";
				for ($i = 0; $i <= $maxpagenum; $i++)
				{
					$val = $i+1;
					if ($val < 10) {
						$val = "\&nbsp\;$val";
					}
					print "[ <a href=\"$ENV{'SCRIPT_NAME'}?pagenum=$i\">$val</a> ]\n";
					if ($i == 19) {
						print "<BR>";
					}
				}
				print "</td></tr></table>";
        }elsif($line =~ /\*form\*/){
                open(TEMPLATE, "$htmlpath/$form_template");
                @form = <TEMPLATE>;
                close(TEMPLATE);
                chomp(@form);

                foreach $formline (@form){
                        next if $formline =~ /onClick/;
                        $formline =~ s/\*actionurl\*/$FORM{'actionurl'}/g;
                        $formline =~ s/\*threads\*/$FORM{'threads'}/;
                        if($formline =~ /\*\w+\*/){
                                $formline =~ s/\*\w+\*//g;
                        }
                        print "$formline\n" if $formline !~ /<!--.+-->/;
                }
        }else{
                print "$line\n";
        }
}


exit;

####################################################
# View a message

sub view{

        chomp(@data);

        open(TEMPLATE, "$htmlpath/$msg_template");
        @lines = <TEMPLATE>;
        close(TEMPLATE);
        chomp(@lines);

        #############################################
        # generate substitution fields

        @fields = ('getemail', 'subject', 'name', 'email', 'date', 'body', 'previoussubject', 'previousname', 'previousfilename', 'previousdate', 'url', 'urltitle', 'imageurl', 'sape');

        for ($i=0;$i<=$#data;$i++){
                $mfields{"$fields[$i]"} = "$data[$i]";
        }

        $mfields{'date'} = &date($mfields{'date'});
        $mfields{'list'} = '';
        $mfields{'form'} = '';
        $mfields{'previousfilenameurl'} = "$ENV{'SCRIPT_NAME'}?mode=$FORM{'mode'}&message=$mfields{'previousfilename'}";
        $mfields{'message'} = $message;
        $mfields{'urltitle'} = $mfields{'url'} if $mfields{'urltitle'} eq '';
        $mfields{'boardurl'} = "$ENV{'SCRIPT_NAME'}?mode=$FORM{'mode'}";
        $mfields{'boardurla'} = "$ENV{'SCRIPT_NAME'}?mode=$FORM{'mode'}";
        $mfields{'boardurla'} .= "\" onClick=\"javascript:callList()" if $windows eq 'yes';
        $mfields{'htmlurl'} = $htmlurl;
		
		require "$ENV{DOCUMENT_ROOT}/c213a7a7c5ad5d8221d62c2b4016427b/SAPE.pm";
		my $sape = new SAPE::Client (
			user => 'c213a7a7c5ad5d8221d62c2b4016427b',
			force_show_code => true
		);
		my $sape_context = new SAPE::Context (
			user => 'c213a7a7c5ad5d8221d62c2b4016427b',
			force_show_code => true
		);
		my $str = $sape->get_links;
		
		my $o = {};
		$o->{charset} = 'cp1251';
		$o->{force_show_code} = 1;
		$o->{TRUSTLINK_USER} = 'd3a4a914beb8aaa5af8dd3522e9593d0cc2f6722';

		push @INC, "$ENV{DOCUMENT_ROOT}/$o->{TRUSTLINK_USER}";
		eval("use TrustlinkClient;");
		my $trustlink = new TrustlinkClient($o);
		undef($o);
		$str .= " <!-- Tr -->".$trustlink->build_links();
		
		$mfields{'sape'} = $str;

	    $body = $mfields{'body'};
        $body =~ s/\*br\*/<br>/g;
        $body =~ s/\*p\*/<p>/g;
		$body = $sape_context->replace_in_text_segment($body);
		# print "<!-- !!!!!!!!!!!!!!!!!!!!! $body -->\n";
        $mfields{'body'} = $body;

        #############################################
        # Generate Message

        foreach $line (@lines){
                if (($line =~ /<\/head>/i) and ($windows eq 'yes')){
                        print "$line\n";
                        print "<SCRIPT LANGUAGE=\"Javascript\">\n";
                        print "<!--HIDE\n";
                        print "function callList () {\n";
                        print "        opener.location = 'index.cgi'\n" if defined($counter);
                        print "        opener.focus()\n";
                        print "        self.close()\n";
                        print "}\n";
                        print "//STOP HIDING-->\n";
                        print "</SCRIPT>\n";
                        next;
                }
                exit if $line =~ /name=\"followup/ and defined($counter);
                $line = '' if $line =~ /repl /i and defined($counter);
                foreach $field (keys(%mfields)){
                        if($line =~ /\*$field\*/){
                                if($field eq 'list'){
                                        &replylist;
                                        $line = '';
                                }elsif($field eq 'form'){
                                        &doform;
                                        $line = '';
                                }elsif(($mfields{"$field"} ne '') or ($line =~ /value=/)){
                                        $line =~ s/\*$field\*/$mfields{"$field"}/g;
                                }elsif($field eq 'email'){
                                        $line =~ s/<a.+?>//i;
                                        $line =~ s/<\/a>//i;
                                }else{
                                        $line = '';
                                }
                        }
                }
                $line =~ s/&ast;/\*/g;
                $line =~ s/(<body.*?)(>)/$1 onLoad="self.focus()" $2/i if $windows eq 'yes';
#################################################################### Alex
        $line =~ s/\*bannercode\*/$bannercode/g;
        $line =~ s/\*randomnumber\*/$randomnumber/g;
####################################################################
                print "$line\n" if $line !~ /^<!--.+-->$/ and $line ne '';
        }
}

####### Display Message Form

sub doform{

        ############## Generate Substitution Fields

        $ffields{'name'} = '';
        $ffields{'email'} = '';
        $ffields{'subject'} = '';
        $ffields{'url'} = '';
        $ffields{'urltitle'} = '';
        $ffields{'imageurl'} = '';
        $ffields{'previoussubject'} = $mfields{'subject'};
        $ffields{'previousname'} = $mfields{'name'};
        $ffields{'previousfilename'} = $FORM{'message'};
        $ffields{'previousdate'} = $mfields{'date'};
        $ffields{'quotedsubject'} = ($mfields{'subject'} =~ /Re:/) ? "$mfields{'subject'}" : "Re: $mfields{'subject'}";
        $ffields{'getemail'} = ($mfields{'getemail'} !~ /@/) ? '' : "$mfields{'getemail'}";
        $ffields{'actionurl'} = $FORM{'actionurl'};
        $ffields{'threads'} = $FORM{'threads'};
        $ffields{'mode'} = $FORM{'mode'};

        $text = $mfields{'body'};

        ###########################################
        # Quote Text

        @sections = split(/<p>/, $text);
        for($k=0;$k<=$#sections;$k++){
                @paragraphs = split(/<br>/, $sections[$k]);
                for($i=0;$i<=$#paragraphs;$i++){
                        $para = $paragraphs[$i];
                        if($para =~ /^:/){next};
                        if (length($para) > $len){
                                @sub = ();
                                while(length($para) > $len){
                                        $j = $len;
                                        while((substr($para,$j,1) ne ' ') and ($j)){$j--};
                                        unless($j){$j = $len};
                                        $pretext = substr($para,0,$j+1);
                                        $para = substr($para,$j+1);
                                        push(@sub, $pretext);
                                }
                                push(@sub, $para);
                                splice(@paragraphs, $i, 1, @sub);
                                $i += $#sub;
                        }
                }
                $sections[$k] = join('<br>', @paragraphs);
        }
        $text = join('<p>', @sections);

        $text = "\n" . $ffields{'previousname'} . " $wrote,<br>$text" . '<br>';

        $text =~ s/<br>/\n: /g;
        $text =~ s/<p>/\n:\n: /g;
        $text =~ s/</&lt;/g;
        $text =~ s/>/&gt;/g;
        $text =~ s/"/&quot;/g;
        $text =~ s/: $//;
        $ffields{'quotedtext'} = $text;

        ##############################################
        # Print Message Form

        open(TEMPLATE, "$htmlpath/$form_template");
        @form = <TEMPLATE>;
        close(TEMPLATE);

        chomp(@form);

        foreach $formline (@form){
        next if $formline =~ /onClick/ and $buttons ne 'yes';
                if($formline =~ /getemail/){
                        $formline = "<input type=hidden name=getemail value=\"$ffields{'getemail'}\">";
                }
                foreach $field (keys(%ffields)){
                        if($formline =~ /\*$field\*/){
                                $formline =~ s/\*$field\*/$ffields{"$field"}/;
                                last;
                        }
                }
        $formline =~ s/&ast;/\*/g;
        print "$formline\n" if $formline !~ /<!--.+-->/ and $formline ne '';
        }
}

######## Display Message Page Replies


sub replylist{
		if (open(REPLY, "$htmlpath/replies/$FORM{'message'}.txt"))
		{
			 @list = <REPLY>;
			 for($j=0;$j<=$#list;$j++){
				print $list[$j];
			 }
		}
		else
		{
		open(REPLY, ">$htmlpath/replies/$FORM{'message'}.txt");
        if($FORM{'mode'} eq $current) {open(LIST, "$htmlpath/$mlist")} else {open(LIST, "$htmlpath/$alist")}
        flock LIST, 2 if $lockon eq 'yes';
        @list = <LIST>;
        for($j=0;$j<=$#list;$j++){
                @item = split(/\t/,$list[$j]);
                $k = $j if not $item[0];
                if($FORM{'message'} eq $item[1]){
                        $j = $k;
                        for ($j=$j;$j<=$#list;$j++){
                                $list[$j] =~ s/&ast;/\*/g;
                                @subitem = split(/\t/,$list[$j]);
                                if(($subitem[0]) or ($j == $k)){
                                        $date = &date($subitem[4]);
                                        for($k=0;$k<$subitem[0];$k++){
                                                print "$indent";
                                                print REPLY "$indent";
                                        }
                                        unless ($FORM{'message'} eq $subitem[1]) {
                                                print "<a href=\"$mfields{'boardurl'}&message=$subitem[1]\">";                                        
                                                print REPLY "<a href=\"$mfields{'boardurl'}&message=$subitem[1]\">";
                                        }else {
                                                print "<font color=gray>";
                                                print REPLY "<font color=gray>";                                                
                                        }
                                        if($subitem[0]) {
                                                print "<img src=$replyimage border=0 align=absmiddle alt=\"\">";
                                                print REPLY "<img src=$replyimage border=0 align=absmiddle alt=\"\">";                                                
                                        }else {
                                                print "<img src=$postimage border=0 align=absmiddle alt=\"\">";
                                                print REPLY "<img src=$postimage border=0 align=absmiddle alt=\"\">";                                                
                                        }
                                        print "$subitem[2]<small> - <b>$subitem[3]<\/b><i> on $date<\/small><\/i>\n";
                                        print REPLY "$subitem[2]<small> - <b>$subitem[3]<\/b><i> on $date<\/small><\/i>\n";                                        
                                        unless ($FORM{'message'} eq $subitem[1]) {
                                                print "<\/a>\n";
                                                print REPLY "<\/a>\n";                                                
                                        }else {
                                                print "<\/font>\n";
                                                print REPLY "<\/font>\n";                                                
                                        }
                                        if ((time - $subitem[5]) < $newtime)
                                        {
											print "$new<br>\n";
											print REPLY "$new<br>\n";
										}
										else 
										{
											print "<br>\n";
											print REPLY "<br>\n";
										}
                                }else {last};
                        }
                }
        }
        close(REPLY);
        }
}

##################################################
# View Preview Message

sub preview{

        open(TEMPLATE, "$htmlpath/$prev_template");
        @lines = <TEMPLATE>;
        close(TEMPLATE);
        chomp(@lines);

        &show_rest;
}

##################################################
# View Error Message

sub error{

        open(TEMPLATE, "$htmlpath/$error_template");
        @lines = <TEMPLATE>;
        close(TEMPLATE);
        chomp(@lines);

        &show_rest;
}

##################################################
# Display the Rest of the Page

sub show_rest{

        print "Content-type: text/html\n\n";

        ############################################
        # Generate Substitution Fields

        $FORM{'date'} = localtime;
        $FORM{'body'} =~ s/\r//g;
        $FORM{'quotedtext'} = $FORM{'body'};
        $FORM{'body'} =~ s/\n\n/<p>/g;
        $FORM{'body'} =~ s/\n/<br>/g;

        $FORM{'quotedsubject'} = $FORM{'subject'};

        $FORM{'boardurl'} = "$ENV{'SCRIPT_NAME'}?threads=$FORM{'threads'}&mode=$FORM{'mode'}";
        $FORM{'previousfilenameurl'} = "$FORM{'boardurl'}&message=$FORM{'previousfilename'}";
        $FORM{'actionurl'} = $ENV{'SCRIPT_NAME'};

        $FORM{'form'} = '';

        if ($FORM{'urltitle'} eq ''){
                $FORM{'urltitle'} = $FORM{'url'};
        }

        ##############################################
        # Print Preview or Error Message

        foreach $line (@lines){
                foreach $field (keys(%FORM)){
                        if($line =~ /\*$field\*/){
                                if(($FORM{"$field"} ne '') or ($line =~ /value=/)){
                                        $line =~ s/\*$field\*/$FORM{"$field"}/g;
                                }elsif($field eq 'email'){
                                        $line =~ s/<a.+?>//i;
                                        $line =~ s/<\/a>//i;

                                }elsif($field eq 'form'){
                                        open(TEMPLATE, "$htmlpath/$form_template");
                                        @form = <TEMPLATE>;
                                        close(TEMPLATE);
                                        chomp(@form);

                                        foreach $formline (@form){
                                                if($formline =~ /getemail/){
                                                        unless ($FORM{'previousfilename'}){
                                                                $formline =~ s/>/ CHECKED>/ if $FORM{'getemail'} eq 'yes';
                                                        }else{
                                                                $formline = "<input type=hidden name=getemail value=\"$FORM{'getemail'}\">";
                                                        }
                                                }
                                                foreach $formfield (keys(%FORM)){
                                                        if($formline =~ /\*$formfield\*/){
                                                                $formline =~ s/\*$formfield\*/$FORM{"$formfield"}/;
                                                                last;
                                                        }
                                                }
                                                $formline =~ s/&ast;/\*/g;
                                                print "$formline\n" if $formline !~ /<!--.+-->/ and $formline ne '';
                                        }
                                        $line = '';
                                }else{
                                        $line = '';
                                }
                        }
                }
                $line =~ s/&ast;/\*/g;
        print "$line\n" if $line !~ /<!--.+-->/ and $line ne '';
        }
}

####################################################
# Post Message

sub post{
        print "Content-type: text/html\n\n";
return;
        ##############################################
        # Increment counter

        open(COUNTER, "+<$htmlpath/$countfile");
        flock COUNTER, 2 if $lockon eq 'yes';
        $counter = <COUNTER>;
        $counter ++;
        seek (COUNTER, 0, 0);
        print COUNTER "$counter";
        close(COUNTER);

        $FORM{'date'} = localtime;

        $FORM{'emailbody'} = $FORM{'body'};
        $FORM{'emailbody'} =~ s/&lt;/</g;
        $FORM{'emailbody'} =~ s/&gt;/>/g;
        $FORM{'emailbody'} =~ s/&quot;/\"/g;

        $FORM{'emailsubject'} = $FORM{'subject'};
        $FORM{'emailsubject'} =~ s/&quot;/\"/g;

        $FORM{'body'} =~ s/\r//g;
        $FORM{'body'} =~ s/\n\n/*p*/g;
        $FORM{'body'} =~ s/\n/*br*/g;

        $FORM{'message'} = $counter;

        if($FORM{'getemail'} eq 'yes'){
                $FORM{'getemail'} = $FORM{'email'};
        }

        #################################################
        # Write message Data to File

        open(MESSAGE, ">$htmlpath/messages/$counter.txt");
        flock MESSAGE, 2 if $lockon eq 'yes';
        print MESSAGE "$FORM{'getemail'}\n";
        print MESSAGE "$FORM{'subject'}\n";
        print MESSAGE "$FORM{'name'}\n";
        print MESSAGE "$FORM{'email'}\n";
        print MESSAGE "$FORM{'date'}\n";
        print MESSAGE "$FORM{'body'}\n";
        print MESSAGE "$FORM{'previoussubject'}\n";
        print MESSAGE "$FORM{'previousname'}\n";
        print MESSAGE "$FORM{'previousfilename'}\n";
        print MESSAGE "$FORM{'previousdate'}\n";
        print MESSAGE "$FORM{'url'}\n";
        print MESSAGE "$FORM{'urltitle'}\n";
        print MESSAGE "$FORM{'imageurl'}\n";
        print MESSAGE "$ip";
        close(MESSAGE);

        ###########################################
        # Update Message List (mlist)

        if($FORM{'mode'} eq $current) {open(LIST, "$htmlpath/$mlist")} else {open(LIST, "$htmlpath/$alist")}
        flock LIST, 2 if $lockon eq 'yes';
        @list = <LIST>;

        $FORM{'name'} =~ s/<.*?>//g;
        $time = time;
        $ip = $ENV{'REMOTE_ADDR'};

        unless($FORM{'previousfilename'}){
                $newitem = "0\t$counter\t$FORM{'subject'}\t$FORM{'name'}\t$FORM{'date'}\t$time\n";
                unshift(@list,$newitem);
        }else{
                for($i=0;$i<=$#list;$i++){
                        @item = split (/\t/,$list[$i]);
                        if($item[1] eq $FORM{'previousfilename'}){
                                $level = $item[0];
                                $newlevel = $level + 1;
                                $newitem = "$newlevel\t$counter\t$FORM{'subject'}\t$FORM{'name'}\t$FORM{'date'}\t$time\n";
                                splice(@list, $i+1, 0, $newitem);
                                last;
                        }
                }
        }
        if($FORM{'mode'} eq $current) {
                open(LIST, ">$htmlpath/$mlist");
        }else{
                open(LIST, ">$htmlpath/$alist");
        }
        flock LIST, 2 if $lockon eq 'yes';
        seek (LIST, 0, 0);
        print LIST @list;
        close(LIST);

        open(MESSAGE, "$htmlpath/messages/$counter.txt");
        @data = <MESSAGE>;
        $message = $counter;
        print "Content-type: text/html\n\n";
        &email;
        &view;
}

#################################################
# Get password

sub password{
        print "Content-type: text/html\n\n";
        print "<html><head></head><body>\n";
        print "<center><b>Type in password and click [Submit] to delete";
        print " or archive" if $FORM{'mode'} eq $current;
        print " this message and all of its replies.</b>\n";
        print "<form action=\"$ENV{'SCRIPT_NAME'}\" method=POST>\n";
        print "<input type=text name=password><br>\n";
        print "<b>Delete Message</b><input type=radio name=archive value=no CHECKED><br>\n" if $FORM{'mode'} eq $current;
        print "<b>Archive Message</b><input type=radio name=archive value=yes><br>\n" if $FORM{'mode'} eq $current;
        print "<input type=submit><br>\n";
        print "<a href=\"$ENV{'SCRIPT_NAME'}\">[Return to Board]</a>\n";
        print "<input type=hidden name=admmessage value=$FORM{'admin'}>\n";
        print "<input type=hidden name=threads value=$FORM{'threads'}>\n";
        print "<input type=hidden name=mode value=$FORM{'mode'}>\n";
        print "</form></center></body</html>\n";
}

################################################
# Delete messages

sub delete{
        $message = $FORM{'admmessage'};
        $archive = $FORM{'archive'};
        @templist = () if $archive eq 'yes';
        unlink("$htmlpath/messages/$message.txt") if $archive eq 'no';
        for($i=0;$i<=$#list;$i++){
                @items = split (/\t/, $list[$i]);
                chomp(@items);
                if($items[1] eq $message){
                        $mlevel = $items[0];
                        $temp = splice(@list, $i, 1);
                        push(@templist, $temp) if $archive eq 'yes';
                        @items = split (/\t/, $list[$i]);
                        while((defined($list[$i])) and ($items[0] gt $mlevel)){
                                unlink("$htmlpath/messages/$items[1].txt") if $archive eq 'no';
                                $temp = splice(@list, $i, 1);
                                push(@templist, $temp) if $archive eq 'yes';
                                @items = split (/\t/, $list[$i]);
                        }
                        if($FORM{'mode'} eq $current) {
                                open(MLIST, ">$htmlpath/$mlist");
                                flock MLIST, 2 if $lockon eq 'yes';
                                seek (MLIST, 0, 0);
                                print MLIST @list;
                                close(MLIST);
                                last if $archive eq 'no';
                                open (ALIST, "$htmlpath/$alist");
                                flock ALIST, 2 if $lockon eq 'yes';
                                @alist = <ALIST>;
                                unshift (@alist, @templist);
                                open (ALIST, ">$htmlpath/$alist");
                                flock ALIST, 2 if $lockon eq 'yes';
                                seek (ALIST, 0, 0);
                                print ALIST @alist;
                                close (ALIST);
                                last;
                        }else {
                                open (ALIST, ">$htmlpath/$alist");
                                flock ALIST, 2 if $lockon eq 'yes';
                                seek (ALIST, 0, 0);
                                print ALIST @list;
                                close (ALIST);
                                last;
                        }
                }
        }
}
################################################
#  Subscribe or Cancel

sub subscribe{
        open(SLIST, "$htmlpath/slist.txt");
        @subscribers = <SLIST>;
        close(SLIST);

        if ($FORM{'sub'} eq 'subscribe') {
                push(@subscribers,"$FORM{'subaddress'}\n") unless grep(/$FORM{'subaddress'}/, @subscribers);
        }else {
                for($i=0;$i<=$#subscribers;$i++) {
                        if($subscribers[$i] eq "$FORM{'subaddress'}\n") {
                                splice(@subscribers,$i,1);
                                last;
                        }
                }
        }
        open(SLIST, ">$htmlpath/slist.txt");
        print SLIST @subscribers;
        close(SLIST);
}
#################################################
# Expire old current topics

sub expire1 {
        for($j=$#list;$j>=0;$j--) {
                @items = split(/\t/, $list[$j]);
                next if $items[0] ne '0';
                last if $items[5] > time - $expiration1;
                $FORM{'admmessage'} = $items[1];
                $FORM{'archive'} = $x2archive;
                &delete;
        }
}

#################################################
# Expire old archived topics

sub expire2 {
        for($j=$#list;$j>=0;$j--) {
                @items = split(/\t/, $list[$j]);
                next if $items[0] ne '0';
                last if $items[5] > time - $expiration2;
                $FORM{'admmessage'} = $items[1];
                $FORM{'archive'} = 'no';
                &delete;
        }
}

#################################################
# Email routine

sub email {
return;
        $script_name = $ENV{'SCRIPT_NAME'};
        $script_name =~ s#^/## ;
        $cgiurl = "http://$ENV{'SERVER_NAME'}/$script_name";

        if($sysadmin){&send_email("$sysadmin")}

        if($FORM{'getemail'} =~ /\@/){&send_email("$FORM{'getemail'}")}

  $| = 1;
  $ap_pid = fork();
  if (!$ap_pid) {
    open(SLIST, "$htmlpath/slist.txt");
    @subscribers = <SLIST>;
    close(SLIST);
    foreach $address (@subscribers){
      next if $address !~ /\@/;
      send_email("$address");
    }
   exit;
  }
  $| = 0;
}
sub send_email {
        local($address) = @_;
        chomp($address);
        open(EMAIL, "|$sendmail -t -oi");
        print EMAIL "From: \"Petrovich Message Board\" <mailbot\@rusmoney.com>\n";
        print EMAIL "Subject: $FORM{'emailsubject'}\n";
        print EMAIL "To: $address\n";
        print EMAIL "Reply-To: $FORM{'email'}\n\n";
        print EMAIL "***** Posted by: $FORM{'name'} *****\n";
        print EMAIL "$FORM{'emailbody'}\n\n";
        print EMAIL "LINK IN MESSAGE = $FORM{'url'}\n" if $FORM{'url'};
        print EMAIL "MESSAGE = $cgiurl?message=$counter\n\n";
        print EMAIL "*****\n Сообщение отправлено для $address\n";
        print EMAIL "Отказ от подписки: http://www.rusmoney.com/petrovich/forum/cgi/index.cgi?subform\n";
        print EMAIL "Путеводитель по конференции \"Обыватель на Wall Street\": http://www.rusmoney.com/bm/cgi-bin/ibview.pl?usr=WallStreet\n\n";
        print EMAIL "URL for Remote Delete = $cgiurl?admmessage=$counter&archive=no&password=$password\n\n" if $address eq $sysadmin;
        print EMAIL "Poster's Remote Host = $ENV{'REMOTE_ADDR'}\n" if $address eq $sysadmin;
        close(EMAIL);
}

sub restore {

        $pathto = $htmlpath;

        $time=time;

        unless(opendir(DATAFILES, "$pathto/messages")) {
                       &system_error("Can't open $pathto/messages Directory. <br>Check \$pathto.\n");
                       exit;
        }

        @raw_list = readdir (DATAFILES);
        @message_data_files = map {/(.*)\.txt$/} @raw_list;
        @message_data_files = sort{$a <=> $b} @message_data_files;

        #################################################
        # Restore counter.txt

        unless(open(COUNTER, ">$pathto/counter.txt")){
                &system_error("Can't open $pathto/counter.txt.\n");
                exit;
        }

        print COUNTER "$message_data_files[$#message_data_files]";
        close (COUNTER);

        #################################################
        # Remove archived messages

        unless(open(ALIST, "$pathto/alist.txt")){
                &system_error("Can't open $pathto/alist.txt.\n");
                exit;
        }
        @alist = <ALIST>;
        close(ALIST);

        for($i=0;$i<=$#message_data_files;$i++) {
                $message = $message_data_files[$i];

                for ($j=$#alist;$j>=0;$j--) {
                        @list_data = split (/\t/, $alist[$j]);
                        if ($list_data[1] eq $message) {
                                splice(@message_data_files, $i, 1);
                                splice(@alist, $j, 1);
                                $i--;
                                last;
                        }
                }
        }

        #################################################
        # generate topics

        @mlist = ();

        for($i=0;$i<=$#message_data_files;$i++) {
                $message = $message_data_files[$i];

                unless(open(FILE, "$pathto/messages/$message.txt")){
                        &system_error("Can't open $pathto/messages/$message.txt.\n");
                        exit;
                }
                @message_data=<FILE>;
                chomp(@message_data);

                unless ($message_data[6]){
                        &get_time("$message_data[4]");
                        push(@mlist, "0\t$message\t$message_data[1]\t$message_data[2]\t$message_data[4]\t$time\n");
                        splice(@message_data_files, $i, 1);
                        $i--;
                }
        }

        @mlist = reverse (@mlist);

        #################################################
        # Add replies

        foreach $reply (@message_data_files) {
                unless(open(REPLY, "$pathto/messages/$reply.txt")){
                        &system_error("Can't open $pathto/messages/$reply.txt.\n");
                        exit;
                }

        @reply_data = <REPLY>;
        chomp(@reply_data);

        $previous_filename = $reply_data[8];

                for ($i=$#mlist;$i>=0;$i--) {
                        @mlist_data = split (/\t/, $mlist[$i]);
                        if ($previous_filename eq $mlist_data[1]) {
                                $reply_level = $mlist_data[0]+1;
                                &get_time("$reply_data[4]");
                                $mlist_entry = "$reply_level\t$reply\t$reply_data[1]\t$reply_data[2]\t$reply_data[4]\t$time\n";
                                splice(@mlist, $i+1, 0, $mlist_entry);
                                last;
                        }
                }
        }

        unless(open(MLIST, ">$pathto/mlist.txt")){
                &system_error("Can't open $pathto/mlist.txt.\n");
                exit;
        }
        print MLIST @mlist;
        close(MLIST);

}


sub get_time {
        local ($date) = @_;
        $days = 24*60*60;
        if ($date =~ /(\d\d\d\d)/) {
                $time = ($1 - 1970)*365.25*$days;
        }
        $time -= .75*$days;
        $time += 31*$days if $date =~ /Feb/;
        $time += 59*$days if $date =~ /Mar/;
        $time += 90*$days if $date =~ /Apr/;
        $time += 120*$days if $date =~ /May/;
        $time += 151*$days if $date =~ /Jun/;
        $time += 181*$days if $date =~ /Jul/;
        $time += 212*$days if $date =~ /Aug/;
        $time += 243*$days if $date =~ /Sep/;
        $time += 273*$days if $date =~ /Oct/;
        $time += 304*$days if $date =~ /Nov/;
        $time += 334*$days if $date =~ /Dec/;
        if ($date =~ /\w\w\w\s(.\d)\D/) {
                $time += $1*$days;
        }
        if ($date =~ /(\d\d):(\d\d):(\d\d)/) {
                $time += $1*60*60 + $2*60 + $3;
        }
}


sub system_error {
        local($errmsg) = @_;
        &print_header("System Error");
        print $errmsg;
        &print_footer;
}

sub print_header {
        local($title) = @_;
        print "Content-type: text/html\n\n";

        print "<HTML>\n";
        print "<HEAD>\n";
        print "<TITLE>$title</TITLE>\n";
        print "</HEAD>\n";
        print "<BODY>\n";
        print "<H1>$title</H1>\n";
}

sub print_footer {
        print "</BODY>\n";
        print "</HTML>\n";
}

sub date {
        local($date) = @_;
        $date =~ s/^([A-Z][a-z][a-z]) /$1, /;
        $date =~ s/([A-Z][a-z][a-z])[a-z].*?\s/ $1 /;
        $date =~ s/(\d\d:\d\d):\d\d/at $1/;
        $date =~ s/at at/at/;
        $date =~ s/ \d\d\d\d//;
        if ($date =~ /(\d\d):/) {$hour = $1}
        if ($hour >12) {
                $hour -= 12;
                $m = 'pm';
        }else {
                $m = 'am';
        }
        $date =~ s/\d\d:(\d\d)/$hour:$1$m/;
        return($date);
}
########################################
# check for banned status

sub ban_check {
        $ip = $ENV{'REMOTE_ADDR'};

        open (BANLIST,"$htmlpath/$banlist");
        @blist = <BANLIST>;
        close (BANLIST);

        foreach $bannedip (@blist) {
                chomp($bannedip);
                if ($ip =~ /$bannedip/) {
                        print "Content-type: text/html\n\n";
                        print "<html><head></head><body>\n";
                        print "<h1 align=center>Sorry, you've been denied access to this Board.</h1>\n";
                        print "</body></html>";
                        exit;
                }
        }
}
sub serverload {
  return 100 if !open(LA, "/proc/loadavg");
  my $buff = <LA>;
  close LA;
  my ($l1, $l5, $l15) = split(/\s+/, $buff);
  $l1 = 100 if $l1 eq undef;
  $l5 = 100 if $l5 eq undef;
  return ($l1 > $l5) ? $l5 : $l1;
}
#
#
