Annotation of loncom/metadata_database/searchcat.pl, revision 1.47
1.1 harris41 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # searchcat.pl "Search Catalog" batch script
1.16 harris41 4: #
1.47 ! www 5: # $Id: searchcat.pl,v 1.46 2003/12/24 20:41:32 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.45 www 68: use strict;
69:
1.17 harris41 70: use lib '/home/httpd/lib/perl/';
71: use LONCAPA::Configuration;
72:
1.1 harris41 73: use IO::File;
74: use HTML::TokeParser;
1.6 harris41 75: use DBI;
1.21 www 76: use GDBM_File;
1.24 www 77: use POSIX qw(strftime mktime);
1.1 harris41 78:
1.45 www 79: require "find.pl";
80:
1.1 harris41 81: my @metalist;
1.21 www 82:
1.45 www 83: my $simplestatus='';
1.38 www 84: my %countext=();
1.36 www 85:
1.45 www 86: # ----------------------------------------------------- write out simple status
1.36 www 87: sub writesimple {
88: open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
89: print SMP $simplestatus."\n";
90: close(SMP);
91: }
1.28 harris41 92:
1.38 www 93: sub writecount {
94: open(RSMP,'>/home/httpd/html/lon-status/rescount.txt');
95: foreach (keys %countext) {
96: print RSMP $_.'='.$countext{$_}.'&';
97: }
98: print RSMP 'time='.time."\n";
99: close(RSMP);
100: }
101:
1.45 www 102: # -------------------------------------- counts files with different extensions
1.38 www 103: sub count {
104: my $file=shift;
105: $file=~/\.(\w+)$/;
106: my $ext=lc($1);
107: if (defined($countext{$ext})) {
108: $countext{$ext}++;
109: } else {
110: $countext{$ext}=1;
111: }
112: }
1.31 harris41 113: # ----------------------------------------------------- Un-Escape Special Chars
1.28 harris41 114:
1.31 harris41 115: sub unescape {
116: my $str=shift;
1.21 www 117: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.31 harris41 118: return $str;
119: }
1.21 www 120:
1.31 harris41 121: # -------------------------------------------------------- Escape Special Chars
1.22 www 122:
1.31 harris41 123: sub escape {
124: my $str=shift;
1.22 www 125: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
1.31 harris41 126: return $str;
127: }
1.28 harris41 128:
1.31 harris41 129: # ------------------------------------------- Code to evaluate dynamic metadata
1.28 harris41 130:
1.31 harris41 131: sub dynamicmeta {
1.30 www 132: my $url=&declutter(shift);
133: $url=~s/\.meta$//;
134: my %returnhash=();
135: my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
1.31 harris41 136: my $prodir=&propath($adomain,$aauthor);
1.45 www 137:
1.44 www 138: # Get metadata except counts
1.45 www 139: if (tie(my %evaldata,'GDBM_File',
1.44 www 140: $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) {
141: my %sum=();
142: my %cnt=();
143: my %concat=();
144: my %listitems=(
145: 'course' => 'add',
146: 'goto' => 'add',
147: 'comefrom' => 'add',
148: 'avetries' => 'avg',
149: 'stdno' => 'add',
150: 'difficulty' => 'avg',
151: 'clear' => 'avg',
152: 'technical' => 'avg',
153: 'helpful' => 'avg',
154: 'correct' => 'avg',
155: 'depth' => 'avg',
156: 'comments' => 'app',
157: 'usage' => 'cnt'
158: );
159:
160: my $regexp=$url;
161: $regexp=~s/(\W)/\\$1/g;
162: $regexp='___'.$regexp.'___([a-z]+)$';
163: while (my ($esckey,$value)=each %evaldata) {
1.45 www 164: my $key=&unescape($esckey);
1.44 www 165: if ($key=~/$regexp/) {
1.45 www 166: my ($item,$purl,$cat)=split(/___/,$key);
1.44 www 167: if (defined($cnt{$cat})) { $cnt{$cat}++; } else { $cnt{$cat}=1; }
168: unless ($listitems{$cat} eq 'app') {
169: if (defined($sum{$cat})) {
1.45 www 170: $sum{$cat}+=$evaldata{$esckey};
1.44 www 171: $concat{$cat}.=','.$item;
172: } else {
1.45 www 173: $sum{$cat}=$evaldata{$esckey};
1.44 www 174: $concat{$cat}=$item;
175: }
176: } else {
177: if (defined($sum{$cat})) {
1.45 www 178: if ($evaldata{$esckey}=~/\w/) {
179: $sum{$cat}.='<hr>'.$evaldata{$esckey};
1.44 www 180: }
181: } else {
1.45 www 182: $sum{$cat}=''.$evaldata{$esckey};
1.44 www 183: }
184: }
1.35 www 185: }
1.44 www 186: }
187: untie(%evaldata);
1.45 www 188: # transfer gathered data to returnhash, calculate averages where applicable
189: while (my $cat=each(%cnt)) {
190: if ($listitems{$cat} eq 'avg') {
191: $returnhash{$cat}=int(($sum{$cat}/$cnt{$cat})*100.0+0.5)/100.0;
192: } elsif ($listitems{$cat} eq 'cnt') {
193: $returnhash{$cat}=$cnt{$cat};
194: } else {
195: $returnhash{$cat}=$sum{$cat};
196: }
197: $returnhash{$cat.'_list'}=$concat{$cat};
1.44 www 198: }
199: }
200: # get count
1.45 www 201: if (tie(my %evaldata,'GDBM_File',
1.44 www 202: $prodir.'/nohist_accesscount.db',&GDBM_READER(),0640)) {
1.45 www 203: my $escurl=&escape($url);
204: if (! exists($evaldata{$escurl})) {
1.46 www 205: $returnhash{'count'}=0;
1.44 www 206: } else {
1.45 www 207: $returnhash{'count'}=$evaldata{$escurl};
1.44 www 208: }
209: untie %evaldata;
210: }
211: return %returnhash;
1.30 www 212: }
1.35 www 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.45 www 227: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
228: my $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
1.33 matthew 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.47 ! www 252: # Make temporary table
! 253: $dbh->do("DROP TABLE IF EXISTS newmetadata");
! 254: my $make_metadata_table = "CREATE TABLE IF NOT EXISTS newmetadata (".
1.31 harris41 255: "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
256: "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
257: "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
1.47 ! www 258: "copyright TEXT, ".
! 259: "count INTEGER UNSIGNED, ".
! 260: "course INTEGER UNSIGNED, course_list TEXT, ".
! 261: "goto INTEGER UNSIGNED, goto_list TEXT, ".
! 262: "comefrom INTEGER UNSIGNED, comefrom_list TEXT, ".
! 263: "fusage INTEGER UNSIGNED, fusage_list TEXT, ".
! 264: "stdno INTEGER UNSIGNED, stdno_list TEXT, ".
! 265: "avetries FLOAT, avetries_list TEXT, ".
! 266: "difficulty FLOAT, difficulty_list TEXT, ".
! 267: "FULLTEXT idx_title (title), ".
1.31 harris41 268: "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
269: "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
270: "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
271: "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
272: "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
1.47 ! www 273: "FULLTEXT idx_copyright (copyright)) ".
! 274: "TYPE=MyISAM";
1.31 harris41 275: # It would sure be nice to have some logging mechanism.
1.47 ! www 276: unless ($dbh->do($make_metadata_table)) {
! 277: print LOG "\nMySQL Error Create: ".$dbh->errstr."\n";
! 278: die $dbh->errstr;
! 279: }
1.31 harris41 280: }
1.27 www 281:
1.31 harris41 282: # ------------------------------------------------------------- get .meta files
283: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
1.33 matthew 284: my @homeusers = grep {
285: &ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")
286: } grep {!/^\.\.?$/} readdir(RESOURCES);
1.31 harris41 287: closedir RESOURCES;
1.34 matthew 288:
289: #
290: # Create the statement handlers we need
291:
292: my $insert_sth = $dbh->prepare
1.47 ! www 293: ("INSERT INTO newmetadata VALUES (".
1.34 matthew 294: "?,". # title
295: "?,". # author
296: "?,". # subject
1.47 ! www 297: "?,". # declutter url
1.34 matthew 298: "?,". # version
299: "?,". # current
300: "?,". # notes
301: "?,". # abstract
302: "?,". # mime
303: "?,". # language
304: "?,". # creationdate
305: "?,". # revisiondate
306: "?,". # owner
1.47 ! www 307: "?,". # copyright
! 308: "?,". # count
! 309: "?,". # course
! 310: "?,". # course_list
! 311: "?,". # goto
! 312: "?,". # goto_list
! 313: "?,". # comefrom
! 314: "?,". # comefrom_list
! 315: "?,". # usage
! 316: "?,". # usage_list
! 317: "?,". # stdno
! 318: "?,". # stdno_list
! 319: "?,". # avetries
! 320: "?,". # avetries_list
! 321: "?,". # difficulty
! 322: "?," # difficulty_list
1.34 matthew 323: );
324:
1.31 harris41 325: foreach my $user (@homeusers) {
326: print LOG "\n=== User: ".$user."\n\n";
1.44 www 327:
1.31 harris41 328: my $prodir=&propath($perlvar{'lonDefDomain'},$user);
1.33 matthew 329: # Use find.pl
1.31 harris41 330: undef @metalist;
331: @metalist=();
332: &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
1.33 matthew 333: # -- process each file to get metadata and put into search catalog SQL
334: # database. Also, check to see if already there.
335: # I could just delete (without searching first), but this works for now.
336: foreach my $m (@metalist) {
337: print LOG "- ".$m."\n";
338: my $ref=&metadata($m);
1.41 www 339: my $m2='/res/'.&declutter($m);
340: $m2=~s/\.meta$//;
1.40 www 341: if ($ref->{'obsolete'}) { print LOG "obsolete\n"; next; }
342: if ($ref->{'copyright'} eq 'private') { print LOG "private\n"; next; }
1.47 ! www 343: my %dyn=&dynamicmeta($m2);
1.38 www 344: &count($m2);
1.47 ! www 345: unless ($insert_sth->execute(
! 346: $ref->{'title'},
1.34 matthew 347: $ref->{'author'},
348: $ref->{'subject'},
349: $m2,
350: $ref->{'keywords'},
351: 'current',
352: $ref->{'notes'},
353: $ref->{'abstract'},
354: $ref->{'mime'},
355: $ref->{'language'},
356: sqltime($ref->{'creationdate'}),
357: sqltime($ref->{'lastrevisiondate'}),
358: $ref->{'owner'},
1.47 ! www 359: $ref->{'copyright'},
! 360: $dyn{'count'},
! 361: $dyn{'course'},
! 362: $dyn{'course_list'},
! 363: $dyn{'goto'},
! 364: $dyn{'goto_list'},
! 365: $dyn{'comefrom'},
! 366: $dyn{'comefrom_list'},
! 367: $dyn{'usage'},
! 368: $dyn{'usage_list'},
! 369: $dyn{'stdno'},
! 370: $dyn{'stdno_list'},
! 371: $dyn{'avetries'},
! 372: $dyn{'avetries_list'},
! 373: $dyn{'difficulty'},
! 374: $dyn{'difficulty_list'}
! 375: )) {
! 376: print LOG "\nMySQL Error Insert: ".$dbh->errstr."\n";
! 377: die $dbh->errstr;
! 378: }
1.34 matthew 379: $ref = undef;
1.31 harris41 380: }
381: }
382: # --------------------------------------------------- Close database connection
1.47 ! www 383: $dbh->do("DROP TABLE IF EXISTS metadata");
! 384: unless ($dbh->do("RENAME TABLE newmetadata TO metadata")) {
! 385: print LOG "\nMySQL Error Rename: ".$dbh->errstr."\n";
! 386: die $dbh->errstr;
! 387: }
! 388: unless ($dbh->disconnect) {
! 389: print LOG "\nMySQL Error Disconnect: ".$dbh->errstr."\n";
! 390: die $dbh->errstr;
! 391: }
1.31 harris41 392: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
393: close(LOG);
1.36 www 394: &writesimple();
1.38 www 395: &writecount();
1.31 harris41 396: exit 0;
1.33 matthew 397:
398:
399:
1.31 harris41 400: # =============================================================================
1.1 harris41 401:
1.31 harris41 402: # ---------------------------------------------------------------- Get metadata
403: # significantly altered from subroutine present in lonnet
404: sub metadata {
405: my ($uri,$what)=@_;
1.47 ! www 406: my %metacache=();
1.31 harris41 407: $uri=&declutter($uri);
408: my $filename=$uri;
409: $uri=~s/\.meta$//;
410: $uri='';
411: unless ($metacache{$uri.'keys'}) {
412: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
413: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
414: my $parser=HTML::TokeParser->new(\$metastring);
415: my $token;
416: while ($token=$parser->get_token) {
1.33 matthew 417: if ($token->[0] eq 'S') {
418: my $entry=$token->[1];
419: my $unikey=$entry;
420: if (defined($token->[2]->{'part'})) {
421: $unikey.='_'.$token->[2]->{'part'};
422: }
423: if (defined($token->[2]->{'name'})) {
424: $unikey.='_'.$token->[2]->{'name'};
425: }
426: if ($metacache{$uri.'keys'}) {
427: $metacache{$uri.'keys'}.=','.$unikey;
428: } else {
429: $metacache{$uri.'keys'}=$unikey;
430: }
431: map {
432: $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
433: } @{$token->[3]};
434: unless (
435: $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
436: ) { $metacache{$uri.''.$unikey}=
437: $metacache{$uri.''.$unikey.'.default'};
438: }
439: }
440: }
1.31 harris41 441: }
442: return \%metacache;
443: }
1.28 harris41 444:
1.31 harris41 445: # ------------------------------------------------------------ Serves up a file
446: # returns either the contents of the file or a -1
447: sub getfile {
1.33 matthew 448: my $file=shift;
449: if (! -e $file ) { return -1; };
450: my $fh=IO::File->new($file);
451: my $a='';
452: while (<$fh>) { $a .=$_; }
453: return $a;
1.31 harris41 454: }
1.28 harris41 455:
1.31 harris41 456: # ------------------------------------------------------------- Declutters URLs
457: sub declutter {
458: my $thisfn=shift;
459: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
460: $thisfn=~s/^\///;
461: $thisfn=~s/^res\///;
462: return $thisfn;
463: }
1.28 harris41 464:
1.31 harris41 465: # --------------------------------------- Is this the home server of an author?
466: # (copied from lond, modification of the return value)
467: sub ishome {
468: my $author=shift;
469: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
470: my ($udom,$uname)=split(/\//,$author);
471: my $proname=propath($udom,$uname);
472: if (-e $proname) {
473: return 1;
474: } else {
475: return 0;
476: }
477: }
1.28 harris41 478:
1.31 harris41 479: # -------------------------------------------- Return path to profile directory
480: # (copied from lond)
481: sub propath {
482: my ($udom,$uname)=@_;
483: $udom=~s/\W//g;
484: $uname=~s/\W//g;
485: my $subdir=$uname.'__';
486: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
487: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
488: return $proname;
489: }
1.28 harris41 490:
1.31 harris41 491: # ---------------------------- convert 'time' format into a datetime sql format
492: sub sqltime {
1.13 harris41 493: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.31 harris41 494: localtime(&unsqltime(@_[0]));
495: $mon++; $year+=1900;
496: return "$year-$mon-$mday $hour:$min:$sec";
497: }
1.28 harris41 498:
1.31 harris41 499: sub maketime {
500: my %th=@_;
1.33 matthew 501: return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
502: $th{'day'},$th{'month'}-1,
503: $th{'year'}-1900,0,0,$th{'dlsav'}));
1.31 harris41 504: }
1.28 harris41 505:
506:
1.31 harris41 507: #########################################
508: #
509: # Retro-fixing of un-backward-compatible time format
1.28 harris41 510:
1.31 harris41 511: sub unsqltime {
512: my $timestamp=shift;
513: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1.33 matthew 514: $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
515: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1.31 harris41 516: }
517: return $timestamp;
518: }
1.28 harris41 519:
1.45 www 520: # ----------------- Code to enable 'find' subroutine listing of the .meta files
521:
522: no strict "vars";
523:
524: sub wanted {
525: (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
526: -f _ &&
527: /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
528: push(@metalist,"$dir/$_");
529: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>