#################################################################################
# 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
#
#
# Search Functions.
#
#################################################################################
package Search::API::api_global;
use strict;

require 'Lib/FUNC.pm';
my $std  = FUNC::STD->new();
#require Boardinfo;

#$iB::INFO = Boardinfo->new();


# Global search functions

sub clean_up {

    # Lets make sure that we have a /Temp/Searches/ directory.

    unless (-e $iB::INFO->{'DB_DIR'}.'Temp/Searches' ) {
        mkdir ($iB::INFO->{'DB_DIR'}.'Temp/Searches', 0777);
    }

    # Searches expire after a week
    opendir(DIR, $iB::INFO->{'DB_DIR'}.'Temp/Searches');
    while (my $file = readdir(DIR)) {
        if ((stat($iB::INFO->{'DB_DIR'}.'Temp/Searches'."/$file"))[9] < (time - (7*24*60*60))) {  
            unlink($iB::INFO->{'DB_DIR'}.'Temp/Searches'."/$file");
        }
    }
    closedir(DIR);
    
    return 1;
}

sub get_searchable_forums {
    # Gets the forum details and filters out the ones we can't search in - returns
    # an array ref containing the forum ID's we can legally use.
    my $db = shift;
    
    my @s_forums;

    # Get the forum info..
    my $forums = $db->query( TABLE     => 'forum_info',
                             SORT_KEY  => 'FORUM_POSITION',
                             SORT_BY   => 'A-Z',
                             MATCH     => 'ALL',
                             COLUMNS   => ['FORUM_ID', 'FORUM_PROTECT', 'FORUM_VIEW_THREADS'],
                           );

    
    if ($iB::CGI->param('forums') eq 'all') {

    # Loop through all the forums, pushing any matched ones into a final
    # "Search these forums" array.

        for my $i (@{$forums}) {

            if ($i->{'FORUM_PROTECT'}) {
                if (exists $iB::COOKIES->{ $iB::INFO->{'COOKIE_ID'}.'iBForum' . $i->{'FORUM_ID'} }) {
                    next unless $iB::COOKIES->{ $iB::INFO->{'COOKIE_ID'}.'iBForum' . $i->{'FORUM_ID'} } eq $i->{'FORUM_PROTECT'};
                } else {
                    next;
                }
            }

            if ($i->{'FORUM_VIEW_THREADS'} ne '*') {
                unless (grep { $_ == $iB::MEMBER->{'MEMBER_GROUP'} } (split /,/,$i->{'FORUM_VIEW_THREADS'}) ) {
                    next;
                }
            }
        
            push @s_forums, $i->{'FORUM_ID'};
        }
    }
    else {
        # Or, if we've defined our forum numbers, simply build the
        # array from the numbers we got from the select box
        @s_forums = grep { $_ =~ /^(\d+)$/ } $iB::CGI->param('forums');
    }
    return \@s_forums;
}



sub keyword_filter {
    # Fix up the keywords to make sure they are legal, etc.
    my $words = shift;
    # as iDatabase uses % characters as a wildcard
    # we'll need to make them safe first..
    $words =~ s!%!\\%!g;
    $words =~ s!_!\\_!g;
    # If the user entered an asterisk as a wildcard
    # convert it into the % sign.
    $words =~ s!\*!%!g;
    # Get rid of evil unsearchable junk
    $words =~ s![\[\]\(\)\"/':;\|\!\#\{\}\-\+\\\\]!!gs;
    # Force to lowercase
    $words = lc($words);
    $words =~ s!(?:and|or+)$!!i;
    $words = ' '.$words.' ';
    return $words;
}


sub my_gen_id {
    my $obj = shift;
    srand($$|time);
    my $session = int(rand(60000000));
    return unpack("H*", pack("Nnn", time, $$, $session));
}

sub do_row {
    # Prepares the HTML for each topic entry
    my $row = shift;

    $row->{'LAST_POSTER'}      = ($row->{'TOPIC_LAST_POSTER'} != 0)   ? qq[<b><a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$row->{'TOPIC_LAST_POSTER'}'>$row->{'TOPIC_LASTP_N'}</a></b>]
                                                                      : qq[-$row->{'TOPIC_LASTP_N'}-];

    $row->{'FOLDER_ICON'}      = folder_icon($row);

    $row->{'TOPIC_LAST_DATE'}  = $std->get_date(TIME => $row->{'TOPIC_LAST_DATE'}, METHOD => 'LONG');

    $row->{'TOPIC_ICON'}       = $row->{'TOPIC_ICON'} ? '<img src="'.$iB::INFO->{'IMAGES_URL'} . '/PostIcons/icon' . $row->{'TOPIC_ICON'} . '.gif" border="0" alt="">'
                                                      : '<img src="'.$iB::INFO->{'IMAGES_URL'} . '/PostIcons/icon0.gif" border="0" alt="">';

    $row->{'TOPIC_START_DATE'} = $std->get_date( TIME => $row->{'TOPIC_START_DATE'}, METHOD => 'LONG');

    my $Pages = ($row->{'TOPIC_POSTS'} + 1) / $iB::INFO->{'DISPLAY_MAX_POSTS'};
    my ($Int, $Dec) = split /\./,$Pages;
    $Dec > 0 ? ($Pages = $Int + 1) : ($Pages = $Int);
    $Pages = 1 if $Pages < 1;
    if ($Pages > 1) {
        $row->{'PAGES'} = qq[(Pages ];
        my $i = 0;
        for(0 .. $Pages-1) {
            my $RealNo = $i * $iB::INFO->{'DISPLAY_MAX_POSTS'}; my $PageNo = $i + 1;
            if ($PageNo == 4) { $row->{'PAGES'} .= qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=ST;f=$row->{'FORUM_ID'};t=$row->{'TOPIC_ID'};hl=$row->{KEYWORDS};st=] . ($Pages - 1) * $iB::INFO->{'DISPLAY_MAX_POSTS'} . qq['>..$Pages </a>]; last; }
            $row->{'PAGES'} .= qq[<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=ST;f=$row->{'FORUM_ID'};t=$row->{'TOPIC_ID'};hl=$row->{KEYWORDS};st=$RealNo'>$PageNo </a>];
            ++$i;
        }
        $row->{'PAGES'} .= qq[)];
    }
    return SearchView::row( $row );
}

sub folder_icon ($) {
    my $row = shift;
    return $iB::SKIN->{'B_NORM'}       unless $iB::MEMBER->{'MEMBER_ID'};
    return $iB::SKIN->{'B_LOCKED'}     if     $row->{'TOPIC_STATE'} eq 'closed';
    return $iB::SKIN->{'B_POLL'}       if     (($row->{'POLL_STATE'}) and ($iB::last_visit  && ($row->{'LAST_VOTE'} > $iB::last_visit )));
    return $iB::SKIN->{'B_MOVED'}      if     $row->{'TOPIC_STATE'} eq 'moved' or $row->{'TOPIC_STATE'} eq 'link';
    return $iB::SKIN->{'B_HOT_NN'}     if     (($row->{'TOPIC_POSTS'} + 1 >= $iB::INFO->{'HOT_TOPIC'}) and ($iB::last_visit  && ($row->{'TOPIC_LAST_DATE'} < $iB::last_visit )));
    return $iB::SKIN->{'B_HOT'}        if     $row->{'TOPIC_POSTS'} + 1 >= $iB::INFO->{'HOT_TOPIC'};
    return $iB::SKIN->{'B_NEW'}        if     $iB::last_visit  && ($row->{'TOPIC_LAST_DATE'} > $iB::last_visit );
    return $iB::SKIN->{'B_NORM'};
}


1;