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