source: trunk/gsdl/perllib/plugins/HTMLPlug.pm@ 2735

Last change on this file since 2735 was 2735, checked in by sjboddie, 23 years ago

Fixed up bugs I introduced with recent change to BasPlug

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 19.1 KB
Line 
1###########################################################################
2#
3# HTMLPlug.pm -- basic html plugin
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 1999 New Zealand Digital Library Project
10#
11# This program 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# This program 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 this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26
27#
28# Note that this plugin handles frames only in a very simple way
29# i.e. each frame is treated as a separate document. This means
30# search results will contain links to individual frames rather
31# than linking to the top level frameset.
32# There may also be some problems caused by the _parent target
33# (it's removed by this plugin)
34# To use frames properly you'll need to use the WebPlug plugin.
35#
36
37
38package HTMLPlug;
39
40use BasPlug;
41use ghtml;
42use unicode;
43use util;
44use parsargv;
45
46sub BEGIN {
47 @ISA = ('BasPlug');
48}
49
50sub print_usage {
51 print STDERR "\n usage: plugin HTMLPlug [options]\n\n";
52 print STDERR " options:\n";
53 print STDERR " -nolinks Don't make any attempt to trap links (setting this flag may\n";
54 print STDERR " improve speed of building/importing but any relative links within\n";
55 print STDERR " documents will be broken).\n";
56 print STDERR " -keep_head Don't remove headers from html files.\n";
57 print STDERR " -no_metadata Don't attempt to extract any metadata from files.\n";
58 print STDERR " -metadata_fields Comma separated list of metadata fields to attempt to extract.\n";
59 print STDERR " Defaults to 'Title'.\n";
60 print STDERR " Use 'tag<tagname>' to have the contents of the first <tagname>\n";
61 print STDERR " pair put in a metadata element called 'tagname' Capitalise \n";
62 print STDERR " 'tagname' as you want the metadata capitalised in the GML \n";
63 print STDERR " file, since the tag extraction is case insensitive.\n";
64 print STDERR " -hunt_creator_metadata Find as much metadata as possible on authorship and place it in the\n ";
65 print STDERR " 'Creator' field. Requires the -metadata_fields flag.\n ";
66 print STDERR " -file_is_url Set if input filenames make up url of original source documents\n";
67 print STDERR " e.g. if a web mirroring tool was used to create the import\n";
68 print STDERR " directory structure\n";
69 print STDERR " -assoc_files Perl regular expression of file extensions to associate with\n";
70 print STDERR " html documents. Defaults to '(?i)\.(jpe?g|gif|png|css)\$'\n";
71 print STDERR " -rename_assoc_files Renames files associated with documents (e.g. images). Also\n";
72 print STDERR " creates much shallower directory structure (useful when creating\n";
73 print STDERR " collections to go on cd-rom).\n\n";
74 print STDERR " -title_sub Substitution expression to modify string stored as Title.\n";
75 print STDERR " Used by, for example, PDFHtml to remove Page 1 etc from text\n";
76 print STDERR " chosen to be used as the title.\n";
77}
78
79sub new {
80 my $class = shift (@_);
81 my $self = new BasPlug ($class, @_);
82
83 if (!parsargv::parse(\@_,
84 q^nolinks^, \$self->{'nolinks'},
85 q^keep_head^, \$self->{'keep_head'},
86 q^no_metadata^, \$self->{'no_metadata'},
87 q^metadata_fields/.*/Title^, \$self->{'metadata_fields'},
88 q^hunt_creator_metadata^, \$self->{'hunt_creator_metadata'},
89 q^w3mir^, \$self->{'w3mir'},
90 q^file_is_url^, \$self->{'file_is_url'},
91 q^assoc_files/.*/(?i)\.(jpe?g|gif|png|css)$^, \$self->{'assoc_files'},
92 q^rename_assoc_files^, \$self->{'rename_assoc_files'},
93 q^title_sub/.*/^, \$self->{'title_sub'},
94 "allow_extra_options")) {
95
96 print STDERR "\nIncorrect options passed to HTMLPlug, check your collect.cfg configuration file\n";
97 &print_usage();
98 die "\n";
99 }
100
101 # retain this for backward compatibility (w3mir option was replaced by
102 # file_is_url)
103 if ($self->{'w3mir'}) {
104 $self->{'file_is_url'} = 1;
105 }
106
107 $self->{'aux_files'} = {};
108 $self->{'dir_num'} = 0;
109 $self->{'file_num'} = 0;
110
111 return bless $self, $class;
112}
113
114
115sub get_default_block_exp {
116 my $self = shift (@_);
117
118 return q^(?i)\.(gif|jpe?g|png|css)$^;
119}
120
121sub get_default_process_exp {
122 my $self = shift (@_);
123
124 # the last option is an attempt to encode the concept of an html query ...
125 return q^(?i)(\.html?|\.shtml|\.shm|\.asp|\.php|\.cgi|.+\?.+=.*)$^;
126}
127
128
129# do plugin specific processing of doc_obj
130sub process {
131 my $self = shift (@_);
132 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
133 my $outhandle = $self->{'outhandle'};
134
135 print $outhandle "HTMLPlug: processing $file\n"
136 if $self->{'verbosity'} > 1;
137
138 my $cursection = $doc_obj->get_top_section();
139
140 $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection)
141 unless $self->{'no_metadata'};
142
143 # Store URL for page as metadata - this can be used for an
144 # altavista style search interface. The URL won't be valid
145 # unless the file structure contains the domain name (i.e.
146 # like when w3mir is used to download a website).
147 my $web_url = "http://$file";
148 $web_url =~ s/\\/\//g; # for windows
149 $doc_obj->add_utf8_metadata($cursection, "URL", $web_url);
150
151 # remove header and footer
152 if (!$self->{'keep_head'}) {
153 $$textref =~ s/^.*?<body[^>]*>//is;
154 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
155 }
156
157 # trap links
158 if (!$self->{'nolinks'}) {
159
160 # usemap="./#index" not handled correctly => change to "#index"
161 $$textref =~ s/(<img[^>]*?usemap\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
162 $self->replace_usemap_links($1, $2, $3)/isge;
163
164 $$textref =~ s/(<(?:a|area|frame|link)\s+[^>]*?\s*(?:href|src)\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
165 $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
166 }
167
168 # trap images
169
170 # allow spaces if inside quotes - jrm21
171 $$textref =~ s/(<img[^>]*?src\s*=\s*)(\"[^\"]+\"|[^\s>]+)([^>]*>)/
172 $self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
173
174 # add text to document object
175 $doc_obj->add_utf8_text($cursection, $$textref);
176
177 return 1;
178}
179
180
181
182
183sub replace_images {
184 my $self = shift (@_);
185 my ($front, $link, $back, $base_dir,
186 $file, $doc_obj, $section) = @_;
187 # remove quotes from link at start and end if necessary
188 if ($link=~/^\"/) {
189 $link=~s/^\"//;$link=~s/\"$//;
190 $front.='"';
191 $back="\"$back";
192 }
193
194 $link =~ s/\n/ /g;
195 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
196 return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
197}
198
199sub replace_href_links {
200 my $self = shift (@_);
201 my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;
202
203 # attempt to sort out targets - frames are not handled
204 # well in this plugin and some cases will screw things
205 # up - e.g. the _parent target (so we'll just remove
206 # them all ;-)
207 $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
208 $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
209 $front =~ s/target=\"?_parent\"?//is;
210 $back =~ s/target=\"?_parent\"?//is;
211
212 return $front . $link . $back if $link =~ /^\#/s;
213 $link =~ s/\n/ /g;
214
215 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
216 # href may use '\'s where '/'s should be on Windows
217 $href =~ s/\\/\//g;
218
219 my ($filename) = $href =~ /^(?:.*?):(?:\/\/)?(.*)/;
220
221 ##### leave all these links alone (they won't be picked up by intermediate
222 ##### pages). I think that's safest when dealing with frames, targets etc.
223 ##### (at least until I think of a better way to do it). Problems occur with
224 ##### mailto links from within small frames, the intermediate page is displayed
225 ##### within that frame and can't be seen. There is still potential for this to
226 ##### happen even with html pages - the solution seems to be to somehow tell
227 ##### the browser from the server side to display the page being sent (i.e.
228 ##### the intermediate page) in the top level window - I'm not sure if that's
229 ##### possible - the following line should probably be deleted if that can be done
230 return $front . $link . $back if $href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/is;
231
232
233 if (($rl == 0) || ($filename =~ /$self->{'process_exp'}/) ||
234 ($href =~ /\/$/) || ($href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
235 &ghtml::urlsafe ($href);
236 return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
237
238 } else {
239 # link is to some other type of file (eg image) so we'll
240 # need to associate that file
241 return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
242 }
243}
244
245sub add_file {
246 my $self = shift (@_);
247 my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
248 my ($newname);
249
250 my $filename = $href;
251 $filename =~ s/^[^:]*:\/\///;
252 $filename = &util::filename_cat($base_dir, $filename);
253
254 my ($ext) = $filename =~ /(\.[^\.]*)$/;
255
256 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
257 return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
258 }
259
260 if ($self->{'rename_assoc_files'}) {
261 if (defined $self->{'aux_files'}->{$href}) {
262 $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
263 $self->{'aux_files'}->{$href}->{'file_num'} . $ext;
264 } else {
265 $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
266 $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
267 $self->inc_filecount ();
268 }
269 $doc_obj->associate_file($filename, $newname, undef, $section);
270 return "_httpcollimg_/$newname";
271
272 } else {
273 ($newname) = $filename =~ /([^\/\\]*)$/;
274 $doc_obj->associate_file($filename, $newname, undef, $section);
275 return "_httpdocimg_/$newname";
276 }
277}
278
279
280sub format_link {
281 my $self = shift (@_);
282 my ($link, $base_dir, $file) = @_;
283
284 my ($before_hash, $hash_part) = $link =~ /^([^\#]*)(\#?.*)$/;
285
286 $hash_part = "" if !defined $hash_part;
287 if (!defined $before_hash || $before_hash !~ /[\w\.\/]/) {
288 my $outhandle = $self->{'outhandle'};
289 print $outhandle "HTMLPlug: ERROR - badly formatted tag ignored ($link)\n"
290 if $self->{'verbosity'};
291 return ($link, "", 0);
292 }
293
294 if ($before_hash =~ s/^((?:http|ftp|file):\/\/)//i) {
295 my $type = $1;
296
297 if ($link =~ /^(http|ftp):/i) {
298 # Turn url (using /) into file name (possibly using \ on windows)
299 my @http_dir_split = split('/', $before_hash);
300 $before_hash = &util::filename_cat(@http_dir_split);
301 }
302
303 $before_hash = $self->eval_dir_dots($before_hash);
304
305 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
306
307 my $rl = 0;
308 $rl = 1 if (-e $linkfilename);
309
310 # make sure there's a slash on the end if it's a directory
311 if ($before_hash !~ /\/$/) {
312 $before_hash .= "/" if (-d $linkfilename);
313 }
314
315 return ($type . $before_hash, $hash_part, $rl);
316
317 } elsif ($link !~ /^(mailto|news|gopher|nntp|telnet|javascript):/i) {
318 if ($before_hash =~ s/^\/// || $before_hash =~ /\\/) {
319
320 # the first directory will be the domain name if file_is_url
321 # to generate archives, otherwise we'll assume all files are
322 # from the same site and base_dir is the root
323 # This is not called in Windows
324 if ($self->{'file_is_url'}) {
325 my @dirs = split /[\/\\]/, $file;
326 my $domname = shift (@dirs);
327 $before_hash = &util::filename_cat($domname, $before_hash);
328 $before_hash =~ s/\\/\//g; # for windows
329 }
330 else
331 {
332 # see if link shares directory with source document
333 # => turn into relative link if this is so!
334 my $before_hash_fix = "";
335
336 # filename_cat appends / or \ to the beginning of the
337 # file pathname but in Windows we don't want to do that
338 if ($ENV{'GSDLOS'} =~ /^windows/i) {
339 $before_hash_fix = $before_hash;
340 }
341 else {
342 $before_hash_fix = &util::filename_cat("",$before_hash);
343 }
344
345 my $base_dir_win_match = $base_dir;
346 $base_dir_win_match =~ s/\\/\\\\/g;
347
348 $before_hash_fix =~ s/^$base_dir_win_match(\\|\/)//;
349 $before_hash = $before_hash_fix;
350
351 }
352
353 } else {
354 # Turn relative file path into full path
355 my $dirname = &File::Basename::dirname($file);
356 $before_hash = &util::filename_cat($dirname, $before_hash);
357 $before_hash = $self->eval_dir_dots($before_hash);
358 }
359
360 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
361
362 # make sure there's a slash on the end if it's a directory
363 if ($before_hash !~ /\/$/) {
364 $before_hash .= "/" if (-d $linkfilename);
365 }
366
367 return ("http://" . $before_hash, $hash_part, 1);
368
369 } else {
370 # mailto, news, nntp, telnet, javascript or gopher link
371 return ($before_hash, "", 0);
372 }
373}
374
375sub extract_first_NNNN_characters {
376 my $self = shift (@_);
377 my ($textref, $doc_obj, $thissection) = @_;
378
379 foreach my $size (split /,/, $self->{'first'}) {
380 my $tmptext = $$textref;
381 $tmptext =~ s/.*<body[^>]*>//i;
382 $tmptext =~ s/$self->{'title_sub'}// if (defined $self->{'title_sub'});
383 $tmptext =~ s/<[^>]*>/ /g;
384 $tmptext =~ s/&nbsp;/ /g;
385 $tmptext =~ s/^\s+//;
386 $tmptext =~ s/\s+$//;
387 $tmptext =~ s/\s+/ /gs;
388 $tmptext = substr ($tmptext, 0, $size);
389 $tmptext =~ s/\s\S*$/&#8230;/;
390 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
391 }
392}
393
394sub extract_metadata {
395 my $self = shift (@_);
396 my ($textref, $metadata, $doc_obj, $section) = @_;
397 my $outhandle = $self->{'outhandle'};
398
399 # if we don't want metadata, we may as well not be here ...
400 return if (!defined $self->{'metadata_fields'});
401
402 # hunt for an author look in the metadata elements:
403 if (defined $self->{'hunt_creator_metadata'}) {
404 for my $name (split /,/, "AUTHOR,AUTHOR.EMAIL,CREATOR,DC.CREATOR,DC.CREATOR.CORPORATENAME") {
405 if ($$textref =~ /<meta(\s*?)(?:name|http-equiv)\s*=\s*\"?$name\"?([^>]*)/is) {
406 my $content = $1 . $2;
407 if ($content =~ /content\s*=\s*\"?(.*)\"?/is) {
408 if (defined $1) {
409 my $value = $1;
410 $value =~ s/\"$//;
411 $value =~ s/\s+/ /gs;
412 $doc_obj->add_utf8_metadata($section, "Creator", $value);
413 print $outhandle " extracted Creator metadata \"$value\"\n"
414 if ($self->{'verbosity'} > 2);
415 next;
416 }
417 }
418 }
419 }
420 }
421
422 foreach my $field (split /,/, $self->{'metadata_fields'}) {
423
424 # don't need to extract field if it was passed in from a previous
425 # (recursive) plugin
426 next if defined $metadata->{$field};
427
428 # see if there's a <meta> tag for this field
429 if ($$textref =~ /<meta(\s*?)(?:name|http-equiv)\s*=\s*\"?$field\"?([^>]*)/is) {
430 my $content = $1 . $2;
431 if ($content =~ /content\s*=\s*\"?(.*)\"?/is) {
432 if (defined $1) {
433 my $value = $1;
434 $value =~ s/\"$//;
435 $value =~ s/\s+/ /gs;
436 $value =~ s/\".*//gs;
437 $doc_obj->add_utf8_metadata($section, $field, $value);
438 print $outhandle " extracted \"$field\" metadata \"$value\"\n"
439 if ($self->{'verbosity'} > 2);
440 next;
441 }
442 }
443 }
444
445 # TITLE: extract the document title
446
447 if ($field =~ /^title$/i) {
448
449 # see if there's a <title> tag
450 if ($$textref =~ /<title[^>]*>([^<]*)<\/title[^>]*>/is) {
451 if (defined $1) {
452 my $title = $1;
453 if ($title =~ /\w/) {
454 $title =~ s/<[^>]*>/ /g;
455 $title =~ s/&nbsp;/ /g;
456 $title =~ s/\s+/ /gs;
457 $title =~ s/^\s+//;
458 $title =~ s/\s+$//;
459 $doc_obj->add_utf8_metadata ($section, $field, $title);
460 print $outhandle " extracted \"$field\" metadata \"$title\"\n"
461 if ($self->{'verbosity'} > 2);
462 next;
463 }
464 }
465 }
466
467 # if no title use first 100 characters
468 my $tmptext = $$textref;
469 $tmptext =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
470 $tmptext =~ s/<[^>]*>/ /g;
471 $tmptext =~ s/&nbsp;/ /g;
472 $tmptext =~ s/^\s+//s;
473 $tmptext =~ s/\s+$//;
474 $tmptext =~ s/\s+/ /gs;
475 $tmptext =~ s/$self->{'title_sub'}// if (defined $self->{'title_sub'});
476 $tmptext = substr ($tmptext, 0, 100);
477 $tmptext =~ s/\s\S*$/.../;
478 $doc_obj->add_utf8_metadata ($section, $field, $tmptext);
479 print $outhandle " extracted \"$field\" metadata \"$tmptext\"\n"
480 if ($self->{'verbosity'} > 2);
481 next;
482 }
483
484
485 # tag: extract the text between the first <H1> and </H1> tags
486 if ($field =~ /^tag[a-z0-9]+$/i) {
487
488 my $tag = $field;
489 $tag =~ s/^tag//i;
490 my $tmptext = $$textref;
491 $tmptext =~ s/\s+/ /gs;
492 if ($tmptext =~ /<$tag[^>]*>/i) {
493 foreach my $word ($tmptext =~ m/<$tag[^>]*>(.*?)<\/$tag[^>]*>/g) {
494 $word =~ s/&nbsp;/ /g;
495 $word =~ s/<[^>]*>/ /g;
496 $word =~ s/^\s+//;
497 $word =~ s/\s+$//;
498 $word =~ s/\s+/ /gs;
499 if ($word ne "") {
500 $doc_obj->add_utf8_metadata ($section, $tag, $word);
501 print $outhandle " extracted \"$tag\" metadata \"$word\"\n"
502 if ($self->{'verbosity'} > 2);
503 }
504 }
505 }
506 next;
507 }
508 }
509}
510
511
512# evaluate any "../" to next directory up
513# evaluate any "./" as here
514sub eval_dir_dots {
515 my $self = shift (@_);
516 my ($filename) = @_;
517
518 my $dirsep_os = &util::get_os_dirsep();
519 my @dirsep = split(/$dirsep_os/,$filename);
520
521 my @eval_dirs = ();
522 foreach my $d (@dirsep) {
523 if ($d eq "..") {
524 pop(@eval_dirs);
525
526 } elsif ($d eq ".") {
527 # do nothing!
528
529 } else {
530 push(@eval_dirs,$d);
531 }
532 }
533
534 return &util::filename_cat(@eval_dirs);
535}
536
537sub replace_usemap_links {
538 my $self = shift (@_);
539 my ($front, $link, $back) = @_;
540
541 $link =~ s/^\.\///;
542 return $front . $link . $back;
543}
544
545sub inc_filecount {
546 my $self = shift (@_);
547
548 if ($self->{'file_num'} == 1000) {
549 $self->{'dir_num'} ++;
550 $self->{'file_num'} = 0;
551 } else {
552 $self->{'file_num'} ++;
553 }
554}
555
556
557# Extend the BasPlug read_file so that strings like &eacute; are
558# converted to UTF8 internally.
559#
560# We don't convert &lt; or &gt; or &amp; or &quot; in case
561# they interfere with the GML files
562
563sub read_file {
564 my ($self, $filename, $encoding, $language, $textref) = @_;
565
566 &BasPlug::read_file($self, $filename, $encoding, $language, $textref);
567
568 # turn \ into \\ so that the rest of greenstone doesn't think there
569 # is an escape code following.
570 $$textref =~ s/\\/\\\\/go;
571
572 # Convert things like &eacute; to their UTF8 equivalents
573 $$textref =~ s/&(lt|gt|amp|quot);/&z$1;/go;
574 $$textref =~ s/&([^;]+);/&unicode::ascii2utf8(\&ghtml::getcharequiv($1,1))/gseo;
575 $$textref =~ s/&z(lt|gt|amp|quot);/&$1;/go;
576}
577
5781;
Note: See TracBrowser for help on using the repository browser.