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

Last change on this file since 9057 was 9057, checked in by kjdon, 19 years ago

tidied up previous commit

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 29.6 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#
35
36package HTMLPlug;
37
38use BasPlug;
39use ghtml;
40use unicode;
41use util;
42use parsargv;
43use XMLParser;
44
45sub BEGIN {
46 @HTMLPlug::ISA = ('BasPlug');
47}
48
49use strict; # every perl program should have this!
50no strict 'refs'; # make an exception so we can use variables as filehandles
51
52my $arguments =
53 [ { 'name' => "process_exp",
54 'desc' => "{BasPlug.process_exp}",
55 'type' => "regexp",
56 'deft' => &get_default_process_exp() },
57 { 'name' => "block_exp",
58 'desc' => "{BasPlug.block_exp}",
59 'type' => 'regexp',
60 'deft' => &get_default_block_exp() },
61 { 'name' => "nolinks",
62 'desc' => "{HTMLPlug.nolinks}",
63 'type' => "flag" },
64 { 'name' => "keep_head",
65 'desc' => "{HTMLPlug.keep_head}",
66 'type' => "flag" },
67 { 'name' => "no_metadata",
68 'desc' => "{HTMLPlug.no_metadata}",
69 'type' => "flag" },
70 { 'name' => "metadata_fields",
71 'desc' => "{HTMLPlug.metadata_fields}",
72 'type' => "string",
73 'deft' => "Title" },
74 { 'name' => "hunt_creator_metadata",
75 'desc' => "{HTMLPlug.hunt_creator_metadata}",
76 'type' => "flag" },
77 { 'name' => "file_is_url",
78 'desc' => "{HTMLPlug.file_is_url}",
79 'type' => "flag" },
80 { 'name' => "assoc_files",
81 'desc' => "{HTMLPlug.assoc_files}",
82 'type' => "regexp",
83 'deft' => &get_default_block_exp() },
84 { 'name' => "rename_assoc_files",
85 'desc' => "{HTMLPlug.rename_assoc_files}",
86 'type' => "flag" },
87 { 'name' => "title_sub",
88 'desc' => "{HTMLPlug.title_sub}",
89 'type' => "string",
90 'deft' => "" },
91 { 'name' => "description_tags",
92 'desc' => "{HTMLPlug.description_tags}",
93 'type' => "flag" } ,
94 { 'name' => "no_strip_metadata_html",
95 'desc' => "{HTMLPlug.no_strip_metadata_html}",
96 'type' => "string",
97 'deft' => "",
98 'reqd' => "no"}
99 ];
100
101my $options = { 'name' => "HTMLPlug",
102 'desc' => "{HTMLPlug.desc}",
103 'abstract' => "no",
104 'inherits' => "yes",
105 'args' => $arguments };
106
107sub new {
108 my $class = shift (@_);
109 my $self = new BasPlug ($class, @_);
110 $self->{'plugin_type'} = "HTMLPlug";
111 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
112 my $option_list = $self->{'option_list'};
113 push( @{$option_list}, $options );
114
115 if (!parsargv::parse(\@_,
116 q^nolinks^, \$self->{'nolinks'},
117 q^keep_head^, \$self->{'keep_head'},
118 q^no_metadata^, \$self->{'no_metadata'},
119 q^metadata_fields/.*/Title^, \$self->{'metadata_fields'},
120 q^hunt_creator_metadata^, \$self->{'hunt_creator_metadata'},
121 q^w3mir^, \$self->{'w3mir'},
122 q^file_is_url^, \$self->{'file_is_url'},
123 q^assoc_files/.*/(?i)\.(jpe?g|jpe|gif|png|css)$^, \$self->{'assoc_files'},
124 q^rename_assoc_files^, \$self->{'rename_assoc_files'},
125 q^title_sub/.*/^, \$self->{'title_sub'},
126 q^description_tags^, \$self->{'description_tags'},
127 q^no_strip_metadata_html/.*/^, \$self->{'no_strip_metadata_html'},
128 "allow_extra_options")) {
129
130 print STDERR "\nIncorrect options passed to HTMLPlug, check your collect.cfg configuration file\n";
131 $self->print_txt_usage(""); # Use default resource bundle
132 die "\n";
133 }
134
135 # retain this for backward compatibility (w3mir option was replaced by
136 # file_is_url)
137 if ($self->{'w3mir'}) {
138 $self->{'file_is_url'} = 1;
139 }
140
141 $self->{'aux_files'} = {};
142 $self->{'dir_num'} = 0;
143 $self->{'file_num'} = 0;
144
145 return bless $self, $class;
146}
147
148# may want to use (?i)\.(gif|jpe?g|jpe|png|css|js(?:@.*)?)$
149# if have eg <script language="javascript" src="img/lib.js@123">
150sub get_default_block_exp {
151 my $self = shift (@_);
152
153 return q^(?i)\.(gif|jpe?g|jpe|jpg|png|css)$^;
154}
155
156sub get_default_process_exp {
157 my $self = shift (@_);
158
159 # the last option is an attempt to encode the concept of an html query ...
160 return q^(?i)(\.html?|\.shtml|\.shm|\.asp|\.php\d?|\.cgi|.+\?.+=.*)$^;
161}
162
163
164sub metadata_read {
165 my $self = shift (@_);
166 my ($pluginfo, $base_dir, $file, $metadata, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
167
168 my $outhandle = $self->{'outhandle'};
169
170 my $filename = $file;
171 $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
172
173 my ($dir) = $filename =~ /^(.*?)[^\/\\]*$/;
174
175 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
176 return undef; # can't recognise
177 }
178
179 if ($self->{'smart_block'}) {
180 # Do encoding stuff
181 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename);
182
183 # read in file ($text will be in utf8)
184 my $text = "";
185 $self->read_file ($filename, $encoding, $language, \$text);
186 $self->store_block_files (\$text, $filename);
187 }
188 return 1;
189}
190
191sub store_block_files
192{
193 my $self =shift (@_);
194 my ($textref, $filename) = @_;
195
196 my $html_fname = $filename;
197 my @file_blocks;
198
199 my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
200 my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
201 $$textref =~ s/$opencom(.*?)$closecom//gs;
202
203 my $attval = "\\\"[^\\\"]+\\\"|[^\\s>]+";
204 my @img_matches = ($$textref =~ m/<img[^>]*?src\s*=\s*($attval)[^>]*>/igs);
205 my @usemap_matches = ($$textref =~ m/<img[^>]*?usemap\s*=\s*($attval)[^>]*>/igs);
206 my @link_matches = ($$textref =~ m/<link[^>]*?href\s*=\s*($attval)[^>]*>/igs);
207
208
209 foreach my $link (@img_matches, @usemap_matches, @link_matches) {
210
211 # remove quotes from link at start and end if necessary
212 if ($link=~/^\"/) {
213 $link=~s/^\"//;
214 $link=~s/\"$//;
215 }
216
217 $link =~ s/\#.*$//s; # remove any anchor names, e.g. foo.html#name becomes foo.html
218
219 if ($link !~ s@^/@@ && $link !~ /^([A-Z]:?)\\/) {
220 # Turn relative file path into full path
221 my $dirname = &File::Basename::dirname($filename);
222 $link = &util::filename_cat($dirname, $link);
223 }
224 $link = $self->eval_dir_dots($link);
225 $self->{'file_blocks'}->{$link} = 1;
226 }
227}
228
229# do plugin specific processing of doc_obj
230sub process {
231 my $self = shift (@_);
232 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
233 my $outhandle = $self->{'outhandle'};
234
235 print STDERR "<Processing n='$file' p='HTMLPlug'>\n" if ($gli);
236
237 print $outhandle "HTMLPlug: processing $file\n"
238 if $self->{'verbosity'} > 1;
239
240 if ($ENV{'GSDLOS'} =~ /^windows/i) {
241 # this makes life so much easier... perl can cope with unix-style '/'s.
242 $base_dir =~ s@(\\)+@/@g;
243 $file =~ s@(\\)+@/@g;
244 }
245
246 # reset per-doc stuff...
247 $self->{'aux_files'} = {};
248 $self->{'dir_num'} = 0;
249 $self->{'file_num'} = 0;
250
251 my $cursection = $doc_obj->get_top_section();
252
253 $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection)
254 unless $self->{'no_metadata'} || $self->{'description_tags'};
255
256 # Store URL for page as metadata - this can be used for an
257 # altavista style search interface. The URL won't be valid
258 # unless the file structure contains the domain name (i.e.
259 # like when w3mir is used to download a website).
260 my $web_url = "http://$file";
261 $doc_obj->add_metadata($cursection, "URL", $web_url);
262
263 if ($self->{'description_tags'}) {
264 # remove the html header - note that doing this here means any
265 # sections defined within the header will be lost (so all <Section>
266 # tags must appear within the body of the HTML)
267 my ($head_keep) = ($$textref =~ m/^(.*?)<body[^>]*>/is);
268
269 $$textref =~ s/^.*?<body[^>]*>//is;
270 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
271
272 my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
273 my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
274
275 my $lt = '(?:<|&lt;)';
276 my $gt = '(?:>|&gt;)';
277 my $quot = '(?:"|&quot;|&rdquo;|&ldquo;)';
278
279 my $dont_strip = '';
280 if ($self->{'no_strip_metadata_html'}) {
281 ($dont_strip = $self->{'no_strip_metadata_html'}) =~ s{,}{|}g;
282 }
283
284 my $found_something = 0; my $top = 1;
285 while ($$textref =~ s/^(.*?)$opencom(.*?)$closecom//s) {
286 my $text = $1;
287 my $comment = $2;
288 if (defined $text) {
289 # text before a comment - note that getting to here
290 # doesn't necessarily mean there are Section tags in
291 # the document
292 $self->process_section(\$text, $base_dir, $file, $doc_obj, $cursection);
293 }
294 while ($comment =~ s/$lt(.*?)$gt//s) {
295 my $tag = $1;
296 if ($tag eq "Section") {
297 $found_something = 1;
298 $cursection = $doc_obj->insert_section($doc_obj->get_end_child($cursection)) unless $top;
299 $top = 0;
300 } elsif ($tag eq "/Section") {
301 $found_something = 1;
302 $cursection = $doc_obj->get_parent_section ($cursection);
303 } elsif ($tag =~ /^Metadata name=$quot(.*?)$quot/s) {
304 my $metaname = $1;
305 my $accumulate = $tag =~ /mode=${quot}accumulate${quot}/ ? 1 : 0;
306 $comment =~ s/^(.*?)$lt\/Metadata$gt//s;
307 my $metavalue = $1;
308 $metavalue =~ s/^\s+//;
309 $metavalue =~ s/\s+$//;
310 # assume that no metadata value intentionally includes
311 # carriage returns or HTML tags (if they're there they
312 # were probably introduced when converting to HTML from
313 # some other format).
314 # actually some people want to have html tags in their
315 # metadata.
316 $metavalue =~ s/[\cJ\cM]/ /sg;
317 $metavalue =~ s/<[^>]+>//sg
318 unless $dont_strip && ($dont_strip eq 'all' || $metaname =~ /^($dont_strip)$/);
319 $metavalue =~ s/\s+/ /sg;
320 if ($accumulate) {
321 $doc_obj->add_utf8_metadata($cursection, $metaname, $metavalue);
322 } else {
323 $doc_obj->set_utf8_metadata_element($cursection, $metaname, $metavalue);
324 }
325 } elsif ($tag eq "Description" || $tag eq "/Description") {
326 # do nothing with containing Description tags
327 } else {
328 # simple HTML tag (probably created by the conversion
329 # to HTML from some other format) - we'll ignore it and
330 # hope for the best ;-)
331 }
332 }
333 }
334 if ($cursection ne "") {
335 print $outhandle "HTMLPlug: WARNING: $file contains unmatched <Section></Section> tags\n";
336 }
337
338 $$textref =~ s/^.*?<body[^>]*>//is;
339 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
340 if ($$textref =~ /\S/) {
341 if (!$found_something) {
342 if ($self->{'verbosity'} > 2) {
343 print $outhandle "HTMLPlug: WARNING: $file appears to contain no Section tags so\n";
344 print $outhandle " will be processed as a single section document\n";
345 }
346
347 # go ahead and process single-section document
348 $self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
349
350 # if document contains no Section tags we'll go ahead
351 # and extract metadata (this won't have been done
352 # above as the -description_tags option prevents it)
353 my $complete_text = $head_keep.$doc_obj->get_text($cursection);
354 $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection)
355 unless $self->{'no_metadata'};
356
357 } else {
358 print $outhandle "HTMLPlug: WARNING: $file contains the following text outside\n";
359 print $outhandle " of the final closing </Section> tag. This text will\n";
360 print $outhandle " be ignored.";
361
362 my ($text);
363 if (length($$textref) > 30) {
364 $text = substr($$textref, 0, 30) . "...";
365 } else {
366 $text = $$textref;
367 }
368 $text =~ s/\n/ /isg;
369 print $outhandle " ($text)\n";
370 }
371 } elsif (!$found_something) {
372
373 if ($self->{'verbosity'} > 2) {
374 # may get to here if document contained no valid Section
375 # tags but did contain some comments. The text will have
376 # been processed already but we should print the warning
377 # as above and extract metadata
378 print $outhandle "HTMLPlug: WARNING: $file appears to contain no Section tags and\n";
379 print $outhandle " is blank or empty. Metadata will be assigned if present.\n";
380 }
381
382 my $complete_text = $head_keep.$doc_obj->get_text($cursection);
383 $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection)
384 unless $self->{'no_metadata'};
385 }
386
387 } else {
388
389 # remove header and footer
390 if (!$self->{'keep_head'} || $self->{'description_tags'}) {
391 $$textref =~ s/^.*?<body[^>]*>//is;
392 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
393 }
394
395 # single section document
396 $self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
397 }
398 return 1;
399}
400
401# note that process_section may be called multiple times for a single
402# section (relying on the fact that add_utf8_text appends the text to any
403# that may exist already).
404sub process_section {
405 my $self = shift (@_);
406 my ($textref, $base_dir, $file, $doc_obj, $cursection) = @_;
407 # trap links
408 if (!$self->{'nolinks'}) {
409
410 # usemap="./#index" not handled correctly => change to "#index"
411 $$textref =~ s/(<img[^>]*?usemap\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
412 $self->replace_usemap_links($1, $2, $3)/isge;
413
414 $$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*\"?)([^\">\s]+)(\"?[^>]*>)/
415 $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
416 }
417
418 # trap images
419
420 # allow spaces if inside quotes - jrm21
421 $$textref =~ s/(<img[^>]*?src\s*=\s*)(\"[^\"]+\"|[^\s>]+)([^>]*>)/
422 $self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
423
424 # add text to document object
425 # turn \ into \\ so that the rest of greenstone doesn't think there
426 # is an escape code following. (Macro parsing loses them...)
427 $$textref =~ s/\\/\\\\/go;
428 $doc_obj->add_utf8_text($cursection, $$textref);
429}
430
431sub replace_images {
432 my $self = shift (@_);
433 my ($front, $link, $back, $base_dir,
434 $file, $doc_obj, $section) = @_;
435
436 # remove quotes from link at start and end if necessary
437 if ($link=~/^\"/) {
438 $link=~s/^\"//;$link=~s/\"$//;
439 $front.='"';
440 $back="\"$back";
441 }
442
443 $link =~ s/\n/ /g;
444
445 # Hack to overcome Windows wv 0.7.1 bug that causes embedded images to be broken
446 # If the Word file path has spaces in it, wv messes up and you end up with
447 # absolute paths for the images, and without the "file://" prefix
448 # So check for this special case and massage the data to be correct
449 if ($ENV{'GSDLOS'} =~ /^windows/i && $self->{'plugin_type'} eq "WordPlug" && $link =~ /^[A-Za-z]\:\\/) {
450 $link =~ s/^.*\\([^\\]+)$/$1/;
451 }
452
453 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
454
455 my $img_file = $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section);
456 my $anchor_name = $img_file;
457 $anchor_name =~ s/^.*\///;
458 $anchor_name = "<a name=\"$anchor_name\">";
459
460 return $front . $img_file . $back . $anchor_name;
461}
462
463sub replace_href_links {
464 my $self = shift (@_);
465 my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;
466
467 # attempt to sort out targets - frames are not handled
468 # well in this plugin and some cases will screw things
469 # up - e.g. the _parent target (so we'll just remove
470 # them all ;-)
471 $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
472 $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
473 $front =~ s/target=\"?_parent\"?//is;
474 $back =~ s/target=\"?_parent\"?//is;
475
476 return $front . $link . $back if $link =~ /^\#/s;
477 $link =~ s/\n/ /g;
478
479 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
480 # href may use '\'s where '/'s should be on Windows
481 $href =~ s/\\/\//g;
482
483 my ($filename) = $href =~ /^(?:.*?):(?:\/\/)?(.*)/;
484
485
486 ##### leave all these links alone (they won't be picked up by intermediate
487 ##### pages). I think that's safest when dealing with frames, targets etc.
488 ##### (at least until I think of a better way to do it). Problems occur with
489 ##### mailto links from within small frames, the intermediate page is displayed
490 ##### within that frame and can't be seen. There is still potential for this to
491 ##### happen even with html pages - the solution seems to be to somehow tell
492 ##### the browser from the server side to display the page being sent (i.e.
493 ##### the intermediate page) in the top level window - I'm not sure if that's
494 ##### possible - the following line should probably be deleted if that can be done
495 return $front . $link . $back if $href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/is;
496
497
498 if (($rl == 0) || ($filename =~ /$self->{'process_exp'}/) ||
499 ($href =~ /\/$/) || ($href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
500 &ghtml::urlsafe ($href);
501 return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
502 } else {
503 # link is to some other type of file (eg image) so we'll
504 # need to associate that file
505 return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
506 }
507}
508
509sub add_file {
510 my $self = shift (@_);
511 my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
512 my ($newname);
513
514 my $filename = $href;
515 $filename =~ s/^[^:]*:\/\///;
516 $filename = &util::filename_cat($base_dir, $filename);
517
518 # Replace %20's in URL with a space if required. Note that the filename
519 # may include the %20 in some situations
520 if ($filename =~ /\%20/) {
521 if (!-e $filename) {
522 $filename =~ s/\%20/ /g;
523 }
524 }
525
526 my ($ext) = $filename =~ /(\.[^\.]*)$/;
527
528 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
529 return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
530 }
531 if ($self->{'rename_assoc_files'}) {
532 if (defined $self->{'aux_files'}->{$href}) {
533 $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
534 $self->{'aux_files'}->{$href}->{'file_num'} . $ext;
535 } else {
536 $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
537 $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
538 $self->inc_filecount ();
539 }
540 $doc_obj->associate_file($filename, $newname, undef, $section);
541 return "_httpdocimg_/$newname";
542 } else {
543 ($newname) = $filename =~ /([^\/\\]*)$/;
544 $doc_obj->associate_file($filename, $newname, undef, $section);
545 return "_httpdocimg_/$newname";
546 }
547}
548
549
550sub format_link {
551 my $self = shift (@_);
552 my ($link, $base_dir, $file) = @_;
553
554 my ($before_hash, $hash_part) = $link =~ /^([^\#]*)(\#?.*)$/;
555
556 $hash_part = "" if !defined $hash_part;
557 if (!defined $before_hash || $before_hash !~ /[\w\.\/]/) {
558 my $outhandle = $self->{'outhandle'};
559 print $outhandle "HTMLPlug: ERROR - badly formatted tag ignored ($link)\n"
560 if $self->{'verbosity'};
561 return ($link, "", 0);
562 }
563
564 if ($before_hash =~ s@^((?:http|ftp|file)://)@@i) {
565 my $type = $1;
566
567 if ($link =~ /^(http|ftp):/i) {
568 # Turn url (using /) into file name (possibly using \ on windows)
569 my @http_dir_split = split('/', $before_hash);
570 $before_hash = &util::filename_cat(@http_dir_split);
571 }
572
573 $before_hash = $self->eval_dir_dots($before_hash);
574
575 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
576
577 my $rl = 0;
578 $rl = 1 if (-e $linkfilename);
579
580 # make sure there's a slash on the end if it's a directory
581 if ($before_hash !~ /\/$/) {
582 $before_hash .= "/" if (-d $linkfilename);
583 }
584
585 return ($type . $before_hash, $hash_part, $rl);
586
587 } elsif ($link !~ /^(mailto|news|gopher|nntp|telnet|javascript):/i) {
588 if ($before_hash =~ s@^/@@ || $before_hash =~ /\\/) {
589
590 # the first directory will be the domain name if file_is_url
591 # to generate archives, otherwise we'll assume all files are
592 # from the same site and base_dir is the root
593
594 if ($self->{'file_is_url'}) {
595 my @dirs = split /[\/\\]/, $file;
596 my $domname = shift (@dirs);
597 $before_hash = &util::filename_cat($domname, $before_hash);
598 $before_hash =~ s@\\@/@g; # for windows
599 }
600 else
601 {
602 # see if link shares directory with source document
603 # => turn into relative link if this is so!
604
605 if ($ENV{'GSDLOS'} =~ /^windows/i) {
606 # too difficult doing a pattern match with embedded '\'s...
607 my $win_before_hash=$before_hash;
608 $win_before_hash =~ s@(\\)+@/@g;
609 # $base_dir is already similarly "converted" on windows.
610 if ($win_before_hash =~ s@^$base_dir/@@o) {
611 # if this is true, we removed a prefix
612 $before_hash=$win_before_hash;
613 }
614 }
615 else {
616 $before_hash = &util::filename_cat("",$before_hash);
617 $before_hash =~ s@^$base_dir/@@;
618 }
619 }
620 } else {
621 # Turn relative file path into full path
622 my $dirname = &File::Basename::dirname($file);
623 $before_hash = &util::filename_cat($dirname, $before_hash);
624 $before_hash = $self->eval_dir_dots($before_hash);
625 }
626
627 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
628 # make sure there's a slash on the end if it's a directory
629 if ($before_hash !~ /\/$/) {
630 $before_hash .= "/" if (-d $linkfilename);
631 }
632 return ("http://" . $before_hash, $hash_part, 1);
633 } else {
634 # mailto, news, nntp, telnet, javascript or gopher link
635 return ($before_hash, "", 0);
636 }
637}
638
639sub extract_first_NNNN_characters {
640 my $self = shift (@_);
641 my ($textref, $doc_obj, $thissection) = @_;
642
643 foreach my $size (split /,/, $self->{'first'}) {
644 my $tmptext = $$textref;
645 # skip to the body
646 $tmptext =~ s/.*<body[^>]*>//i;
647 # remove javascript
648 $tmptext =~ s@<script.*?</script>@ @sig;
649 $tmptext =~ s/<[^>]*>/ /g;
650 $tmptext =~ s/&nbsp;/ /g;
651 $tmptext =~ s/^\s+//;
652 $tmptext =~ s/\s+$//;
653 $tmptext =~ s/\s+/ /gs;
654 # with perl 5.6 at least, substr might segment at a multi-byte char...
655 use utf8;
656 $tmptext = substr ($tmptext, 0, $size);
657 $tmptext =~ s/\s\S*$/&#8230;/; # adds an ellipse (...)
658 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
659 }
660}
661
662
663sub extract_metadata {
664 my $self = shift (@_);
665 my ($textref, $metadata, $doc_obj, $section) = @_;
666 my $outhandle = $self->{'outhandle'};
667 # if we don't want metadata, we may as well not be here ...
668 return if (!defined $self->{'metadata_fields'});
669
670 # metadata fields to extract/save. 'key' is the (lowercase) name of the
671 # html meta, 'value' is the metadata name for greenstone to use
672 my %find_fields = ();
673
674 my %creator_fields = (); # short-cut for lookups
675
676
677 foreach my $field (split /,/, $self->{'metadata_fields'}) {
678 # support tag<tagname>
679 if ($field =~ /^(.*?)<(.*?)>$/) {
680 # "$2" is the user's preferred gs metadata name
681 $find_fields{lc($1)}=$2; # lc = lowercase
682 } else { # no <tagname> for mapping
683 # "$field" is the user's preferred gs metadata name
684 $find_fields{lc($field)}=$field; # lc = lowercase
685 }
686 }
687
688 if (defined $self->{'hunt_creator_metadata'} &&
689 $self->{'hunt_creator_metadata'} == 1 ) {
690 my @extra_fields =
691 (
692 'author',
693 'author.email',
694 'creator',
695 'dc.creator',
696 'dc.creator.corporatename',
697 );
698
699 # add the creator_metadata fields to search for
700 foreach my $field (@extra_fields) {
701 $creator_fields{$field}=0; # add to lookup hash
702 }
703 }
704
705
706 # find the header in the html file, which has the meta tags
707 $$textref =~ m@<head>(.*?)</head>@si;
708
709 my $html_header=$1;
710 # go through every <meta... tag defined in the html and see if it is
711 # one of the tags we want to match.
712
713 # special case for title - we want to remember if its been found
714 my $found_title = 0;
715 # this assumes that ">" won't appear. (I don't think it's allowed to...)
716 $html_header =~ /^/; # match the start of the string, for \G assertion
717
718 while ($html_header =~ m/\G.*?<meta(.*?)>/sig) {
719 my $metatag=$1;
720 my ($tag, $value);
721
722 # find the tag name
723 $metatag =~ /(?:name|http-equiv)\s*=\s*([\"\'])?(.*?)\1/is;
724 $tag=$2;
725 # in case they're not using " or ', but they should...
726 if (! $tag) {
727 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
728 $tag=$1;
729 }
730
731 if (!defined $tag) {
732 print $outhandle "HTMLPlug: can't find NAME in \"$metatag\"\n";
733 next;
734 }
735
736 # don't need to assign this field if it was passed in from a previous
737 # (recursive) plugin
738 if (defined $metadata->{$tag}) {next}
739
740 # find the tag content
741 $metatag =~ /content\s*=\s*([\"\'])?(.*?)\1/is;
742 $value=$2;
743 if (! $value) {
744 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
745 $value=$1;
746 }
747 if (!defined $value) {
748 print $outhandle "HTMLPlug: can't find VALUE in \"$metatag\"\n";
749 next;
750 }
751
752 # clean up and add
753 $value =~ s/\s+/ /gs;
754 chomp($value); # remove trailing \n, if any
755 if (exists $creator_fields{lc($tag)}) {
756 # map this value onto greenstone's "Creator" metadata
757 $tag='Creator';
758 } elsif (!exists $find_fields{lc($tag)}) {
759 next; # don't want this tag
760 } else {
761 # get the user's preferred capitalisation
762 $tag = $find_fields{lc($tag)};
763 }
764 if (lc($tag) eq "title") {
765 $found_title = 1;
766 }
767 print $outhandle " extracted \"$tag\" metadata \"$value\"\n"
768 if ($self->{'verbosity'} > 2);
769 $doc_obj->add_utf8_metadata($section, $tag, $value);
770
771 }
772
773 # TITLE: extract the document title
774 if (exists $find_fields{'title'} && !$found_title) {
775 # we want a title, and didn't find one in the meta tags
776 # see if there's a <title> tag
777 my $title;
778 my $from = ""; # for debugging output only
779 if ($html_header =~ /<title[^>]*>([^<]+)<\/title[^>]*>/is) {
780 $title = $1;
781 $from = "<title> tags";
782 }
783
784 if (!defined $title) {
785 $from = "first 100 chars";
786 # if no title use first 100 or so characters
787 $title = $$textref;
788 $title =~ s/^\xFE\xFF//; # Remove unicode byte order mark
789 $title =~ s/^.*?<body>//si;
790 # ignore javascript!
791 $title =~ s@<script.*?</script>@ @sig;
792 $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
793 $title =~ s/<[^>]*>/ /g; # remove all HTML tags
794 $title = substr ($title, 0, 100);
795 $title =~ s/\s\S*$/.../;
796 }
797 $title =~ s/<[^>]*>/ /g; # remove html tags
798 $title =~ s/&nbsp;/ /g;
799 $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
800 $title =~ s/\s+/ /gs; # collapse multiple spaces
801 $title =~ s/^\s*//; # remove leading spaces
802 $title =~ s/\s*$//; # remove trailing spaces
803
804 $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
805 $title =~ s/^\s+//s; # in case title_sub introduced any...
806 $doc_obj->add_utf8_metadata ($section, 'Title', $title);
807 print $outhandle " extracted Title metadata \"$title\" from $from\n"
808 if ($self->{'verbosity'} > 2);
809 }
810
811 # add FileFormat metadata
812 $doc_obj->add_metadata($section,"FileFormat", "HTML");
813
814 # Special, for metadata names such as tagH1 - extracts
815 # the text between the first <H1> and </H1> tags into "H1" metadata.
816
817 foreach my $field (keys %find_fields) {
818 if ($field !~ /^tag([a-z0-9]+)$/i) {next}
819 my $tag = $1;
820 if ($$textref =~ m@<$tag[^>]*>(.*?)</$tag[^>]*>@g) {
821 my $content = $1;
822 $content =~ s/&nbsp;/ /g;
823 $content =~ s/<[^>]*>/ /g;
824 $content =~ s/^\s+//;
825 $content =~ s/\s+$//;
826 $content =~ s/\s+/ /gs;
827 if ($content) {
828 $tag=$find_fields{"tag$tag"}; # get the user's capitalisation
829 $tag =~ s/^tag//i;
830 $doc_obj->add_utf8_metadata ($section, $tag, $content);
831 print $outhandle " extracted \"$tag\" metadata \"$content\"\n"
832 if ($self->{'verbosity'} > 2);
833 }
834 }
835 }
836}
837
838
839# evaluate any "../" to next directory up
840# evaluate any "./" as here
841sub eval_dir_dots {
842 my $self = shift (@_);
843 my ($filename) = @_;
844 my $dirsep_os = &util::get_os_dirsep();
845 my @dirsep = split(/$dirsep_os/,$filename);
846
847 my @eval_dirs = ();
848 foreach my $d (@dirsep) {
849 if ($d eq "..") {
850 pop(@eval_dirs);
851
852 } elsif ($d eq ".") {
853 # do nothing!
854
855 } else {
856 push(@eval_dirs,$d);
857 }
858 }
859
860 # Need to fiddle with number of elements in @eval_dirs if the
861 # first one is the empty string. This is because of a
862 # modification to util::filename_cat that supresses the addition
863 # of a leading '/' character (or \ if windows) (intended to help
864 # filename cat with relative paths) if the first entry in the
865 # array is the empty string. Making the array start with *two*
866 # empty strings is a way to defeat this "smart" option.
867 #
868 if (scalar(@eval_dirs) > 0) {
869 if ($eval_dirs[0] eq ""){
870 unshift(@eval_dirs,"");
871 }
872 }
873 return &util::filename_cat(@eval_dirs);
874}
875
876sub replace_usemap_links {
877 my $self = shift (@_);
878 my ($front, $link, $back) = @_;
879
880 $link =~ s/^\.\///;
881 return $front . $link . $back;
882}
883
884sub inc_filecount {
885 my $self = shift (@_);
886
887 if ($self->{'file_num'} == 1000) {
888 $self->{'dir_num'} ++;
889 $self->{'file_num'} = 0;
890 } else {
891 $self->{'file_num'} ++;
892 }
893}
894
895
896# Extend the BasPlug read_file so that strings like &eacute; are
897# converted to UTF8 internally.
898#
899# We don't convert &lt; or &gt; or &amp; or &quot; in case
900# they interfere with the GML files
901
902sub read_file {
903 my ($self, $filename, $encoding, $language, $textref) = @_;
904
905 &BasPlug::read_file($self, $filename, $encoding, $language, $textref);
906
907 # Convert entities to their UTF8 equivalents
908 $$textref =~ s/&(lt|gt|amp|quot|nbsp);/&z$1;/go;
909 $$textref =~ s/&([^;]+);/&ghtml::getcharequiv($1,1)/gseo;
910 $$textref =~ s/&z(lt|gt|amp|quot|nbsp);/&$1;/go;
911}
912
9131;
Note: See TracBrowser for help on using the repository browser.