File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.40: download - view: text, annotated - select for diffs
Fri Sep 26 00:23:09 2003 UTC (20 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Start to respect "obsolete"

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

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