File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.48: download - view: text, annotated - select for diffs
Thu Dec 25 13:11:56 2003 UTC (20 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Slowing getting there. Still needs subjective evaluation data included.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.48 2003/12/25 13:11:56 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.
   60: 
   61: This script is playing an increasingly important role for a loncapa
   62: library server.  The proper operation of this script is critical for a smooth
   63: and correct user experience.
   64: 
   65: =cut
   66: 
   67: use strict;
   68: 
   69: use lib '/home/httpd/lib/perl/';
   70: use LONCAPA::Configuration;
   71: 
   72: use IO::File;
   73: use HTML::TokeParser;
   74: use DBI;
   75: use GDBM_File;
   76: use POSIX qw(strftime mktime);
   77: 
   78: require "find.pl";
   79: 
   80: my @metalist;
   81: 
   82: my $simplestatus='';
   83: my %countext=();
   84: 
   85: # ----------------------------------------------------- write out simple status
   86: sub writesimple {
   87:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
   88:     print SMP $simplestatus."\n";
   89:     close(SMP);
   90: }
   91: 
   92: sub writecount {
   93:     open(RSMP,'>/home/httpd/html/lon-status/rescount.txt');
   94:     foreach (keys %countext) {
   95: 	print RSMP $_.'='.$countext{$_}.'&';
   96:     }
   97:     print RSMP 'time='.time."\n";
   98:     close(RSMP);
   99: }
  100: 
  101: # -------------------------------------- counts files with different extensions
  102: sub count {
  103:     my $file=shift;
  104:     $file=~/\.(\w+)$/;
  105:     my $ext=lc($1);
  106:     if (defined($countext{$ext})) {
  107: 	$countext{$ext}++;
  108:     } else {
  109: 	$countext{$ext}=1;
  110:     }
  111: }
  112: # ----------------------------------------------------- Un-Escape Special Chars
  113: 
  114: sub unescape {
  115:     my $str=shift;
  116:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  117:     return $str;
  118: }
  119: 
  120: # -------------------------------------------------------- Escape Special Chars
  121: 
  122: sub escape {
  123:     my $str=shift;
  124:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  125:     return $str;
  126: }
  127: 
  128: # ------------------------------------------- Code to evaluate dynamic metadata
  129: 
  130: sub dynamicmeta {
  131:     my $url=&declutter(shift);
  132:     $url=~s/\.meta$//;
  133:     my %returnhash=(
  134: 		    'count' => 0,
  135: 		    'course' => 0,
  136: 		    'course_list' => '',
  137: 		    'avetries' => 0,
  138: 		    'avetries_list' => '',
  139: 		    'stdno' => 0,
  140: 		    'stdno_list' => '',
  141: 		    'usage' => 0,
  142: 		    'usage_list' => '',
  143: 		    'goto' => 0,
  144: 		    'goto_list' => '',
  145: 		    'comefrom' => 0,
  146: 		    'comefrom_list' => '',
  147: 		    'difficulty' => 0,
  148: 		    'difficulty_list' => ''
  149: 		    );
  150:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
  151:     my $prodir=&propath($adomain,$aauthor);
  152: 
  153: # Get metadata except counts
  154:     if (tie(my %evaldata,'GDBM_File',
  155:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) {
  156: 	my %sum=();
  157: 	my %cnt=();
  158: 	my %concat=();
  159: 	my %listitems=(
  160: 		       'course'       => 'add',
  161: 		       'goto'         => 'add',
  162: 		       'comefrom'     => 'add',
  163: 		       'avetries'     => 'avg',
  164: 		       'stdno'        => 'add',
  165: 		       'difficulty'   => 'avg',
  166: 		       'clear'        => 'avg',
  167: 		       'technical'    => 'avg',
  168: 		       'helpful'      => 'avg',
  169: 		       'correct'      => 'avg',
  170: 		       'depth'        => 'avg',
  171: 		       'comments'     => 'app',
  172: 		       'usage'        => 'cnt'
  173: 		       );
  174: 	
  175: 	my $regexp=$url;
  176: 	$regexp=~s/(\W)/\\$1/g;
  177: 	$regexp='___'.$regexp.'___([a-z]+)$';
  178: 	while (my ($esckey,$value)=each %evaldata) {
  179: 	    my $key=&unescape($esckey);
  180: 	    if ($key=~/$regexp/) {
  181: 		my ($item,$purl,$cat)=split(/___/,$key);
  182: 		if (defined($cnt{$cat})) { $cnt{$cat}++; } else { $cnt{$cat}=1; }
  183: 		unless ($listitems{$cat} eq 'app') {
  184: 		    if (defined($sum{$cat})) {
  185: 			$sum{$cat}+=$evaldata{$esckey};
  186: 			$concat{$cat}.=','.$item;
  187: 		    } else {
  188: 			$sum{$cat}=$evaldata{$esckey};
  189: 			$concat{$cat}=$item;
  190: 		    }
  191: 		} else {
  192: 		    if (defined($sum{$cat})) {
  193: 			if ($evaldata{$esckey}=~/\w/) {
  194: 			    $sum{$cat}.='<hr>'.$evaldata{$esckey};
  195: 			}
  196: 		    } else {
  197: 			$sum{$cat}=''.$evaldata{$esckey};
  198: 		    }
  199: 		}
  200: 	    }
  201: 	}
  202: 	untie(%evaldata);
  203: # transfer gathered data to returnhash, calculate averages where applicable
  204: 	while (my $cat=each(%cnt)) {
  205: 	    if ($cnt{$cat} eq 'nan') { next; }
  206: 	    if ($sum{$cat} eq 'nan') { next; }
  207: 	    if ($listitems{$cat} eq 'avg') {
  208: 		if ($cnt{$cat}) {
  209: 		    $returnhash{$cat}=int(($sum{$cat}/$cnt{$cat})*100.0+0.5)/100.0;
  210: 		} else {
  211: 		    $returnhash{$cat}='NULL';
  212: 		}
  213: 	    } elsif ($listitems{$cat} eq 'cnt') {
  214: 		$returnhash{$cat}=$cnt{$cat};
  215: 	    } else {
  216: 		$returnhash{$cat}=$sum{$cat};
  217: 	    }
  218: 	    $returnhash{$cat.'_list'}=$concat{$cat};
  219: 	}
  220:     }
  221: # get count
  222:     if (tie(my %evaldata,'GDBM_File',
  223:             $prodir.'/nohist_accesscount.db',&GDBM_READER(),0640)) {
  224: 	my $escurl=&escape($url);
  225: 	if (! exists($evaldata{$escurl})) {
  226: 	    $returnhash{'count'}=0;
  227: 	} else {
  228: 	    $returnhash{'count'}=$evaldata{$escurl};
  229: 	}
  230: 	untie %evaldata;
  231:     }
  232:     return %returnhash;
  233: }
  234:   
  235: # ---------------  Read loncapa_apache.conf and loncapa.conf and get variables
  236: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  237: my %perlvar=%{$perlvarref};
  238: undef $perlvarref; # remove since sensitive and not needed
  239: delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
  240: 
  241: # ------------------------------------- Only run if machine is a library server
  242: exit unless $perlvar{'lonRole'} eq 'library';
  243: 
  244: # ----------------------------- Make sure this process is running from user=www
  245: 
  246: my $wwwid=getpwnam('www');
  247: if ($wwwid!=$<) {
  248:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  249:     my $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  250:     system("echo 'User ID mismatch. searchcat.pl must be run as user www.' |\
  251:  mailto $emailto -s '$subj' > /dev/null");
  252:     exit 1;
  253: }
  254: 
  255: 
  256: # ---------------------------------------------------------- We are in business
  257: 
  258: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
  259: print LOG '==== Searchcat Run '.localtime()."====\n\n";
  260: $simplestatus='time='.time.'&';
  261: my $dbh;
  262: # ------------------------------------- Make sure that database can be accessed
  263: {
  264:     unless (
  265: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  266: 	    ) { 
  267: 	print LOG "Cannot connect to database!\n";
  268: 	$simplestatus.='mysql=defunct';
  269: 	&writesimple();
  270: 	exit;
  271:     }
  272: 
  273: # Make temporary table
  274:     $dbh->do("DROP TABLE IF EXISTS newmetadata");
  275:     my $make_metadata_table = "CREATE TABLE IF NOT EXISTS newmetadata (".
  276:         "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
  277:         "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
  278:         "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
  279:         "copyright TEXT, ".
  280:         "count INTEGER UNSIGNED, ".
  281:         "course INTEGER UNSIGNED, course_list TEXT, ".
  282:         "goto INTEGER UNSIGNED, goto_list TEXT, ".
  283:         "comefrom INTEGER UNSIGNED, comefrom_list TEXT, ".
  284:         "sequsage INTEGER UNSIGNED, sequsage_list TEXT, ".
  285:         "stdno INTEGER UNSIGNED, stdno_list TEXT, ".
  286: 	"avetries FLOAT, avetries_list TEXT, ".
  287:         "difficulty FLOAT, difficulty_list TEXT, ".
  288:         "FULLTEXT idx_title (title), ".
  289:         "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
  290:         "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
  291:         "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
  292:         "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
  293:         "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
  294:         "FULLTEXT idx_copyright (copyright)) ".
  295:         "TYPE=MyISAM";
  296:     # It would sure be nice to have some logging mechanism.
  297:     unless ($dbh->do($make_metadata_table)) {
  298: 	print LOG "\nMySQL Error Create: ".$dbh->errstr."\n";
  299: 	die $dbh->errstr;
  300:     }
  301: }
  302: 
  303: # ------------------------------------------------------------- get .meta files
  304: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
  305: my @homeusers = grep {
  306:     &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
  307:     } grep {!/^\.\.?$/} readdir(RESOURCES);
  308: closedir RESOURCES;
  309: 
  310: #
  311: # Create the statement handlers we need
  312: 
  313: my $insert_sth = $dbh->prepare
  314:     ("INSERT INTO newmetadata VALUES (".
  315:      "?,".   # title
  316:      "?,".   # author
  317:      "?,".   # subject
  318:      "?,".   # declutter url
  319:      "?,".   # version
  320:      "?,".   # current
  321:      "?,".   # notes
  322:      "?,".   # abstract
  323:      "?,".   # mime
  324:      "?,".   # language
  325:      "?,".   # creationdate
  326:      "?,".   # revisiondate
  327:      "?,".   # owner
  328:      "?,".   # copyright
  329:      "?,".   # count
  330:      "?,".   # course
  331:      "?,".   # course_list
  332:      "?,".   # goto
  333:      "?,".   # goto_list
  334:      "?,".   # comefrom
  335:      "?,".   # comefrom_list
  336:      "?,".   # usage
  337:      "?,".   # usage_list
  338:      "?,".   # stdno
  339:      "?,".   # stdno_list
  340:      "?,".   # avetries
  341:      "?,".   # avetries_list
  342:      "?,".   # difficulty
  343:      "?".    # difficulty_list
  344:      ")"
  345:      );
  346: 
  347: foreach my $user (@homeusers) {
  348:     print LOG "\n=== User: ".$user."\n\n";
  349: 
  350:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
  351:     # Use find.pl
  352:     undef @metalist;
  353:     @metalist=();
  354:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  355:     # -- process each file to get metadata and put into search catalog SQL
  356:     # database.  Also, check to see if already there.
  357:     # I could just delete (without searching first), but this works for now.
  358:     foreach my $m (@metalist) {
  359:         print LOG "- ".$m."\n";
  360:         my $ref=&metadata($m);
  361:         my $m2='/res/'.&declutter($m);
  362:         $m2=~s/\.meta$//;
  363:  	if ($ref->{'obsolete'}) { print LOG "obsolete\n"; next; }
  364: 	if ($ref->{'copyright'} eq 'private') { print LOG "private\n"; next; }
  365:         my %dyn=&dynamicmeta($m2);
  366: 	&count($m2);
  367:         unless ($insert_sth->execute(
  368: 			     $ref->{'title'},
  369:                              $ref->{'author'},
  370:                              $ref->{'subject'},
  371:                              $m2,
  372:                              $ref->{'keywords'},
  373:                              'current',
  374:                              $ref->{'notes'},
  375:                              $ref->{'abstract'},
  376:                              $ref->{'mime'},
  377:                              $ref->{'language'},
  378:                              sqltime($ref->{'creationdate'}),
  379:                              sqltime($ref->{'lastrevisiondate'}),
  380:                              $ref->{'owner'},
  381:                              $ref->{'copyright'},
  382: 			     $dyn{'count'},
  383: 			     $dyn{'course'},
  384: 			     $dyn{'course_list'},
  385: 			     $dyn{'goto'},
  386: 			     $dyn{'goto_list'},
  387: 			     $dyn{'comefrom'},
  388: 			     $dyn{'comefrom_list'},
  389: 			     $dyn{'usage'},
  390: 			     $dyn{'usage_list'},
  391: 			     $dyn{'stdno'},
  392: 			     $dyn{'stdno_list'},
  393: 			     $dyn{'avetries'},
  394: 			     $dyn{'avetries_list'},
  395: 			     $dyn{'difficulty'},
  396: 			     $dyn{'difficulty_list'}			     
  397: 			     )) {
  398: 	    print LOG "\nMySQL Error Insert: ".$dbh->errstr."\n";
  399: 	    die $dbh->errstr;
  400: 	}
  401:         $ref = undef;
  402:     }
  403: }
  404: # --------------------------------------------------- Close database connection
  405: $dbh->do("DROP TABLE IF EXISTS metadata");
  406: unless ($dbh->do("RENAME TABLE newmetadata TO metadata")) {
  407:     print LOG "\nMySQL Error Rename: ".$dbh->errstr."\n";
  408:     die $dbh->errstr;
  409: }
  410: unless ($dbh->disconnect) {
  411:     print LOG "\nMySQL Error Disconnect: ".$dbh->errstr."\n";
  412:     die $dbh->errstr;
  413: }
  414: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  415: close(LOG);
  416: &writesimple();
  417: &writecount();
  418: exit 0;
  419: 
  420: 
  421: 
  422: # =============================================================================
  423: 
  424: # ---------------------------------------------------------------- Get metadata
  425: # significantly altered from subroutine present in lonnet
  426: sub metadata {
  427:     my ($uri,$what)=@_;
  428:     my %metacache=();
  429:     $uri=&declutter($uri);
  430:     my $filename=$uri;
  431:     $uri=~s/\.meta$//;
  432:     $uri='';
  433:     unless ($metacache{$uri.'keys'}) {
  434:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  435: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  436:         my $parser=HTML::TokeParser->new(\$metastring);
  437:         my $token;
  438:         while ($token=$parser->get_token) {
  439:             if ($token->[0] eq 'S') {
  440:                 my $entry=$token->[1];
  441:                 my $unikey=$entry;
  442:                 if (defined($token->[2]->{'part'})) { 
  443:                     $unikey.='_'.$token->[2]->{'part'}; 
  444:                 }
  445:                 if (defined($token->[2]->{'name'})) { 
  446:                     $unikey.='_'.$token->[2]->{'name'}; 
  447:                 }
  448:                 if ($metacache{$uri.'keys'}) {
  449:                     $metacache{$uri.'keys'}.=','.$unikey;
  450:                 } else {
  451:                     $metacache{$uri.'keys'}=$unikey;
  452:                 }
  453:                 map {
  454:                     $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  455:                 } @{$token->[3]};
  456:                 unless (
  457:                         $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  458:                         ) { $metacache{$uri.''.$unikey}=
  459:                                 $metacache{$uri.''.$unikey.'.default'};
  460:                         }
  461:             }
  462:         }
  463:     }
  464:     return \%metacache;
  465: }
  466: 
  467: # ------------------------------------------------------------ Serves up a file
  468: # returns either the contents of the file or a -1
  469: sub getfile {
  470:     my $file=shift;
  471:     if (! -e $file ) { return -1; };
  472:     my $fh=IO::File->new($file);
  473:     my $a='';
  474:     while (<$fh>) { $a .=$_; }
  475:     return $a;
  476: }
  477: 
  478: # ------------------------------------------------------------- Declutters URLs
  479: sub declutter {
  480:     my $thisfn=shift;
  481:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  482:     $thisfn=~s/^\///;
  483:     $thisfn=~s/^res\///;
  484:     return $thisfn;
  485: }
  486: 
  487: # --------------------------------------- Is this the home server of an author?
  488: # (copied from lond, modification of the return value)
  489: sub ishome {
  490:     my $author=shift;
  491:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  492:     my ($udom,$uname)=split(/\//,$author);
  493:     my $proname=propath($udom,$uname);
  494:     if (-e $proname) {
  495: 	return 1;
  496:     } else {
  497:         return 0;
  498:     }
  499: }
  500: 
  501: # -------------------------------------------- Return path to profile directory
  502: # (copied from lond)
  503: sub propath {
  504:     my ($udom,$uname)=@_;
  505:     $udom=~s/\W//g;
  506:     $uname=~s/\W//g;
  507:     my $subdir=$uname.'__';
  508:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  509:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  510:     return $proname;
  511: } 
  512: 
  513: # ---------------------------- convert 'time' format into a datetime sql format
  514: sub sqltime {
  515:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  516: 	localtime(&unsqltime(@_[0]));
  517:     $mon++; $year+=1900;
  518:     return "$year-$mon-$mday $hour:$min:$sec";
  519: }
  520: 
  521: sub maketime {
  522:     my %th=@_;
  523:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
  524:                           $th{'day'},$th{'month'}-1,
  525:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
  526: }
  527: 
  528: 
  529: #########################################
  530: #
  531: # Retro-fixing of un-backward-compatible time format
  532: 
  533: sub unsqltime {
  534:     my $timestamp=shift;
  535:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  536:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
  537:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  538:     }
  539:     return $timestamp;
  540: }
  541: 
  542: # ----------------- Code to enable 'find' subroutine listing of the .meta files
  543: 
  544: no strict "vars";
  545: 
  546: sub wanted {
  547:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
  548:          -f _ &&
  549:          /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
  550:          push(@metalist,"$dir/$_");
  551: }

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