File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.24: download - view: text, annotated - select for diffs
Fri Oct 18 13:54:31 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug 839

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

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