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

Last change on this file since 9706 was 9228, checked in by davidb, 19 years ago

Changed setting URL metadata back to always being done (regardless of
whether -file_is_url is set or not. This is because URL metadata is used
elsewhere in runtime Greenstone to resolve internal links. Setting
"weblink" and "webicon" are still only done if -file_is_url is true.

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