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

Last change on this file since 10121 was 10121, checked in by mdewsnip, 19 years ago

Added the "sectionalise_using_h_tags" option to HTMLPlug, which automatically creates a sectioned document based on h1, h2, ... hX tags. Many thanks to Emanuel Dejanu for this code.

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