# UBB Search Routines : Perl Code

# get assigned style template!


%vars_style = &LoadStyleTemplate($template_match{search});

&set_page_elements;

sub get_daily {
	local (%daily_date_time, %subject_subset, @topic_file, @stat_file, @last_post, $the_last_post, @reverse_topic, $key, @topics, $total_topics, $more, $previous, %ExactPath, $current, @get_path, %forum_names);

	# get from cache? - doesn't use ServeFromCache due to extra reqs
	if (
		(($in{start_point} eq '') ||
		($in{start_point} == 0)) &&
		($vars_misc{use_cache} ne 'no') &&
		((-s "$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc/ubb_daily_topics.cgi") &&
		(-s "$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/daily_index-$GotTime{LastLoginJulianDATE}-main.cgi"))
		) {

		$ThisHTML = &OpenFileAsVar("$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc/ubb_daily_topics.cgi");

		print "$ThisHTML";
		exit(0);

	}


	if (-s "$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/daily_index-$GotTime{LastLoginJulianDATE}-main.cgi") {

		# the sole, lone require() in the entire UBB code... :)
		eval { require "$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/daily_index-$GotTime{LastLoginJulianDATE}-main.cgi"; };

		if ($@) {
			unlink("$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/daily_index-$GotTime{LastLoginJulianDATE}-main.cgi");
			&StandardHTML("$vars_wordlets_err{no_daily_topics}*");
		}

	} else {

		&StandardHTML("$vars_wordlets_err{no_daily_topics}");

	}

	#need promo sr:
	&RequireCode("$vars_config{CGIPath}/ubb_lib_posting.cgi");

	# sort by date/time-> newest to oldest
	@topics = sort { $daily_date_time{$b} <=> $daily_date_time{$a} } keys %daily_date_time;

	# set page limit
	my $page_limit  = 50;
	my $array_limit = $page_limit - 1;
	$current = "$vars_wordlets{additional_topics}";

	# total topics in list:
	$total_topics = @topics;

	# truncate array, if necessary

	if (($in{start_point} eq '') || ($in{start_point} == 0)) {

		if ($total_topics <= $page_limit) {
			$current  = '';
			$more     = '';
			$previous = '';
		} else {
			@topics   = @topics[0 .. $array_limit];
			$more     = qq!<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_daily&start_point=$page_limit">&#187;&#187;</a>!;
			$previous = '';
		}

	} else {

		# make sure startpoint input is a number!
		unless ($in{start_point} >= 0) {
			&StandardHTML("$vars_wordlets_err{start_point_number}");
		}

		my $end_point = $in{start_point} + $array_limit;
		my $back      = $in{start_point} - $page_limit;

		if ($total_topics <= ($end_point + 1)) {
			$end_point = $total_topics - 1;
			$more      = '';
			$previous  = qq!<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_daily&start_point=$back">&#171;&#171;</a>!;


		} else {

			my $next = $in{start_point} + $page_limit;
			$more     = qq!<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_daily&start_point=$next">&#187;&#187;</a>!;
			$previous = qq!<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_daily&start_point=$back">&#171;&#171;</a>!;

		}

		@topics  = @topics[$in{start_point} .. $end_point];
		$current = "$vars_wordlets{additional_topics}";
	}


	# get HTML bits for this page
	&LoadTemplate("public_daily_topics");

	# get top of page from public_common.pl
	$ThisHTML = $Header;
	$ThisHTML .= &page_top;


	$ThisHTML .= &todays_topics_body;


	$ThisHTML .= &page_bottom;

	# get bottom of page from public_common.pl
	$ThisHTML .= $Footer;

	print "$ThisHTML";

	# print to cache if start point = 0
	if ((($in{start_point} eq '') || ($in{start_point} == 0)) && ($vars_misc{use_cache} ne 'no')) {

		# is ubb_files/misc directory created?
		unless (-d "$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc") {
			mkdir("$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc", 0777);
			chmod(0777, "$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc");
		}

		unless (-w "$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc/ubb_daily_topics.cgi") {
			unlink "$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc/ubb_daily_topics.cgi";
		}

		&WriteFileAsString("$vars_config{NonCGIPath}/cache-$cache_cookie/ubb_files/misc/ubb_daily_topics.cgi", $ThisHTML);

	}
	exit(0);
}    # end get_daily sr

