#!/usr/bin/perl

#use Apache;
use DBI;
use Digest::MD5 qw(md5_hex);
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser);
use Tie::IxHash;
use HTML::Template;
use HTML::Parser;  
use HTML::Filter;
#use IO::Socket::INET;
use Mail::Sender;
use Mail::Send;
use IPC::SharedCache;
use lib '/home/oc/cgi-bin/';
use OC;
use strict;

use vars qw /
%list
%navigation
%CONFIG
@EXCLUDE
%form
%cookie
@NOTE
$template
$self_url
$textarea_width

$smtp_host

$db_host
$db_name
$db_username
$db_password
$db_port

$_FOLDER   
$_FILE
$_ERROR 

/;


sub Initialize {
    @EXCLUDE=('webmasters'); 

    $ENV{PATH}="/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:.";

    $smtp_host='localhost';
 
    $db_host="kenny";
    $db_name="oc";
    $db_username="root";   
    $db_password="";     
    $db_port="3306";  

    $textarea_width=70;
    tie (%list,'Tie::IxHash');
    %list=();

    %CONFIG=%{OC::CONFIG};

#    $self_url=$ENV{REQUEST_URI};
#    $self_url=~s/^(.*)\?.*$/$1/;
#    $self_url=~s/^(.*.cgi).*$/$1/;
    $self_url=$CONFIG{forum_url};     

    @NOTE=();

    %form=();
    my $query=new CGI;
    foreach ($query->param) {
        $form{$_}=$query->param($_);
    }
    %cookie=();
    foreach ($query->cookie) {
        $cookie{$_}=$query->cookie($_);
    }

    $CONFIG{htsearch}='/home/oc/cgi-bin/htsearch';
    $CONFIG{majordomo_email}='majordomo@opencores.org';
    $CONFIG{majordomo_list_folder}='/usr/local/majordomo/lists/';
    $CONFIG{month_folder}=$OC::CONFIG{month_folder};
    $CONFIG{archive_folder}='/home/oc/ml-archive/archives';
    $CONFIG{tmpl_default_file}='/home/oc/www/tmpl/forum_default.tmpl';
    $CONFIG{tmpl_list_file}='/home/oc/www/tmpl/forum_list.tmpl';
    $CONFIG{tmpl_folder_file}='/home/oc/www/tmpl/forum_folder.tmpl';
    $CONFIG{tmpl_message_file}='/home/oc/www/tmpl/forum_message.tmpl';
    $CONFIG{tmpl_post_file}='/home/oc/www/tmpl/forum_post.tmpl';
    $CONFIG{tmpl_empty_file}='/home/oc/www/tmpl/forum_empty.tmpl';

    $navigation{home}{name}="OC home";
    $navigation{home}{link}="/";

    $_FOLDER=2;
    $_FILE=1;  
    $_ERROR=-1;

}

sub ConnectToDatabase {
    if (!defined $::db) {
        $::db = DBI->connect("DBI:mysql:$db_name:$db_host:$db_port",$db_username,$db_password)
          || die "Can't connect to database server.";
    }
    return $::db;
}
 
sub PrepareSQL {
    my ($str) = (@_);
    $::sth=$::db->prepare($str);
}
 
sub ExecuteSQL {
    $::sth->execute(@_) || die "Could not execute SQL statement";
}
 
sub SendSQL {
    PrepareSQL(@_);
    ExecuteSQL();  
}
 
sub FetchSQLData {
    return $::sth->fetchrow_array();
}

sub Header {
    return header(-type  =>  'text/html',-charset=>'');
}

sub File_Type {
    my $mode=(stat($_[0]))[2];
    return $_ERROR unless ($mode);
    if (substr(sprintf("%04o", $mode),0,1) ne '1') {
        return $_FOLDER;
    } else {
        return $_FILE;
    }
}

sub Exclude {
    my @folders=@_;
    my @pf=();
    foreach my $folder (@folders) {
        my $excluded=0;
	foreach (@{$CONFIG{exclude}}) {
            $excluded=1 if (index($folder,$_)==0);
        }
        push(@pf,$folder) unless($excluded);
    }
    return @pf;
}

