File:  [LON-CAPA] / loncom / metadata_database / searchcat.pl
Revision 1.26: download - view: text, annotated - select for diffs
Sat Jan 4 15:04:12 2003 UTC (21 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #1111
searchcat.pl is apparently running as "root" and changed ownership on
nohist_resevaldata.db to "root". Need to make "www" owner of that file.
This should go into 0.6.1

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # searchcat.pl "Search Catalog" batch script
    4: #
    5: # $Id: searchcat.pl,v 1.26 2003/01/04 15:04:12 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:     system('chown www:www '.$prodir.'/nohist_resevaldata.db');
  255: }
  256: # --------------------------------------------------- Close database connection
  257: $dbh->disconnect;
  258: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
  259: close(LOG);
  260: exit 0;
  261: # =============================================================================
  262: 
  263: # ---------------------------------------------------------------- Get metadata
  264: # significantly altered from subroutine present in lonnet
  265: sub metadata {
  266:     my ($uri,$what)=@_;
  267:     my %metacache;
  268:     $uri=&declutter($uri);
  269:     my $filename=$uri;
  270:     $uri=~s/\.meta$//;
  271:     $uri='';
  272:     unless ($metacache{$uri.'keys'}) {
  273:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
  274: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
  275:         my $parser=HTML::TokeParser->new(\$metastring);
  276:         my $token;
  277:         while ($token=$parser->get_token) {
  278:            if ($token->[0] eq 'S') {
  279: 	      my $entry=$token->[1];
  280:               my $unikey=$entry;
  281:               if (defined($token->[2]->{'part'})) { 
  282:                  $unikey.='_'.$token->[2]->{'part'}; 
  283: 	      }
  284:               if (defined($token->[2]->{'name'})) { 
  285:                  $unikey.='_'.$token->[2]->{'name'}; 
  286: 	      }
  287:               if ($metacache{$uri.'keys'}) {
  288:                  $metacache{$uri.'keys'}.=','.$unikey;
  289:               } else {
  290:                  $metacache{$uri.'keys'}=$unikey;
  291: 	      }
  292:               map {
  293: 		  $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
  294:               } @{$token->[3]};
  295:               unless (
  296:                  $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
  297: 		      ) { $metacache{$uri.''.$unikey}=
  298: 			      $metacache{$uri.''.$unikey.'.default'};
  299: 		      }
  300:           }
  301:        }
  302:     }
  303:     return \%metacache;
  304: }
  305: 
  306: # ------------------------------------------------------------ Serves up a file
  307: # returns either the contents of the file or a -1
  308: sub getfile {
  309:   my $file=shift;
  310:   if (! -e $file ) { return -1; };
  311:   my $fh=IO::File->new($file);
  312:   my $a='';
  313:   while (<$fh>) { $a .=$_; }
  314:   return $a
  315: }
  316: 
  317: # ------------------------------------------------------------- Declutters URLs
  318: sub declutter {
  319:     my $thisfn=shift;
  320:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
  321:     $thisfn=~s/^\///;
  322:     $thisfn=~s/^res\///;
  323:     return $thisfn;
  324: }
  325: 
  326: # --------------------------------------- Is this the home server of an author?
  327: # (copied from lond, modification of the return value)
  328: sub ishome {
  329:     my $author=shift;
  330:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  331:     my ($udom,$uname)=split(/\//,$author);
  332:     my $proname=propath($udom,$uname);
  333:     if (-e $proname) {
  334: 	return 1;
  335:     } else {
  336:         return 0;
  337:     }
  338: }
  339: 
  340: # -------------------------------------------- Return path to profile directory
  341: # (copied from lond)
  342: sub propath {
  343:     my ($udom,$uname)=@_;
  344:     $udom=~s/\W//g;
  345:     $uname=~s/\W//g;
  346:     my $subdir=$uname.'__';
  347:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  348:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  349:     return $proname;
  350: } 
  351: 
  352: # ---------------------------- convert 'time' format into a datetime sql format
  353: sub sqltime {
  354:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  355: 	localtime(&unsqltime(@_[0]));
  356:     $mon++; $year+=1900;
  357:     return "$year-$mon-$mday $hour:$min:$sec";
  358: }
  359: 
  360: sub maketime {
  361:     my %th=@_;
  362:     return POSIX::mktime(
  363:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
  364:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
  365: }
  366: 
  367: 
  368: #########################################
  369: #
  370: # Retro-fixing of un-backward-compatible time format
  371: 
  372: sub unsqltime {
  373:     my $timestamp=shift;
  374:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
  375:        $timestamp=&maketime(
  376: 	   'year'=>$1,'month'=>$2,'day'=>$3,
  377:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
  378:     }
  379:     return $timestamp;
  380: }
  381: 

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