Annotation of loncom/metadata_database/searchcat.pl, revision 1.24

1.1       harris41    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # searchcat.pl "Search Catalog" batch script
1.16      harris41    4: #
1.24    ! www         5: # $Id: searchcat.pl,v 1.23 2002/10/08 18:45:33 albertel Exp $
1.16      harris41    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
1.17      harris41   30: # 04/14/2001, 04/16/2001 Scott Harrison
1.16      harris41   31: #
1.17      harris41   32: # YEAR=2002
                     33: # 05/11/2002 Scott Harrison
1.16      harris41   34: #
                     35: ###
1.1       harris41   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: 
1.17      harris41   41: use lib '/home/httpd/lib/perl/';
                     42: use LONCAPA::Configuration;
                     43: 
1.1       harris41   44: use IO::File;
                     45: use HTML::TokeParser;
1.6       harris41   46: use DBI;
1.21      www        47: use GDBM_File;
1.24    ! www        48: use POSIX qw(strftime mktime);
1.1       harris41   49: 
                     50: my @metalist;
1.21      www        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: 
1.22      www        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: 
1.21      www        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',
1.23      albertel   88:             $prodir.'/nohist_resevaldata.db',&GDBM_WRCREAT(),0640)) {
1.21      www        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/) {
1.22      www       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{$_};
1.21      www       126: 	          }
1.22      www       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'};
1.21      www       148:      }
                    149:      untie(%evaldata);
                    150:    }
                    151:    return %returnhash;
                    152: }
                    153:   
1.1       harris41  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 _ &&
1.10      harris41  159:     /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
1.1       harris41  160:     push(@metalist,"$dir/$_");
                    161: }
                    162: 
1.18      matthew   163: # ---------------  Read loncapa_apache.conf and loncapa.conf and get variables
1.20      harris41  164: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.17      harris41  165: my %perlvar=%{$perlvarref};
                    166: undef $perlvarref; # remove since sensitive and not needed
                    167: delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
1.15      harris41  168: 
                    169: # ------------------------------------- Only run if machine is a library server
                    170: exit unless $perlvar{'lonRole'} eq 'library';
1.1       harris41  171: 
1.3       harris41  172: my $dbh;
1.1       harris41  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:     }
1.19      matthew   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);
1.1       harris41  194: }
                    195: 
                    196: # ------------------------------------------------------------- get .meta files
1.2       harris41  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: }
1.1       harris41  205: 
                    206: # -- process each file to get metadata and put into search catalog SQL database
1.9       harris41  207: # Also, check to see if already there.
1.11      harris41  208: # I could just delete (without searching first), but this works for now.
1.1       harris41  209: foreach my $m (@metalist) {
                    210:     my $ref=&metadata($m);
1.11      harris41  211:     my $m2='/res/'.&declutter($m);
1.12      harris41  212:     $m2=~s/\.meta$//;
1.21      www       213:     &dynamicmeta($m2);
1.12      harris41  214:     my $q2="select * from metadata where url like binary '$m2'";
1.9       harris41  215:     my $sth = $dbh->prepare($q2);
                    216:     $sth->execute();
                    217:     my $r1=$sth->fetchall_arrayref;
                    218:     if (@$r1) {
1.12      harris41  219: 	$sth=$dbh->prepare("delete from metadata where url like binary '$m2'");
1.9       harris41  220:         $sth->execute();
                    221:     }
                    222:     $sth=$dbh->prepare('insert into metadata values ('.
1.8       harris41  223: 			  '"'.delete($ref->{'title'}).'"'.','.
                    224: 			  '"'.delete($ref->{'author'}).'"'.','.
                    225: 			  '"'.delete($ref->{'subject'}).'"'.','.
1.12      harris41  226: 			  '"'.$m2.'"'.','.
1.8       harris41  227: 			  '"'.delete($ref->{'keywords'}).'"'.','.
1.9       harris41  228: 			  '"'.'current'.'"'.','.
1.8       harris41  229: 			  '"'.delete($ref->{'notes'}).'"'.','.
                    230: 			  '"'.delete($ref->{'abstract'}).'"'.','.
                    231: 			  '"'.delete($ref->{'mime'}).'"'.','.
                    232: 			  '"'.delete($ref->{'language'}).'"'.','.
1.13      harris41  233: 			  '"'.sqltime(delete($ref->{'creationdate'})).'"'.','.
                    234: 			  '"'.sqltime(delete($ref->{'lastrevisiondate'})).'"'.','.
1.8       harris41  235: 			  '"'.delete($ref->{'owner'}).'"'.','.
                    236: 			  '"'.delete($ref->{'copyright'}).'"'.')');
1.1       harris41  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: }
1.2       harris41  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: } 
1.13      harris41  335: 
                    336: # ---------------------------- convert 'time' format into a datetime sql format
                    337: sub sqltime {
                    338:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.24    ! www       339: 	localtime(&unsqltime(@_[0]));
1.14      harris41  340:     $mon++; $year+=1900;
1.13      harris41  341:     return "$year-$mon-$mday $hour:$min:$sec";
                    342: }
1.24    ! www       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>