File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.44: download - view: text, annotated - select for diffs
Tue Dec 23 15:47:26 2003 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Just saving my work on retrieving dynamic metadata - this does not work yet.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.44 2003/12/23 15:47:26 www Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: ###
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: B<searchcat.pl> - put authoritative filesystem data into sql database.
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Ordinarily this script is to be called from a loncapa cron job
   40: (CVS source location: F<loncapa/loncom/cron/loncapa>; typical
   41: filesystem installation location: F</etc/cron.d/loncapa>).
   42: 
   43: Here is the cron job entry.
   44: 
   45: C<# Repopulate and refresh the metadata database used for the search catalog.>
   46: C<10 1 * * 7    www    /home/httpd/perl/searchcat.pl>
   47: 
   48: This script only allows itself to be run as the user C<www>.
   49: 
   50: =head1 DESCRIPTION
   51: 
   52: This script goes through a loncapa resource directory and gathers metadata.
   53: The metadata is entered into a SQL database.
   54: 
   55: This script also does general database maintenance such as reformatting
   56: the C<loncapa:metadata> table if it is deprecated.
   57: 
   58: This script evaluates dynamic metadata from the authors'
   59: F<nohist_resevaldata.db> database file in order to store it in MySQL, as
   60: well as to compress the filesize (add up all "count"-type metadata).
   61: 
   62: This script is playing an increasingly important role for a loncapa
   63: library server.  The proper operation of this script is critical for a smooth
   64: and correct user experience.
   65: 
   66: =cut
   67: 
   68: use lib '/home/httpd/lib/perl/';
   69: use LONCAPA::Configuration;
   70: 
   71: use IO::File;
   72: use HTML::TokeParser;
   73: use DBI;
   74: use GDBM_File;
   75: use POSIX qw(strftime mktime);
   76: 
   77: my @metalist;
   78: 
   79: $simplestatus='';
   80: my %countext=();
   81: 
   82: sub writesimple {
   83:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
   84:     print SMP $simplestatus."\n";
   85:     close(SMP);
   86: }
   87: 
   88: sub writecount {
   89:     open(RSMP,'>/home/httpd/html/lon-status/rescount.txt');
   90:     foreach (keys %countext) {
   91: 	print RSMP $_.'='.$countext{$_}.'&';
   92:     }
   93:     print RSMP 'time='.time."\n";
   94:     close(RSMP);
   95: }
   96: 
   97: sub count {
   98:     my $file=shift;
   99:     $file=~/\.(\w+)$/;
  100:     my $ext=lc($1);
  101:     if (defined($countext{$ext})) {
  102: 	$countext{$ext}++;
  103:     } else {
  104: 	$countext{$ext}=1;
  105:     }
  106: }
  107: # ----------------------------------------------------- Un-Escape Special Chars
  108: 
  109: sub unescape {
  110:     my $str=shift;
  111:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  112:     return $str;
  113: }
  114: 
  115: # -------------------------------------------------------- Escape Special Chars
  116: 
  117: sub escape {
  118:     my $str=shift;
  119:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  120:     return $str;
  121: }
  122: 
  123: 
  124: # ------------------------------------------- Code to evaluate dynamic metadata
  125: 
  126: sub dynamicmeta {
  127:     my $url=&declutter(shift);
  128:     $url=~s/\.meta$//;
  129:     my %returnhash=();
  130:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
  131:     my $prodir=&propath($adomain,$aauthor);
  132: # Get metadata except counts
  133:     if (tie(%evaldata,'GDBM_File',
  134:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) {
  135: 	my %sum=();
  136: 	my %cnt=();
  137: 	my %concat=();
  138: 	my %listitems=(
  139: 		       'course'       => 'add',
  140: 		       'goto'         => 'add',
  141: 		       'comefrom'     => 'add',
  142: 		       'avetries'     => 'avg',
  143: 		       'stdno'        => 'add',
  144: 		       'difficulty'   => 'avg',
  145: 		       'clear'        => 'avg',
  146: 		       'technical'    => 'avg',
  147: 		       'helpful'      => 'avg',
  148: 		       'correct'      => 'avg',
  149: 		       'depth'        => 'avg',
  150: 		       'comments'     => 'app',
  151: 		       'usage'        => 'cnt'
  152: 		       );
  153: 	
  154: 	my $regexp=$url;
  155: 	$regexp=~s/(\W)/\\$1/g;
  156: 	$regexp='___'.$regexp.'___([a-z]+)$';
  157: 	while (my ($esckey,$value)=each %evaldata) {
  158: 	    $key=&unescape($esckey);
  159: 	    if ($key=~/$regexp/) {
  160: 		my ($item,$purl,$cat)=split(/___/,$_);
  161: 		if (defined($cnt{$cat})) { $cnt{$cat}++; } else { $cnt{$cat}=1; }
  162: 		unless ($listitems{$cat} eq 'app') {
  163: 		    if (defined($sum{$cat})) {
  164: 			$sum{$cat}+=$evaldata{$_};
  165: 			$concat{$cat}.=','.$item;
  166: 		    } else {
  167: 			$sum{$cat}=$evaldata{$_};
  168: 			$concat{$cat}=$item;
  169: 		    }
  170: 		} else {
  171: 		    if (defined($sum{$cat})) {
  172: 			if ($evaldata{$_}) {
  173: 			    $sum{$cat}.='<hr>'.$evaldata{$_};
  174: 			}
  175: 		    } else {
  176: 			$sum{$cat}=''.$evaldata{$_};
  177: 		    }
  178: 		}
  179: 	    }
  180: 	}
  181: 	untie(%evaldata);
  182:     }
  183: # construct the return hash for non-count data
  184:     my %returnhash=();
  185:     while ($_=each(%cnt)) {
  186: 	if ($listitems{$_} eq 'avg') {
  187: 	    $returnhash{$_}=int(($sum{$_}/$cnt{$_})*100.0+0.5)/100.0;
  188: 	} elsif ($listitems{$_} eq 'cnt') {
  189: 	    $returnhash{$_}=$cnt{$_};
  190: 	} else {
  191: 	    $returnhash{$_}=$sum{$_};
  192: 	}
  193: 	$returnhash{$_.'_list'}=$concat{$_};
  194:     }
  195: # get count
  196:     if (tie(%evaldata,'GDBM_File',
  197:             $prodir.'/nohist_accesscount.db',&GDBM_READER(),0640)) {
  198: 	if (! exists($evaldata{$uri})) {
  199: 	    $returnhash{'count'}='Not Available';
  200: 	} else {
  201: 	    $returnhash{'count'}=$evaldata{$uri};
  202: 	}
  203: 	untie %evaldata;
  204:     }
  205:     return %returnhash;
  206: }
  207:   
  208: # ----------------- Code to enable 'find' subroutine listing of the .meta files
  209: require "find.pl";
  210: sub wanted {
  211:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
  212:         -f _ &&
  213:         /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
  214:         push(@metalist,"$dir/$_");
  215: }
  216: 
  217: # ---------------  Read loncapa_apache.conf and loncapa.conf and get variables
  218: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  219: my %perlvar=%{$perlvarref};
  220: undef $perlvarref; # remove since sensitive and not needed
  221: delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
  222: 
  223: # ------------------------------------- Only run if machine is a library server
  224: exit unless $perlvar{'lonRole'} eq 'library';
  225: 
  226: # ----------------------------- Make sure this process is running from user=www
  227: 
  228: my $wwwid=getpwnam('www');
  229: if ($wwwid!=$<) {
  230:     $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  231:     $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  232:     system("echo 'User ID mismatch. searchcat.pl must be run as user www.' |\
  233:  mailto $emailto -s '$subj' > /dev/null");
  234:     exit 1;
  235: }
  236: 
  237: 
  238: # ---------------------------------------------------------- We are in business
  239: 
  240: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
  241: print LOG '==== Searchcat Run '.localtime()."====\n\n";
  242: $simplestatus='time='.time.'&';
  243: my $dbh;
  244: # ------------------------------------- Make sure that database can be accessed
  245: {
  246:     unless (
  247: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  248: 	    ) { 
  249: 	print LOG "Cannot connect to database!\n";
  250: 	$simplestatus.='mysql=defunct';
  251: 	&writesimple();
  252: 	exit;
  253:     }
  254: 
  255:     my $make_metadata_table = "CREATE TABLE IF NOT EXISTS metadata (".
  256:         "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
  257:         "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
  258:         "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
  259:         "copyright TEXT, FULLTEXT idx_title (title), ".
  260:         "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
  261:         "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
  262:         "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
  263:         "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
  264:         "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
  265:         "FULLTEXT idx_copyright (copyright)) TYPE=MYISAM";
  266:     # It would sure be nice to have some logging mechanism.
  267:     $dbh->do($make_metadata_table);
  268: }
  269: 
  270: # ------------------------------------------------------------- get .meta files
  271: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
  272: my @homeusers = grep {
  273:     &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
  274:     } grep {!/^\.\.?$/} readdir(RESOURCES);
  275: closedir RESOURCES;
  276: 
  277: #
  278: # Create the statement handlers we need
  279: my $delete_sth = $dbh->prepare
  280:     ("DELETE FROM metadata WHERE url LIKE BINARY ?");
  281: 
  282: my $insert_sth = $dbh->prepare
  283:     ("INSERT INTO metadata VALUES (".
  284:      "?,".   # title
  285:      "?,".   # author
  286:      "?,".   # subject
  287:      "?,".   # m2???
  288:      "?,".   # version
  289:      "?,".   # current
  290:      "?,".   # notes
  291:      "?,".   # abstract
  292:      "?,".   # mime
  293:      "?,".   # language
  294:      "?,".   # creationdate
  295:      "?,".   # revisiondate
  296:      "?,".   # owner
  297:      "?)"    # copyright
  298:      );
  299: 
  300: foreach my $user (@homeusers) {
  301:     print LOG "\n=== User: ".$user."\n\n";
  302: 
  303:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
  304:     # Use find.pl
  305:     undef @metalist;
  306:     @metalist=();
  307:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  308:     # -- process each file to get metadata and put into search catalog SQL
  309:     # database.  Also, check to see if already there.
  310:     # I could just delete (without searching first), but this works for now.
  311:     foreach my $m (@metalist) {
  312:         print LOG "- ".$m."\n";
  313:         my $ref=&metadata($m);
  314:         my $m2='/res/'.&declutter($m);
  315:         $m2=~s/\.meta$//;
  316:         &dynamicmeta($m2);
  317:  	if ($ref->{'obsolete'}) { print LOG "obsolete\n"; next; }
  318: 	if ($ref->{'copyright'} eq 'private') { print LOG "private\n"; next; }
  319: 	&count($m2);
  320:         $delete_sth->execute($m2);
  321:         $insert_sth->execute($ref->{'title'},
  322:                              $ref->{'author'},
  323:                              $ref->{'subject'},
  324:                              $m2,
  325:                              $ref->{'keywords'},
  326:                              'current',
  327:                              $ref->{'notes'},
  328:                              $ref->{'abstract'},
  329:                              $ref->{'mime'},
  330:                              $ref->{'language'},
  331:                              sqltime($ref->{'creationdate'}),
  332:                              sqltime($ref->{'lastrevisiondate'}),
  333:                              $ref->{'owner'},
  334:                              $ref->{'copyright'});
  335: #        if ($dbh->err()) {
  336: #            print STDERR "Error:".$dbh->errstr()."\n";
  337: #        }
  338:         $ref = undef;
  339:     }
  340:     
  341:     # --------------------------------------------------- Clean up database
  342:     # Need to, perhaps, remove stale SQL database records.
  343:     # ... not yet implemented
  344:         
  345: }
  346: # --------------------------------------------------- Close database connection
  347: $dbh->disconnect;
  348: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  349: close(LOG);
  350: &writesimple();
  351: &writecount();
  352: exit 0;
  353: 
  354: 
  355: 
  356: # =============================================================================
  357: 
  358: # ---------------------------------------------------------------- Get metadata
  359: # significantly altered from subroutine present in lonnet
  360: sub metadata {
  361:     my ($uri,$what)=@_;
  362:     my %metacache;
  363:     $uri=&declutter($uri);
  364:     my $filename=$uri;
  365:     $uri=~s/\.meta$//;
  366:     $uri='';
  367:     unless ($metacache{$uri.'keys'}) {
  368:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  369: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  370:         my $parser=HTML::TokeParser->new(\$metastring);
  371:         my $token;
  372:         while ($token=$parser->get_token) {
  373:             if ($token->[0] eq 'S') {
  374:                 my $entry=$token->[1];
  375:                 my $unikey=$entry;
  376:                 if (defined($token->[2]->{'part'})) { 
  377:                     $unikey.='_'.$token->[2]->{'part'}; 
  378:                 }
  379:                 if (defined($token->[2]->{'name'})) { 
  380:                     $unikey.='_'.$token->[2]->{'name'}; 
  381:                 }
  382:                 if ($metacache{$uri.'keys'}) {
  383:                     $metacache{$uri.'keys'}.=','.$unikey;
  384:                 } else {
  385:                     $metacache{$uri.'keys'}=$unikey;
  386:                 }
  387:                 map {
  388:                     $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  389:                 } @{$token->[3]};
  390:                 unless (
  391:                         $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  392:                         ) { $metacache{$uri.''.$unikey}=
  393:                                 $metacache{$uri.''.$unikey.'.default'};
  394:                         }
  395:             }
  396:         }
  397:     }
  398:     return \%metacache;
  399: }
  400: 
  401: # ------------------------------------------------------------ Serves up a file
  402: # returns either the contents of the file or a -1
  403: sub getfile {
  404:     my $file=shift;
  405:     if (! -e $file ) { return -1; };
  406:     my $fh=IO::File->new($file);
  407:     my $a='';
  408:     while (<$fh>) { $a .=$_; }
  409:     return $a;
  410: }
  411: 
  412: # ------------------------------------------------------------- Declutters URLs
  413: sub declutter {
  414:     my $thisfn=shift;
  415:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  416:     $thisfn=~s/^\///;
  417:     $thisfn=~s/^res\///;
  418:     return $thisfn;
  419: }
  420: 
  421: # --------------------------------------- Is this the home server of an author?
  422: # (copied from lond, modification of the return value)
  423: sub ishome {
  424:     my $author=shift;
  425:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  426:     my ($udom,$uname)=split(/\//,$author);
  427:     my $proname=propath($udom,$uname);
  428:     if (-e $proname) {
  429: 	return 1;
  430:     } else {
  431:         return 0;
  432:     }
  433: }
  434: 
  435: # -------------------------------------------- Return path to profile directory
  436: # (copied from lond)
  437: sub propath {
  438:     my ($udom,$uname)=@_;
  439:     $udom=~s/\W//g;
  440:     $uname=~s/\W//g;
  441:     my $subdir=$uname.'__';
  442:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  443:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  444:     return $proname;
  445: } 
  446: 
  447: # ---------------------------- convert 'time' format into a datetime sql format
  448: sub sqltime {
  449:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  450: 	localtime(&unsqltime(@_[0]));
  451:     $mon++; $year+=1900;
  452:     return "$year-$mon-$mday $hour:$min:$sec";
  453: }
  454: 
  455: sub maketime {
  456:     my %th=@_;
  457:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
  458:                           $th{'day'},$th{'month'}-1,
  459:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
  460: }
  461: 
  462: 
  463: #########################################
  464: #
  465: # Retro-fixing of un-backward-compatible time format
  466: 
  467: sub unsqltime {
  468:     my $timestamp=shift;
  469:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  470:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
  471:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  472:     }
  473:     return $timestamp;
  474: }
  475: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>