sub List {
    my @files=();
    my @folders=();
    foreach (split(/ \//,join(' ',<$_[0]>))) {
        $_='/'.$_ unless($_=~m/^\//);
        my $ft=File_Type($_);
        if ($ft eq $_FOLDER) {
            push(@folders,$_.'/');
        } elsif ($ft eq $_FILE) {
            push(@files,$_);
        }
    }
    @folders=Exclude(@folders);
    @files=Exclude(@files);
    return(\@folders,\@files);
}

sub Note {
    foreach (@NOTE) {
        my %note=%{$_};
        if ($note{note} eq $_[0]) {
            return;
        }
    }
    my %row_data=();
    $row_data{note}=$_[0];
    if (lc($CONFIG{detailednotes}[0]) eq 'yes') {
        my ($package, $filename, $line, $subroutine,
          $hasargs, $wantarray, $evaltext, $is_require, $line2)=caller(0);
        ($package, $filename, $line2, $subroutine,
          $hasargs, $wantarray, $evaltext, $is_require)=caller(1);
        $subroutine=~s/^main:://g;
        $row_data{note}.="<br>". "&nbsp;&nbsp;<font color=\"#bf0000\">subroutine: $subroutine, line: $line</font>";
    } 
    push(@NOTE,\%row_data);
}

sub Send_Mail {
    my %msg=%{$_[0]};
    my $headers='';
    open(SENDMAIL,"| sendmail $msg{header}{to}"); 
    foreach (keys %{$msg{header}}) {
        print SENDMAIL ucfirst($_).": $msg{header}{$_}\n";
        $headers.=ucfirst($_).": $msg{header}{$_}; ";
    }
    print SENDMAIL "\n";
    print SENDMAIL $msg{body};
    close(SENDMAIL);
    OC::Log("$headers");
}


sub Get_Lists {

    foreach my $lname (OC::Get_Mailing_Lists) {
        $list{$lname}{name}=$lname;
    }
    foreach my $lname (keys %list) {
        if (File_Type($CONFIG{majordomo_list_folder}."/$lname".'-digest')==$_FILE) {
            $list{$lname}{has_digest}=1;
        }
       
        $list{$lname}{name}=~s/_/ /g; 
        $list{$lname}{name}=ucfirst($list{$lname}{name});

        my $description='';
        open(FILE,$CONFIG{majordomo_list_folder}."/$lname.info");
        while (my $line=<FILE>) {
            $description.=$line;
        }
        close(FILE);
        $list{$lname}{description}=$description;

        if (File_Type($CONFIG{majordomo_list_folder}."/$lname")==$_FILE) {
            $list{$lname}{member_count}=`/usr/bin/wc $CONFIG{majordomo_list_folder}/$lname`;
            $list{$lname}{member_count}=~s/^[\t ]*(\d*).*$/$1/;
        }
    }
 
}

sub Mon_Months {
    return ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
}

sub Split_Time {
    my $time=time;
    $time=$_[0] if ($_[0]);
    my ($sec,$min,$hour,$mday,$mon,$year)=localtime($time);
#    $year=substr($year+=1900,2,2);
    $year+=1900;
    $mon++;
    foreach ($sec,$min,$hour,$mday,$mon) {
        $_='0'.$_ if (length($_)<2);
    }
    return($year,$mon,$mday,$hour,$min,$sec);
}

sub Long_Year {
    my $year=$_[0];
    if (substr($year,0,2)>=70) {
        $year='19'.$year;
    } else {
        $year='20'.$year;
    } 
    return $year;
}

sub List_By_Month {
    my $lname=$_[0];
    my ($folders,$junk)=List("$CONFIG{archive_folder}/$lname/*");
    my @tmp_folders=();
    @tmp_folders=@{$folders};
    
#    @tmp_folders=sort(@tmp_folders);
    foreach my $folder (@tmp_folders) {
        $folder=~s/^.*\/([^\/]*)\/$/$1/;
        my $year=substr($folder,0,2);
        my $month=substr($folder,2,2);
        my ($junk,$files)=List("$CONFIG{archive_folder}/$lname/$folder/msg*.shtml");
        my $mcount=scalar(@{$files});
        $year=Long_Year($year);
        if ($mcount>0) {
            $list{$lname}{year}{$year}{$month}{msg_count}=$mcount;
            $list{$lname}{year}{$year}{$month}{path}="$CONFIG{archive_folder}/$lname/$folder";
            my $thread_file="$CONFIG{archive_folder}/$lname/$folder/threads.shtml";
            my $date_file="$CONFIG{archive_folder}/$lname/$folder/maillist.shtml";
            if (File_Type($thread_file)==$_FILE) {
                $list{$lname}{year}{$year}{$month}{thread_file}=$thread_file;
            }
            if (File_Type($date_file)==$_FILE) {
                $list{$lname}{year}{$year}{$month}{date_file}=$date_file;
            }
        }
    }
    my ($junk,$files)=List("$CONFIG{month_folder}/$lname/msg*.shtml");
    my $mcount=scalar(@{$files});
    my ($year,$month)=Split_Time;
    $list{$lname}{year}{$year}{$month}{msg_count}=$mcount;# if ($mcount>0);
    $list{$lname}{year}{$year}{$month}{path}="$CONFIG{month_folder}/$lname";
    my $thread_file="$CONFIG{month_folder}/$lname/threads.shtml";
    my $date_file="$CONFIG{month_folder}/$lname/maillist.shtml";
    if (File_Type($thread_file)==$_FILE) {
        $list{$lname}{year}{$year}{$month}{thread_file}=$thread_file;
    }
    if (File_Type($date_file)==$_FILE) {
        $list{$lname}{year}{$year}{$month}{date_file}=$date_file;
    }
}

sub Str_To_Email {
    my $email=$_[0];
    $email=~s/<font[^>]*>|<\/font>//ig;
    $email=~s/<a href=[^>]*>|<\/a>//ig;
    $email=~s/ dot /\./g;
    $email=~s/ at /\@/g;
    return $email;
}

sub Month_By_Date {
    my ($lname,$year,$month)=@_;
    my $date_file=$list{$lname}{year}{$year}{$month}{date_file};

    tie (%{$list{$lname}{year}{$year}{$month}{by_date}},'Tie::IxHash');;

    if (open(FILE,$date_file)) {
        my $msg_id=0;
        my $date='';
        my $mcount=0;
        while (my $line=<FILE>) {
            if ($line=~m/(.*)<STRONG><A NAME="([^"]+)" href="([^"]+)">(.*)<\/a>/i) {
                my $tmp_date=$1;
                $msg_id=$2;
                my $href=$3;
                my $subject=$4; 
                if ($tmp_date=~m/tt>(.*)<\/tt> - /i) {
                    $tmp_date=$1;
                } else {
                    my @month=Mon_Months;
                    $tmp_date=$month[$month-1]."/$year";
                }
                $date=$tmp_date if ($tmp_date);
                $mcount++;
                $list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{date}=$date;
                $href=$list{$lname}{year}{$year}{$month}{path}.'/'.$href;
                $list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{file}=$href;
                $list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{subject}=$subject;
            } elsif ($line=~m/<LI><EM>From<\/EM>: (.*)<\/LI><\/UL>/i) {
                my $from=$1;
                $from=~s/<font class=email>//g;
                $from=~s/<\/font>//g;
                $from=Str_To_Email($from);
                $list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{from}=$from;
            }
        }
        $list{$lname}{year}{$year}{$month}{msg_count}=$mcount;
        close(FILE);
    } else {
        Note("Can't open file: $date_file");
    }
}

sub Month_By_Thread {
    my ($lname,$year,$month)=@_;
    my $thread_file=$list{$lname}{year}{$year}{$month}{thread_file};

    tie (%{$list{$lname}{year}{$year}{$month}{by_thread}},'Tie::IxHash');;

    if (open(FILE,$thread_file)) {
        my $msg_id=0;
        my $date='';
        my $mcount=0;
        my $depth=0;
        while (my $line=<FILE>) {
            if ($line=~m/<ul>/i) {
                $depth++;
            }
            if ($line=~m/<\/ul>/i) {
                $depth--;
            }
            if ($line=~m/<tt>(.*)<\/tt> - <STRONG><A NAME="([^"]+)" HREF="([^"]+)">(.*)<\/a>/i) {
                my $tmp_date=$1;
                $date=$tmp_date if ($tmp_date);
                $msg_id=$2;
                my $href=$3;
                my $subject=$4;
                $mcount++;
                $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{date}=$date;
                $href=$list{$lname}{year}{$year}{$month}{path}.'/'.$href;
                $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{file}=$href;
                $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{subject}=$subject;
                $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{depth}=$depth;
            } elsif($line=~m/<EM>(.*)<\/EM>/i) {
                my $from=$1;
                $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{from}=$from;
            }
        }
        close(FILE);
    } else {
        Note("Can't open file: $thread_file");
    }    
}

sub Parse_Message {
    my ($lname,$year,$month,$msg_id,$view)=@_;
    $view='date' unless ($view);
    my $file=$list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{file};
    my %msg=();
    if (open(FILE,$file)) {
       $msg{source}='';
       while(my $line=<FILE>) {
           while ($line=~m/(<font class=email>)([^>]* at [^>]* dot [^>]*)(<\/font>)/gi) {
               my $email=Str_To_Email($2);
               $line=~s/$1$2$3/$email/g;
           }
           $msg{source}.=$line;
       }
       close(FILE);
       if ($msg{source}=~m/\n([^\n]*Date Prev[^\n]*Date Next[^\n]*Thread Index)[^\n]*\n/is) {
           my $navig_line=$1;
           if ($navig_line=~m/<A HREF="msg([\d]{5,5})\.s?html">Thread Prev<\/A>/i) {
               $msg{thread_prev}=$1;
           }
           if ($navig_line=~m/<A HREF="msg([\d]{5,5})\.s?html">Thread Next<\/A>/i) {
               $msg{thread_next}=$1;
           }
       }
       if ($msg{source}=~m/<!--X-Head-of-Message-->(.*)<!--X-Head-of-Message-End-->/is) {
           $msg{header}=$1;
           if ($msg{header}=~m/<LI><em>From<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{from}=Str_To_Email($1);
           }
           if ($msg{header}=~m/<LI><em>To<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{to}=Str_To_Email($1);
           }
           if ($msg{header}=~m/<LI><em>Reply-To<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{reply_to}=Str_To_Email($1);
           }
           if ($msg{header}=~m/<LI><em>Cc<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{cc}=Str_To_Email($1);
           }
           if ($msg{header}=~m/<LI><em>Date<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{date}=$1;
           }
           if ($msg{header}=~m/<LI><em>Subject<\/em>: ([^\n]*)<\/LI>/msi) {
               $msg{subject}=$1;
           }
       }


       

       if ($msg{source}=~m/<!--X-Body-of-Message-->(.*)<!--X-Body-of-Message-End-->/is) {
           $msg{body}=$1;

           # remove oc unsubscribe footer
           $msg{body}=~s/--\n?[^\n]*To unsubscribe from[^\n]+\n?[^\n]+mailinglists[^\n]+//isg;
          
           #remove yahoo footer
           $msg{body}=~s/\n[^\n]*___*\n[^\n]*Do you Yahoo[^\n]*\n[^\n]*yahoo[^\n]*\n[^\n]*yahoo[^\n]*//isg;

           #remove hotmail footer
           $msg{body}=~s/\n[^\n]*___*\n[^\n]*Get your private[^\n]*hotmail[^\n]*//isg;

           #remove hotmail footer
           $msg{body}=~s/\n[^\n]*___*\n[^\n]*Get your FREE[^\n]*msn[^\n]*//isg;

       }

       if ($msg{source}=~m/<!--X-References-->(.*)<!--X-References-End-->/is) {
           my @reference=split(/<LI><STRONG>/,$1);
           my @tmp_ref=();
           foreach (@reference) {
               my %row_data=();
               if ($_=~m/<A NAME="([\d]+)" HREF=".*">(.*)<\/A><\/STRONG>.*<UL><LI><EM>From:<\/EM> (.*)<\/LI><\/UL><\/LI>.*/is) {
                   $row_data{name}=$1; 
                   $row_data{subject}=$2;
                   $row_data{from}=Str_To_Email($3);
                   push(@tmp_ref,\%row_data);
               }
           }
           $msg{references}=\@tmp_ref;
       }

       if ($msg{source}=~m/<!--X-Follow-Ups-->(.*)<!--X-Follow-Ups-End-->/is) {
           my @follow_up=split(/<LI><STRONG>/,$1);
           my @tmp_fu=();
           foreach (@follow_up) {
               my %row_data=();
               if ($_=~m/<A NAME="([\d]+)" HREF=".*">(.*)<\/A><\/STRONG>.*<UL><LI><EM>From:<\/EM> (.*)<\/LI><\/UL><\/LI>.*/is) {
                   $row_data{name}=$1; 
                   $row_data{subject}=$2;
                   $row_data{from}=Str_To_Email($3);
                   push(@tmp_fu,\%row_data);
               }
           }
           $msg{follow_ups}=\@tmp_fu;
       }
       $list{$lname}{year}{$year}{$month}{"by_".$view}{$msg_id}{message}=\%msg;
    } else {
        Note("Can't open file $file");
    }

}

sub Html2Text {
    @::line=();
    my $tag=1;

    my $body=$_[0];
    unless ($body=~m/<(div|table|tr|br|block)/i) {
        $body=~s/< *\/* *pre *>//isg;
        $body=~s/< *a +[^>]*href="([^"]*)"[^>]*>[^<]*< *\/a[^>]*>/$1/isg;
	$body=~s/< *\/a[^>]*>//gis;
        return $body;
    }

sub tag_handler {
    return if ($tag);
    my $in=$_[0];
    if ($in=~m/^p$/i) {
	    $tag=1;
        push(@::line,"\n\n");
    }
    if ($in=~m/^(div|table|tr|br|block)/i) {
        $tag=1;
        push(@::line,"\n");
    }
}

sub text_handler {
    my $in=$_[0]; 
    $in=~s/\n/ /g;
    $in=~s/&nbsp;/ /g;
    push(@::line,$in); 
    $tag=0;
}

    my $p=HTML::Parser->new(api_version => 3);
    $p->handler(text => \&text_handler, "text");
    $p->handler(start => \&tag_handler, "tagname");
    $p->parse($body);
    $p->eof;
    my $result=join('',@::line);
    $result=~s/ +/ /sg;
    $result=~s/^(\n| )*//sg;
    return $result;
}

sub Format_Text {
    my $result='';
    my @line=split(/\n/,$_[0]);
    foreach my $line (@line) {
        my $new_line='';
        foreach my $word (split(/ /,$line)) {
            if (length($new_line.$word)>$_[1]-1) {
                $result.=$new_line."\n";
                $new_line="$word ";
            } else {
                $new_line.=$word;
                $new_line.=' ';
            }
        }
        $result.=$new_line."\n";
    }
    return $result;
}


sub Email_To_Name {
    my $email=$_[0];
    $email=~s/<font[^>]*>|<\/font>//ig;
    $email=~s/&lt;/</g;
    $email=~s/&gt;/>/g;
    if ($email=~m/"?([^>^"]*)"? <?[^ ]*\@[^ ]*>?/i) {
        $email=$1;
    }
    if ($email=~m/^<?(.*)\@/i) {
        $email=$1;
        $email=~s/\./ /g;
        $email=ucfirst($email);
    }
    return ucfirst($email);
}



sub Prepare_Template {
    $template=HTML::Template->new(
	filename=>$_[0],
        die_on_bad_params=>0,
        loop_context_vars=>1,
        global_vars=>0,
	shared_cache=>0,
    );
    $template->param(table_color1=>$CONFIG{color}{table1});
}


sub Tmpl_Fill_Lists {
    my @lists=();
    foreach my $lname (keys %list) {
        my %row_data=();
        $row_data{name}=$list{$lname}{name};
        $row_data{description}=$list{$lname}{description};
        $row_data{description}=~s/\n\n/<p>/g;
        $row_data{link}=$self_url.'/'.$lname.'/' if ($_[0] ne $lname);
        $row_data{selected}=1 if ($_[0] eq  $lname);
        $row_data{has_digest} = $list{$lname}{has_digest} ? 'yes' : 'no';
        push(@lists,\%row_data);
    }
    $template->param(
        mailinglists=>\@lists,
        list_count=>scalar(keys %list),
    );
}

sub Tmpl_Fill_Month_Table {
    my ($lname,$year_in)=@_;
    my (@year,@tmp_year)=();
    foreach (keys %{$list{$lname}{year}}) {
        push(@tmp_year,$_) if ($_);
    }
    @tmp_year=sort(@tmp_year);
    foreach (@tmp_year) {
        @year=($_,@year);
    }
    
    my @year_loop=();
    my %year_data=();
    my @month_loop=();
    foreach (Mon_Months) {
        my %month_data=();
        $month_data{month}=$_;
        push(@month_loop,\%month_data);
    }
    $year_data{months}=\@month_loop;
    push(@year_loop,\%year_data);
    foreach my $year (@year) {
        next if (exists $list{$lname}{year}{$year_in} && $year ne $year_in);
        my @month_loop=();
        my %year_data=();
        $year_data{year}=$year;
        foreach my $month (01..12) {
            $month='0'.$month if (length($month)<2);
            my %month_data=();
            $month_data{month}=$list{$lname}{year}{$year}{$month}{msg_count};
            $month_data{month}='&nbsp;' unless ($month_data{month}>0);
            $month_data{link}=$self_url."/$lname/$year/$month/" if ($month_data{month}>0);
            $month_data{color}=1;
            push(@month_loop,\%month_data);
        }

        $year_data{months}=\@month_loop;
        push(@year_loop,\%year_data);
    }
    $template->param(month_table=>\@year_loop);

}

sub Tmpl_Fill_Navigation {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my @navigation_loop=();
    foreach my $navig (keys %navigation) {
        my %row_data=();
        $row_data{name}=$navigation{$navig}{name};
        $row_data{link}=$navigation{$navig}{link};
        push(@navigation_loop,\%row_data);
    }

    my %row_data=();
    $row_data{name}='All forums';
    if ($lname || $cmd eq 'post') {
        $row_data{link}=$self_url."/";
    } else {
        $row_data{selected}=1;
    }
    push(@navigation_loop,\%row_data);

    my %row_data=();
    $row_data{name}=ucfirst("Current forum");
    if (($lname && exists $list{$lname} && $year ne '' && $month ne '')  
      || ($cmd eq 'post' && exists $list{$lname} && exists $list{$lname}{name})) {
        $row_data{link}=$self_url."/$lname/";
    } elsif ($lname && $cmd ne 'post') {
        $row_data{selected}=1;
    }
    if ($cmd eq 'subscribe' || ($cmd eq 'search' && $lname)) {
        $row_data{selected}=0;
        $row_data{link}=$self_url."/$lname/";
        push(@navigation_loop,\%row_data);
        my %row_data=();
        $row_data{name}=ucfirst($cmd);
        $row_data{selected}=1;
        push(@navigation_loop,\%row_data);    
    } else {
        push(@navigation_loop,\%row_data);
    }

    my %row_data=();
    $row_data{name}='Message List';
    if (($lname && $year && $month && $msg_id) 
      || ($lname && $year && $month && $cmd eq 'post')) {
        $row_data{link}=$self_url."/$lname/$year/$month/";
    } elsif ($lname && $year && $month && $cmd ne 'post') {
        $row_data{selected}=1;
    }
    push(@navigation_loop,\%row_data);

    my %row_data=();
    $row_data{name}='Message';
    if ($lname && $year && $month && $msg_id ) {
        unless ($cmd=~m/^(reply|reply_all|post|send)$/) {
            $row_data{selected}=1;
        } else {
            $row_data{link}="$self_url/$lname/$year/$month/$msg_id";
        }
    }
    push(@navigation_loop,\%row_data);

    my %row_data=();
    $row_data{name}='';
    push(@navigation_loop,\%row_data);


    my %row_data=();
    $row_data{name}='Post';
    if ($lname && $year && $month && $msg_id && ($cmd=~m/^(reply|reply_all)$/) || $cmd=~m/^(post|send)$/) {
        $row_data{selected}=1;
    } elsif ($lname) {
        my @tmp=();
        foreach ($year,$month,$msg_id) {
            push(@tmp,$_) if (defined $_);
        }
        $row_data{link}=join('/',$self_url,$lname,@tmp,'post');
    }
    push(@navigation_loop,\%row_data);

    $template->param(navigation=>\@navigation_loop);

}

sub Tmpl_Fill_Common {
    my ($lname,$year,$month)=@_;
    $template->param(
        list=>$lname,
        name=>$list{$lname}{name},
        description=>$list{$lname}{description},
        member_count=>$list{$lname}{member_count} ? $list{$lname}{member_count} : '' ,
        page_title=>$list{$lname}{name},
    );
}

sub Month_Links {
    my ($lname)=@_;
    my @year=();
    foreach my $y (sort keys %{$list{$lname}{year}}) {
        foreach my $m (sort keys %{$list{$lname}{year}{$y}}) {
            my $msg_count=$list{$lname}{year}{$y}{$m}{msg_count};
            if ($msg_count>0) {
                push(@year,"$y/$m/$msg_count");
            } 
        }
    } 
    return \@year;
}


sub Msg_Id {
    my $msg_id=$_[0];
    if (length($msg_id)<5) {
        foreach (1..(5-length($msg_id))) {
            $msg_id='0'.$msg_id;
        }
    }
    return $msg_id;
}


sub Next_Message {
    my ($lname,$year,$month,$msg_id,$no_msg)=@_;
    $msg_id=~m/^(0*)([^0]{1}.*)$/;
    my ($zeros,$rest)=($1,$2);
    my $next_id=Msg_Id($rest+1);
    if (exists $list{$lname}{year}{$year}{$month}{by_date}{$next_id}) {
        return "$self_url/$lname/$year/$month/$next_id";
    } else {
        my @year=@{Month_Links($lname)};
        my ($py,$pm,$pmc)=undef;
        foreach (@year) {
            my ($cy,$cm,$msg_count)=split(/\//,$_);
            if ($py==$year && $pm==$month && defined $msg_count) {
                if ($no_msg) {
                    return "$self_url/$lname/$cy/$cm/";
                } else {
                    return "$self_url/$lname/$cy/$cm/00000";
                }
            }
            ($py,$pm,$pmc)=($cy,$cm,$msg_count);
        }
    }
}

sub Prev_Message {
    my ($lname,$year,$month,$msg_id,$no_msg)=@_;
    $msg_id=~m/^(0*)([^0]{1}.*)$/;
    my ($zeros,$rest)=($1,$2);
    if ($rest>0) {
        my $prev_id=Msg_Id($rest-1);
        return "$self_url/$lname/$year/$month/$prev_id";
    } else {
        my @year=@{Month_Links($lname)};
        my ($py,$pm,$pmc)=undef;
        foreach (@year) {
            my ($cy,$cm,$msg_count)=split(/\//,$_);
            if ($cy==$year && $cm==$month) {
                if (defined $pmc) {
                    $pmc--;
                    $pmc=Msg_Id($pmc);
                    if ($no_msg) {
                        return "$self_url/$lname/$py/$pm/";
                    } else {
                        return "$self_url/$lname/$py/$pm/$pmc";
                    }
                } else {
                    return undef;
                }
            }
            ($py,$pm,$pmc)=($cy,$cm,$msg_count);
        }
    }
}

sub Tmpl_Fill_Folder {
    my ($lname,$year,$month)=@_;

    my $view='date';
    if ($form{view} eq 'thread') {
        $view='thread';
    }

    my @loop_data=();
    foreach my $msg_id (keys %{$list{$lname}{year}{$year}{$month}{"by_$view"}}) {
        my %row_data=();
        $row_data{from}=Email_To_Name($list{$lname}{year}{$year}{$month}{"by_$view"}{$msg_id}{from});
        $row_data{subject}=$list{$lname}{year}{$year}{$month}{"by_$view"}{$msg_id}{subject};
        $row_data{date}=$list{$lname}{year}{$year}{$month}{"by_$view"}{$msg_id}{date};
        $row_data{link}="$self_url/$lname/$year/$month/$msg_id";
        if ($view eq 'thread' && $list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{depth}>1) {
            $row_data{depth}="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" x ($list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{depth}-1);
        }
        if (length($row_data{from})>30) {
            $row_data{from}=substr($row_data{from},0,27).'...';
        }
        if (length($row_data{subject})>60) {
            $row_data{subject}=substr($row_data{subject},0,57).'...';
        }
        $row_data{thread}=1 if ($view eq 'thread');
        push(@loop_data,\%row_data);
    }

    my @view_type=();
    foreach ('date','thread') {
        my %row_data=();
        $row_data{name}=ucfirst($_)." Index";
        $row_data{link}=$self_url."/$lname/$year/$month/?view=$_" if ($view ne $_);
        push(@view_type,\%row_data);
    }

    
    Next_Message($lname,$year,$month,'99999',1);
    Month_Links();

    $template->param(
        prev_folder=>Prev_Message($lname,$year,$month,'00000',1),
        next_folder=>Next_Message($lname,$year,$month,'99999',1),
        messages=>\@loop_data,
        message_count=>scalar(@loop_data),
        view_type=>\@view_type,
        thread=>$view eq 'thread' ? 1 : 0 ,
        page_title=>"$list{$lname}{name}/$year/$month",
    );
}

sub Tmpl_Fill_Message {
    my ($lname,$year,$month,$msg_id)=@_;
    my %msg=%{$list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{message}};

    my @references=();
    foreach my $ref (@{$msg{references}}) {
        my %row_data=();
        $row_data{link}="$self_url/$lname/$year/$month/${%{$ref}}{name}";
        $row_data{subject}=${%{$ref}}{subject};
        if ($row_data{subject} eq '') {
            $row_data{subject}='No subject';
        }
        $row_data{from}=Email_To_Name(${%{$ref}}{from});
        $row_data{from}='Unknown' unless ($row_data{from});
        push(@references,\%row_data);
    }
    $template->param(references=>\@references) if (scalar(@references));


    my @follow_ups=();
    foreach my $fu (@{$msg{follow_ups}}) {
        my %row_data=();
        $row_data{link}="$self_url/$lname/$year/$month/${%{$fu}}{name}";
        $row_data{subject}=${%{$fu}}{subject};
        $row_data{subject}='No subject' unless ($row_data{subject});
        $row_data{from}=Email_To_Name(${%{$fu}}{from});
        $row_data{from}='Unknown' unless ($row_data{from});
        push(@follow_ups,\%row_data);
    }
    $template->param(follow_ups=>\@follow_ups) if (scalar(@follow_ups));

    $msg_id=~m/^(0*)([^0]{1}.*)$/;
    my ($zeros,$rest)=($1,$2);
    my $prev_id=$zeros.($rest-1);
    my $next_id=$zeros.($rest+1);

    $template->param(date_prev=>Prev_Message($lname,$year,$month,$msg_id));
    $template->param(date_next=>Next_Message($lname,$year,$month,$msg_id));


    if ($msg{thread_prev}) {
        $template->param(thread_prev=>"$self_url/$lname/$year/$month/$msg{thread_prev}");
    }
    if ($msg{thread_next}) {
        $template->param(thread_next=>"$self_url/$lname/$year/$month/$msg{thread_next}");
    }
    
    $msg{body}=${OC::Filter_Emails(\$msg{body},1,$lname,$year,$month,$msg_id)};
    $msg{to}=${OC::Filter_Emails(\$msg{to},1,$lname,$year,$month,$msg_id)};
    $msg{from}=${OC::Filter_Emails(\$msg{from},1,$lname,$year,$month,$msg_id)};
    $msg{subject}=${OC::Filter_Emails(\$msg{subject},0,$lname,$year,$month,$msg_id)};

    my $cnt=0;
    while ($msg{body}=~m!^(.*)<pre>(.*)</pre>(.*)$!si) {
        my $p1=$1;
        my $p2=$2;
        my $p3=$3;
        $p2=~s/\n\n/<p>/g;
        $p2=~s/\n/<br>/g;
        $msg{body}=$p1.$p2.$p3;
        $cnt++;
        if ($cnt>10) {
            OC::Log("While loop error!!!");
            last;
        }
       
    }


    $template->param(
        date_index=>"$self_url/$lname/$year/$month/?view=date",
        thread_index=>"$self_url/$lname/$year/$month/?view=thread",
        from=>$msg{from},
        to=>$msg{to},
        subject=>$msg{subject},
        date=>$msg{date},
        reply_to=>$msg{reply_to},
        body=>$msg{body},
        message_url=>"$self_url/$lname/$year/$month/$msg_id",
        page_title=>$msg{subject}
    );
}

sub Tmpl_Fill_Reply {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my %msg=%{$list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{message}};
    my $subject=$msg{subject};
    $subject='Re: '.$subject unless ($subject=~m/^ *re:/i);
    my $from=$cookie{post_from};
    my $body=Html2Text($msg{body});
    $body=Format_Text($body,$textarea_width-2);   
    $body='> '.$body; 
    $body=~s/\r?\n/\n> /gs;
    my $cc='';
    $cc="\n$msg{cc}" if ($msg{cc});
    my $date='';
    $date="\nDate: $msg{date}" if ($msg{date});
    my $header="\n\n\n".
      "----- Original Message -----\n".
      "From: $msg{from}\n".
      "To: $msg{to}$cc$date\n".
      "Subject: $msg{subject}\n";
    $body=Format_Text($header,$textarea_width-2)."\n".$body;

    my $to=$msg{from};

    if ($msg{reply_to} ne '') {
        $to=$msg{reply_to};
    }
    my %tmp=();
    $tmp{from}=$msg{from};
    $tmp{cc}=$msg{cc};
    $tmp{reply_to}=$msg{reply_to};
    foreach (qw(from cc reply_to)) {
        $tmp{from}='' if ($tmp{$_} eq $tmp{from} && $_ ne 'from');
        $tmp{cc}='' if ($tmp{$_} eq $tmp{cc} && $_ ne 'cc');
        $tmp{reply_to}='' if ($tmp{$_} eq $tmp{reply_to} && $_ ne 'reply_to');
    }
    if ($cmd eq 'reply_all') {
        $to=join(', ', ($tmp{from},$tmp{cc},$tmp{reply_to}));
    }
    $to=~s/, , /, /g;
    $to=~s/, *$//g;

    my @tmp=();
    foreach (split(/, /,$to)) {
        my $list='a-z0-9_-';
        if ($_=~m/([\.$list]+\@[\.$list]+\.[$list]+)/i) {
            $_=$1;
        }
        $_=~s/^ *| *$//;
        SendSQL("select hash from email_hash where email='$_'");
        my $result=FetchSQLData;
        push(@tmp,$result);
    }
    my $to_hash=join(',',@tmp);
    my @tmp=();
    foreach ($lname,$year,$month,$msg_id) {
        push(@tmp,$_)  if (defined $_);
    }
    my $post_url=join('/',$self_url,@tmp,'send');

    $template->param(
        post_url=>$post_url,
        to=>${OC::Filter_Emails(\$to,0)},
        to_hash=>$to_hash,
        subject=>$subject,
        from=>$from,
        body=>${OC::Filter_Emails(\$body,0)},
    );
    
}

sub Tmpl_Fill_Post {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my $from=$cookie{post_from};
    my $to='';
    my $to_hash='';
    if ($form{to}) {
        SendSQL("select email from email_hash where hash='$form{to}'");
        ($to)=FetchSQLData;
        $to_hash=$form{to};
    } else {
        $to="$lname\@opencores.org";
        $to_hash=OC::Store_Email($to);
    }
    $to=${OC::Filter_Emails(\$to,0)};
    my @tmp=();
    foreach ($lname,$year,$month,$msg_id) {
        push(@tmp,$_)  if (defined $_);
    }
    my $post_url=join('/',$self_url,@tmp,'send');
    $template->param(
        from=>$from,
        to=>$to,
        to_hash=>$to_hash,
        post_url=>$post_url,
    );
}

sub Tmpl_Fill_Send {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my $subject=$form{subject};
    my $from=$form{from};
    foreach ($from,$subject) {
        $_=~s/^ *//;
        $_=~s/ *$//;
    }
    my @error=();
    unless ($from=~m/.+\@.+\..+/i) {
        push(@error,"Invalid from address!");
    }
    unless ($subject=~m/.+/i) {
        push(@error,"Message must have subject..");
    }
    unless ($form{body}=~m/.+/i) {
        push(@error,"Cannot send an empty message..");
    }
    my @bad_result=();
    my @to=();
    my @to_hash=split(',',$form{to});
    foreach (@to_hash) {
        SendSQL("select email from email_hash where hash='$_'");
        my $to_email=FetchSQLData;
        if ($to_email ne '') {
            push(@to,$to_email);
        } else {
            push(@bad_result,"Invalid hash: $_");
        }
    }
    my $set_cookie;
    if (scalar(@bad_result)) {
        my $result=>join('<br>',@bad_result);
        $template->param(
            result=>$result,
        );
    } elsif (scalar(@error)>0) {
        my $error=join('<br>',@error);
        $error="<font color=red>$error</font>";
        my @tmp=();
        foreach ($lname,$year,$month,$msg_id) {
            push(@tmp,$_)  if (defined $_);
        }
        my $post_url=join('/',$self_url,@tmp,'send');
        my $to=join(', ',@to);
        $template->param(
            post_url=>$post_url,
            error=>$error,
            from=>$form{from},
            subject=>$form{subject},
            body=>$form{body},
            to_hash=>$form{to},
            to=>${OC::Filter_Emails(\$to,0)},
        );
    } else {
        my $result='';
        my $to=join(', ',@to);
        my $sender=new Mail::Sender{
            smtp=>$smtp_host,
            from=>$from,
            to=>'mlampret@opencores.org',
            subject=>$subject,
	    headers => "X-Originating-IP: $ENV{REMOTE_ADDR}\r\n",
        };
        my %msg=();
        $msg{header}{from}=$from;
        $msg{header}{to}=$to;
        $msg{header}{subject}=$subject;
        $msg{body}=$form{body};
        Send_Mail(\%msg);
        my $date=`date`;
        system("echo \"$date\tIp: $ENV{'REMOTE_ADDR'}\n\tFrom: $form{from}\n\tTo: $to\n\tSubject: $subject\n\t\n\" >> /tmp/forumpost.log");
        $result="Message successfully sent.";
        $set_cookie=1 if ($cookie{post_from});

        $template->param(
            result=>$result, 
        );
    }
    if ($set_cookie) {
        my $cookie=cookie(
            -name=>"post_from",
            -value=>$from,
            -expires=>'+1y',
        );
        print header(
            -cookie=>[$cookie],
            -type=>'text/html',
            -charset=>''
        );
    } else {
        print Header;
    }
}

sub Tmpl_Fill_List_Screen {
    my ($lname)=@_;
    my @restrict=();
    my %row=();
    $row{path}="$self_url/$lname";
    $row{display}=$list{$lname}{name};
    push(@restrict,\%row);
    my %row=();
    $row{path}=$self_url;
    $row{display}='All forums';
    push(@restrict,\%row);
    my @subscribe_to=();
    my %row=();
    $row{list}="$lname";
    $row{display}="$lname";
    push(@subscribe_to,\%row);
    if ($list{$lname}{has_digest}) {
        my %row=();
        $row{display}="$lname-digest";
        $row{list}="$lname-digest";
        push(@subscribe_to,\%row);
    }
    $template->param(
        subscribe_action=>"$self_url/$lname/subscribe",
        subscribe_to=>\@subscribe_to,
        search_action=>"$self_url/$lname/search",
        restrict=>\@restrict,
    );
}

sub Tmpl_Fill_Search {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my $result=`$CONFIG{htsearch} "words=$form{words}&restrict=$form{restrict}"`;

    my ($selected_list,$selected_all)='';
    if ($form{restrict}=~m!$lname!) {
        $selected_list=' selected  ';
    } else {
        $selected_all=' selected ';
    }
    $result=~s/^.*\n//;
    $result=~s/.*Search results//s;
    $result=~s!If the.*$!!s;
    $result=~s!<hr noshade size="1">\n*<b>Advanced search</b>.*$!!s;
    $result.="<hr size=1 noshade><p><b>Search again</b><p>".
      "<form action='$self_url/$lname/search'>
      in forum <select name=restrict>
      <option $selected_list value='$self_url/$lname'>$list{$lname}{name}</option>
      <option $selected_all value='$self_url/'>All forums</option>
      </select> for words
      <input type=query name=words value='$form{words}'><input type=submit value='Search'></form>
    ";

    $template->param(
        page_title=>"Search results",
        title=>"Search results",
        body=>"$result",
    );

}

sub Tmpl_Fill_Subscribe {
    Note("Subscribe");
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    my $body='';

    if ($form{email}=~m/^.+\@.+\..+/ && $form{list} ne '' ) {
        my %msg=();
        $msg{header}{from}=$form{email};
        $msg{header}{to}=$CONFIG{majordomo_email};
        $msg{header}{subject}='Subscribe';
        $msg{body}="subscribe $form{list}";
        Send_Mail(\%msg);
        $body='You will receive an e-mail report about your request.';
    } else {
        $body="Subscribe failed. Invalid email address: '$form{email}'";   
    }

    $template->param(
        page_title=>"Subscribe",
        title=>"Subscribe",
        body=>$body,
    );
}

sub Output_Default_Template {
    Tmpl_Fill_Navigation;
    Tmpl_Fill_Lists;
}

sub Output_List_Template {
    my ($lname,$year)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Month_Table($lname,$year);
    Tmpl_Fill_Navigation($lname);
    Tmpl_Fill_List_Screen($lname);
    Tmpl_Fill_Common($lname);
}


sub Output_Folder_Template {
    my ($lname,$year,$month)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Folder($lname,$year,$month);
}

sub Output_Message_Template {
    my ($lname,$year,$month,$msg_id)=@_;
    Tmpl_Fill_Month_Table($lname); 
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Message($lname,$year,$month,$msg_id);
}

sub Output_Reply_Template {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id,$cmd);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Reply($lname,$year,$month,$msg_id,$cmd);
}

sub Output_Post_Template {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id,$cmd);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Post($lname,$year,$month,$msg_id,$cmd);
}

sub Output_Send_Template {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id,$cmd);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Send($lname,$year,$month,$msg_id,$cmd);
}

