File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.36: download - view: text, annotated - select for diffs
Wed Jul 30 16:49:27 2003 UTC (20 years, 10 months ago) by www
Branches: MAIN
CVS tags: version_0_99_4, HEAD
Simple one-line status for cluster-wide automated reporting

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

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