File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.43: download - view: text, annotated - select for diffs
Wed Oct 8 19:38:41 2003 UTC (20 years, 7 months ago) by www
Branches: MAIN
CVS tags: version_1_1_X, version_1_1_3, version_1_1_2, version_1_1_1, version_1_1_0, version_1_0_99_3, version_1_0_99_2, version_1_0_99_1, version_1_0_99, version_1_0_3, version_1_0_2, HEAD
Does what the previous one did, but uses less memory. The next version needs
to address file locking, etc., which is going to be a major change.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.43 2003/10/08 19:38:41 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: 
  128:     my $url=&declutter(shift);
  129:     $url=~s/\.meta$//;
  130:     my %returnhash=();
  131:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
  132:     my $prodir=&propath($adomain,$aauthor);
  133:     if ((tie(%evaldata,'GDBM_File',
  134:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
  135:         (tie(%newevaldata,'GDBM_File',
  136:             $prodir.'/nohist_new_resevaldata.db',&GDBM_WRCREAT(),0640))) {
  137:        my %sum=();
  138:        my %cnt=();
  139:        my %listitems=('count'        => 'add',
  140:                       'course'       => 'add',
  141: 		      'goto'         => 'add',
  142: 		      'comefrom'     => 'add',
  143:                       'avetries'     => 'avg',
  144:                       'stdno'        => 'add',
  145:                       'difficulty'   => 'avg',
  146:                       'clear'        => 'avg',
  147:                       'technical'    => 'avg',
  148:                       'helpful'      => 'avg',
  149:                       'correct'      => 'avg',
  150:                       'depth'        => 'avg',
  151:                       'comments'     => 'app',
  152:                       'usage'        => 'cnt'
  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 $ctype=$1;
  161:             if (defined($cnt{$ctype})) { 
  162:                $cnt{$ctype}++; 
  163:             } else { 
  164:                $cnt{$ctype}=1; 
  165:             }
  166:             unless ($listitems{$ctype} eq 'app') {
  167:                if (defined($sum{$ctype})) {
  168:                   $sum{$ctype}+=$value;
  169:    	       } else {
  170:                   $sum{$ctype}=$value;
  171: 	       }
  172:             } else {
  173:                if (defined($sum{$ctype})) {
  174:                   if ($value) {
  175:                      $sum{$ctype}.='<hr>'.$value;
  176: 	          }
  177:  	       } else {
  178: 	             $sum{$ctype}=''.$value;
  179: 	       }
  180: 	    }
  181: 	    if ($ctype ne 'count') {
  182: 	       $newevaldata{$esckey}=$value;
  183: 	   }
  184: 	 }
  185:       }
  186:       foreach (keys %cnt) {
  187:          if ($listitems{$_} eq 'avg') {
  188: 	     $returnhash{$_}=int(($sum{$_}/$cnt{$_})*100.0+0.5)/100.0;
  189:          } elsif ($listitems{$_} eq 'cnt') {
  190:              $returnhash{$_}=$cnt{$_};
  191:          } else {
  192:              $returnhash{$_}=$sum{$_};
  193:          }
  194:      }
  195:      if ($returnhash{'count'}) {
  196:          my $newkey=$$.'_'.time.'_searchcat___'.&escape($url).'___count';
  197:          $newevaldata{$newkey}=$returnhash{'count'};
  198:      }
  199:      untie(%evaldata);
  200:      untie(%newevaldata);
  201:    }
  202:    return %returnhash;
  203: }
  204:   
  205: # ----------------- Code to enable 'find' subroutine listing of the .meta files
  206: require "find.pl";
  207: sub wanted {
  208:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
  209:         -f _ &&
  210:         /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
  211:         push(@metalist,"$dir/$_");
  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:     $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  228:     $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:     # Remove left-over db-files from potentially crashed searchcat run
  300:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
  301:     unlink($prodir.'/nohist_new_resevaldata.db');
  302:     # Use find.pl
  303:     undef @metalist;
  304:     @metalist=();
  305:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  306:     # -- process each file to get metadata and put into search catalog SQL
  307:     # database.  Also, check to see if already there.
  308:     # I could just delete (without searching first), but this works for now.
  309:     foreach my $m (@metalist) {
  310:         print LOG "- ".$m."\n";
  311:         my $ref=&metadata($m);
  312:         my $m2='/res/'.&declutter($m);
  313:         $m2=~s/\.meta$//;
  314:         &dynamicmeta($m2);
  315:  	if ($ref->{'obsolete'}) { print LOG "obsolete\n"; next; }
  316: 	if ($ref->{'copyright'} eq 'private') { print LOG "private\n"; next; }
  317: 	&count($m2);
  318:         $delete_sth->execute($m2);
  319:         $insert_sth->execute($ref->{'title'},
  320:                              $ref->{'author'},
  321:                              $ref->{'subject'},
  322:                              $m2,
  323:                              $ref->{'keywords'},
  324:                              'current',
  325:                              $ref->{'notes'},
  326:                              $ref->{'abstract'},
  327:                              $ref->{'mime'},
  328:                              $ref->{'language'},
  329:                              sqltime($ref->{'creationdate'}),
  330:                              sqltime($ref->{'lastrevisiondate'}),
  331:                              $ref->{'owner'},
  332:                              $ref->{'copyright'});
  333: #        if ($dbh->err()) {
  334: #            print STDERR "Error:".$dbh->errstr()."\n";
  335: #        }
  336:         $ref = undef;
  337:     }
  338:     
  339:     # --------------------------------------------------- Clean up database
  340:     # Need to, perhaps, remove stale SQL database records.
  341:     # ... not yet implemented
  342:         
  343:     # ------------------------------------------- Copy over the new db-files
  344:     #
  345: 
  346: 	    system('mv '.$prodir.'/nohist_new_resevaldata.db '.
  347: 		   $prodir.'/nohist_resevaldata.db');
  348: 
  349: }
  350: # --------------------------------------------------- Close database connection
  351: $dbh->disconnect;
  352: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  353: close(LOG);
  354: &writesimple();
  355: &writecount();
  356: exit 0;
  357: 
  358: 
  359: 
  360: # =============================================================================
  361: 
  362: # ---------------------------------------------------------------- Get metadata
  363: # significantly altered from subroutine present in lonnet
  364: sub metadata {
  365:     my ($uri,$what)=@_;
  366:     my %metacache;
  367:     $uri=&declutter($uri);
  368:     my $filename=$uri;
  369:     $uri=~s/\.meta$//;
  370:     $uri='';
  371:     unless ($metacache{$uri.'keys'}) {
  372:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  373: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  374:         my $parser=HTML::TokeParser->new(\$metastring);
  375:         my $token;
  376:         while ($token=$parser->get_token) {
  377:             if ($token->[0] eq 'S') {
  378:                 my $entry=$token->[1];
  379:                 my $unikey=$entry;
  380:                 if (defined($token->[2]->{'part'})) { 
  381:                     $unikey.='_'.$token->[2]->{'part'}; 
  382:                 }
  383:                 if (defined($token->[2]->{'name'})) { 
  384:                     $unikey.='_'.$token->[2]->{'name'}; 
  385:                 }
  386:                 if ($metacache{$uri.'keys'}) {
  387:                     $metacache{$uri.'keys'}.=','.$unikey;
  388:                 } else {
  389:                     $metacache{$uri.'keys'}=$unikey;
  390:                 }
  391:                 map {
  392:                     $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  393:                 } @{$token->[3]};
  394:                 unless (
  395:                         $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  396:                         ) { $metacache{$uri.''.$unikey}=
  397:                                 $metacache{$uri.''.$unikey.'.default'};
  398:                         }
  399:             }
  400:         }
  401:     }
  402:     return \%metacache;
  403: }
  404: 
  405: # ------------------------------------------------------------ Serves up a file
  406: # returns either the contents of the file or a -1
  407: sub getfile {
  408:     my $file=shift;
  409:     if (! -e $file ) { return -1; };
  410:     my $fh=IO::File->new($file);
  411:     my $a='';
  412:     while (<$fh>) { $a .=$_; }
  413:     return $a;
  414: }
  415: 
  416: # ------------------------------------------------------------- Declutters URLs
  417: sub declutter {
  418:     my $thisfn=shift;
  419:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  420:     $thisfn=~s/^\///;
  421:     $thisfn=~s/^res\///;
  422:     return $thisfn;
  423: }
  424: 
  425: # --------------------------------------- Is this the home server of an author?
  426: # (copied from lond, modification of the return value)
  427: sub ishome {
  428:     my $author=shift;
  429:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  430:     my ($udom,$uname)=split(/\//,$author);
  431:     my $proname=propath($udom,$uname);
  432:     if (-e $proname) {
  433: 	return 1;
  434:     } else {
  435:         return 0;
  436:     }
  437: }
  438: 
  439: # -------------------------------------------- Return path to profile directory
  440: # (copied from lond)
  441: sub propath {
  442:     my ($udom,$uname)=@_;
  443:     $udom=~s/\W//g;
  444:     $uname=~s/\W//g;
  445:     my $subdir=$uname.'__';
  446:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  447:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  448:     return $proname;
  449: } 
  450: 
  451: # ---------------------------- convert 'time' format into a datetime sql format
  452: sub sqltime {
  453:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  454: 	localtime(&unsqltime(@_[0]));
  455:     $mon++; $year+=1900;
  456:     return "$year-$mon-$mday $hour:$min:$sec";
  457: }
  458: 
  459: sub maketime {
  460:     my %th=@_;
  461:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
  462:                           $th{'day'},$th{'month'}-1,
  463:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
  464: }
  465: 
  466: 
  467: #########################################
  468: #
  469: # Retro-fixing of un-backward-compatible time format
  470: 
  471: sub unsqltime {
  472:     my $timestamp=shift;
  473:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  474:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
  475:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  476:     }
  477:     return $timestamp;
  478: }
  479: 

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