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

Last change on this file since 12947 was 12947, checked in by kjdon, 16 years ago

added new -extract_style option to HTMLPlug. looks for style, script and link tags in the html head tag, and saves them as ex.DocumentHeader metadata. -metadata_fields can now be used with -description_tags - why shouldn't we have metadata in the header as well as in the description tags?? can always turn head metadata off using -no_metadata. -hunt_creator_metadata no longer needs -metadata_fields option to be set.

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