sub search {

	#check for search directory
	unless (-d "$vars_config{NonCGIPath}/searchlogs") {
		mkdir("$vars_config{NonCGIPath}/searchlogs", 0777);
		chmod(0777, "$vars_config{NonCGIPath}/searchlogs");
	}

	local ($forum_list, @all_forums, @user_profile, @forums, @forum_info, $is_one, $user_access, %forum_selected);
	undef($forum_list);

	# generate forum list, based on user's permissions
	@all_forums = &OpenForumsFile;

	LOOPER: foreach (@all_forums) {

		@forum_info = split (/\|\^\|/, $_);
		$forum_selected{$forum_info[8]} = '';

		# is forum open?
		if ($forum_info[3] eq 'Off') { next LOOPER; }

		# is forum private? If so, check permission!
		if ($forum_info[6] eq 'private') {

			# must be logged in!
			if ($username eq '') { next LOOPER; }

			# check user permissions
			@user_profile = &verify_id_num($username, $password, $user_number);
			chomp($user_profile[8]);

			# is admin/mod?
			$is_one = &is_admin_or_mod($forum_info[8], @user_profile);

			if ($is_one eq 'true') {
				push (@forums, $forum_info[8]);
			} else {

				$user_access = &user_access($forum_info[8], @user_profile);
				if ($user_access eq 'true') {
					push (@forums, $forum_info[8]);
				} else {
					next LOOPER;
				}

			}

			# end private forum checks...

		} else {

			# not a private forum, so:
			push (@forums, $forum_info[8]);
		}


	}    # end forum loop


	# set forum?
	if ($in{search_forum} ne '') {
		my $fn = $in{search_forum};
		$forum_selected{$fn} = 'selected="selected"';
	}

	# @forums contains all forum numbers user is permitted to search
	if ($vars_search{AllowTotalSearch} eq 'TRUE') {
		$forum_list = qq!<option value="ALL"> $vars_wordlets{search_all_forums}</option>!;
	}

	foreach (@forums) {
		@this_forum = &GetForumRecord($_);
		$forum_list .= qq~<option value="$_" $forum_selected{$_}>&raquo; $this_forum[1]</option>
~;
	}

	# display profile info
	&LoadTemplate("public_search");

}


