File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.39: download - view: text, annotated - select for diffs
Thu Aug 21 01:48:22 2003 UTC (20 years, 9 months ago) by www
Branches: MAIN
CVS tags: version_1_0_1, HEAD
Comment out calls to dynamic meta function.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.39 2003/08/21 01:48:22 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:         my $m2='/res/'.&declutter($m);
  311:         $m2=~s/\.meta$//;
  312: #        &dynamicmeta($m2);
  313: 	&count($m2);
  314:         $delete_sth->execute($m2);
  315:         $insert_sth->execute($ref->{'title'},
  316:                              $ref->{'author'},
  317:                              $ref->{'subject'},
  318:                              $m2,
  319:                              $ref->{'keywords'},
  320:                              'current',
  321:                              $ref->{'notes'},
  322:                              $ref->{'abstract'},
  323:                              $ref->{'mime'},
  324:                              $ref->{'language'},
  325:                              sqltime($ref->{'creationdate'}),
  326:                              sqltime($ref->{'lastrevisiondate'}),
  327:                              $ref->{'owner'},
  328:                              $ref->{'copyright'});
  329: #        if ($dbh->err()) {
  330: #            print STDERR "Error:".$dbh->errstr()."\n";
  331: #        }
  332:         $ref = undef;
  333:     }
  334:     
  335:     # --------------------------------------------------- Clean up database
  336:     # Need to, perhaps, remove stale SQL database records.
  337:     # ... not yet implemented
  338:         
  339:     # ------------------------------------------- Copy over the new db-files
  340:     #
  341:     # Check the size of nohist_new_resevaldata.db compared to 
  342:     # nohist_resevaldata.db
  343: #    my @stat_result = stat($prodir.'/nohist_new_resevaldata.db');
  344: #    my $new_size = $stat_result[7];
  345: #    @stat_result = stat($prodir.'/nohist_resevaldata.db');
  346: #    my $old_size = $stat_result[7];
  347: #    if ($old_size) {
  348: #	if ($new_size/$old_size > 0.15 ) {
  349: #	    system('mv '.$prodir.'/nohist_new_resevaldata.db '.
  350: #		   $prodir.'/nohist_resevaldata.db');
  351: #	} else {
  352: #	    print LOG "Size of '$user' old nohist_reseval: $old_size ".
  353: #		"Size of new: $new_size.  Not overwriting.\n";
  354: #	    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  355: #	    my $subj="LON: $perlvar{'lonHostID'} searchcat.pl $user reseval ".
  356: #		"modification error.";
  357: #	    system("echo ".
  358: #		"'See /home/httpd/perl/logs/searchcat.txt for information.' ".
  359: #		   "| mailto $emailto -s '$subj' > /dev/null");
  360: #	}
  361: #    }   
  362: }
  363: # --------------------------------------------------- Close database connection
  364: $dbh->disconnect;
  365: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  366: close(LOG);
  367: &writesimple();
  368: &writecount();
  369: exit 0;
  370: 
  371: 
  372: 
  373: # =============================================================================
  374: 
  375: # ---------------------------------------------------------------- Get metadata
  376: # significantly altered from subroutine present in lonnet
  377: sub metadata {
  378:     my ($uri,$what)=@_;
  379:     my %metacache;
  380:     $uri=&declutter($uri);
  381:     my $filename=$uri;
  382:     $uri=~s/\.meta$//;
  383:     $uri='';
  384:     unless ($metacache{$uri.'keys'}) {
  385:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  386: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  387:         my $parser=HTML::TokeParser->new(\$metastring);
  388:         my $token;
  389:         while ($token=$parser->get_token) {
  390:             if ($token->[0] eq 'S') {
  391:                 my $entry=$token->[1];
  392:                 my $unikey=$entry;
  393:                 if (defined($token->[2]->{'part'})) { 
  394:                     $unikey.='_'.$token->[2]->{'part'}; 
  395:                 }
  396:                 if (defined($token->[2]->{'name'})) { 
  397:                     $unikey.='_'.$token->[2]->{'name'}; 
  398:                 }
  399:                 if ($metacache{$uri.'keys'}) {
  400:                     $metacache{$uri.'keys'}.=','.$unikey;
  401:                 } else {
  402:                     $metacache{$uri.'keys'}=$unikey;
  403:                 }
  404:                 map {
  405:                     $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  406:                 } @{$token->[3]};
  407:                 unless (
  408:                         $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  409:                         ) { $metacache{$uri.''.$unikey}=
  410:                                 $metacache{$uri.''.$unikey.'.default'};
  411:                         }
  412:             }
  413:         }
  414:     }
  415:     return \%metacache;
  416: }
  417: 
  418: # ------------------------------------------------------------ Serves up a file
  419: # returns either the contents of the file or a -1
  420: sub getfile {
  421:     my $file=shift;
  422:     if (! -e $file ) { return -1; };
  423:     my $fh=IO::File->new($file);
  424:     my $a='';
  425:     while (<$fh>) { $a .=$_; }
  426:     return $a;
  427: }
  428: 
  429: # ------------------------------------------------------------- Declutters URLs
  430: sub declutter {
  431:     my $thisfn=shift;
  432:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  433:     $thisfn=~s/^\///;
  434:     $thisfn=~s/^res\///;
  435:     return $thisfn;
  436: }
  437: 
  438: # --------------------------------------- Is this the home server of an author?
  439: # (copied from lond, modification of the return value)
  440: sub ishome {
  441:     my $author=shift;
  442:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  443:     my ($udom,$uname)=split(/\//,$author);
  444:     my $proname=propath($udom,$uname);
  445:     if (-e $proname) {
  446: 	return 1;
  447:     } else {
  448:         return 0;
  449:     }
  450: }
  451: 
  452: # -------------------------------------------- Return path to profile directory
  453: # (copied from lond)
  454: sub propath {
  455:     my ($udom,$uname)=@_;
  456:     $udom=~s/\W//g;
  457:     $uname=~s/\W//g;
  458:     my $subdir=$uname.'__';
  459:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  460:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  461:     return $proname;
  462: } 
  463: 
  464: # ---------------------------- convert 'time' format into a datetime sql format
  465: sub sqltime {
  466:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  467: 	localtime(&unsqltime(@_[0]));
  468:     $mon++; $year+=1900;
  469:     return "$year-$mon-$mday $hour:$min:$sec";
  470: }
  471: 
  472: sub maketime {
  473:     my %th=@_;
  474:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
  475:                           $th{'day'},$th{'month'}-1,
  476:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
  477: }
  478: 
  479: 
  480: #########################################
  481: #
  482: # Retro-fixing of un-backward-compatible time format
  483: 
  484: sub unsqltime {
  485:     my $timestamp=shift;
  486:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  487:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
  488:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  489:     }
  490:     return $timestamp;
  491: }
  492: 

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