#!/GWD/bioinfo/apps/bin/perl
#
# Author: TWiki:Main.CraigMeyer
# Date: Jan-23-2007
#
package SuggestTopic;
use strict;
#use Data::Dumper; # Debug only
use CGI::Thin;
use FileHandle;
use DirHandle;
BEGIN {
use vars qw(
$DATA_DIR
$START_LIST
$END_LIST
$START_ITEM
$END_ITEM
$LINE_LIMIT
$CACHE_FILE
);
# Note: The limit for how many hits to return
$LINE_LIMIT = 10;
# Note: Modify the following to suit your installation of TWiki
$DATA_DIR = "/local/bixweb/apache/instances/bixweb-ump2.gsk.com.3074/htdocs/tw/data";
# Note: This is the Cache File for the current directory search results
$CACHE_FILE = '.TopicList';
# Use These for Scriptaculous.js AutoCompleter
$START_LIST = '
';
$START_ITEM = '';
$END_ITEM = '';
# These are for Beauscott.com AutoComplete
# $START_LIST = '';
# $END_LIST = '';
# $START_ITEM = '';
# $END_ITEM = '';
} # BEGIN
sub load_files {
my($path, $sep, $pattern) = @_;
my($file, @list, $hdir);
# print STDERR "[load_files] [$path] [$sep] [$pattern]\n";
$hdir = new DirHandle($path) or die "Can't open dir $path\n";
foreach $file ( $hdir->read() ){
next if( $file eq "." || $file eq "..");
if( -f join($sep, $path, $file) &&
defined($pattern) && $file =~ m|$pattern|i ){
push(@list, $file);
}
}
$hdir->close();
return(\@list);
} # load_files
sub create_cache {
my($cache_file, $path, $topic, $limit) = @_;
my($pfiles, $hfile, $file, $pat, @hits);
$hfile = new FileHandle(">$cache_file");
if( defined($hfile) ){
$pat = qr/^($topic.*)$/i;
$pfiles = load_files($path, '/', qq[\\.txt\$]);
# print STDOUT "loaded files: ", scalar(@$pfiles), "\n";
foreach $file ( sort { lc($a) cmp lc($b); } @$pfiles ){
$file =~ s/\.txt$//;
print $hfile $file, "\n";
if( $limit > 0 ){
if( $file =~ m/$pat/ ){
push(@hits, $1);
$limit--;
}
}
}
$hfile->close();
}
return(\@hits);
} # create_cache
sub read_cache {
my($cache_file, $topic, $limit) = @_;
my(@hits, $hfile, $pat);
$hfile = new FileHandle("<$cache_file");
if( defined($hfile) ){
$pat = qr/^($topic.*)$/i;
foreach ( <$hfile> ){
last if( $limit <= 0 );
if( $_ =~ m/$pat/ ){
push(@hits, $1);
$limit--;
}
}
$hfile->close();
}
return(\@hits);
} # read_cache
sub Main {
my(%form, $path, $topic);
$path = join('', $DATA_DIR, $ENV{PATH_INFO});
%form = &Parse_CGI();
$topic = $form{topic};
# DEBUG
# $path = join('/', $DATA_DIR, 'BixEng');
# $topic = 'Web';
# $topic = 'Bio';
# print STDERR "SuggestTopic[$path][$topic]\n";
my($pfiles, $file, $cache_file, $cache_stamp, $dir_stamp);
$pfiles = [];
$cache_file = join('/', $path, $CACHE_FILE);
$cache_stamp = (stat($cache_file))[9] || 0;
$dir_stamp = (stat($path))[9];
if( $dir_stamp > $cache_stamp ){ # Something has changed
$pfiles = create_cache($cache_file, $path, $topic, $LINE_LIMIT);
} else {
$pfiles = read_cache($cache_file, $topic, $LINE_LIMIT);
}
print STDOUT qq[\n], $START_LIST, "\n";
foreach $file ( @$pfiles ){
print STDOUT $START_ITEM, $file, $END_ITEM, "\n";
}
print STDOUT $END_LIST, "\n";
} #Main
&Main();