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