package Boards;
use strict;
use Time::Local;
#################################################################################
# Ikonboard v3 by Jarvis Entertainment Group, Inc.
#
# No parts of this script can be used outside Ikonboard without prior consent.
#
# More information available from <ib-license@jarvisgroup.net>
# (c)2001 Jarvis Entertainment Group, Inc.
# 
# http://www.ikonboard.com
#
# Please Read the license for more information
#+-----------------------------------------------------------------+
#
# Boards: Display the board summary
#
#################################################################################

BEGIN { require 'Lib/FUNC.pm'; }

my $std    = FUNC::STD->new();
my $output = FUNC::Output->new();

my $cats_printed = {};
    
sub new {
    my $pkg = shift;
    my $obj = { '_html' => undef, 'nav' => [] };
    bless $obj, $pkg;
    return $obj;
}


sub ShowStart {
    my ($obj, $db) = @_;
    

    $Boards::lang = $std->LoadLanguage('BoardWords');
    require $iB::SKIN->{'DIR'} . '/BoardsView.pm' or die $!;


    $obj->{'_html'} .= BoardsView::PageTop();

    $obj->{'TOTAL_CATS'}   = $db->query(TABLE     => 'categories',
                                        SORT_KEY  => 'CAT_POS',
                                        SORT_BY   => 'A-Z',
                                        MATCH     => 'ALL',
                                      ) || die $db->{'error'};

    $obj->{'MODERATORS'}   = $db->query(TABLE     => 'forum_moderators',
                                        SORT_KEY  => 'MEMBER_NAME',
                                        SORT_BY   => 'A-Z',
                                        MATCH     => 'ALL'
                                      ) || die $db->{'error'};

    
    $obj->{'TOTAL_FORUMS'} = $db->query(TABLE     => 'forum_info',
                                        SORT_KEY  => 'FORUM_POSITION',
                                        SORT_BY   => 'A-Z',
                                        MATCH     => 'ALL'
                                      ) || die $db->{'error'};

    unless (-e $iB::PTH.'/Data/ForumJump.pm') {
        $std->build_forumjump( DB     => $db,
                               CATS   => $obj->{'TOTAL_CATS'},
                               FORUMS => $obj->{'TOTAL_FORUMS'}
                             );
    }
    
    # Build up a list of categories that contain a sub category.
    
    $obj->{subcat} = {};
    
    my $i = 0;
    for (@{$obj->{TOTAL_CATS}}) {
        if ($_->{SUB_CAT_ID}) {
            unless ($obj->{subcat}->{$_->{SUB_CAT_ID}}) {
                $obj->{subcat}->{$_->{SUB_CAT_ID}} = [];
            }
            push @{$obj->{subcat}->{$_->{SUB_CAT_ID}}}, { 
                                                          ID  => $_->{CAT_ID},
                                                          IDX => $i
                                                        };
        }
        ++$i;
    }
    
    # Are we printing a total list of all the forums and
    # categories, or just the category only?

    $iB::IN{'act'} eq 'SC' ? $obj->show_cat($db) : $obj->show_list($db);
    

    # Print the footer stuff based on the users prefs
    
    if ($iB::INFO->{'SHOW_ONLINE'}) {
        my $Names;
        # Get the formatting options
        my %format;
        for (split /\|/, $iB::INFO->{AU_FORMAT}) {
            /^(\d+)\~(.+?),(.+?)$/;
            $format{ $1 } = { ST  => $2, END => $3 };
        }
        foreach (@{ $iB::ACTIVE->{'NAMES'} }) {
            $Names .= qq! <span id='highlight'>&gt;</span><a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?act=Profile;CODE=03;MID=$_->{'ID'}'>$format{ $_->{GROUP} }->{ST}$_->{'NAME'}$format{ $_->{GROUP} }->{END}</a>!;
        }
    
        my $link = $iB::INFO->{'ALLOW_ONLINE_LIST'} ? qq|&nbsp;&nbsp;[ <a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Online;CODE=listall">$Boards::lang->{'browser_user_list'}</a> ]| : '';
        
        $obj->{'_html'} .= BoardsView::ActiveUsers($Names,
                                  $link,
                                  $iB::ACTIVE->{'MEMBERS'} || 0,
                                  $iB::ACTIVE->{'GUESTS'}  || 0,
                                  $iB::ACTIVE->{'ANON'}    || 0,
                                  $iB::ACTIVE->{'MEMBERS'} + $iB::ACTIVE->{'GUESTS'} + $iB::ACTIVE->{'ANON'} || 0,
                                 );

        # Added by Infection

        if ($iB::INFO->{'CALENDAR'}) {
           my @data  = localtime;
           my $day   = $data[3];
           my $month = $data[4] + 1; #because months begin from 0 to 11 in array!
           my $year;
   
           my $birth_users = $db->query( TABLE => 'calendar',
                                         WHERE => qq[DAY == '$day' and MONTH == '$month'],
                                        );
   
           my $birth_lang;
           my ($time_adjust,$dat,$data,$newdata,@dat,$birthusers,$i);
           foreach my $w (@{$birth_users}) {
                if ($w->{'YEAR'}) {
                    $year = $data[5] + 1900 - $w->{'YEAR'};
                    $year = "(<b>".$year."</b>)";
                }
                $data  = time + ($iB::INFO->{'TIME_ZONE'} * 3600) + ($iB::MEMBER->{TIME_ADJUST}*3600);
                $dat   = timelocal(0,0,0,$w->{'DAY'},--$w->{'MONTH'},$data[5]+1900);
                @dat   = localtime($data);
                if ($dat[3] == $w->{'DAY'}) {
                    $i++;
                    $birthusers .= qq~<span id='highlight'>&gt;</span><a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?act=Profile;CODE=03;MID=$w->{'MEMBER_ID'}'>$w->{'MEMBER_NAME'}</a> $year ~;
                }
           }
           if ($i > 0) {
               $birth_lang = ($i > 1)?$Boards::lang->{'birth_users'}:$Boards::lang->{'birth_user'};
           } else {
               $birth_lang = $Boards::lang->{'no_birth_users'}
           }
           
           my $birthday = BoardsView::birthday( $birthusers, $i, $birth_lang );
           
           $obj->{'_html'} =~ s#<!--BIRTHDAY HTML-->#$birthday#i;
           
        }

    }
    

    if ($iB::INFO->{'USE_SSI'}) {
        require SSI::Parser;
        my $names = {};
        foreach (@{ $iB::ACTIVE->{'NAMES'} }) {
            $names->{ $_->{'NAME'} } = qq~$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?act=Profile;CODE=03;MID=$_->{'ID'}~;
        }

        SSI::Parser::parse( DB       => $db,
                            TEMPLATE => 'ONLINE_LIST',
                            EXTRA    => $names
                          );

        SSI::Parser::parse( DB       => $db,
                            TEMPLATE => 'ONLINE_COUNT',
                            VALUES   => { "number of guests"  => $iB::ACTIVE->{'GUESTS'},
                                          "number of members" => $iB::ACTIVE->{'MEMBERS'},
                                          "total online"      => $iB::ACTIVE->{'MEMBERS'} + $iB::ACTIVE->{'GUESTS'} + $iB::ACTIVE->{'ANON'} || 0
                                        }
                          );
    }



   
    if ($iB::INFO->{'SHOW_STATS'}) {
        my $stats = $std->ib_stats;
        $stats->{'M_ONLINE_COUNT'} ||= 0;
        # Do we have more users on this time than ever before?
        my $current_user_count = $iB::ACTIVE->{'MEMBERS'} + $iB::ACTIVE->{'GUESTS'} + $iB::ACTIVE->{'ANON'};
        if ($current_user_count > $stats->{'M_ONLINE_COUNT'}) {
            $std->ib_stats( { M_ONLINE_COUNT => $current_user_count, M_ONLINE_DATE  => time } );
            $stats->{'M_ONLINE_COUNT'} = $current_user_count;
            $stats->{'M_ONLINE_DATE'}  = time;
        }
        $stats->{'M_ONLINE_DATE'} = $std->get_date( TIME => $stats->{'M_ONLINE_DATE'}, METHOD => 'LONG');
        $Boards::lang->{'most_online'} =~ s!<#NUM#>!$stats->{'M_ONLINE_COUNT'}!;
        $Boards::lang->{'most_online'} =~ s!<#DATE#>!$stats->{'M_ONLINE_DATE'}!;
        $obj->{'_html'} .= BoardsView::ShowStats($stats);
    }   
    



    $obj->{'_html'} .= BoardsView::Invite_Friend() if ($iB::INFO->{'INVITE_FRIEND'} and $iB::MEMBER_GROUP->{'INVITE_FRIEND'});
    $obj->{'_html'} .= BoardsView::BoardInformation();

    $output->print_ikonboard( DB => $db, STD => $std, OUTPUT  => $obj->{'_html'}, TITLE => $iB::INFO->{'BOARDNAME'}, NAV => $obj->{'nav'});
    undef $obj->{'_html'};
}




sub show_list {
    my ($obj, $db) = @_;

    for my $this_cat (@{ $obj->{'TOTAL_CATS'} }) {
    
        # Is it on?
        
        next unless $this_cat->{CAT_STATE};
        
        # If it's a sub category, don't print it yet.
        next if $this_cat->{SUB_CAT_ID};

        #XXX Skip it if the category has already been printed or we don't have permission to view the category

        #next if exists $cats_printed->{ $this_cat->{'CAT_ID'} };

        if ($this_cat->{'VIEW'} ne '*') {
            next unless grep { $_ == $iB::MEMBER->{'MEMBER_GROUP'} } (split (/,/, $this_cat->{'VIEW'}) );
        }

        #XXX Grab all the forums in this main category
        
        my @these_cat_forums = grep { $_->{'CATEGORY'} == $this_cat->{'CAT_ID'} } @{ $obj->{'TOTAL_FORUMS'} };
        $this_cat->{CAT_SPONSOR} = '&nbsp;';
        if ($this_cat->{URL} and $this_cat->{IMAGE}) {
            $this_cat->{IMAGE}       = "<img src='$this_cat->{IMAGE}' border='0' alt=''>";
            $this_cat->{CAT_SPONSOR} = "<a href='$this_cat->{URL}' target='_blank'>$this_cat->{IMAGE}</a>";
        }
        
        $obj->{'_html'} .= BoardsView::CatHeader_Expanded($this_cat);

        #XXX Grab any sub categories in this main category

        if (exists $obj->{subcat}->{$this_cat->{'CAT_ID'}}) { 
            for (@{$obj->{subcat}->{$this_cat->{'CAT_ID'}}}) {
                $obj->{'_html'} .= $obj->render_subcat( @{$obj->{TOTAL_CATS}}[ $_->{IDX} ] );
            }
        }
    
        #XXX Print the rest of the forums (if there are any!)
        
        for my $this_forum (@these_cat_forums) {
        
            $obj->{'_html'} .= $obj->render_forum($this_forum);

        }
        
    }
}




sub show_cat {
    my ($obj, $db) = @_;

    $std->Error( DB => $db, STD => $std, MESSAGE => 'no_action') unless defined $iB::IN{'c'};

    my $this_cat = $db->select( TABLE => 'categories',
                                KEY   => $iB::IN{'c'}
                              );

    if ($this_cat->{'VIEW'} ne '*') {
        unless ( grep { $_ == $iB::MEMBER->{'MEMBER_GROUP'} } (split (/,/, $this_cat->{'VIEW'}) ) ) {
            $std->Error( DB => $db, STD => $std, MESSAGE => 'no_permission');
        }
    }

    my @these_cat_forums = grep { $_->{'CATEGORY'} == $this_cat->{'CAT_ID'} } @{ $obj->{'TOTAL_FORUMS'} };

    if ($this_cat->{'SUB_CAT_ID'}) {
        my $sub_cat = $db-> select( TABLE => 'categories',
                                    KEY   => $this_cat->{'SUB_CAT_ID'}
                                  );
        push @{ $obj->{'nav'} }, qq[<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=SC;c=$sub_cat->{'CAT_ID'}" class='nav'>$sub_cat->{'CAT_NAME'}</a>];
    }

    push @{ $obj->{'nav'} }, qq!$this_cat->{'CAT_NAME'}!;

    $obj->{'_html'} .= BoardsView::CatHeader_Expanded($this_cat);

    #XXX Grab any sub categories in this main category

    if (exists $obj->{subcat}->{$this_cat->{'CAT_ID'}}) { 
        for (@{$obj->{subcat}->{$this_cat->{'CAT_ID'}}}) {
            $obj->{'_html'} .= $obj->render_subcat( @{$obj->{TOTAL_CATS}}[ $_->{IDX} ] );
        }
    }
    
    for my $this_forum (@these_cat_forums) {
    
        $obj->{'_html'} .= $obj->render_forum($this_forum);
        
    }
}





####################################################################
#
# Parses all the info and returns the created HTML for a cat entry
#
####################################################################


sub render_subcat {
    my ($obj, $subcat) = @_;
    
    #XXX: Grab all the forums for this sub category

    my @these_sub_cat_forums = grep { $_->{'CATEGORY'} == $subcat->{'CAT_ID'} } @{ $obj->{'TOTAL_FORUMS'} };
    
    for my $forum (@these_sub_cat_forums) {
        if ($forum->{'FORUM_VIEW_THREADS'} ne '*') {
            next unless grep { $_ == $iB::MEMBER->{'MEMBER_GROUP'} } (split /,/,$forum->{'FORUM_VIEW_THREADS'});
        }
        $subcat->{'TOTAL_FORUMS'} += 1;
        $subcat->{'POSTS'}        += $forum->{'FORUM_POSTS'};
        $subcat->{'TOPICS'}       += $forum->{'FORUM_TOPICS'};
        if ($forum->{'FORUM_LAST_POST'} > $subcat->{'LAST_POST'}) {
            $subcat->{'LAST_POST'}         = $forum->{'FORUM_LAST_POST'};
            $subcat->{'LAST_POSTER_N'}     = $forum->{'FORUM_LAST_POSTER_N'};
            $subcat->{'LAST_POSTER'}       = $forum->{'FORUM_LAST_POSTER'};
            $subcat->{'TOPIC_TITLE'}       = $forum->{'L_TOPIC_TITLE'};
            $subcat->{'FORUM_ID'}          = $forum->{'FORUM_ID'};
            $subcat->{'TOPIC_ID'}          = $forum->{'L_TOPIC_ID'};
            $subcat->{'NEW_POST_IMG'}      = $obj->new_cat_posts($forum);
            $subcat->{'_is_private'}       = $forum->{'FORUM_PROTECT'};
        }
    }
    
    # Make sure we have a last post image:
    $subcat->{'NEW_POST_IMG'}      ||= $obj->new_cat_posts({FORUM_LAST_POST => $subcat->{'LAST_POST'}});
    
    
    $subcat->{'LAST_POST'}  = $std->get_date( TIME => $subcat->{'LAST_POST'}, METHOD => 'LONG');
    $subcat->{'LAST_POST'}  = '--' unless $subcat->{'LAST_POST'};
    $subcat->{'N_LINK'}     = ($subcat->{'TOPIC_TITLE'} and defined $subcat->{'TOPIC_ID'})
                              ? qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=ST;f=$subcat->{'FORUM_ID'};t=$subcat->{'TOPIC_ID'}'>$subcat->{'TOPIC_TITLE'}</a>]
                              : $Boards::lang->{'f_none'};
                              
    if ($subcat->{'_is_private'}) {
        $subcat->{'N_LINK'} = $Boards::lang->{'f_protected'};
    }

    if ($subcat->{'LAST_POSTER_N'}) {
        $subcat->{'P_LINK'} = $subcat->{'LAST_POSTER'} ? qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$subcat->{'LAST_POSTER'}'>$subcat->{'LAST_POSTER_N'}</a>]
                                                           : $subcat->{'LAST_POSTER_N'};
    }
    $subcat->{'P_LINK'} = $Boards::lang->{'f_none'} unless $subcat->{'P_LINK'};
    
    # Because in perl, 1 minus 1 equals -1 (can't be zero as zero is 'nothing') we need
    # to make it human readable..
    $subcat->{'POSTS'} = 0  if $subcat->{'POSTS'} < 0;
    $subcat->{'TOPICS'} = 0 if $subcat->{'TOPICS'} < 0;

    #XXX Are there any forums in this category that we're allowed to see?
    #XXX If not, there's no point printing it...
    
    $cats_printed->{ $subcat->{'CAT_ID'} } = 1;
    
    if ($subcat->{'TOTAL_FORUMS'} > 0) {
        return BoardsView::CatHeader_Collapsed($subcat);
    }
}              
               

####################################################################
#
# Parses all the info and returns the created HTML for a forum entry
#
####################################################################

sub render_forum {
    my ($obj, $this_forum) = @_;
    
    # Double check the validity of the BD
    next unless defined $this_forum->{'FORUM_ID'};

    if ($this_forum->{'FORUM_VIEW_THREADS'} ne '*') {
        next unless grep { $_ == $iB::MEMBER->{'MEMBER_GROUP'} } (split /,/,$this_forum->{'FORUM_VIEW_THREADS'});
    }

    $this_forum->{'N_LINK'} = ($this_forum->{'L_TOPIC_TITLE'} and defined $this_forum->{'L_TOPIC_ID'})
                            ? qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=ST;f=$this_forum->{'FORUM_ID'};t=$this_forum->{'L_TOPIC_ID'}' class='misc'>$this_forum->{'L_TOPIC_TITLE'}</a>]
                            : $Boards::lang->{'f_none'};
                            
    if ($this_forum->{'FORUM_LAST_POSTER_N'}) {
        $this_forum->{'P_LINK'} = $this_forum->{'FORUM_LAST_POSTER'} ? qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$this_forum->{'FORUM_LAST_POSTER'}' class='misc'>$this_forum->{'FORUM_LAST_POSTER_N'}</a>]
                                                                 : $this_forum->{'FORUM_LAST_POSTER_N'};
    } else {
        $this_forum->{'P_LINK'} = $Boards::lang->{'f_none'};
    }

    if ($this_forum->{'FORUM_PROTECT'}) {
        next unless $iB::MEMBER->{'MEMBER_ID'};
        $this_forum->{'N_LINK'} = qq[$Boards::lang->{'f_protected'}];
        $this_forum->{'P_LINK'} = '--';
    }

    $this_forum->{'NEW_POST_IMG'}       = $obj->new_posts($this_forum);
    $this_forum->{'FORUM_LAST_POST'}    = $std->get_date( TIME => $this_forum->{'FORUM_LAST_POST'}, METHOD => 'LONG');
    $this_forum->{'FORUM_USERS'}        = $iB::ACTIVE->{'FORUMS'}->{ $this_forum->{'FORUM_ID'} } || 0;
                                    
    my @mods;
    for ( grep { $this_forum->{'FORUM_ID'} == $_->{'FORUM_ID'} } @{ $obj->{'MODERATORS'} }  ) {
        push @mods, "<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$_->{'MEMBER_ID'}'>$_->{'MEMBER_NAME'}</a>";
    }

    $this_forum->{'MODERATOR'} = $Boards::lang->{'forum_leader'} . join ", ", @mods if @mods > 0;
    
    # Because in perl, 1 minus 1 equals -1 (can't be zero as zero is 'nothing') we need
    # to make it human readable..
    $this_forum->{'FORUM_TOPICS'} = 0  if $this_forum->{'FORUM_TOPICS'} < 0;
    $this_forum->{'FORUM_POSTS'}  = 0  if $this_forum->{'FORUM_POSTS'}  < 0;        
	
	
    return BoardsView::ForumRow($this_forum);
}



sub new_cat_posts {
    my ($obj, $this_forum) = @_;
    my $fcookie   = $iB::COOKIES->{ $iB::INFO->{COOKIE_ID}.'forum-'.$this_forum->{FORUM_ID} };
    my $lastvisit = $fcookie && $fcookie > $iB::last_visit ? $fcookie : $iB::last_visit;
    return $iB::SKIN->{'C_OFF_CAT'} unless $this_forum->{'FORUM_POSTS'} > 0 or $lastvisit;
    return $this_forum->{'FORUM_LAST_POST'} > $lastvisit  ? $iB::SKIN->{'C_ON_CAT'}
                                                          : $iB::SKIN->{'C_OFF_CAT'};
}


sub new_posts ($) {
    my ($obj, $this_forum) = @_;
    return $iB::SKIN->{'C_LOCKED'} unless $this_forum->{'FORUM_STATUS'};
    
    my $fcookie   = $iB::COOKIES->{ $iB::INFO->{COOKIE_ID}.'forum-'.$this_forum->{FORUM_ID} };
    my $lastvisit = $fcookie && $fcookie > $iB::last_visit ? $fcookie : $iB::last_visit;
    
    if ($this_forum->{'FORUM_PROTECT'}) {
        return $this_forum->{'FORUM_LAST_POST'} > $lastvisit  ? $iB::SKIN->{'C_ON_RES'}
                                                              : $iB::SKIN->{'C_OFF_RES'};
    }
    return $iB::SKIN->{'C_OFF'} unless $lastvisit;
    return $this_forum->{'FORUM_LAST_POST'} > $lastvisit  ? $iB::SKIN->{'C_ON'}
                                                          : $iB::SKIN->{'C_OFF'};
}




1;
