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

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

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