Annotation of loncom/metadata_database/searchcat.pl, revision 1.26
1.1 harris41 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # searchcat.pl "Search Catalog" batch script
1.16 harris41 4: #
1.26 ! www 5: # $Id: searchcat.pl,v 1.25 2002/11/18 20:44:15 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.25 www 167: # ---------------------------------------------------------- We are in business
168:
169: open(LOG,'>'.$perlvar{'lonDaemons'}.'/logs/searchcat.log');
170: print LOG '==== Searchcat Run '.localtime()."====\n\n";
1.3 harris41 171: my $dbh;
1.1 harris41 172: # ------------------------------------- Make sure that database can be accessed
173: {
174: unless (
175: $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
176: ) {
1.25 www 177: print LOG "Cannot connect to database!\n";
1.1 harris41 178: exit;
179: }
1.19 matthew 180: my $make_metadata_table = "CREATE TABLE IF NOT EXISTS metadata (".
181: "title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, ".
182: "version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, ".
183: "creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, ".
184: "copyright TEXT, FULLTEXT idx_title (title), ".
185: "FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), ".
186: "FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), ".
187: "FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), ".
188: "FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), ".
189: "FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), ".
190: "FULLTEXT idx_copyright (copyright)) TYPE=MYISAM";
191: # It would sure be nice to have some logging mechanism.
192: $dbh->do($make_metadata_table);
1.1 harris41 193: }
194:
195: # ------------------------------------------------------------- get .meta files
1.2 harris41 196: opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
197: my @homeusers=grep
198: {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
199: grep {!/^\.\.?$/} readdir(RESOURCES);
200: closedir RESOURCES;
201: foreach my $user (@homeusers) {
1.25 www 202: print LOG "\n=== User: ".$user."\n\n";
203: # Remove left-over db-files from potentially crashed searchcat run
204: my $prodir=&propath($perlvar{'lonDefDomain'},$user);
205: unlink($prodir.'/nohist_new_resevaldata.db');
206: # Use find.pl
207: undef @metalist;
208: @metalist=();
1.2 harris41 209: &find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
1.1 harris41 210:
211: # -- process each file to get metadata and put into search catalog SQL database
1.9 harris41 212: # Also, check to see if already there.
1.11 harris41 213: # I could just delete (without searching first), but this works for now.
1.1 harris41 214: foreach my $m (@metalist) {
1.25 www 215: print LOG "- ".$m."\n";
1.1 harris41 216: my $ref=&metadata($m);
1.11 harris41 217: my $m2='/res/'.&declutter($m);
1.12 harris41 218: $m2=~s/\.meta$//;
1.21 www 219: &dynamicmeta($m2);
1.12 harris41 220: my $q2="select * from metadata where url like binary '$m2'";
1.9 harris41 221: my $sth = $dbh->prepare($q2);
222: $sth->execute();
223: my $r1=$sth->fetchall_arrayref;
224: if (@$r1) {
1.12 harris41 225: $sth=$dbh->prepare("delete from metadata where url like binary '$m2'");
1.9 harris41 226: $sth->execute();
227: }
228: $sth=$dbh->prepare('insert into metadata values ('.
1.8 harris41 229: '"'.delete($ref->{'title'}).'"'.','.
230: '"'.delete($ref->{'author'}).'"'.','.
231: '"'.delete($ref->{'subject'}).'"'.','.
1.12 harris41 232: '"'.$m2.'"'.','.
1.8 harris41 233: '"'.delete($ref->{'keywords'}).'"'.','.
1.9 harris41 234: '"'.'current'.'"'.','.
1.8 harris41 235: '"'.delete($ref->{'notes'}).'"'.','.
236: '"'.delete($ref->{'abstract'}).'"'.','.
237: '"'.delete($ref->{'mime'}).'"'.','.
238: '"'.delete($ref->{'language'}).'"'.','.
1.13 harris41 239: '"'.sqltime(delete($ref->{'creationdate'})).'"'.','.
240: '"'.sqltime(delete($ref->{'lastrevisiondate'})).'"'.','.
1.8 harris41 241: '"'.delete($ref->{'owner'}).'"'.','.
242: '"'.delete($ref->{'copyright'}).'"'.')');
1.1 harris41 243: $sth->execute();
244: }
245:
246: # ----------------------------------------------------------- Clean up database
247: # Need to, perhaps, remove stale SQL database records.
248: # ... not yet implemented
249:
1.25 www 250:
251: # -------------------------------------------------- Copy over the new db-files
252: system('mv '.$prodir.'/nohist_new_resevaldata.db '.
253: $prodir.'/nohist_resevaldata.db');
1.26 ! www 254: system('chown www:www '.$prodir.'/nohist_resevaldata.db');
1.25 www 255: }
1.1 harris41 256: # --------------------------------------------------- Close database connection
257: $dbh->disconnect;
1.25 www 258: print LOG "\n==== Searchcat completed ".localtime()." ====\n";
259: close(LOG);
260: exit 0;
261: # =============================================================================
1.1 harris41 262:
263: # ---------------------------------------------------------------- Get metadata
264: # significantly altered from subroutine present in lonnet
265: sub metadata {
266: my ($uri,$what)=@_;
267: my %metacache;
268: $uri=&declutter($uri);
269: my $filename=$uri;
270: $uri=~s/\.meta$//;
271: $uri='';
272: unless ($metacache{$uri.'keys'}) {
273: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
274: my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
275: my $parser=HTML::TokeParser->new(\$metastring);
276: my $token;
277: while ($token=$parser->get_token) {
278: if ($token->[0] eq 'S') {
279: my $entry=$token->[1];
280: my $unikey=$entry;
281: if (defined($token->[2]->{'part'})) {
282: $unikey.='_'.$token->[2]->{'part'};
283: }
284: if (defined($token->[2]->{'name'})) {
285: $unikey.='_'.$token->[2]->{'name'};
286: }
287: if ($metacache{$uri.'keys'}) {
288: $metacache{$uri.'keys'}.=','.$unikey;
289: } else {
290: $metacache{$uri.'keys'}=$unikey;
291: }
292: map {
293: $metacache{$uri.''.$unikey.'.'.$_}=$token->[2]->{$_};
294: } @{$token->[3]};
295: unless (
296: $metacache{$uri.''.$unikey}=$parser->get_text('/'.$entry)
297: ) { $metacache{$uri.''.$unikey}=
298: $metacache{$uri.''.$unikey.'.default'};
299: }
300: }
301: }
302: }
303: return \%metacache;
304: }
305:
306: # ------------------------------------------------------------ Serves up a file
307: # returns either the contents of the file or a -1
308: sub getfile {
309: my $file=shift;
310: if (! -e $file ) { return -1; };
311: my $fh=IO::File->new($file);
312: my $a='';
313: while (<$fh>) { $a .=$_; }
314: return $a
315: }
316:
317: # ------------------------------------------------------------- Declutters URLs
318: sub declutter {
319: my $thisfn=shift;
320: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
321: $thisfn=~s/^\///;
322: $thisfn=~s/^res\///;
323: return $thisfn;
324: }
1.2 harris41 325:
326: # --------------------------------------- Is this the home server of an author?
327: # (copied from lond, modification of the return value)
328: sub ishome {
329: my $author=shift;
330: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
331: my ($udom,$uname)=split(/\//,$author);
332: my $proname=propath($udom,$uname);
333: if (-e $proname) {
334: return 1;
335: } else {
336: return 0;
337: }
338: }
339:
340: # -------------------------------------------- Return path to profile directory
341: # (copied from lond)
342: sub propath {
343: my ($udom,$uname)=@_;
344: $udom=~s/\W//g;
345: $uname=~s/\W//g;
346: my $subdir=$uname.'__';
347: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
348: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
349: return $proname;
350: }
1.13 harris41 351:
352: # ---------------------------- convert 'time' format into a datetime sql format
353: sub sqltime {
354: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.24 www 355: localtime(&unsqltime(@_[0]));
1.14 harris41 356: $mon++; $year+=1900;
1.13 harris41 357: return "$year-$mon-$mday $hour:$min:$sec";
358: }
1.24 www 359:
360: sub maketime {
361: my %th=@_;
362: return POSIX::mktime(
363: ($th{'seconds'},$th{'minutes'},$th{'hours'},
364: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
365: }
366:
367:
368: #########################################
369: #
370: # Retro-fixing of un-backward-compatible time format
371:
372: sub unsqltime {
373: my $timestamp=shift;
374: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
375: $timestamp=&maketime(
376: 'year'=>$1,'month'=>$2,'day'=>$3,
377: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
378: }
379: return $timestamp;
380: }
381:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>