Annotation of loncom/metadata_database/searchcat.pl, revision 1.27
1.1 harris41 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # searchcat.pl "Search Catalog" batch script
1.16 harris41 4: #
1.27 ! www 5: # $Id: searchcat.pl,v 1.26 2003/01/04 15:04:12 www Exp $
1.16 harris41 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: # YEAR=2001
1.17 harris41 30: # 04/14/2001, 04/16/2001 Scott Harrison
1.16 harris41 31: #
1.17 harris41 32: # YEAR=2002
33: # 05/11/2002 Scott Harrison
1.16 harris41 34: #
35: ###
1.1 harris41 36:
37: # This script goes through a LON-CAPA resource
38: # directory and gathers metadata.
39: # The metadata is entered into a SQL database.
40:
1.17 harris41 41: use lib '/home/httpd/lib/perl/';
42: use LONCAPA::Configuration;
43:
1.1 harris41 44: use IO::File;
45: use HTML::TokeParser;
1.6 harris41 46: use DBI;
1.21 www 47: use GDBM_File;
1.24 www 48: use POSIX qw(strftime mktime);
1.1 harris41 49:
50: my @metalist;
1.21 www 51:
52:
53: # ----------------------------------------------------- Un-Escape Special Chars
54:
55: sub unescape {
56: my $str=shift;
57: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
58: return $str;
59: }
60:
1.22 www 61: # -------------------------------------------------------- Escape Special Chars
62:
63: sub escape {
64: my $str=shift;
65: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
66: return $str;
67: }
68:
1.21 www 69:
70: # ------------------------------------------- Code to evaluate dynamic metadata
71:
72: sub dynamicmeta {
1.25 www 73:
1.21 www 74: my $url=&declutter(shift);
75: $url=~s/\.meta$//;
76: my %returnhash=();
77: my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
78: my $prodir=&propath($adomain,$aauthor);
1.25 www 79: if ((tie(%evaldata,'GDBM_File',
80: $prodir.'/nohist_resevaldata.db',&GDBM_READER(),0640)) &&
81: (tie(%newevaldata,'GDBM_File',
82: $prodir.'/nohist_new_resevaldata.db',&GDBM_WRCREAT(),0640))) {
1.21 www 83: my %sum=();
84: my %cnt=();
85: my %listitems=('count' => 'add',
86: 'course' => 'add',
87: 'avetries' => 'avg',
88: 'stdno' => 'add',
89: 'difficulty' => 'avg',
90: 'clear' => 'avg',
91: 'technical' => 'avg',
92: 'helpful' => 'avg',
93: 'correct' => 'avg',
94: 'depth' => 'avg',
95: 'comments' => 'app',
96: 'usage' => 'cnt'
97: );
98: my $regexp=$url;
99: $regexp=~s/(\W)/\\$1/g;
100: $regexp='___'.$regexp.'___([a-z]+)$';
101: foreach (keys %evaldata) {
102: my $key=&unescape($_);
103: if ($key=~/$regexp/) {
1.22 www 104: my $ctype=$1;
105: if (defined($cnt{$ctype})) {
106: $cnt{$ctype}++;
107: } else {
108: $cnt{$ctype}=1;
109: }
110: unless ($listitems{$ctype} eq 'app') {
111: if (defined($sum{$ctype})) {
112: $sum{$ctype}+=$evaldata{$_};
113: } else {
114: $sum{$ctype}=$evaldata{$_};
115: }
116: } else {
117: if (defined($sum{$ctype})) {
118: if ($evaldata{$_}) {
119: $sum{$ctype}.='<hr>'.$evaldata{$_};
1.21 www 120: }
1.22 www 121: } else {
122: $sum{$ctype}=''.$evaldata{$_};
123: }
124: }
1.25 www 125: if ($ctype ne 'count') {
126: $newevaldata{$_}=$evaldata{$_};
127: }
1.22 www 128: }
129: }
130: foreach (keys %cnt) {
131: if ($listitems{$_} eq 'avg') {
132: $returnhash{$_}=int(($sum{$_}/$cnt{$_})*100.0+0.5)/100.0;
133: } elsif ($listitems{$_} eq 'cnt') {
134: $returnhash{$_}=$cnt{$_};
135: } else {
136: $returnhash{$_}=$sum{$_};
137: }
138: }
139: if ($returnhash{'count'}) {
140: my $newkey=$$.'_'.time.'_searchcat___'.&escape($url).'___count';
1.25 www 141: $newevaldata{$newkey}=$returnhash{'count'};
1.21 www 142: }
143: untie(%evaldata);
1.25 www 144: untie(%newevaldata);
1.21 www 145: }
146: return %returnhash;
147: }
148:
1.1 harris41 149: # ----------------- Code to enable 'find' subroutine listing of the .meta files
150: require "find.pl";
151: sub wanted {
152: (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
153: -f _ &&
1.10 harris41 154: /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
1.1 harris41 155: push(@metalist,"$dir/$_");
156: }
157:
1.18 matthew 158: # --------------- Read loncapa_apache.conf and loncapa.conf and get variables
1.20 harris41 159: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.17 harris41 160: my %perlvar=%{$perlvarref};
161: undef $perlvarref; # remove since sensitive and not needed
162: delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
1.15 harris41 163:
164: # ------------------------------------- Only run if machine is a library server
165: exit unless $perlvar{'lonRole'} eq 'library';
1.1 harris41 166:
1.27 ! www 167: # ----------------------------- Make sure this process is running from user=www
! 168:
! 169: my $wwwid=getpwnam('www');
! 170: if ($wwwid!=$<) {
! 171: $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
! 172: $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
! 173: system("echo 'User ID mismatch. searchcat.pl must be run as user www.' |\
! 174: mailto $emailto -s '$subj' > /dev/null");
! 175: exit 1;
! 176: }
! 177:
! 178:
1.25 www 179: # ---------------------------------------------------------- We are in business
180:
181: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
182: print LOG '==== Searchcat Run '.localtime()."====\n\n";
1.3 harris41 183: my $dbh;
1.1 harris41 184: # ------------------------------------- Make sure that database can be accessed
185: {
186: unless (
187: $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
188: ) {
1.25 www 189: print LOG "Cannot connect to database!\n";
1.1 harris41 190: exit;
191: }
1.19 matthew 192: my $make_metadata_table = "CREATE TABLE IF NOT EXISTS metadata (".
193: "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
194: "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
195: "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
196: "copyright TEXT, FULLTEXT idx_title (title), ".
197: "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
198: "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
199: "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
200: "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
201: "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
202: "FULLTEXT idx_copyright (copyright)) TYPE=MYISAM";
203: # It would sure be nice to have some logging mechanism.
204: $dbh->do($make_metadata_table);
1.1 harris41 205: }
206:
207: # ------------------------------------------------------------- get .meta files
1.2 harris41 208: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
209: my @homeusers=grep
210: {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
211: grep {!/^\.\.?$/} readdir(RESOURCES);
212: closedir RESOURCES;
213: foreach my $user (@homeusers) {
1.25 www 214: print LOG "\n=== User: ".$user."\n\n";
215: # Remove left-over db-files from potentially crashed searchcat run
216: my $prodir=&propath($perlvar{'lonDefDomain'},$user);
217: unlink($prodir.'/nohist_new_resevaldata.db');
218: # Use find.pl
219: undef @metalist;
220: @metalist=();
1.2 harris41 221: &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
1.1 harris41 222:
223: # -- process each file to get metadata and put into search catalog SQL database
1.9 harris41 224: # Also, check to see if already there.
1.11 harris41 225: # I could just delete (without searching first), but this works for now.
1.1 harris41 226: foreach my $m (@metalist) {
1.25 www 227: print LOG "- ".$m."\n";
1.1 harris41 228: my $ref=&metadata($m);
1.11 harris41 229: my $m2='/res/'.&declutter($m);
1.12 harris41 230: $m2=~s/\.meta$//;
1.21 www 231: &dynamicmeta($m2);
1.12 harris41 232: my $q2="select * from metadata where url like binary '$m2'";
1.9 harris41 233: my $sth = $dbh->prepare($q2);
234: $sth->execute();
235: my $r1=$sth->fetchall_arrayref;
236: if (@$r1) {
1.12 harris41 237: $sth=$dbh->prepare("delete from metadata where url like binary '$m2'");
1.9 harris41 238: $sth->execute();
239: }
240: $sth=$dbh->prepare('insert into metadata values ('.
1.8 harris41 241: '"'.delete($ref->{'title'}).'"'.','.
242: '"'.delete($ref->{'author'}).'"'.','.
243: '"'.delete($ref->{'subject'}).'"'.','.
1.12 harris41 244: '"'.$m2.'"'.','.
1.8 harris41 245: '"'.delete($ref->{'keywords'}).'"'.','.
1.9 harris41 246: '"'.'current'.'"'.','.
1.8 harris41 247: '"'.delete($ref->{'notes'}).'"'.','.
248: '"'.delete($ref->{'abstract'}).'"'.','.
249: '"'.delete($ref->{'mime'}).'"'.','.
250: '"'.delete($ref->{'language'}).'"'.','.
1.13 harris41 251: '"'.sqltime(delete($ref->{'creationdate'})).'"'.','.
252: '"'.sqltime(delete($ref->{'lastrevisiondate'})).'"'.','.
1.8 harris41 253: '"'.delete($ref->{'owner'}).'"'.','.
254: '"'.delete($ref->{'copyright'}).'"'.')');
1.1 harris41 255: $sth->execute();
256: }
257:
258: # ----------------------------------------------------------- Clean up database
259: # Need to, perhaps, remove stale SQL database records.
260: # ... not yet implemented
261:
1.25 www 262:
263: # -------------------------------------------------- Copy over the new db-files
264: system('mv '.$prodir.'/nohist_new_resevaldata.db '.
265: $prodir.'/nohist_resevaldata.db');
266: }
1.1 harris41 267: # --------------------------------------------------- Close database connection
268: $dbh->disconnect;
1.25 www 269: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
270: close(LOG);
271: exit 0;
272: # =============================================================================
1.1 harris41 273:
274: # ---------------------------------------------------------------- Get metadata
275: # significantly altered from subroutine present in lonnet
276: sub metadata {
277: my ($uri,$what)=@_;
278: my %metacache;
279: $uri=&declutter($uri);
280: my $filename=$uri;
281: $uri=~s/\.meta$//;
282: $uri='';
283: unless ($metacache{$uri.'keys'}) {
284: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
285: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
286: my $parser=HTML::TokeParser->new(\$metastring);
287: my $token;
288: while ($token=$parser->get_token) {
289: if ($token->[0] eq 'S') {
290: my $entry=$token->[1];
291: my $unikey=$entry;
292: if (defined($token->[2]->{'part'})) {
293: $unikey.='_'.$token->[2]->{'part'};
294: }
295: if (defined($token->[2]->{'name'})) {
296: $unikey.='_'.$token->[2]->{'name'};
297: }
298: if ($metacache{$uri.'keys'}) {
299: $metacache{$uri.'keys'}.=','.$unikey;
300: } else {
301: $metacache{$uri.'keys'}=$unikey;
302: }
303: map {
304: $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
305: } @{$token->[3]};
306: unless (
307: $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
308: ) { $metacache{$uri.''.$unikey}=
309: $metacache{$uri.''.$unikey.'.default'};
310: }
311: }
312: }
313: }
314: return \%metacache;
315: }
316:
317: # ------------------------------------------------------------ Serves up a file
318: # returns either the contents of the file or a -1
319: sub getfile {
320: my $file=shift;
321: if (! -e $file ) { return -1; };
322: my $fh=IO::File->new($file);
323: my $a='';
324: while (<$fh>) { $a .=$_; }
325: return $a
326: }
327:
328: # ------------------------------------------------------------- Declutters URLs
329: sub declutter {
330: my $thisfn=shift;
331: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
332: $thisfn=~s/^\///;
333: $thisfn=~s/^res\///;
334: return $thisfn;
335: }
1.2 harris41 336:
337: # --------------------------------------- Is this the home server of an author?
338: # (copied from lond, modification of the return value)
339: sub ishome {
340: my $author=shift;
341: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
342: my ($udom,$uname)=split(/\//,$author);
343: my $proname=propath($udom,$uname);
344: if (-e $proname) {
345: return 1;
346: } else {
347: return 0;
348: }
349: }
350:
351: # -------------------------------------------- Return path to profile directory
352: # (copied from lond)
353: sub propath {
354: my ($udom,$uname)=@_;
355: $udom=~s/\W//g;
356: $uname=~s/\W//g;
357: my $subdir=$uname.'__';
358: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
359: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
360: return $proname;
361: }
1.13 harris41 362:
363: # ---------------------------- convert 'time' format into a datetime sql format
364: sub sqltime {
365: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.24 www 366: localtime(&unsqltime(@_[0]));
1.14 harris41 367: $mon++; $year+=1900;
1.13 harris41 368: return "$year-$mon-$mday $hour:$min:$sec";
369: }
1.24 www 370:
371: sub maketime {
372: my %th=@_;
373: return POSIX::mktime(
374: ($th{'seconds'},$th{'minutes'},$th{'hours'},
375: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
376: }
377:
378:
379: #########################################
380: #
381: # Retro-fixing of un-backward-compatible time format
382:
383: sub unsqltime {
384: my $timestamp=shift;
385: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
386: $timestamp=&maketime(
387: 'year'=>$1,'month'=>$2,'day'=>$3,
388: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
389: }
390: return $timestamp;
391: }
392:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>