Annotation of loncom/metadata_database/searchcat.pl, revision 1.37
1.1 harris41 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # searchcat.pl "Search Catalog" batch script
1.16 harris41 4: #
1.37 ! matthew 5: # $Id: searchcat.pl,v 1.36 2003/07/30 16:49:27 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.37 ! matthew 319: #
! 320: # Check the size of nohist_new_resevaldata.db compared to
! 321: # nohist_resevaldata.db
! 322: my @stat_result = stat($prodir.'/nohist_new_resevaldata.db');
! 323: my $new_size = $stat_result[7];
! 324: @stat_result = stat($prodir.'/nohist_resevaldata.db');
! 325: my $old_size = $stat_result[7];
! 326: if ($new_size/$old_size > 0.15 ) {
! 327: system('mv '.$prodir.'/nohist_new_resevaldata.db '.
! 328: $prodir.'/nohist_resevaldata.db');
! 329: } else {
! 330: print LOG "Size of '$user' old nohist_reseval: $old_size ".
! 331: "Size of new: $new_size. Not overwriting.\n";
! 332: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
! 333: my $subj="LON: $perlvar{'lonHostID'} searchcat.pl $user reseval ".
! 334: "modification error.";
! 335: system("echo ".
! 336: "'See /home/httpd/perl/logs/searchcat.txt for information.' ".
! 337: "| mailto $emailto -s '$subj' > /dev/null");
! 338: }
! 339:
1.31 harris41 340: }
341: # --------------------------------------------------- Close database connection
342: $dbh->disconnect;
343: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
344: close(LOG);
1.36 www 345: &writesimple();
1.31 harris41 346: exit 0;
1.33 matthew 347:
348:
349:
1.31 harris41 350: # =============================================================================
1.1 harris41 351:
1.31 harris41 352: # ---------------------------------------------------------------- Get metadata
353: # significantly altered from subroutine present in lonnet
354: sub metadata {
355: my ($uri,$what)=@_;
356: my %metacache;
357: $uri=&declutter($uri);
358: my $filename=$uri;
359: $uri=~s/\.meta$//;
360: $uri='';
361: unless ($metacache{$uri.'keys'}) {
362: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
363: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
364: my $parser=HTML::TokeParser->new(\$metastring);
365: my $token;
366: while ($token=$parser->get_token) {
1.33 matthew 367: if ($token->[0] eq 'S') {
368: my $entry=$token->[1];
369: my $unikey=$entry;
370: if (defined($token->[2]->{'part'})) {
371: $unikey.='_'.$token->[2]->{'part'};
372: }
373: if (defined($token->[2]->{'name'})) {
374: $unikey.='_'.$token->[2]->{'name'};
375: }
376: if ($metacache{$uri.'keys'}) {
377: $metacache{$uri.'keys'}.=','.$unikey;
378: } else {
379: $metacache{$uri.'keys'}=$unikey;
380: }
381: map {
382: $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
383: } @{$token->[3]};
384: unless (
385: $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
386: ) { $metacache{$uri.''.$unikey}=
387: $metacache{$uri.''.$unikey.'.default'};
388: }
389: }
390: }
1.31 harris41 391: }
392: return \%metacache;
393: }
1.28 harris41 394:
1.31 harris41 395: # ------------------------------------------------------------ Serves up a file
396: # returns either the contents of the file or a -1
397: sub getfile {
1.33 matthew 398: my $file=shift;
399: if (! -e $file ) { return -1; };
400: my $fh=IO::File->new($file);
401: my $a='';
402: while (<$fh>) { $a .=$_; }
403: return $a;
1.31 harris41 404: }
1.28 harris41 405:
1.31 harris41 406: # ------------------------------------------------------------- Declutters URLs
407: sub declutter {
408: my $thisfn=shift;
409: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
410: $thisfn=~s/^\///;
411: $thisfn=~s/^res\///;
412: return $thisfn;
413: }
1.28 harris41 414:
1.31 harris41 415: # --------------------------------------- Is this the home server of an author?
416: # (copied from lond, modification of the return value)
417: sub ishome {
418: my $author=shift;
419: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
420: my ($udom,$uname)=split(/\//,$author);
421: my $proname=propath($udom,$uname);
422: if (-e $proname) {
423: return 1;
424: } else {
425: return 0;
426: }
427: }
1.28 harris41 428:
1.31 harris41 429: # -------------------------------------------- Return path to profile directory
430: # (copied from lond)
431: sub propath {
432: my ($udom,$uname)=@_;
433: $udom=~s/\W//g;
434: $uname=~s/\W//g;
435: my $subdir=$uname.'__';
436: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
437: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
438: return $proname;
439: }
1.28 harris41 440:
1.31 harris41 441: # ---------------------------- convert 'time' format into a datetime sql format
442: sub sqltime {
1.13 harris41 443: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.31 harris41 444: localtime(&unsqltime(@_[0]));
445: $mon++; $year+=1900;
446: return "$year-$mon-$mday $hour:$min:$sec";
447: }
1.28 harris41 448:
1.31 harris41 449: sub maketime {
450: my %th=@_;
1.33 matthew 451: return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
452: $th{'day'},$th{'month'}-1,
453: $th{'year'}-1900,0,0,$th{'dlsav'}));
1.31 harris41 454: }
1.28 harris41 455:
456:
1.31 harris41 457: #########################################
458: #
459: # Retro-fixing of un-backward-compatible time format
1.28 harris41 460:
1.31 harris41 461: sub unsqltime {
462: my $timestamp=shift;
463: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1.33 matthew 464: $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
465: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1.31 harris41 466: }
467: return $timestamp;
468: }
1.28 harris41 469:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>