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