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

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

Jeffrey's new parsing modifications, committed approx 6 July, 15.16

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