Annotation of loncom/metadata_database/searchcat.pl, revision 1.38

1.1       harris41    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # searchcat.pl "Search Catalog" batch script
1.16      harris41    4: #
1.38    ! www         5: # $Id: searchcat.pl,v 1.37 2003/08/08 12:38:00 matthew Exp $
1.16      harris41    6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
1.29      albertel    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
1.16      harris41   10: #
1.29      albertel   11: # LON-CAPA is free software; you can redistribute it and/or modify
1.16      harris41   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: #
1.29      albertel   16: # LON-CAPA is distributed in the hope that it will be useful,
1.16      harris41   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
1.29      albertel   22: # along with LON-CAPA; if not, write to the Free Software
1.16      harris41   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     24: #
                     25: # /home/httpd/html/adm/gpl.txt
                     26: #
1.29      albertel   27: # http://www.lon-capa.org/
1.16      harris41   28: #
                     29: ###
1.33      matthew    30: 
1.32      www        31: =pod
1.1       harris41   32: 
1.32      www        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
1.1       harris41   67: 
1.17      harris41   68: use lib '/home/httpd/lib/perl/';
                     69: use LONCAPA::Configuration;
                     70: 
1.1       harris41   71: use IO::File;
                     72: use HTML::TokeParser;
1.6       harris41   73: use DBI;
1.21      www        74: use GDBM_File;
1.24      www        75: use POSIX qw(strftime mktime);
1.1       harris41   76: 
                     77: my @metalist;
1.21      www        78: 
1.36      www        79: $simplestatus='';
1.38    ! www        80: my %countext=();
1.36      www        81: 
                     82: sub writesimple {
                     83:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
                     84:     print SMP $simplestatus."\n";
                     85:     close(SMP);
                     86: }
1.28      harris41   87: 
1.38    ! www        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: }
1.31      harris41  107: # ----------------------------------------------------- Un-Escape Special Chars
1.28      harris41  108: 
1.31      harris41  109: sub unescape {
                    110:     my $str=shift;
1.21      www       111:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.31      harris41  112:     return $str;
                    113: }
1.21      www       114: 
1.31      harris41  115: # -------------------------------------------------------- Escape Special Chars
1.22      www       116: 
1.31      harris41  117: sub escape {
                    118:     my $str=shift;
1.22      www       119:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
1.31      harris41  120:     return $str;
                    121: }
1.28      harris41  122: 
                    123: 
