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

Last change on this file since 12610 was 12269, checked in by kjdon, 18 years ago

fixed a typo in a comment

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