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