sub Output_Search_Template {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id,$cmd);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Search($lname,$year,$month,$msg_id,$cmd);
}

sub Output_Subscribe_Template {
    my ($lname,$year,$month,$msg_id,$cmd)=@_;
    Tmpl_Fill_Lists($lname);
    Tmpl_Fill_Navigation($lname,$year,$month,$msg_id,$cmd);
    Tmpl_Fill_Common($lname);
    Tmpl_Fill_Subscribe($lname,$year,$month,$msg_id,$cmd);
}

sub Output {
    print $template->output;
}

sub Print_Lists {
    foreach (keys %list) {
        Note("'$_'");
    }
}

sub First_Page {
    my ($sec,$min,$hour,$mday,$month,$year)=localtime(time);
    my $lname='cores';
    $year+=1900;
    $month++;
    if (length($month)<2) {
        $month='0'.$month;
    }
    List_By_Month($lname);
    Month_By_Thread($lname,$year,$month);
    Month_By_Date($lname,$year,$month);
    my @last_five=();
    my $reply=0;
    my $displays=3;
    foreach my $msg_id (keys %{$list{$lname}{year}{$year}{$month}{by_thread}}) {
        my $subject=$list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{subject};
        my $depth=$list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{depth};
        if ($depth==1 && !($subject=~m/no subject/i) && scalar(@last_five)<$displays) {
            my %msg=();
            $subject=~s/^\[oc\] //;
            if (length($subject)>30) {
                $subject=substr($subject,0,27).'...';
            }
            $msg{subject}=ucfirst($subject);
            Parse_Message($lname,$year,$month,$msg_id,"thread");
            my $body=$list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{message}{body};
            $msg{body}=Html2Text($body);
            $msg{from}=Email_To_Name($list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{message}{from});
            $msg{date}=$list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{message}{date};
            $msg{date}=~s/[a-z]*,//i;
            $msg{date}=~s/[ 0-9A-Z\(\):+-]{4,15}$//i;
            $msg{date}=~s/[0-9]+:[0-9]+$//i;
            my @tmp=split(/ /,$msg{body});
            $msg{link}="$CONFIG{forum_url}/cores/$year/$month/$msg_id";
            $msg{body}='';
            foreach (0..50) {
                $msg{body}.=$tmp[$_];
                $msg{body}.=' ' if ($_<50);
            }
            $msg{body}.='...';
            $msg{reply}=$reply;
            push(@last_five,\%msg);
            $reply=0;
            last if (scalar(@last_five)>=$displays);
        } else {
            $reply++;
        }
     }
    foreach my $msg (@last_five) {
        my %msg=%{$msg};
        print "<b>$msg{subject}</b><br>";
        print "<i>$msg{date} - $msg{from}</i></i><br>";
        print "$msg{body}";
        print "<table width=100%><tr><td align=right><a href='$msg{link}'>Read more</a></td></tr></table>";
    }
}

