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

Last change on this file since 12883 was 12883, checked in by mdewsnip, 18 years ago

Removed a pointless comparison.

  • 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 # remove header and footer
389 if (!$self->{'keep_head'}) {
390 $$textref =~ s/^.*?<body[^>]*>//is;
391 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
392 }
393
394 # single section document
395 $self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
396 }
397 return 1;
398}
399
400
401sub process_heading
402{
403 my ($self, $nHeadNo, $strHeadingText, $arrSections, $file) = @_;
404 $strHeadingText = '' if (!defined($strHeadingText));
405
406 my $strMetadata = $self->update_section_data($arrSections, int($nHeadNo));
407
408 my $strSecMetadata = '';
409 while ($strHeadingText =~ s/<!--gsdl-metadata(.*?)-->//is)
410 {
411 $strSecMetadata .= $1;
412 }
413
414 $strHeadingText =~ s/^\s+//g;
415 $strHeadingText =~ s/\s+$//g;
416 $strSecMetadata =~ s/^\s+//g;
417 $strSecMetadata =~ s/\s+$//g;
418
419 $strMetadata .= "\n<Section>\n\t<Description>\n\t\t<Metadata name=\"Title\">" . $strHeadingText . "</Metadata>\n";
420
421 if (length($strSecMetadata)) {
422 $strMetadata .= "\t\t" . $strSecMetadata . "\n";
423 }
424
425 $strMetadata .= "\t</Description>\n";
426
427 return "<!--" . $strMetadata . "-->";
428}
429
430
431sub update_section_data
432{
433 my ($self, $arrSections, $nCurTocNo) = @_;
434 my ($strBuffer, $nLast, $nSections) = ('', 0, scalar(@$arrSections));
435
436 if ($nSections == 0) {
437 push @$arrSections, $nCurTocNo;
438 return $strBuffer;
439 }
440 $nLast = $arrSections->[$nSections - 1];
441 if ($nCurTocNo > $nLast) {
442 push @$arrSections, $nCurTocNo;
443 return $strBuffer;
444 }
445 for(my $i = $nSections - 1; $i >= 0; $i--) {
446 if ($nCurTocNo <= $arrSections->[$i]) {
447 $strBuffer .= "\n</Section>";
448 pop @$arrSections;
449 }
450 }
451 push @$arrSections, $nCurTocNo;
452 return $strBuffer;
453}
454
455
456# note that process_section may be called multiple times for a single
457# section (relying on the fact that add_utf8_text appends the text to any
458# that may exist already).
459sub process_section {
460 my $self = shift (@_);
461 my ($textref, $base_dir, $file, $doc_obj, $cursection) = @_;
462 # trap links
463 if (!$self->{'nolinks'}) {
464
465 # usemap="./#index" not handled correctly => change to "#index"
466 $$textref =~ s/(<img[^>]*?usemap\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/
467 $self->replace_usemap_links($1, $2, $3)/isge;
468
469 $$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/
470 $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
471 }
472
473 # trap images
474
475 # allow spaces if inside quotes - jrm21
476 $$textref =~ s/(<(?:img|embed|table|tr|td)[^>]*?(?:src|background)\s*=\s*)([\"\'][^\"\']+[\"\']|[^\s>]+)([^>]*>)/
477 $self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
478
479 # add text to document object
480 # turn \ into \\ so that the rest of greenstone doesn't think there
481 # is an escape code following. (Macro parsing loses them...)
482 $$textref =~ s/\\/\\\\/go;
483
484 $doc_obj->add_utf8_text($cursection, $$textref);
485}
486
487sub replace_images {
488 my $self = shift (@_);
489 my ($front, $link, $back, $base_dir,
490 $file, $doc_obj, $section) = @_;
491
492 # remove quotes from link at start and end if necessary
493 if ($link=~/^[\"\']/) {
494 $link=~s/^[\"\']//;$link=~s/[\"\']$//;
495 $front.='"';
496 $back="\"$back";
497 }
498
499 $link =~ s/\n/ /g;
500
501 # Hack to overcome Windows wv 0.7.1 bug that causes embedded images to be broken
502 # If the Word file path has spaces in it, wv messes up and you end up with
503 # absolute paths for the images, and without the "file://" prefix
504 # So check for this special case and massage the data to be correct
505 if ($ENV{'GSDLOS'} =~ /^windows/i && $self->{'plugin_type'} eq "WordPlug" && $link =~ /^[A-Za-z]\:\\/) {
506 $link =~ s/^.*\\([^\\]+)$/$1/;
507 }
508
509 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
510
511 my $img_file = $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section);
512
513 my $anchor_name = $img_file;
514 $anchor_name =~ s/^.*\///;
515 $anchor_name = "<a name=\"$anchor_name\">";
516
517 return $front . $img_file . $back . $anchor_name;
518}
519
520sub replace_href_links {
521 my $self = shift (@_);
522 my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;
523
524 # attempt to sort out targets - frames are not handled
525 # well in this plugin and some cases will screw things
526 # up - e.g. the _parent target (so we'll just remove
527 # them all ;-)
528 $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
529 $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
530 $front =~ s/target=\"?_parent\"?//is;
531 $back =~ s/target=\"?_parent\"?//is;
532
533 return $front . $link . $back if $link =~ /^\#/s;
534 $link =~ s/\n/ /g;
535
536 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
537 # href may use '\'s where '/'s should be on Windows
538 $href =~ s/\\/\//g;
539
540 my ($filename) = $href =~ /^(?:.*?):(?:\/\/)?(.*)/;
541
542
543 ##### leave all these links alone (they won't be picked up by intermediate
544 ##### pages). I think that's safest when dealing with frames, targets etc.
545 ##### (at least until I think of a better way to do it). Problems occur with
546 ##### mailto links from within small frames, the intermediate page is displayed
547 ##### within that frame and can't be seen. There is still potential for this to
548 ##### happen even with html pages - the solution seems to be to somehow tell
549 ##### the browser from the server side to display the page being sent (i.e.
550 ##### the intermediate page) in the top level window - I'm not sure if that's
551 ##### possible - the following line should probably be deleted if that can be done
552 return $front . $link . $back if $href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/is;
553
554
555 if (($rl == 0) || ($filename =~ /$self->{'process_exp'}/) ||
556 ($href =~ /\/$/) || ($href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
557 &ghtml::urlsafe ($href);
558 return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
559 } else {
560 # link is to some other type of file (eg image) so we'll
561 # need to associate that file
562 return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
563 }
564}
565
566sub add_file {
567 my $self = shift (@_);
568 my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
569 my ($newname);
570
571 my $filename = $href;
572 if ($base_dir eq "") {
573 # remove http:/ thereby leaving one slash at the start
574 $filename =~ s/^[^:]*:\///;
575 }
576 else {
577 # remove http://
578 $filename =~ s/^[^:]*:\/\///;
579 }
580
581 $filename = &util::filename_cat($base_dir, $filename);
582
583 # Replace %20's in URL with a space if required. Note that the filename
584 # may include the %20 in some situations
585 if ($filename =~ /\%20/) {
586 if (!-e $filename) {
587 $filename =~ s/\%20/ /g;
588 }
589 }
590
591 my ($ext) = $filename =~ /(\.[^\.]*)$/;
592
593 if ($rl == 0) {
594 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
595 return "_httpextlink_&rl=0&el=prompt&href=" . $href . $hash_part;
596 }
597 else {
598 return "_httpextlink_&rl=0&el=direct&href=" . $href . $hash_part;
599 }
600 }
601
602 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
603 return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
604 }
605 if ($self->{'rename_assoc_files'}) {
606 if (defined $self->{'aux_files'}->{$href}) {
607 $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
608 $self->{'aux_files'}->{$href}->{'file_num'} . $ext;
609 } else {
610 $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
611 $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
612 $self->inc_filecount ();
613 }
614 $doc_obj->associate_file($filename, $newname, undef, $section);
615 return "_httpdocimg_/$newname";
616 } else {
617 ($newname) = $filename =~ /([^\/\\]*)$/;
618 $doc_obj->associate_file($filename, $newname, undef, $section);
619 return "_httpdocimg_/$newname";
620 }
621}
622
623
624sub format_link {
625 my $self = shift (@_);
626 my ($link, $base_dir, $file) = @_;
627
628 my ($before_hash, $hash_part) = $link =~ /^([^\#]*)(\#?.*)$/;
629
630 $hash_part = "" if !defined $hash_part;
631 if (!defined $before_hash || $before_hash !~ /[\w\.\/]/) {
632 my $outhandle = $self->{'outhandle'};
633 print $outhandle "HTMLPlug: ERROR - badly formatted tag ignored ($link)\n"
634 if $self->{'verbosity'};
635 return ($link, "", 0);
636 }
637
638 if ($before_hash =~ s@^((?:http|ftp|file)://)@@i) {
639 my $type = $1;
640
641 if ($link =~ /^(http|ftp):/i) {
642 # Turn url (using /) into file name (possibly using \ on windows)
643 my @http_dir_split = split('/', $before_hash);
644 $before_hash = &util::filename_cat(@http_dir_split);
645 }
646
647 $before_hash = $self->eval_dir_dots($before_hash);
648
649 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
650
651 my $rl = 0;
652 $rl = 1 if (-e $linkfilename);
653
654 # make sure there's a slash on the end if it's a directory
655 if ($before_hash !~ /\/$/) {
656 $before_hash .= "/" if (-d $linkfilename);
657 }
658
659 return ($type . $before_hash, $hash_part, $rl);
660
661 } elsif ($link !~ /^(mailto|news|gopher|nntp|telnet|javascript):/i && $link !~ /^\//) {
662 if ($before_hash =~ s@^/@@ || $before_hash =~ /\\/) {
663
664 # the first directory will be the domain name if file_is_url
665 # to generate archives, otherwise we'll assume all files are
666 # from the same site and base_dir is the root
667
668 if ($self->{'file_is_url'}) {
669 my @dirs = split /[\/\\]/, $file;
670 my $domname = shift (@dirs);
671 $before_hash = &util::filename_cat($domname, $before_hash);
672 $before_hash =~ s@\\@/@g; # for windows
673 }
674 else
675 {
676 # see if link shares directory with source document
677 # => turn into relative link if this is so!
678
679 if ($ENV{'GSDLOS'} =~ /^windows/i) {
680 # too difficult doing a pattern match with embedded '\'s...
681 my $win_before_hash=$before_hash;
682 $win_before_hash =~ s@(\\)+@/@g;
683 # $base_dir is already similarly "converted" on windows.
684 if ($win_before_hash =~ s@^$base_dir/@@o) {
685 # if this is true, we removed a prefix
686 $before_hash=$win_before_hash;
687 }
688 }
689 else {
690 # before_hash has lost leading slash by this point,
691 # -> add back in prior to substitution with $base_dir
692 $before_hash = "/$before_hash";
693
694 $before_hash = &util::filename_cat("",$before_hash);
695 $before_hash =~ s@^$base_dir/@@;
696 }
697 }
698 } else {
699 # Turn relative file path into full path
700 my $dirname = &File::Basename::dirname($file);
701 $before_hash = &util::filename_cat($dirname, $before_hash);
702 $before_hash = $self->eval_dir_dots($before_hash);
703 }
704
705 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
706 # make sure there's a slash on the end if it's a directory
707 if ($before_hash !~ /\/$/) {
708 $before_hash .= "/" if (-d $linkfilename);
709 }
710 return ("http://" . $before_hash, $hash_part, 1);
711 } else {
712 # mailto, news, nntp, telnet, javascript or gopher link
713 return ($before_hash, "", 0);
714 }
715}
716
717sub extract_first_NNNN_characters {
718 my $self = shift (@_);
719 my ($textref, $doc_obj, $thissection) = @_;
720
721 foreach my $size (split /,/, $self->{'first'}) {
722 my $tmptext = $$textref;
723 # skip to the body
724 $tmptext =~ s/.*<body[^>]*>//i;
725 # remove javascript
726 $tmptext =~ s@<script.*?</script>@ @sig;
727 $tmptext =~ s/<[^>]*>/ /g;
728 $tmptext =~ s/&nbsp;/ /g;
729 $tmptext =~ s/^\s+//;
730 $tmptext =~ s/\s+$//;
731 $tmptext =~ s/\s+/ /gs;
732 $tmptext = &unicode::substr ($tmptext, 0, $size);
733 $tmptext =~ s/\s\S*$/&#8230;/; # adds an ellipse (...)
734 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
735 }
736}
737
738
739sub extract_metadata {
740 my $self = shift (@_);
741 my ($textref, $metadata, $doc_obj, $section) = @_;
742 my $outhandle = $self->{'outhandle'};
743 # if we don't want metadata, we may as well not be here ...
744 return if (!defined $self->{'metadata_fields'});
745
746 # metadata fields to extract/save. 'key' is the (lowercase) name of the
747 # html meta, 'value' is the metadata name for greenstone to use
748 my %find_fields = ();
749
750 my %creator_fields = (); # short-cut for lookups
751
752
753 foreach my $field (split /,/, $self->{'metadata_fields'}) {
754 # support tag<tagname>
755 if ($field =~ /^(.*?)<(.*?)>$/) {
756 # "$2" is the user's preferred gs metadata name
757 $find_fields{lc($1)}=$2; # lc = lowercase
758 } else { # no <tagname> for mapping
759 # "$field" is the user's preferred gs metadata name
760 $find_fields{lc($field)}=$field; # lc = lowercase
761 }
762 }
763
764 if (defined $self->{'hunt_creator_metadata'} &&
765 $self->{'hunt_creator_metadata'} == 1 ) {
766 my @extra_fields =
767 (
768 'author',
769 'author.email',
770 'creator',
771 'dc.creator',
772 'dc.creator.corporatename',
773 );
774
775 # add the creator_metadata fields to search for
776 foreach my $field (@extra_fields) {
777 $creator_fields{$field}=0; # add to lookup hash
778 }
779 }
780
781
782 # find the header in the html file, which has the meta tags
783 $$textref =~ m@<head>(.*?)</head>@si;
784
785 my $html_header=$1;
786
787 # go through every <meta... tag defined in the html and see if it is
788 # one of the tags we want to match.
789
790 # special case for title - we want to remember if its been found
791 my $found_title = 0;
792 # this assumes that ">" won't appear. (I don't think it's allowed to...)
793 $html_header =~ /^/; # match the start of the string, for \G assertion
794
795 while ($html_header =~ m/\G.*?<meta(.*?)>/sig) {
796 my $metatag=$1;
797 my ($tag, $value);
798
799 # find the tag name
800 $metatag =~ /(?:name|http-equiv)\s*=\s*([\"\'])?(.*?)\1/is;
801 $tag=$2;
802 # in case they're not using " or ', but they should...
803 if (! $tag) {
804 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
805 $tag=$1;
806 }
807
808 if (!defined $tag) {
809 print $outhandle "HTMLPlug: can't find NAME in \"$metatag\"\n";
810 next;
811 }
812
813 # don't need to assign this field if it was passed in from a previous
814 # (recursive) plugin
815 if (defined $metadata->{$tag}) {next}
816
817 # find the tag content
818 $metatag =~ /content\s*=\s*([\"\'])?(.*?)\1/is;
819 $value=$2;
820
821 if (! $value) {
822 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
823 $value=$1;
824 }
825 if (!defined $value) {
826 print $outhandle "HTMLPlug: can't find VALUE in \"$metatag\"\n";
827 next;
828 }
829
830 # clean up and add
831 $value =~ s/\s+/ /gs;
832 chomp($value); # remove trailing \n, if any
833 if (exists $creator_fields{lc($tag)}) {
834 # map this value onto greenstone's "Creator" metadata
835 $tag='Creator';
836 } elsif (!exists $find_fields{lc($tag)}) {
837 next; # don't want this tag
838 } else {
839 # get the user's preferred capitalisation
840 $tag = $find_fields{lc($tag)};
841 }
842 if (lc($tag) eq "title") {
843 $found_title = 1;
844 }
845 print $outhandle " extracted \"$tag\" metadata \"$value\"\n"
846 if ($self->{'verbosity'} > 2);
847 if ($tag =~ /date.*/i){
848 $tag = lc($tag);
849 }
850 $doc_obj->add_utf8_metadata($section, $tag, $value);
851
852 }
853
854 # TITLE: extract the document title
855 if (exists $find_fields{'title'} && !$found_title) {
856 # we want a title, and didn't find one in the meta tags
857 # see if there's a <title> tag
858 my $title;
859 my $from = ""; # for debugging output only
860 if ($html_header =~ /<title[^>]*>([^<]+)<\/title[^>]*>/is) {
861 $title = $1;
862 $from = "<title> tags";
863 }
864
865 if (!defined $title) {
866 $from = "first 100 chars";
867 # if no title use first 100 or so characters
868 $title = $$textref;
869 $title =~ s/^\xFE\xFF//; # Remove unicode byte order mark
870 $title =~ s/^.*?<body>//si;
871 # ignore javascript!
872 $title =~ s@<script.*?</script>@ @sig;
873 $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
874 $title =~ s/<[^>]*>/ /g; # remove all HTML tags
875 $title = substr ($title, 0, 100);
876 $title =~ s/\s\S*$/.../;
877 }
878 $title =~ s/<[^>]*>/ /g; # remove html tags
879 $title =~ s/&nbsp;/ /g;
880 $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
881 $title =~ s/\s+/ /gs; # collapse multiple spaces
882 $title =~ s/^\s*//; # remove leading spaces
883 $title =~ s/\s*$//; # remove trailing spaces
884
885 $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
886 $title =~ s/^\s+//s; # in case title_sub introduced any...
887 $doc_obj->add_utf8_metadata ($section, 'Title', $title);
888 print $outhandle " extracted Title metadata \"$title\" from $from\n"
889 if ($self->{'verbosity'} > 2);
890 }
891
892 # add FileFormat metadata
893 $doc_obj->add_metadata($section,"FileFormat", "HTML");
894
895 # Special, for metadata names such as tagH1 - extracts
896 # the text between the first <H1> and </H1> tags into "H1" metadata.
897
898 foreach my $field (keys %find_fields) {
899 if ($field !~ /^tag([a-z0-9]+)$/i) {next}
900 my $tag = $1;
901 if ($$textref =~ m@<$tag[^>]*>(.*?)</$tag[^>]*>@g) {
902 my $content = $1;
903 $content =~ s/&nbsp;/ /g;
904 $content =~ s/<[^>]*>/ /g;
905 $content =~ s/^\s+//;
906 $content =~ s/\s+$//;
907 $content =~ s/\s+/ /gs;
908 if ($content) {
909 $tag=$find_fields{"tag$tag"}; # get the user's capitalisation
910 $tag =~ s/^tag//i;
911 $doc_obj->add_utf8_metadata ($section, $tag, $content);
912 print $outhandle " extracted \"$tag\" metadata \"$content\"\n"
913 if ($self->{'verbosity'} > 2);
914 }
915 }
916 }
917}
918
919
920# evaluate any "../" to next directory up
921# evaluate any "./" as here
922sub eval_dir_dots {
923 my $self = shift (@_);
924 my ($filename) = @_;
925 my $dirsep_os = &util::get_os_dirsep();
926 my @dirsep = split(/$dirsep_os/,$filename);
927
928 my @eval_dirs = ();
929 foreach my $d (@dirsep) {
930 if ($d eq "..") {
931 pop(@eval_dirs);
932
933 } elsif ($d eq ".") {
934 # do nothing!
935
936 } else {
937 push(@eval_dirs,$d);
938 }
939 }
940
941 # Need to fiddle with number of elements in @eval_dirs if the
942 # first one is the empty string. This is because of a
943 # modification to util::filename_cat that supresses the addition
944 # of a leading '/' character (or \ if windows) (intended to help
945 # filename cat with relative paths) if the first entry in the
946 # array is the empty string. Making the array start with *two*
947 # empty strings is a way to defeat this "smart" option.
948 #
949 if (scalar(@eval_dirs) > 0) {
950 if ($eval_dirs[0] eq ""){
951 unshift(@eval_dirs,"");
952 }
953 }
954 return &util::filename_cat(@eval_dirs);
955}
956
957sub replace_usemap_links {
958 my $self = shift (@_);
959 my ($front, $link, $back) = @_;
960
961 $link =~ s/^\.\///;
962 return $front . $link . $back;
963}
964
965sub inc_filecount {
966 my $self = shift (@_);
967
968 if ($self->{'file_num'} == 1000) {
969 $self->{'dir_num'} ++;
970 $self->{'file_num'} = 0;
971 } else {
972 $self->{'file_num'} ++;
973 }
974}
975
976
977# Extend the BasPlug read_file so that strings like &eacute; are
978# converted to UTF8 internally.
979#
980# We don't convert &lt; or &gt; or &amp; or &quot; in case
981# they interfere with the GML files
982
983sub read_file {
984 my ($self, $filename, $encoding, $language, $textref) = @_;
985
986 &BasPlug::read_file($self, $filename, $encoding, $language, $textref);
987
988 # Convert entities to their UTF8 equivalents
989 $$textref =~ s/&(lt|gt|amp|quot|nbsp);/&z$1;/go;
990 $$textref =~ s/&([^;]+);/&ghtml::getcharequiv($1,1)/gseo;
991 $$textref =~ s/&z(lt|gt|amp|quot|nbsp);/&$1;/go;
992}
993
9941;
Note: See TracBrowser for help on using the repository browser.