File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.25: download - view: text, annotated - select for diffs
Mon Nov 18 20:44:15 2002 UTC (21 years, 6 months ago) by www
Branches: MAIN
CVS tags: version_0_6, HEAD
This took a lot of memory since it first stored ALL filenames in an array.
Now does it in author chunks.
Also tries to condense resevaldata files. First run will take a long time.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.25 2002/11/18 20:44:15 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: # YEAR=2001
   30: # 04/14/2001, 04/16/2001 Scott Harrison
   31: #
   32: # YEAR=2002
   33: # 05/11/2002 Scott Harrison
   34: #
   35: ###
   36: 
   37: # This script goes through a LON-CAPA resource
   38: # directory and gathers metadata.
   39: # The metadata is entered into a SQL database.
   40: 
   41: use lib '/home/httpd/lib/perl/';
   42: use LONCAPA::Configuration;
   43: 
   44: use IO::File;
   45: use HTML::TokeParser;
   46: use DBI;
   47: use GDBM_File;
   48: use POSIX qw(strftime mktime);
   49: 
   50: my @metalist;
   51: 
   52: 
   53: # ----------------------------------------------------- Un-Escape Special Chars
   54: 
   55: sub unescape {
   56:     my $str=shift;
   57:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   58:     return $str;
   59: }
   60: 
   61: # -------------------------------------------------------- Escape Special Chars
   62: 
   63: sub escape {
   64:     my $str=shift;
   65:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
   66:     return $str;
   67: }
   68: 
   69: 
   70: # ------------------------------------------- Code to evaluate dynamic metadata
   71: 
   72: sub dynamicmeta {
   73: 
   74:     my $url=&declutter(shift);
   75:     $url=~s/\.meta$//;
   76:     my %returnhash=();
   77:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
   78:     my $prodir=&propath($adomain,$aauthor);
   79:     if ((tie(%evaldata,'GDBM_File',
   80:             $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
   81:         (tie(%newevaldata,'GDBM_File',
   82:             $prodir.'/nohist_new_resevaldata.db',&GDBM_WRCREAT(),0640))) {
   83:        my %sum=();
   84:        my %cnt=();
   85:        my %listitems=('count'        => 'add',
   86:                       'course'       => 'add',
   87:                       'avetries'     => 'avg',
   88:                       'stdno'        => 'add',
   89:                       'difficulty'   => 'avg',
   90:                       'clear'        => 'avg',
   91:                       'technical'    => 'avg',
   92:                       'helpful'      => 'avg',
   93:                       'correct'      => 'avg',
   94:                       'depth'        => 'avg',
   95:                       'comments'     => 'app',
   96:                       'usage'        => 'cnt'
   97:                       );
   98:        my $regexp=$url;
   99:        $regexp=~s/(\W)/\\$1/g;
  100:        $regexp='___'.$regexp.'___([a-z]+)$';
  101:        foreach (keys %evaldata) {
  102: 	 my $key=&unescape($_);
  103: 	 if ($key=~/$regexp/) {
  104: 	    my $ctype=$1;
  105:             if (defined($cnt{$ctype})) { 
  106:                $cnt{$ctype}++; 
  107:             } else { 
  108:                $cnt{$ctype}=1; 
  109:             }
  110:             unless ($listitems{$ctype} eq 'app') {
  111:                if (defined($sum{$ctype})) {
  112:                   $sum{$ctype}+=$evaldata{$_};
  113:    	       } else {
  114:                   $sum{$ctype}=$evaldata{$_};
  115: 	       }
  116:             } else {
  117:                if (defined($sum{$ctype})) {
  118:                   if ($evaldata{$_}) {
  119:                      $sum{$ctype}.='<hr>'.$evaldata{$_};
  120: 	          }
  121:  	       } else {
  122: 	             $sum{$ctype}=''.$evaldata{$_};
  123: 	       }
  124: 	    }
  125: 	    if ($ctype ne 'count') {
  126: 	       $newevaldata{$_}=$evaldata{$_};
  127: 	   }
  128: 	 }
  129:       }
  130:       foreach (keys %cnt) {
  131:          if ($listitems{$_} eq 'avg') {
  132: 	     $returnhash{$_}=int(($sum{$_}/$cnt{$_})*100.0+0.5)/100.0;
  133:          } elsif ($listitems{$_} eq 'cnt') {
  134:              $returnhash{$_}=$cnt{$_};
  135:          } else {
  136:              $returnhash{$_}=$sum{$_};
  137:          }
  138:      }
  139:      if ($returnhash{'count'}) {
  140:          my $newkey=$$.'_'.time.'_searchcat___'.&escape($url).'___count';
  141:          $newevaldata{$newkey}=$returnhash{'count'};
  142:      }
  143:      untie(%evaldata);
  144:      untie(%newevaldata);
  145:    }
  146:    return %returnhash;
  147: }
  148:   
  149: # ----------------- Code to enable 'find' subroutine listing of the .meta files
  150: require "find.pl";
  151: sub wanted {
  152:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
  153:     -f _ &&
  154:     /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
  155:     push(@metalist,"$dir/$_");
  156: }
  157: 
  158: # ---------------  Read loncapa_apache.conf and loncapa.conf and get variables
  159: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  160: my %perlvar=%{$perlvarref};
  161: undef $perlvarref; # remove since sensitive and not needed
  162: delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
  163: 
  164: # ------------------------------------- Only run if machine is a library server
  165: exit unless $perlvar{'lonRole'} eq 'library';
  166: 
  167: # ---------------------------------------------------------- We are in business
  168: 
  169: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
  170: print LOG '==== Searchcat Run '.localtime()."====\n\n";
  171: my $dbh;
  172: # ------------------------------------- Make sure that database can be accessed
  173: {
  174:     unless (
  175: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  176: 	    ) { 
  177: 	print LOG "Cannot connect to database!\n";
  178: 	exit;
  179:     }
  180:     my $make_metadata_table = "CREATE TABLE IF NOT EXISTS metadata (".
  181:         "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
  182:         "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
  183:         "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
  184:         "copyright TEXT, FULLTEXT idx_title (title), ".
  185:         "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
  186:         "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
  187:         "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
  188:         "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
  189:         "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
  190:         "FULLTEXT idx_copyright (copyright)) TYPE=MYISAM";
  191:     # It would sure be nice to have some logging mechanism.
  192:     $dbh->do($make_metadata_table);
  193: }
  194: 
  195: # ------------------------------------------------------------- get .meta files
  196: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
  197: my @homeusers=grep
  198:           {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
  199:           grep {!/^\.\.?$/} readdir(RESOURCES);
  200: closedir RESOURCES;
  201: foreach my $user (@homeusers) {
  202:     print LOG "\n=== User: ".$user."\n\n";
  203: # Remove left-over db-files from potentially crashed searchcat run
  204:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
  205:     unlink($prodir.'/nohist_new_resevaldata.db');
  206: # Use find.pl
  207:     undef @metalist;
  208:     @metalist=();
  209:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  210: 
  211: # -- process each file to get metadata and put into search catalog SQL database
  212: # Also, check to see if already there.
  213: # I could just delete (without searching first), but this works for now.
  214: foreach my $m (@metalist) {
  215:     print LOG "- ".$m."\n";
  216:     my $ref=&metadata($m);
  217:     my $m2='/res/'.&declutter($m);
  218:     $m2=~s/\.meta$//;
  219:     &dynamicmeta($m2);
  220:     my $q2="select * from metadata where url like binary '$m2'";
  221:     my $sth = $dbh->prepare($q2);
  222:     $sth->execute();
  223:     my $r1=$sth->fetchall_arrayref;
  224:     if (@$r1) {
  225: 	$sth=$dbh->prepare("delete from metadata where url like binary '$m2'");
  226:         $sth->execute();
  227:     }
  228:     $sth=$dbh->prepare('insert into metadata values ('.
  229: 			  '"'.delete($ref->{'title'}).'"'.','.
  230: 			  '"'.delete($ref->{'author'}).'"'.','.
  231: 			  '"'.delete($ref->{'subject'}).'"'.','.
  232: 			  '"'.$m2.'"'.','.
  233: 			  '"'.delete($ref->{'keywords'}).'"'.','.
  234: 			  '"'.'current'.'"'.','.
  235: 			  '"'.delete($ref->{'notes'}).'"'.','.
  236: 			  '"'.delete($ref->{'abstract'}).'"'.','.
  237: 			  '"'.delete($ref->{'mime'}).'"'.','.
  238: 			  '"'.delete($ref->{'language'}).'"'.','.
  239: 			  '"'.sqltime(delete($ref->{'creationdate'})).'"'.','.
  240: 			  '"'.sqltime(delete($ref->{'lastrevisiondate'})).'"'.','.
  241: 			  '"'.delete($ref->{'owner'}).'"'.','.
  242: 			  '"'.delete($ref->{'copyright'}).'"'.')');
  243:     $sth->execute();
  244: }
  245: 
  246: # ----------------------------------------------------------- Clean up database
  247: # Need to, perhaps, remove stale SQL database records.
  248: # ... not yet implemented
  249: 
  250: 
  251: # -------------------------------------------------- Copy over the new db-files
  252:     system('mv '.$prodir.'/nohist_new_resevaldata.db '.
  253: 	         $prodir.'/nohist_resevaldata.db');
  254: }
  255: # --------------------------------------------------- Close database connection
  256: $dbh->disconnect;
  257: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  258: close(LOG);
  259: exit 0;
  260: # =============================================================================
  261: 
  262: # ---------------------------------------------------------------- Get metadata
  263: # significantly altered from subroutine present in lonnet
  264: sub metadata {
  265:     my ($uri,$what)=@_;
  266:     my %metacache;
  267:     $uri=&declutter($uri);
  268:     my $filename=$uri;
  269:     $uri=~s/\.meta$//;
  270:     $uri='';
  271:     unless ($metacache{$uri.'keys'}) {
  272:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  273: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  274:         my $parser=HTML::TokeParser->new(\$metastring);
  275:         my $token;
  276:         while ($token=$parser->get_token) {
  277:            if ($token->[0] eq 'S') {
  278: 	      my $entry=$token->[1];
  279:               my $unikey=$entry;
  280:               if (defined($token->[2]->{'part'})) { 
  281:                  $unikey.='_'.$token->[2]->{'part'}; 
  282: 	      }
  283:               if (defined($token->[2]->{'name'})) { 
  284:                  $unikey.='_'.$token->[2]->{'name'}; 
  285: 	      }
  286:               if ($metacache{$uri.'keys'}) {
  287:                  $metacache{$uri.'keys'}.=','.$unikey;
  288:               } else {
  289:                  $metacache{$uri.'keys'}=$unikey;
  290: 	      }
  291:               map {
  292: 		  $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  293:               } @{$token->[3]};
  294:               unless (
  295:                  $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  296: 		      ) { $metacache{$uri.''.$unikey}=
  297: 			      $metacache{$uri.''.$unikey.'.default'};
  298: 		      }
  299:           }
  300:        }
  301:     }
  302:     return \%metacache;
  303: }
  304: 
  305: # ------------------------------------------------------------ Serves up a file
  306: # returns either the contents of the file or a -1
  307: sub getfile {
  308:   my $file=shift;
  309:   if (! -e $file ) { return -1; };
  310:   my $fh=IO::File->new($file);
  311:   my $a='';
  312:   while (<$fh>) { $a .=$_; }
  313:   return $a
  314: }
  315: 
  316: # ------------------------------------------------------------- Declutters URLs
  317: sub declutter {
  318:     my $thisfn=shift;
  319:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  320:     $thisfn=~s/^\///;
  321:     $thisfn=~s/^res\///;
  322:     return $thisfn;
  323: }
  324: 
  325: # --------------------------------------- Is this the home server of an author?
  326: # (copied from lond, modification of the return value)
  327: sub ishome {
  328:     my $author=shift;
  329:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  330:     my ($udom,$uname)=split(/\//,$author);
  331:     my $proname=propath($udom,$uname);
  332:     if (-e $proname) {
  333: 	return 1;
  334:     } else {
  335:         return 0;
  336:     }
  337: }
  338: 
  339: # -------------------------------------------- Return path to profile directory
  340: # (copied from lond)
  341: sub propath {
  342:     my ($udom,$uname)=@_;
  343:     $udom=~s/\W//g;
  344:     $uname=~s/\W//g;
  345:     my $subdir=$uname.'__';
  346:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  347:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  348:     return $proname;
  349: } 
  350: 
  351: # ---------------------------- convert 'time' format into a datetime sql format
  352: sub sqltime {
  353:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  354: 	localtime(&unsqltime(@_[0]));
  355:     $mon++; $year+=1900;
  356:     return "$year-$mon-$mday $hour:$min:$sec";
  357: }
  358: 
  359: sub maketime {
  360:     my %th=@_;
  361:     return POSIX::mktime(
  362:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
  363:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
  364: }
  365: 
  366: 
  367: #########################################
  368: #
  369: # Retro-fixing of un-backward-compatible time format
  370: 
  371: sub unsqltime {
  372:     my $timestamp=shift;
  373:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  374:        $timestamp=&maketime(
  375: 	   'year'=>$1,'month'=>$2,'day'=>$3,
  376:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  377:     }
  378:     return $timestamp;
  379: }
  380: 

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