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

Last change on this file since 10280 was 10277, checked in by chi, 19 years ago

tidy up the filename in add_file().

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