1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # searchcat.pl "Search Catalog" batch script
4: #
5: # $Id: searchcat.pl,v 1.37 2003/08/08 12:38:00 matthew 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: ###
30:
31: =pod
32:
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
67:
68: use lib '/home/httpd/lib/perl/';
69: use LONCAPA::Configuration;
70:
71: use IO::File;
72: use HTML::TokeParser;
73: use DBI;
74: use GDBM_File;
75: use POSIX qw(strftime mktime);
76:
77: my @metalist;
78:
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: }
86:
87: # ----------------------------------------------------- Un-Escape Special Chars
88:
89: sub unescape {
90: my $str=shift;
91: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
92: return $str;
93: }
94:
95: # -------------------------------------------------------- Escape Special Chars
96:
97: sub escape {
98: my $str=shift;
99: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
100: return $str;
101: }
102:
103:
104: # ------------------------------------------- Code to evaluate dynamic metadata
105:
106: sub dynamicmeta {
107:
108: my $url=&declutter(shift);
109: $url=~s/\.meta$//;
110: my %returnhash=();
111: my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
112: my $prodir=&propath($adomain,$aauthor);
113: if ((tie(%evaldata,'GDBM_File',
114: $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
115: (tie(%newevaldata,'GDBM_File',
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;
139: if (defined($cnt{$ctype})) {
140: $cnt{$ctype}++;
141: } else {
142: $cnt{$ctype}=1;
143: }
144: unless ($listitems{$ctype} eq 'app') {
145: if (defined($sum{$ctype})) {
146: $sum{$ctype}+=$evaldata{$_};
147: } else {
148: $sum{$ctype}=$evaldata{$_};
149: }
150: } else {
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;
181: }
182:
183: # ----------------- Code to enable 'find' subroutine listing of the .meta files
184: require "find.pl";
185: sub wanted {
186: (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
187: -f _ &&
188: /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
189: push(@metalist,"$dir/$_");
190: }
191:
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
197:
198: # ------------------------------------- Only run if machine is a library server
199: exit unless $perlvar{'lonRole'} eq 'library';
200:
201: # ----------------------------- Make sure this process is running from user=www
202:
203: my $wwwid=getpwnam('www');
204: if ($wwwid!=$<) {
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.' |\
208: mailto $emailto -s '$subj' > /dev/null");
209: exit 1;
210: }
211:
212:
213: # ---------------------------------------------------------- We are in business
214:
215: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
216: print LOG '==== Searchcat Run '.localtime()."====\n\n";
217: $simplestatus='time='.time.'&';
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";
225: $simplestatus.='mysql=defunct';
226: &writesimple();
227: exit;
228: }
229:
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: }
244:
245: # ------------------------------------------------------------- get .meta files
246: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
247: my @homeusers = grep {
248: &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
249: } grep {!/^\.\.?$/} readdir(RESOURCES);
250: closedir RESOURCES;
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:
275: foreach my $user (@homeusers) {
276: print LOG "\n=== User: ".$user."\n\n";
277: # Remove left-over db-files from potentially crashed searchcat run
278: my $prodir=&propath($perlvar{'lonDefDomain'},$user);
279: unlink($prodir.'/nohist_new_resevaldata.db');
280: # Use find.pl
281: undef @metalist;
282: @metalist=();
283: &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
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);
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;
312: }
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
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:
340: }
341: # --------------------------------------------------- Close database connection
342: $dbh->disconnect;
343: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
344: close(LOG);
345: &writesimple();
346: exit 0;
347:
348:
349:
350: # =============================================================================
351:
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) {
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: }
391: }
392: return \%metacache;
393: }
394:
395: # ------------------------------------------------------------ Serves up a file
396: # returns either the contents of the file or a -1
397: sub getfile {
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;
404: }
405:
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: }
414:
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: }
428:
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: }
440:
441: # ---------------------------- convert 'time' format into a datetime sql format
442: sub sqltime {
443: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
444: localtime(&unsqltime(@_[0]));
445: $mon++; $year+=1900;
446: return "$year-$mon-$mday $hour:$min:$sec";
447: }
448:
449: sub maketime {
450: my %th=@_;
451: return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
452: $th{'day'},$th{'month'}-1,
453: $th{'year'}-1900,0,0,$th{'dlsav'}));
454: }
455:
456:
457: #########################################
458: #
459: # Retro-fixing of un-backward-compatible time format
460:
461: sub unsqltime {
462: my $timestamp=shift;
463: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
464: $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
465: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
466: }
467: return $timestamp;
468: }
469:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>