File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.27: download - view: text, annotated - select for diffs
Sat Jan 4 19:23:31 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: version_0_6_2, version_0_6_1, HEAD
According to Scott's suggestion, it is better to check the user ID than
to allow running as root, and then fix ownerships.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.27 2003/01/04 19:23: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:     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: # ----------------------------- Make sure this process is running from user=www
  168: 
  169: my $wwwid=getpwnam('www');
  170: if ($wwwid!=$<) {
  171:    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  172:    $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  173:    system("echo 'User ID mismatch. searchcat.pl must be run as user www.' |\
  174:  mailto $emailto -s '$subj' > /dev/null");
  175:    exit 1;
  176: }
  177: 
  178: 
  179: # ---------------------------------------------------------- We are in business
  180: 
  181: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
  182: print LOG '==== Searchcat Run '.localtime()."====\n\n";
  183: my $dbh;
  184: # ------------------------------------- Make sure that database can be accessed
  185: {
  186:     unless (
  187: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  188: 	    ) { 
  189: 	print LOG "Cannot connect to database!\n";
  190: 	exit;
  191:     }
  192:     my $make_metadata_table = "CREATE TABLE IF NOT EXISTS metadata (".
  193:         "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
  194:         "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
  195:         "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
  196:         "copyright TEXT, FULLTEXT idx_title (title), ".
  197:         "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
  198:         "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
  199:         "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
  200:         "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
  201:         "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
  202:         "FULLTEXT idx_copyright (copyright)) TYPE=MYISAM";
  203:     # It would sure be nice to have some logging mechanism.
  204:     $dbh->do($make_metadata_table);
  205: }
  206: 
  207: # ------------------------------------------------------------- get .meta files
  208: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
  209: my @homeusers=grep
  210:           {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
  211:           grep {!/^\.\.?$/} readdir(RESOURCES);
  212: closedir RESOURCES;
  213: foreach my $user (@homeusers) {
  214:     print LOG "\n=== User: ".$user."\n\n";
  215: # Remove left-over db-files from potentially crashed searchcat run
  216:     my $prodir=&propath($perlvar{'lonDefDomain'},$user);
  217:     unlink($prodir.'/nohist_new_resevaldata.db');
  218: # Use find.pl
  219:     undef @metalist;
  220:     @metalist=();
  221:     &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  222: 
  223: # -- process each file to get metadata and put into search catalog SQL database
  224: # Also, check to see if already there.
  225: # I could just delete (without searching first), but this works for now.
  226: foreach my $m (@metalist) {
  227:     print LOG "- ".$m."\n";
  228:     my $ref=&metadata($m);
  229:     my $m2='/res/'.&declutter($m);
  230:     $m2=~s/\.meta$//;
  231:     &dynamicmeta($m2);
  232:     my $q2="select * from metadata where url like binary '$m2'";
  233:     my $sth = $dbh->prepare($q2);
  234:     $sth->execute();
  235:     my $r1=$sth->fetchall_arrayref;
  236:     if (@$r1) {
  237: 	$sth=$dbh->prepare("delete from metadata where url like binary '$m2'");
  238:         $sth->execute();
  239:     }
  240:     $sth=$dbh->prepare('insert into metadata values ('.
  241: 			  '"'.delete($ref->{'title'}).'"'.','.
  242: 			  '"'.delete($ref->{'author'}).'"'.','.
  243: 			  '"'.delete($ref->{'subject'}).'"'.','.
  244: 			  '"'.$m2.'"'.','.
  245: 			  '"'.delete($ref->{'keywords'}).'"'.','.
  246: 			  '"'.'current'.'"'.','.
  247: 			  '"'.delete($ref->{'notes'}).'"'.','.
  248: 			  '"'.delete($ref->{'abstract'}).'"'.','.
  249: 			  '"'.delete($ref->{'mime'}).'"'.','.
  250: 			  '"'.delete($ref->{'language'}).'"'.','.
  251: 			  '"'.sqltime(delete($ref->{'creationdate'})).'"'.','.
  252: 			  '"'.sqltime(delete($ref->{'lastrevisiondate'})).'"'.','.
  253: 			  '"'.delete($ref->{'owner'}).'"'.','.
  254: 			  '"'.delete($ref->{'copyright'}).'"'.')');
  255:     $sth->execute();
  256: }
  257: 
  258: # ----------------------------------------------------------- Clean up database
  259: # Need to, perhaps, remove stale SQL database records.
  260: # ... not yet implemented
  261: 
  262: 
  263: # -------------------------------------------------- Copy over the new db-files
  264:     system('mv '.$prodir.'/nohist_new_resevaldata.db '.
  265: 	         $prodir.'/nohist_resevaldata.db');
  266: }
  267: # --------------------------------------------------- Close database connection
  268: $dbh->disconnect;
  269: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  270: close(LOG);
  271: exit 0;
  272: # =============================================================================
  273: 
  274: # ---------------------------------------------------------------- Get metadata
  275: # significantly altered from subroutine present in lonnet
  276: sub metadata {
  277:     my ($uri,$what)=@_;
  278:     my %metacache;
  279:     $uri=&declutter($uri);
  280:     my $filename=$uri;
  281:     $uri=~s/\.meta$//;
  282:     $uri='';
  283:     unless ($metacache{$uri.'keys'}) {
  284:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  285: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  286:         my $parser=HTML::TokeParser->new(\$metastring);
  287:         my $token;
  288:         while ($token=$parser->get_token) {
  289:            if ($token->[0] eq 'S') {
  290: 	      my $entry=$token->[1];
  291:               my $unikey=$entry;
  292:               if (defined($token->[2]->{'part'})) { 
  293:                  $unikey.='_'.$token->[2]->{'part'}; 
  294: 	      }
  295:               if (defined($token->[2]->{'name'})) { 
  296:                  $unikey.='_'.$token->[2]->{'name'}; 
  297: 	      }
  298:               if ($metacache{$uri.'keys'}) {
  299:                  $metacache{$uri.'keys'}.=','.$unikey;
  300:               } else {
  301:                  $metacache{$uri.'keys'}=$unikey;
  302: 	      }
  303:               map {
  304: 		  $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  305:               } @{$token->[3]};
  306:               unless (
  307:                  $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  308: 		      ) { $metacache{$uri.''.$unikey}=
  309: 			      $metacache{$uri.''.$unikey.'.default'};
  310: 		      }
  311:           }
  312:        }
  313:     }
  314:     return \%metacache;
  315: }
  316: 
  317: # ------------------------------------------------------------ Serves up a file
  318: # returns either the contents of the file or a -1
  319: sub getfile {
  320:   my $file=shift;
  321:   if (! -e $file ) { return -1; };
  322:   my $fh=IO::File->new($file);
  323:   my $a='';
  324:   while (<$fh>) { $a .=$_; }
  325:   return $a
  326: }
  327: 
  328: # ------------------------------------------------------------- Declutters URLs
  329: sub declutter {
  330:     my $thisfn=shift;
  331:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  332:     $thisfn=~s/^\///;
  333:     $thisfn=~s/^res\///;
  334:     return $thisfn;
  335: }
  336: 
  337: # --------------------------------------- Is this the home server of an author?
  338: # (copied from lond, modification of the return value)
  339: sub ishome {
  340:     my $author=shift;
  341:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  342:     my ($udom,$uname)=split(/\//,$author);
  343:     my $proname=propath($udom,$uname);
  344:     if (-e $proname) {
  345: 	return 1;
  346:     } else {
  347:         return 0;
  348:     }
  349: }
  350: 
  351: # -------------------------------------------- Return path to profile directory
  352: # (copied from lond)
  353: sub propath {
  354:     my ($udom,$uname)=@_;
  355:     $udom=~s/\W//g;
  356:     $uname=~s/\W//g;
  357:     my $subdir=$uname.'__';
  358:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  359:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  360:     return $proname;
  361: } 
  362: 
  363: # ---------------------------- convert 'time' format into a datetime sql format
  364: sub sqltime {
  365:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  366: 	localtime(&unsqltime(@_[0]));
  367:     $mon++; $year+=1900;
  368:     return "$year-$mon-$mday $hour:$min:$sec";
  369: }
  370: 
  371: sub maketime {
  372:     my %th=@_;
  373:     return POSIX::mktime(
  374:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
  375:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
  376: }
  377: 
  378: 
  379: #########################################
  380: #
  381: # Retro-fixing of un-backward-compatible time format
  382: 
  383: sub unsqltime {
  384:     my $timestamp=shift;
  385:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  386:        $timestamp=&maketime(
  387: 	   'year'=>$1,'month'=>$2,'day'=>$3,
  388:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  389:     }
  390:     return $timestamp;
  391: }
  392: 

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