File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.45: download - view: text, annotated - select for diffs
Wed Dec 24 19:58:37 2003 UTC (20 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my work. Dynamic metadata now correctly generated, needs to be
put into database

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

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