sub do_search {
	local ($CurrentJDate, $search_words, $search_words_coded, $search_number, @search_list, $Total, $FileName, $SkipSearch, @forum_info, $TotalForums, @the_index, @this_index, @index, $StartAt, $Continue, @good, $SearchFile, $one, $MatchTotal, $StartPoint, $EndPoint, $EP, $SP, $Done, $MaxDisplay, $ForumName, @goodline, $eachone, $NextWording, $TheURL, $ThisYear, $ThisDay, $ThisMo, $index_file, $TheDate, $all, $clean_all, $clean_post, $HyphenIt, $post, @this_user_posts, @new_index);
	local (*FILE);

	# get HTML bits for this page
	&LoadTemplate("public_search_results");

	# if calling search file...
	if (($in{File}) && ($in{File} !~ /^temp/)) {
		&StandardHTML("$vars_wordlets_err{search_file_not_found}");
	}

	#delete old temporary search records
	&prune_temps;

	#prepare search terms--
	if ($in{search_words} ne '') {
		$search_words = $in{search_words};

		$search_words_coded = UBBCGI::escape($search_words);

		$search_words = &strip_lead_trail_space($search_words);
		$search_words =~ s/\n//sg;
		$search_words =~ s/\r//sg;
		$search_words =~ s/\@/\\@/sg;

		if ($search_words =~ / /) {
			@search_list = split (/ /, $search_words);
		} else {
			@search_list = $search_words;
		}

		my @new_search_list;
		foreach(@search_list) {
			&strip_lead_trail_space;
			push(@new_search_list, quotemeta $_);
		}
		@search_list = @new_search_list; @new_search_list = ();

		$search_number = @search_list;

	} else {
		undef(@search_list);
		$search_number = 0;
	}    # end if/else search on words


	if (!$in{Total}) {
		$Total = 0;
	} else {
		$Total = $in{Total};
	}


	#make sure search file is still valid
	unless (($in{File}) && (-e "$vars_config{NonCGIPath}/searchlogs/$in{File}")) {
		$in{File} = '';
		$FileName = '';
	}

	$SkipSearch = '';

	$in{Continue} = "" unless $in{Continue};
	if (($in{Continue} eq 'False') && ($in{File})) {

		if (($in{File}) && (-e "$vars_config{NonCGIPath}/searchlogs/$in{File}")) {
			@good       = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/searchlogs/$in{File}"));
			$SkipSearch = 'true';
		}
	}    #end if temp file exists to draw on


	if ($SkipSearch ne 'true') {
		undef(@index);

		#get forum file
		@forum_info  = &OpenForumsFile;
		$TotalForums = @forum_info;

		# which kind of index file?
		if ($vars_search{IndexMethod} eq 'PERFORUM') {
			$index_file = ("forumindex" . "$in{search_forum}");
		} else {
			$index_file = 'forumindex';
		}
		@index = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/$index_file.cgi"));

		&StandardHTML($vars_wordlets_err{invalid_input}) if(($in{search_forum} eq 'ALL') && ($vars_search{AllowTotalSearch} eq "FALSE"));

		#search one forum or all?
		if ($in{search_forum} ne 'ALL') {

			@this_forum = &GetForumRecord($in{search_forum});

			if ($this_forum[3] eq 'On') {
				if ($vars_search{IndexMethod} ne 'PERFORUM') {
					@index = sort(grep(/^$in{search_forum}\|/, @index));
				} else {
					undef(@index);
				}
			} 
		}     # end if searching all forums

		#determine start point
		if ($in{StartAt}) {
			$StartAt = $in{StartAt};
			$StartAt = $StartAt + 0;
			@index   = @index[$StartAt .. $#index];
		}

		#now we have array to be searched...

		&CheckBadChars($in{File});

		# Determine Current Good Array
		if ($in{File} =~ /^temp\S+\.cgi$/) {
			@good = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/searchlogs/$in{File}"));
		} else {
			undef(@good);
		}

		# Username Search Routine---

		if ($in{search_user} ne '') {
			$in{search_user} = &Do8Digit($in{search_user});
			undef(@new_index);
			undef(@this_new_index);
			undef(@this_index);
			undef(@this_user_posts);

			# get user post file
			my @this_user_posts = &OpenFileAsArray("$vars_config{MembersPath}/user_posts/$in{search_user}.cgi");

			# user_posts_hash idea contributed by Leshrac... thanks!
			my (%user_posts_hash, @this_new_index);

			foreach my $post (@this_user_posts) {
				chomp($post);

				my @this_index = split (/\|/, $post);
				my $elements = scalar(@this_index);
				my $poster   = join ('|', @this_index[1 .. ($elements - 1)]);

				$user_posts_hash{$poster} = 1;

			}

			foreach my $item (@index) {
				$item =~ m/^(\d+\|\d{6}\|\d{6})\|.*/;
				if (exists $user_posts_hash{$1}) {
					push (@this_new_index, $item);
				}
			}

			@index = @this_new_index;
		}    # end search user block

		&find_matches;

		#now we have all matches- write temp file
		if (!$in{File}) {
			$SearchFile = &CreateTempSearchName;
			$FileName   = "temp-$SearchFile.cgi";
		} else {
			$FileName = "$in{File}";
		}

		&WriteFileAsArray("$vars_config{NonCGIPath}/searchlogs/$FileName", @good);

	}    #end skip search check


	$MatchTotal = @good;
	my $MaxDisplay = 40;    #maximum number to view per screen
	if (!$in{StartPoint}) {
		$StartPoint = 1;
		if ($MatchTotal <= $MaxDisplay) {
			$EndPoint = $MatchTotal;
			$Done     = 'true';
		} else {
			$Done     = '';
			$EndPoint = $MaxDisplay;
		}
		$EP   = $EndPoint - 1;
		@good = @good[0 .. $EP];

	} else {

		$StartPoint = $in{'StartPoint'};
		$EndPoint   = $StartPoint + $MaxDisplay;
		$EndPoint   = $EndPoint - 1;
		if ($MatchTotal <= $EndPoint) {
			$EndPoint = $MatchTotal;
			$Done     = 'true';
		} else {
			$Done = '';
		}

	}

	$SP   = $StartPoint - 1;
	$EP   = $EndPoint - 1;
	@good = @good[$SP .. $EP];

	if ($FileName eq '') { $FileName = "$in{File}"; }

	if ($Done ne 'true') {
		$NextStart   = $EndPoint + 1;
		$NextWording = qq(<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=do_search&StartPoint=$NextStart&search_words=$search_words_coded&search_user=$in{search_user}&search_forum=$in{search_forum}&search_in=$in{search_in}&search_date=$in{search_date}&match_all=$in{match_all}&File=$FileName&Continue=False">[$vars_wordlets{search_next}]</a>);
	} else {
		$NextWording = '';
	}

	if ($MatchTotal == 0) {
		$StartPoint = 0;
	}

	# Search Page Top
	$ThisHTML = &PageTop;

	for $eachone (@good) {
		@goodline = split (/\|/, $eachone);

		@GetForumName = &GetForumRecord("$goodline[0]");
		$ForumName    = "$GetForumName[1]";
		$TheURL       = "$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_topic&f=$goodline[0]&t=$goodline[1]";

		($ThisMo, $ThisDay, $ThisYear) = split (/-/, $goodline[3]);
		$ThisYear = &Y2K($ThisYear);
		$HyphenIt = "$ThisMo-$ThisDay-$ThisYear";

		# format the date
		$TheDate = &DateFormat($HyphenIt);

		# Row HTML
		$ThisHTML .= &MatchRow;

	}    # loop thru each match

	# HTML for Search Results Page Bottom
	$ThisHTML .= &PageBottom;

	# display finished page!
	print "$ThisHTML";
	exit(0);
}    # end do_search



sub prune_temps {
	local ($temp, $j, $JDate, $CompareDate, $JTime, $diff);
	local (*DIR);

	opendir(DIR, "$vars_config{NonCGIPath}/searchlogs");
	my @all_temps = readdir(DIR);
	closedir(DIR);

	my @temps = grep(/\.cgi/, @all_temps);

	foreach $temp (@temps) {
		($j, $JDate, $JTime, $j) = split (/-/, $temp);
		$CompareDate = ($JDate + ($JTime * 0.000001));
		$diff        = $GotTime{LastLoginJulian} - $CompareDate;
		if ($diff > 0.015) {
			unlink("$vars_config{NonCGIPath}/searchlogs/$temp");
		}
	}
}    # end prune_temps


sub find_matches {
	local ($count_it, $line, $Bad, @indie, $GoodOne, %ForumPerm, %ExactPath, @get_path, $month, $word, $day, $theyear, $PostDate, $PostJDay, $Year, $Total, @testit, @testit2, $CutOff, $Duplicate, $dupcheck, $MaxSearch, @user_profile, $user_perm);

	$count_it = 0;

	SEARCHMATCHES: foreach $line (@index) {
		$count_it++;
		$Bad = 'no';
		@indie = split (/\|/, $line);
		chomp($indie[5]);

		# set exact path, if necessary
		unless ($ExactPath{$indie[0]}) {
			@get_path = &GetForumRecord($indie[0]);
			if ($get_path[6] eq 'private') {
				$ExactPath{$indie[0]} = "Forum$indie[0]/private-$get_path[7]";
				if ($username eq '') {
					$ForumPerm{$indie[0]} = 'no';
				} else {

					# grab user profile
					@user_profile = &verify_id_num($username, $password, $user_number);

					# make sure user has authority
					$user_perm = &is_admin_or_mod($indie[0], @user_profile);
					if ($user_perm eq 'true') {
						$ForumPerm{$indie[0]} = 'yes';
					} else {
						$user_perm = &user_access($indie[0], @user_profile);

						if ($user_perm eq 'true') {
							$ForumPerm{$indie[0]} = 'yes';
						} else {
							$ForumPerm{$indie[0]} = 'no';
						}
					}
				}

			} else {
				$ExactPath{$indie[0]} = "Forum$indie[0]";
				$ForumPerm{$indie[0]} = 'yes';
			}
		}
		$exact_path = $ExactPath{$indie[0]};
		$user_perm  = $ForumPerm{$indie[0]};

		if ($user_perm eq 'no') { next; }

		$GoodOne = '';

		# Keyword Search:
		$search_words = "" unless $search_words;
		if (($search_words ne '') && ($Bad ne 'yes')) {


			foreach $word (@search_list) {

				# $word = quotemeta $word;
				if ($in{match_all} eq 'yes') {

					if ($in{search_in} eq 'SUBJECT') {
						unless ($indie[4] =~ /$word/i) { $Bad = 'yes'; }
					} else {
						unless (($indie[5] =~ /$word/i) || ($indie[4] =~ /$word/i)) { $Bad = 'yes'; }
					}

				} else {

					if ($in{search_in} eq 'SUBJECT') {
						if ($indie[4] =~ /$word/i) { $GoodOne = 'yes'; }
					} else {
						if (($indie[4] =~ /$word/i) || ($indie[5] =~ m/$word/i)) { $GoodOne = 'yes'; }
					}
				}
			}
		}

		if (($in{match_all} eq 'no') && ($GoodOne ne 'yes')) {
			$Bad = 'yes';
		}

		#  Date Search


		if (($in{search_date} ne 'ALL') && ($Bad ne "yes")) {

			$PostDate = $indie[3];
			chomp($PostDate);
			($month, $day, $theyear) = split (/-/, $PostDate);

			$Year     = &Y2K($theyear);
			$PostJDay = &jday($month, $day, $Year);

			#current jday is $GotTime{LastLoginJulianDATE}

			if ($in{search_date} eq '1') {
				$CutOff = ($GotTime{LastLoginJulianDATE} - 1);
				unless ($PostJDay >= $CutOff) { $Bad = 'yes'; }
			}

			if ($in{search_date} eq '5') {
				$CutOff = ($GotTime{LastLoginJulianDATE} - 5);
				unless ($PostJDay >= $CutOff) { $Bad = 'yes'; }
			}

			if ($in{search_date} eq '10') {
				$CutOff = ($GotTime{LastLoginJulianDATE} - 10);
				unless ($PostJDay >= $CutOff) { $Bad = 'yes'; }
			}
			if ($in{search_date} eq '30') {
				$CutOff = ($GotTime{LastLoginJulianDATE} - 30);
				unless ($PostJDay >= $CutOff) { $Bad = 'yes'; }
			}

		}

		if ($Bad ne 'yes') {
			(@testit) = split (/\|/, $line);
			$testit    = ("$testit[0]" . "$testit[1]");
			$Duplicate = '';
			for $dupcheck (@good) {
				(@testit2) = split (/\|/, $dupcheck);
				$testit2 = ("$testit2[0]" . "$testit2[1]");

				if ($testit eq "$testit2") {
					$Duplicate = 'true';
				}
			}

			if (($Duplicate ne 'true') && (-e "$vars_config{NonCGIPath}/$exact_path/$indie[1].cgi")) {
				$Total++;
				push (@good, $line);
				if ($Total >= 200) {
					$ProcessNext = 'false';
					$MaxSearch   = 'true';
				}
			}
		}    #end if $Bad

		if (!$MaxSearch) { $MaxSearch = ''; }
		if (!$CountIt)   { $CountIt   = 0; }

		if ($MaxSearch eq 'true') {
			last SEARCHMATCHES;
		}

		unless (($vars_search{IndexMethod} eq 'PERFORUM') && ($in{search_forum} eq 'ALL')) {
			if ($CountIt > 9999) {
				if ($in{StartAt} ne '') {
					$StartPoint = $in{StartAt} + $CountIt;
					$StartPoint--;
				} else {
					$StartPoint = $CountIt;
				}

				&ContinueSearch($StartPoint, $Total);
				exit(0);
			}
		}


	}    #end foreach $line

	$ProcessNext = "" unless $ProcessNext;
	if (($ProcessNext eq 'true') && ($vars_search{IndexMethod} eq 'PERFORUM') && ($in{search_forum} eq 'ALL')) {
		&ContinueSearch($NextForum, $Total);
		exit(0);
	}

}    # find_matches end


sub ContinueSearch {
	local ($SearchFile, $one, $Totalmatches);

	my $ArrayNum = shift;
	my $Total    = shift;

	#check for search directory
	unless (-d "$vars_config{NonCGIPath}/searchlogs") {
		mkdir("$vars_config{NonCGIPath}/searchlogs", 0777);
		chmod(0777, "$vars_config{NonCGIPath}/searchlogs");
	}

	#create temp file to hold search results

	&CheckBadChars($in{File});

	if ($in{File} eq '') {
		$SearchFile = &CreateTempSearchName;
		$FileName   = "temp-$SearchFile.cgi";
	} else {
		$FileName = "$in{File}";
	}

	&WriteFileAsArray("$vars_config{NonCGIPath}/searchlogs/$FileName", @good);

	$Totalmatches = @good;
	%vars_style = &LoadStyleTemplate($template_match{transition});
	&set_page_elements;
	&Transition("$vars_config{CGIURL}/ultimatebb.cgi?ubb=do_search&search_in=$in{search_in}&search_forum=$in{search_forum}&search_words=$search_words_coded&match_all=$in{match_all}&search_date=$in{search_date}&search_user=$in{search_user}&File=$FileName&Total=$Total&StartAt=$ArrayNum", "$vars_wordlets{search_wait}<p>$vars_wordlets{matches_thus_far} $Totalmatches</p><p>$vars_wordlets{search_limit}</p>", "$vars_wordlets{search_continuing}");
	exit(0);
}

sub CreateTempSearchName {
	local (@digit, $num1, $num2, $num3, $num4, $Random4, $search_file);
	@digit = ("A", "B", "F", "G", "H", "I", "n", "p", "q", "r", "s", "t", "u", "v", "w", "y", "z", "2", "3", "4", "5", "6", "7", "8", "9");
	srand(time);
	$num1        = rand(@digit);
	$num2        = rand(@digit);
	$num3        = rand(@digit);
	$num4        = rand(@digit);
	$Random4     = ("$digit[$num1]" . "$digit[$num2]" . "$digit[$num3]" . "$digit[$num4]");
	$search_file = ("$GotTime{SearchJulian}" . "-$Random4");
	return ($search_file);
}


sub do_search_2 {

	# for PERFORUM index Searches

	local ($CurrentJDate, $search_words, $search_words_coded, $search_number, @search_list, $Total, $FileName, $SkipSearch, @forum_info, $TotalForums, @the_index, @this_index, @index, $StartAt, $Continue, @good, $SearchFile, $one, $MatchTotal, $StartPoint, $EndPoint, $EP, $SP, $Done, $MaxDisplay, $ForumName, @goodline, $eachone, $NextWording, $TheURL, $ThisYear, $ThisDay, $ThisMo, $TheDate, $line, $all, $clean_all, $clean_post, $HyphenIt, $post, @this_user_posts, @new_index, $ProcessNext, $NextForum, @rev_forums, @last_forum, $last_forum_number, @searchthru, @this_forum);
	local (*FILE);

	# get HTML bits for this page
	&LoadTemplate("public_search_results");

	# if calling search file...
	if (($in{File}) && ($in{File} !~ /^temp/)) {
		&StandardHTML("$vars_wordlets_err{search_file_not_found}");
	}

	#delete old temporary search records
	&prune_temps;

	#prepare search terms--
	if ($in{search_words} ne '') {
		$search_words = $in{search_words};

		$search_words_coded = UBBCGI::escape($search_words);

		$search_words = &strip_lead_trail_space($search_words);
		$search_words =~ s/\n//sg;
		$search_words =~ s/\r//sg;
		$search_words =~ s/\@/\\@/sg;

		if ($search_words =~ / /) {
			@search_list = split (/ /, $search_words);
		} else {
			@search_list = $search_words;
		}

		my @new_search_list;
		foreach(@search_list) {
			&strip_lead_trail_space;
			push(@new_search_list, quotemeta $_);
		}
		@search_list = @new_search_list; @new_search_list = ();

		$search_number = @search_list;

	} else {
		undef(@search_list);
		$search_number = 0;
	}    # end if/else search on words


	if ($in{Total} eq '') {
		$Total = 0;
	} else {
		$Total = $in{Total};
	}


	#make sure search file is still valid
	unless (-e "$vars_config{NonCGIPath}/searchlogs/$in{File}") {
		$in{File} = '';
		$FileName = '';
	}

	$SkipSearch = '';

	if (($in{Continue} eq 'False') && ($in{File} ne '')) {

		if (-e "$vars_config{NonCGIPath}/searchlogs/$in{File}") {
			@good       = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/searchlogs/$in{File}"));
			$SkipSearch = "true";
		}
	}    #end if temp file exists to draw on


	if ($SkipSearch ne 'true') {
		undef(@index);

		#get forum file
		@forum_info  = &OpenForumsFile;
		$TotalForums = @forum_info;

		# determine highest forum number
		@last_forum        = split (/\|\^\|/, $forum_info[($TotalForums - 1)]);
		$last_forum_number = $last_forum[8];

		# only option is to search all for this sr:

		# assemble array of forum numbers
		foreach (@forum_info) {
			@eachone = split (/\|\^\|/, $_);
			if ($eachone[3] eq 'On') { push (@searchthru, $eachone[8]); }
		}

		# determine starting point
		if ($in{StartAt} eq '') {

			@this_forum = split (/\|\^\|/, $forum_info[0]);

			if ($this_forum[3] eq 'On') {
				@index = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/forumindex$this_forum[8].cgi"));
			} else {
				undef(@index);
			}

			# next steps
			if ($TotalForums > 1) {
				$NextForum = $searchthru[1];
				chomp($NextForum);
				$ProcessNext = 'true';
			} else {
				$ProcessNext = 'false';
			}


		} else {

			# if not the first forum
			foreach $line (@forum_info) {
				@checkit = split (/\|\^\|/, $line);
				if ($checkit[8] >= $in{StartAt}) {
					@this_forum = &GetForumRecord($checkit[8]);
					$in{StartAt} = $checkit[8];
					last;
				}
			}

			if ($this_forum[3] eq 'On') {
				@index = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/cache-$cache_cookie/search_index/forumindex$this_forum[8].cgi"));
			} else {
				undef(@index);
			}

			$NextForum = $this_forum[8] + 1;
			if ($NextForum > $last_forum_number) {
				$ProcessNext = 'false';
			} else {
				$ProcessNext = 'true';
			}

		}    # end if/else this is the first forum

		# note: don't worry about user permissions- that is checked in &find_matches

		#@index = sort(@this_index);

		# now we have array to be searched...

		&CheckBadChars($in{File});

		# Determine Current Good Array
		if ($in{File} =~ /^temp\S+\.cgi$/) {
			@good = sort(&OpenFileAsArray("$vars_config{NonCGIPath}/searchlogs/$in{File}"));
		} else {
			undef(@good);
		}

		# Username Search Routine---

		if ($in{search_user} ne '') {
			$in{search_user} = &Do8Digit($in{search_user});

			# get user post file
			my @this_user_posts = &OpenFileAsArray("$vars_config{MembersPath}/user_posts/$in{search_user}.cgi");

			# user_posts_hash idea contributed by Leshrac... thanks!
			my (%user_posts_hash, @this_new_index);

			foreach my $post (@this_user_posts) {
				chomp($post);

				my @this_index = split (/\|/, $post);
				my $elements = scalar(@this_index);
				my $poster   = join ('|', @this_index[1 .. ($elements - 1)]);

				$user_posts_hash{$poster} = 1;

			}

			foreach my $item (@index) {
				$item =~ m/^(\d+\|\d{6}\|\d{6})\|.*/;
				if (exists $user_posts_hash{$1}) {
					push (@this_new_index, $item);
				}
			}

			@index = @this_new_index;
		}    # end search user block


		&find_matches;

		#now we have all matches- write temp file
		if ($in{File} eq '') {
			$SearchFile = &CreateTempSearchName;
			$FileName   = "temp-$SearchFile.cgi";

			#print "test: $SearchFile"; exit(0);
		} else {
			$FileName = "$in{File}";
		}


		&WriteFileAsArray("$vars_config{NonCGIPath}/searchlogs/$FileName", @good);

	}    #end skip search check


	$MatchTotal = @good;
	my $MaxDisplay = 40;    #maximum number to view per screen
	if ($in{StartPoint} eq "") {
		$StartPoint = 1;
		if ($MatchTotal <= $MaxDisplay) {
			$EndPoint = $MatchTotal;
			$Done     = 'true';
		} else {
			$Done     = '';
			$EndPoint = $MaxDisplay;
		}
		$EP   = $EndPoint - 1;
		@good = @good[0 .. $EP];

	} else {

		$StartPoint = $in{'StartPoint'};
		$EndPoint   = $StartPoint + $MaxDisplay;
		$EndPoint   = $EndPoint - 1;
		if ($MatchTotal <= $EndPoint) {
			$EndPoint = $MatchTotal;
			$Done     = 'true';
		} else {
			$Done = '';
		}

	}

	$SP   = $StartPoint - 1;
	$EP   = $EndPoint - 1;
	@good = @good[$SP .. $EP];

	if ($FileName eq '') { $FileName = "$in{File}"; }

	if ($Done ne 'true') {
		$NextStart   = $EndPoint + 1;
		$NextWording = qq(<a href="$vars_config{CGIURL}/ultimatebb.cgi?ubb=do_search&StartPoint=$NextStart&search_words=$search_words_coded&search_user=$in{search_user}&search_forum=$in{search_forum}&search_in=$in{search_in}&search_date=$in{search_date}&match_all=$in{match_all}&File=$FileName&Continue=False">[$vars_wordlets{search_next}]</a>);
	} else {
		$NextWording = '';
	}

	if ($MatchTotal == 0) {
		$StartPoint = 0;
	}

	# Search Page Top
	$ThisHTML = &PageTop;

	for $eachone (@good) {
		@goodline = split (/\|/, $eachone);

		#it is not an archive, but a forum
		@GetForumName = &GetForumRecord("$goodline[0]");
		$ForumName    = "$GetForumName[1]";
		$TheURL       = "$vars_config{CGIURL}/ultimatebb.cgi?ubb=get_topic&f=$goodline[0]&t=$goodline[1]";

		($ThisMo, $ThisDay, $ThisYear) = split (/-/, $goodline[3]);
		$ThisYear = &Y2K($ThisYear);
		$HyphenIt = "$ThisMo-$ThisDay-$ThisYear";

		# format the date
		$TheDate = &DateFormat($HyphenIt);

		# Row HTML
		$ThisHTML .= &MatchRow;


	}    # loop thru each match

	# HTML for Search Results Page Bottom
	$ThisHTML .= &PageBottom;

	# display finished page!
	print "$ThisHTML";
	exit(0);
}    # end do_search_2

# DANGER: Do not remove the next line!
1;