sub Main {
    Initialize;
    ConnectToDatabase;

    Get_Lists;

    if ($form{cmd} eq 'first_page') {
        print Header;
        First_Page;
        exit;
    }

    if ($ARGV[0] eq '-fp') {
        First_Page;
        exit;
    }

    my ($junk,$lname,$year,$month,$msg_id,$cmd)=split(/\//,$ENV{PATH_INFO});
    foreach ($lname,$year,$month,$msg_id,$cmd) {
        $_=undef if ($_ eq '');
        if (defined $lname && $_ eq 'post' && exists $list{$lname} && exists $list{$lname}{name}) {
            $_=undef;
            $cmd='post';
        }
        if ($_ eq 'send') {
            $_=undef;
            $cmd='send';
        }
        if ($_ eq 'search') {
            $_=undef;
            $cmd='search';
        }
        if ($_ eq 'subscribe') {
            $_=undef;
            $cmd='subscribe';
        }
    }
    if ($lname eq 'post') {
        $lname=undef;
        $cmd='post';
    }


    my $view_type='default';


    if (defined $lname && exists $list{$lname} && exists $list{$lname}{name}) {
        $view_type='list';
        List_By_Month($lname);
        if (exists $list{$lname}{year}{$year} && $list{$lname}{year}{$year}{$month}{msg_count}>0) {
            $view_type='folder';
            if ($form{view} eq 'thread') {
                Month_By_Thread($lname,$year,$month);
            } else {
                Month_By_Date($lname,$year,$month);
            }
            if (defined $msg_id && (($list{$lname}{year}{$year}{$month}{by_thread}{$msg_id}{file} ne '' && $form{view} eq 'thread')
              || ($list{$lname}{year}{$year}{$month}{by_date}{$msg_id}{file} ne '' && $form{view} ne 'thread'))) {
                if ($cmd=~m/^(reply|reply_all)$/) {
                    $view_type='post';
                    Parse_Message($lname,$year,$month,$msg_id,$form{view});
                } elsif ($cmd ne 'post' && $cmd ne 'send') {
                    $view_type='message';
                    Parse_Message($lname,$year,$month,$msg_id,$form{view});
                }
            }
        }
    }

    if ($cmd=~m/^(post|send)$/) {
        $view_type='post';
    } elsif ($cmd=~m/^(search|subscribe)$/) {
        $view_type='empty';
    }

    Prepare_Template($CONFIG{'tmpl_'.$view_type.'_file'});
    
    if ($cmd eq 'subscribe') {
        Output_Subscribe_Template($lname,$year,$month,$msg_id,$cmd);
    } elsif ($cmd eq 'search') {
        Output_Search_Template($lname,$year,$month,$msg_id,$cmd);
    } elsif ($cmd eq 'send') {
        Output_Send_Template($lname,$year,$month,$msg_id,$cmd);
    } elsif ($cmd eq 'post') {
        Output_Post_Template($lname,$year,$month,$msg_id,$cmd);
    } elsif ($cmd=~m/^(reply|reply_all)$/ && $view_type eq 'post') {
        Output_Reply_Template($lname,$year,$month,$msg_id,$cmd);
    } elsif ($view_type eq 'message') {
        Output_Message_Template($lname,$year,$month,$msg_id);
    } elsif ($view_type eq 'folder') {
        Output_Folder_Template($lname,$year,$month);
    } elsif ($view_type eq 'list') {
        Output_List_Template($lname,$year);
    } else {
        Output_Default_Template;
    }

    print Header if ($cmd ne 'send');

    if ($form{cmd} eq 'xemails') {
        print "<table border=1>";
        SendSQL("select email,hash from email_hash order by email");
        while (my @result=FetchSQLData) {
            print "<tr><td>$result[0]</td><td>http://www.opencores.org$CONFIG{post_url}?to=$result[1]</td></tr>";
        }
        print "</table>";
    } else {
        Output;
    }

#    foreach my $note (@NOTE) {
#        print "${%{$note}}{note}<br>";
#    }
        
}

Main;