1.31      harris41  124: # ------------------------------------------- Code to evaluate dynamic metadata
1.28      harris41  125: 
1.31      harris41  126: sub dynamicmeta {
1.28      harris41  127: 
1.30      www       128:     my $url=&declutter(shift);
                    129:     $url=~s/\.meta$//;
                    130:     my %returnhash=();
                    131:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
1.31      harris41  132:     my $prodir=&propath($adomain,$aauthor);
1.25      www       133:     if ((tie(%evaldata,'GDBM_File',
1.35      www       134:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
1.25      www       135:         (tie(%newevaldata,'GDBM_File',
1.35      www       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;
1.34      matthew   159:             if (defined($cnt{$ctype})) { 
1.35      www       160:                $cnt{$ctype}++; 
1.34      matthew   161:             } else { 
1.35      www       162:                $cnt{$ctype}=1; 
1.34      matthew   163:             }
                    164:             unless ($listitems{$ctype} eq 'app') {
1.35      www       165:                if (defined($sum{$ctype})) {
                    166:                   $sum{$ctype}+=$evaldata{$_};
                    167:    	       } else {
                    168:                   $sum{$ctype}=$evaldata{$_};
                    169: 	       }
1.34      matthew   170:             } else {
1.35      www       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;
1.30      www       201: }
1.35      www       202:   
1.31      harris41  203: # ----------------- Code to enable 'find' subroutine listing of the .meta files
                    204: require "find.pl";
                    205: sub wanted {
1.1       harris41  206:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
1.33      matthew   207:         -f _ &&
                    208:         /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
                    209:         push(@metalist,"$dir/$_");
1.31      harris41  210: }
1.28      harris41  211: 
1.31      harris41  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
1.28      harris41  217: 
1.31      harris41  218: # ------------------------------------- Only run if machine is a library server
                    219: exit unless $perlvar{'lonRole'} eq 'library';
1.1       harris41  220: 
1.31      harris41  221: # ----------------------------- Make sure this process is running from user=www
1.15      harris41  222: 
1.31      harris41  223: my $wwwid=getpwnam('www');
                    224: if ($wwwid!=$<) {
1.33      matthew   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.' |\
1.31      harris41  228:  mailto $emailto -s '$subj' > /dev/null");
1.33      matthew   229:     exit 1;
1.31      harris41  230: }
1.1       harris41  231: 
1.27      www       232: 
1.31      harris41  233: # ---------------------------------------------------------- We are in business
1.27      www       234: 
1.31      harris41  235: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
                    236: print LOG '==== Searchcat Run '.localtime()."====\n\n";
1.36      www       237: $simplestatus='time='.time.'&';
1.31      harris41  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";
1.36      www       245: 	$simplestatus.='mysql=defunct';
                    246: 	&writesimple();
1.31      harris41  247: 	exit;
                    248:     }
1.36      www       249: 
1.31      harris41  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: }
1.27      www       264: 
1.31      harris41  265: # ------------------------------------------------------------- get .meta files
                    266: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
1.33      matthew   267: my @homeusers = grep {
                    268:     &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
                    269:     } grep {!/^\.\.?$/} readdir(RESOURCES);
1.31      harris41  270: closedir RESOURCES;
1.34      matthew   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: 
1.31      harris41  295: foreach my $user (@homeusers) {
                    296:     print LOG "\n=== User: ".$user."\n\n";
1.33      matthew   297:     # Remove left-over db-files from potentially crashed searchcat run
1.31      harris41  298:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
                    299:     unlink($prodir.'/nohist_new_resevaldata.db');
1.33      matthew   300:     # Use find.pl
1.31      harris41  301:     undef @metalist;
                    302:     @metalist=();
                    303:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
1.33      matthew   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);
1.38    ! www       313: 	&count($m2);
1.34      matthew   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;
1.31      harris41  333:     }
1.33      matthew   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
1.37      matthew   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];
1.38    ! www       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:     }   
1.31      harris41  362: }
                    363: # --------------------------------------------------- Close database connection
                    364: $dbh->disconnect;
                    365: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
                    366: close(LOG);
1.36      www       367: &writesimple();
1.38    ! www       368: &writecount();
1.31      harris41  369: exit 0;
1.33      matthew   370: 
                    371: 
                    372: 
1.31      harris41  373: # =============================================================================
1.1       harris41  374: 
1.31      harris41  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) {
1.33      matthew   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:         }
1.31      harris41  414:     }
                    415:     return \%metacache;
                    416: }
1.28      harris41  417: 
1.31      harris41  418: # ------------------------------------------------------------ Serves up a file
                    419: # returns either the contents of the file or a -1
                    420: sub getfile {
1.33      matthew   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;
1.31      harris41  427: }
1.28      harris41  428: 
1.31      harris41  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: }
1.28      harris41  437: 
1.31      harris41  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: }
1.28      harris41  451: 
1.31      harris41  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: } 
1.28      harris41  463: 
1.31      harris41  464: # ---------------------------- convert 'time' format into a datetime sql format
                    465: sub sqltime {
1.13      harris41  466:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.31      harris41  467: 	localtime(&unsqltime(@_[0]));
                    468:     $mon++; $year+=1900;
                    469:     return "$year-$mon-$mday $hour:$min:$sec";
                    470: }
1.28      harris41  471: 
1.31      harris41  472: sub maketime {
                    473:     my %th=@_;
1.33      matthew   474:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
                    475:                           $th{'day'},$th{'month'}-1,
                    476:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
1.31      harris41  477: }
1.28      harris41  478: 
                    479: 
1.31      harris41  480: #########################################
                    481: #
                    482: # Retro-fixing of un-backward-compatible time format
1.28      harris41  483: 
1.31      harris41  484: sub unsqltime {
                    485:     my $timestamp=shift;
                    486:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1.33      matthew   487:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
                    488:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1.31      harris41  489:     }
                    490:     return $timestamp;
                    491: }
1.28      harris41  492: 

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