File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.35: download - view: text, annotated - select for diffs
Wed Jun 25 14:42:00 2003 UTC (20 years, 10 months ago) by www
Branches: MAIN
CVS tags: version_0_99_3, HEAD
Part of bug #1638: Rollback of changes to dynamic_metadata routine to version
1.32. New routine had been corrupting the data file.

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

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