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

1.1       harris41    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # searchcat.pl "Search Catalog" batch script
1.16      harris41    4: #
1.35    ! www         5: # $Id: searchcat.pl,v 1.34 2003/06/19 20:24:57 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.28      harris41   79: 
1.31      harris41   80: # ----------------------------------------------------- Un-Escape Special Chars
1.28      harris41   81: 
1.31      harris41   82: sub unescape {
                     83:     my $str=shift;
1.21      www        84:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.31      harris41   85:     return $str;
                     86: }
1.21      www        87: 
1.31      harris41   88: # -------------------------------------------------------- Escape Special Chars
1.22      www        89: 
1.31      harris41   90: sub escape {
                     91:     my $str=shift;
1.22      www        92:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
1.31      harris41   93:     return $str;
                     94: }
1.28      harris41   95: 
                     96: 
1.31      harris41   97: # ------------------------------------------- Code to evaluate dynamic metadata
1.28      harris41   98: 
1.31      harris41   99: sub dynamicmeta {
1.28      harris41  100: 
1.30      www       101:     my $url=&declutter(shift);
                    102:     $url=~s/\.meta$//;
                    103:     my %returnhash=();
                    104:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
1.31      harris41  105:     my $prodir=&propath($adomain,$aauthor);
1.25      www       106:     if ((tie(%evaldata,'GDBM_File',
1.35    ! www       107:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
1.25      www       108:         (tie(%newevaldata,'GDBM_File',
1.35    ! www       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;
1.34      matthew   132:             if (defined($cnt{$ctype})) { 
1.35    ! www       133:                $cnt{$ctype}++; 
1.34      matthew   134:             } else { 
1.35    ! www       135:                $cnt{$ctype}=1; 
1.34      matthew   136:             }
                    137:             unless ($listitems{$ctype} eq 'app') {
1.35    ! www       138:                if (defined($sum{$ctype})) {
        !           139:                   $sum{$ctype}+=$evaldata{$_};
        !           140:    	       } else {
        !           141:                   $sum{$ctype}=$evaldata{$_};
        !           142: 	       }
1.34      matthew   143:             } else {
1.35    ! www       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;
1.30      www       174: }
1.35    ! www       175:   
1.31      harris41  176: # ----------------- Code to enable 'find' subroutine listing of the .meta files
                    177: require "find.pl";
                    178: sub wanted {
1.1       harris41  179:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
1.33      matthew   180:         -f _ &&
                    181:         /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
                    182:         push(@metalist,"$dir/$_");
1.31      harris41  183: }
1.28      harris41  184: 
1.31      harris41  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
1.28      harris41  190: 
1.31      harris41  191: # ------------------------------------- Only run if machine is a library server
                    192: exit unless $perlvar{'lonRole'} eq 'library';
1.1       harris41  193: 
1.31      harris41  194: # ----------------------------- Make sure this process is running from user=www
1.15      harris41  195: 
1.31      harris41  196: my $wwwid=getpwnam('www');
                    197: if ($wwwid!=$<) {
1.33      matthew   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.' |\
1.31      harris41  201:  mailto $emailto -s '$subj' > /dev/null");
1.33      matthew   202:     exit 1;
1.31      harris41  203: }
1.1       harris41  204: 
1.27      www       205: 
1.31      harris41  206: # ---------------------------------------------------------- We are in business
1.27      www       207: 
1.31      harris41  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: }
1.27      www       233: 
1.31      harris41  234: # ------------------------------------------------------------- get .meta files
                    235: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
1.33      matthew   236: my @homeusers = grep {
                    237:     &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
                    238:     } grep {!/^\.\.?$/} readdir(RESOURCES);
1.31      harris41  239: closedir RESOURCES;
1.34      matthew   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: 
1.31      harris41  264: foreach my $user (@homeusers) {
                    265:     print LOG "\n=== User: ".$user."\n\n";
1.33      matthew   266:     # Remove left-over db-files from potentially crashed searchcat run
1.31      harris41  267:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
                    268:     unlink($prodir.'/nohist_new_resevaldata.db');
1.33      matthew   269:     # Use find.pl
1.31      harris41  270:     undef @metalist;
                    271:     @metalist=();
                    272:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
1.33      matthew   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);
1.34      matthew   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;
1.31      harris41  301:     }
1.33      matthew   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
1.31      harris41  308:     system('mv '.$prodir.'/nohist_new_resevaldata.db '.
1.33      matthew   309:            $prodir.'/nohist_resevaldata.db');
1.31      harris41  310: }
                    311: # --------------------------------------------------- Close database connection
                    312: $dbh->disconnect;
                    313: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
                    314: close(LOG);
                    315: exit 0;
1.33      matthew   316: 
                    317: 
                    318: 
1.31      harris41  319: # =============================================================================
1.1       harris41  320: 
1.31      harris41  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) {
1.33      matthew   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:         }
1.31      harris41  360:     }
                    361:     return \%metacache;
                    362: }
1.28      harris41  363: 
1.31      harris41  364: # ------------------------------------------------------------ Serves up a file
                    365: # returns either the contents of the file or a -1
                    366: sub getfile {
1.33      matthew   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;
1.31      harris41  373: }
1.28      harris41  374: 
1.31      harris41  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: }
1.28      harris41  383: 
1.31      harris41  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: }
1.28      harris41  397: 
1.31      harris41  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: } 
1.28      harris41  409: 
1.31      harris41  410: # ---------------------------- convert 'time' format into a datetime sql format
                    411: sub sqltime {
1.13      harris41  412:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.31      harris41  413: 	localtime(&unsqltime(@_[0]));
                    414:     $mon++; $year+=1900;
                    415:     return "$year-$mon-$mday $hour:$min:$sec";
                    416: }
1.28      harris41  417: 
1.31      harris41  418: sub maketime {
                    419:     my %th=@_;
1.33      matthew   420:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
                    421:                           $th{'day'},$th{'month'}-1,
                    422:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
1.31      harris41  423: }
1.28      harris41  424: 
                    425: 
1.31      harris41  426: #########################################
                    427: #
                    428: # Retro-fixing of un-backward-compatible time format
1.28      harris41  429: 
1.31      harris41  430: sub unsqltime {
                    431:     my $timestamp=shift;
                    432:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1.33      matthew   433:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
                    434:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1.31      harris41  435:     }
                    436:     return $timestamp;
                    437: }
1.28      harris41  438: 

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