source: gsdl/trunk/perllib/plugins/HTMLPlugin.pm@ 16735

Last change on this file since 16735 was 16735, checked in by ak19, 16 years ago

When a directory of interlinking html files is dropped into GLI, adjusted web_url variable so that interlinking still works after the collection is built.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 48.0 KB
Line 
1###########################################################################
2#
3# HTMLPlugin.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 HTMLPlugin;
37
38use ReadTextFile;
39use HBPlugin;
40use ghtml;
41use unicode;
42use util;
43use XMLParser;
44
45use Image::Size;
46use File::Copy;
47
48sub BEGIN {
49 @HTMLPlugin::ISA = ('ReadTextFile', 'HBPlugin');
50}
51
52use strict; # every perl program should have this!
53no strict 'refs'; # make an exception so we can use variables as filehandles
54
55my $arguments =
56 [ { 'name' => "process_exp",
57 'desc' => "{BasePlugin.process_exp}",
58 'type' => "regexp",
59 'deft' => &get_default_process_exp() },
60 { 'name' => "block_exp",
61 'desc' => "{BasePlugin.block_exp}",
62 'type' => 'regexp',
63 'deft' => &get_default_block_exp() },
64 { 'name' => "nolinks",
65 'desc' => "{HTMLPlugin.nolinks}",
66 'type' => "flag" },
67 { 'name' => "keep_head",
68 'desc' => "{HTMLPlugin.keep_head}",
69 'type' => "flag" },
70 { 'name' => "no_metadata",
71 'desc' => "{HTMLPlugin.no_metadata}",
72 'type' => "flag" },
73 { 'name' => "metadata_fields",
74 'desc' => "{HTMLPlugin.metadata_fields}",
75 'type' => "string",
76 'deft' => "Title" },
77 { 'name' => "hunt_creator_metadata",
78 'desc' => "{HTMLPlugin.hunt_creator_metadata}",
79 'type' => "flag" },
80 { 'name' => "file_is_url",
81 'desc' => "{HTMLPlugin.file_is_url}",
82 'type' => "flag" },
83 { 'name' => "assoc_files",
84 'desc' => "{HTMLPlugin.assoc_files}",
85 'type' => "regexp",
86 'deft' => &get_default_block_exp() },
87 { 'name' => "rename_assoc_files",
88 'desc' => "{HTMLPlugin.rename_assoc_files}",
89 'type' => "flag" },
90 { 'name' => "title_sub",
91 'desc' => "{HTMLPlugin.title_sub}",
92 'type' => "string",
93 'deft' => "" },
94 { 'name' => "description_tags",
95 'desc' => "{HTMLPlugin.description_tags}",
96 'type' => "flag" },
97 # retain this for backward compatibility (w3mir option was replaced by
98 # file_is_url)
99 { 'name' => "w3mir",
100# 'desc' => "{HTMLPlugin.w3mir}",
101 'type' => "flag",
102 'hiddengli' => "yes"},
103 { 'name' => "no_strip_metadata_html",
104 'desc' => "{HTMLPlugin.no_strip_metadata_html}",
105 'type' => "string",
106 'deft' => "",
107 'reqd' => "no"},
108 { 'name' => "sectionalise_using_h_tags",
109 'desc' => "{HTMLPlugin.sectionalise_using_h_tags}",
110 'type' => "flag" },
111 { 'name' => "use_realistic_book",
112 'desc' => "{HTMLPlugin.tidy_html}",
113 'type' => "flag"},
114 { 'name' => "old_style_HDL",
115 'desc' => "{HTMLPlugin.old_style_HDL}",
116 'type' => "flag"}
117 ];
118
119my $options = { 'name' => "HTMLPlugin",
120 'desc' => "{HTMLPlugin.desc}",
121 'abstract' => "no",
122 'inherits' => "yes",
123 'args' => $arguments };
124
125
126sub HB_read_html_file {
127 my $self = shift (@_);
128 my ($htmlfile, $text) = @_;
129
130 # load in the file
131 if (!open (FILE, $htmlfile)) {
132 print STDERR "ERROR - could not open $htmlfile\n";
133 return;
134 }
135
136 my $foundbody = 0;
137 $self->HB_gettext (\$foundbody, $text, "FILE");
138 close FILE;
139
140 # just in case there was no <body> tag
141 if (!$foundbody) {
142 $foundbody = 1;
143 open (FILE, $htmlfile) || return;
144 $self->HB_gettext (\$foundbody, $text, "FILE");
145 close FILE;
146 }
147 # text is in utf8
148}
149
150# converts the text to utf8, as ghtml does that for &eacute; etc.
151sub HB_gettext {
152 my $self = shift (@_);
153 my ($foundbody, $text, $handle) = @_;
154
155 my $line = "";
156 while (defined ($line = <$handle>)) {
157 # look for body tag
158 if (!$$foundbody) {
159 if ($line =~ s/^.*<body[^>]*>//i) {
160 $$foundbody = 1;
161 } else {
162 next;
163 }
164 }
165
166 # check for symbol fonts
167 if ($line =~ /<font [^>]*?face\s*=\s*\"?(\w+)\"?/i) {
168 my $font = $1;
169 print STDERR "HBPlug::HB_gettext - warning removed font $font\n"
170 if ($font !~ /^arial$/i);
171 }
172
173 $$text .= $line;
174 }
175
176 if ($self->{'input_encoding'} eq "iso_8859_1") {
177 # convert to utf-8
178 $$text=&unicode::unicode2utf8(&unicode::convert2unicode("iso_8859_1", $text));
179 }
180 # convert any alphanumeric character entities to their utf-8
181 # equivalent for indexing purposes
182 #&ghtml::convertcharentities ($$text);
183
184 $$text =~ s/\s+/ /g; # remove \n's
185}
186
187sub HB_clean_section {
188 my $self = shift (@_);
189 my ($section) = @_;
190
191 # remove tags without a starting tag from the section
192 my ($tag, $tagstart);
193 while ($section =~ /<\/([^>]{1,10})>/) {
194 $tag = $1;
195 $tagstart = index($section, "<$tag");
196 last if (($tagstart >= 0) && ($tagstart < index($section, "<\/$tag")));
197 $section =~ s/<\/$tag>//;
198 }
199
200 # remove extra paragraph tags
201 while ($section =~ s/<p\b[^>]*>\s*<p\b/<p/ig) {}
202
203 # remove extra stuff at the end of the section
204 while ($section =~ s/(<u>|<i>|<b>|<p\b[^>]*>|&nbsp;|\s)$//i) {}
205
206 # add a newline at the beginning of each paragraph
207 $section =~ s/(.)\s*<p\b/$1\n\n<p/gi;
208
209 # add a newline every 80 characters at a word boundary
210 # Note: this regular expression puts a line feed before
211 # the last word in each section, even when it is not
212 # needed.
213 $section =~ s/(.{1,80})\s/$1\n/g;
214
215 # fix up the image links
216 $section =~ s/<img[^>]*?src=\"?([^\">]+)\"?[^>]*>/
217 <center><img src=\"$1\" \/><\/center><br\/>/ig;
218 $section =~ s/&lt;&lt;I&gt;&gt;\s*([^\.]+\.(png|jpg|gif))/
219 <center><img src=\"$1\" \/><\/center><br\/>/ig;
220
221 return $section;
222}
223
224# Will convert the oldHDL format to the new HDL format (using the Section tag)
225sub convert_to_newHDLformat
226{
227 my $self = shift (@_);
228 my ($file,$cnfile) = @_;
229 my $input_filename = $file;
230 my $tmp_filename = $cnfile;
231
232 # write HTML tmp file with new HDL format
233 open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
234
235 # read in the file and do basic html cleaning (removing header etc)
236 my $html = "";
237 $self->HB_read_html_file ($input_filename, \$html);
238
239 # process the file one section at a time
240 my $curtoclevel = 1;
241 my $firstsection = 1;
242 my $toclevel = 0;
243 while (length ($html) > 0) {
244 if ($html =~ s/^.*?(?:<p\b[^>]*>)?((<b>|<i>|<u>|\s)*)&lt;&lt;TOC(\d+)&gt;&gt;\s*(.*?)<p\b/<p/i) {
245 $toclevel = $3;
246 my $title = $4;
247 my $sectiontext = "";
248 if ($html =~ s/^(.*?)((?:<p\b[^>]*>)?((<b>|<i>|<u>|\s)*)&lt;&lt;TOC\d+&gt;&gt;)/$2/i) {
249 $sectiontext = $1;
250 } else {
251 $sectiontext = $html;
252 $html = "";
253 }
254
255 # remove tags and extra spaces from the title
256 $title =~ s/<\/?[^>]+>//g;
257 $title =~ s/^\s+|\s+$//g;
258
259 # close any sections below the current level and
260 # create a new section (special case for the firstsection)
261 print PROD "<!--\n";
262 while (($curtoclevel > $toclevel) ||
263 (!$firstsection && $curtoclevel == $toclevel)) {
264 $curtoclevel--;
265 print PROD "</Section>\n";
266 }
267 if ($curtoclevel+1 < $toclevel) {
268 print STDERR "WARNING - jump in toc levels in $input_filename " .
269 "from $curtoclevel to $toclevel\n";
270 }
271 while ($curtoclevel < $toclevel) {
272 $curtoclevel++;
273 }
274
275 if ($curtoclevel == 1) {
276 # add the header tag
277 print PROD "-->\n";
278 print PROD "<HTML>\n<HEAD>\n<TITLE>$title</TITLE>\n</HEAD>\n<BODY>\n";
279 print PROD "<!--\n";
280 }
281
282 print PROD "<Section>\n\t<Description>\n\t\t<Metadata name=\"Title\">$title</Metadata>\n\t</Description>\n";
283
284 print PROD "-->\n";
285
286 # clean up the section html
287 $sectiontext = $self->HB_clean_section($sectiontext);
288
289 print PROD "$sectiontext\n";
290
291 } else {
292 print STDERR "WARNING - leftover text\n" , $self->shorten($html),
293 "\nin $input_filename\n";
294 last;
295 }
296 $firstsection = 0;
297 }
298
299 print PROD "<!--\n";
300 while ($curtoclevel > 0) {
301 $curtoclevel--;
302 print PROD "</Section>\n";
303 }
304 print PROD "-->\n";
305
306 close (PROD) || die("Error Closing File: $tmp_filename $!");
307
308 return $tmp_filename;
309}
310
311sub shorten {
312 my $self = shift (@_);
313 my ($text) = @_;
314
315 return "\"$text\"" if (length($text) < 100);
316
317 return "\"" . substr ($text, 0, 50) . "\" ... \"" .
318 substr ($text, length($text)-50) . "\"";
319}
320
321sub convert_tidy_or_oldHDL_file
322{
323 my $self = shift (@_);
324 my ($file) = @_;
325 my $input_filename = $file;
326
327 if (-d $input_filename)
328 {
329 return $input_filename;
330 }
331
332 # get the input filename
333 my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
334 my $base_dirname = $dirname;
335 $suffix = lc($suffix);
336
337 # derive tmp filename from input filename
338 # Remove any white space from filename -- no risk of name collision, and
339 # makes later conversion by utils simpler. Leave spaces in path...
340 # tidy up the filename with space, dot, hyphen between
341 $tailname =~ s/\s+//g;
342 $tailname =~ s/\.+//g;
343 $tailname =~ s/\-+//g;
344 # convert to utf-8 otherwise we have problems with the doc.xml file
345 # later on
346 &unicode::ensure_utf8(\$tailname);
347
348 # softlink to collection tmp dir
349 my $tmp_dirname = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tidytmp");
350 &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
351
352 my $test_dirname = "";
353 my $f_separator = &util::get_os_dirsep();
354
355 if ($dirname =~ /import$f_separator/)
356 {
357 $test_dirname = $'; #'
358
359 #print STDERR "init $'\n";
360
361 while ($test_dirname =~ /[$f_separator]/)
362 {
363 my $folderdirname = $`;
364 $tmp_dirname = &util::filename_cat($tmp_dirname,$folderdirname);
365 &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
366 $test_dirname = $'; #'
367 }
368 }
369
370 my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
371
372 # tidy or convert the input file if it is a HTML-like file or it is accepted by the process_exp
373 if (($suffix eq ".htm") || ($suffix eq ".html") || ($suffix eq ".shtml"))
374 {
375 #convert the input file to a new style HDL
376 my $hdl_output_filename = $input_filename;
377 if ($self->{'old_style_HDL'})
378 {
379 $hdl_output_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
380 $hdl_output_filename = $self->convert_to_newHDLformat($input_filename,$hdl_output_filename);
381 }
382
383 #just for checking copy all other file from the base dir to tmp dir if it is not exists
384 opendir(DIR,$base_dirname) or die "Can't open base directory : $base_dirname!";
385 my @files = grep {!/^\.+$/} readdir(DIR);
386 close(DIR);
387
388 foreach my $file (@files)
389 {
390 my $src_file = &util::filename_cat($base_dirname,$file);
391 my $dest_file = &util::filename_cat($tmp_dirname,$file);
392 if ((!-e $dest_file) && (!-d $src_file))
393 {
394 # just copy the original file back to the tmp directory
395 copy($src_file,$dest_file) or die "Can't copy file $src_file to $dest_file $!";
396 }
397 }
398
399 # tidy the input file
400 my $tidy_output_filename = $hdl_output_filename;
401 if ($self->{'tidy_html'})
402 {
403 $tidy_output_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
404 $tidy_output_filename = $self->tmp_tidy_file($hdl_output_filename,$tidy_output_filename);
405 }
406 $tmp_filename = $tidy_output_filename;
407 }
408 else
409 {
410 if (!-e $tmp_filename)
411 {
412 # just copy the original file back to the tmp directory
413 copy($input_filename,$tmp_filename) or die "Can't copy file $input_filename to $tmp_filename $!";
414 }
415 }
416
417 return $tmp_filename;
418}
419
420
421# Will make the html input file as a proper XML file with removed font tag and
422# image size added to the img tag.
423# The tidying process takes place in a collection specific 'tmp' directory so
424# that we don't accidentally damage the input.
425sub tmp_tidy_file
426{
427 my $self = shift (@_);
428 my ($file,$cnfile) = @_;
429 my $input_filename = $file;
430 my $tmp_filename = $cnfile;
431
432 # get the input filename
433 my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
434
435 require HTML::TokeParser::Simple;
436
437 # create HTML parser to decode the input file
438 my $parser = HTML::TokeParser::Simple->new($input_filename);
439
440 # write HTML tmp file without the font tag and image size are added to the img tag
441 open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
442 while (my $token = $parser->get_token())
443 {
444 # is it an img tag
445 if ($token->is_start_tag('img'))
446 {
447 # get the attributes
448 my $attr = $token->return_attr;
449
450 # get the full path to the image
451 my $img_file = &util::filename_cat($dirname,$attr->{src});
452
453 # set the width and height attribute
454 ($attr->{width}, $attr->{height}) = imgsize($img_file);
455
456 # recreate the tag
457 print PROD "<img";
458 print PROD map { qq { $_="$attr->{$_}"} } keys %$attr;
459 print PROD ">";
460 }
461 # is it a font tag
462 else
463 {
464 if (($token->is_start_tag('font')) || ($token->is_end_tag('font')))
465 {
466 # remove font tag
467 print PROD "";
468 }
469 else
470 {
471 # print without changes
472 print PROD $token->as_is;
473 }
474 }
475 }
476 close (PROD) || die("Error Closing File: $tmp_filename $!");
477
478 # run html-tidy on the tmp file to make it a proper XML file
479 my $tidyfile = `tidy -utf8 -wrap 0 -asxml $tmp_filename`;
480
481 # write result back to the tmp file
482 open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
483 print PROD $tidyfile;
484 close (PROD) || die("Error Closing File: $tmp_filename $!");
485
486 # return the output filename
487 return $tmp_filename;
488}
489
490sub read_into_doc_obj
491{
492 my $self = shift (@_);
493 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
494
495 # get the input file
496 my $input_filename = $file;
497 my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
498 $suffix = lc($suffix);
499
500 if (($self->{'tidy_html'}) || ($self->{'old_style_HDL'}))
501 {
502 # because the document has to be sectionalized set the description tags
503 $self->{'description_tags'} = 1;
504
505 # set the file to be tidied
506 $input_filename = &util::filename_cat($base_dir,$file) if $base_dir =~ /\w/;
507
508 # get the tidied file
509 #my $tidy_filename = $self->tmp_tidy_file($input_filename);
510 my $tidy_filename = $self->convert_tidy_or_oldHDL_file($input_filename);
511
512 # derive tmp filename from input filename
513 my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($tidy_filename, "\\.[^\\.]+\$");
514
515 # set the new input file and base_dir to be from the tidied file
516 $file = "$tailname$suffix";
517 $base_dir = $dirname;
518 }
519
520 # call the parent read_into_doc_obj
521 my ($process_status,$doc_obj) = $self->SUPER::read_into_doc_obj($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli);
522
523 return ($process_status,$doc_obj);
524}
525
526sub new {
527 my ($class) = shift (@_);
528 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
529 push(@$pluginlist, $class);
530
531 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
532 push(@{$hashArgOptLists->{"OptList"}},$options);
533
534
535 my $self = new ReadTextFile($pluginlist,$inputargs,$hashArgOptLists);
536
537 if ($self->{'w3mir'}) {
538 $self->{'file_is_url'} = 1;
539 }
540 $self->{'aux_files'} = {};
541 $self->{'dir_num'} = 0;
542 $self->{'file_num'} = 0;
543
544 return bless $self, $class;
545}
546
547# may want to use (?i)\.(gif|jpe?g|jpe|png|css|js(?:@.*)?)$
548# if have eg <script language="javascript" src="img/lib.js@123">
549sub get_default_block_exp {
550 my $self = shift (@_);
551
552 #return q^(?i)\.(gif|jpe?g|jpe|jpg|png|css)$^;
553 return "";
554}
555
556sub get_default_process_exp {
557 my $self = shift (@_);
558
559 # the last option is an attempt to encode the concept of an html query ...
560 return q^(?i)(\.html?|\.shtml|\.shm|\.asp|\.php\d?|\.cgi|.+\?.+=.*)$^;
561}
562
563sub store_block_files
564{
565 my $self =shift (@_);
566 my ($filename_full_path, $block_hash) = @_;
567
568 my $html_fname = $filename_full_path;
569 my @file_blocks;
570
571 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename_full_path);
572
573 # read in file ($text will be in utf8)
574 my $text = "";
575 $self->read_file ($filename_full_path, $encoding, $language, \$text);
576 my $textref = \$text;
577 my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
578 my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
579 $$textref =~ s/$opencom(.*?)$closecom//gs;
580
581 my $attval = "\\\"[^\\\"]+\\\"|[^\\s>]+";
582 my @img_matches = ($$textref =~ m/<img[^>]*?src\s*=\s*($attval)[^>]*>/igs);
583 my @usemap_matches = ($$textref =~ m/<img[^>]*?usemap\s*=\s*($attval)[^>]*>/igs);
584 my @link_matches = ($$textref =~ m/<link[^>]*?href\s*=\s*($attval)[^>]*>/igs);
585 my @embed_matches = ($$textref =~ m/<embed[^>]*?src\s*=\s*($attval)[^>]*>/igs);
586 my @tabbg_matches = ($$textref =~ m/<(?:table|tr|td)[^>]*?background\s*=\s*($attval)[^>]*>/igs);
587 my @script_matches = ($$textref =~ m/<script[^>]*?src\s*=\s*($attval)[^>]*>/igs);
588
589 foreach my $link (@img_matches, @usemap_matches, @link_matches, @embed_matches, @tabbg_matches, @script_matches) {
590
591 # remove quotes from link at start and end if necessary
592 if ($link=~/^\"/) {
593 $link=~s/^\"//;
594 $link=~s/\"$//;
595 }
596
597 $link =~ s/\#.*$//s; # remove any anchor names, e.g. foo.html#name becomes foo.html
598 # some links may just be anchor names
599 next unless ($link =~ /\S+/);
600
601 if ($link !~ m@^/@ && $link !~ m/^([A-Z]:?)\\/) {
602 # Turn relative file path into full path
603 my $dirname = &File::Basename::dirname($filename_full_path);
604 $link = &util::filename_cat($dirname, $link);
605 }
606 $link = $self->eval_dir_dots($link);
607
608 # Replace %XX's in URL with decoded value if required.
609 # Note that the filename may include the %XX in some situations
610 if ($link =~ m/\%[A-F0-9]{2}/i) {
611 if (!-e $link) {
612 $link =~ s/\%([A-F0-9]{2})/pack('C', hex($1))/ige;
613 }
614 }
615
616 $block_hash->{'file_blocks'}->{$link} = 1;
617 }
618}
619
620
621# do plugin specific processing of doc_obj
622sub process {
623 my $self = shift (@_);
624 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
625 my $outhandle = $self->{'outhandle'};
626
627 if ($ENV{'GSDLOS'} =~ /^windows/i) {
628 # this makes life so much easier... perl can cope with unix-style '/'s.
629 $base_dir =~ s@(\\)+@/@g;
630 $file =~ s@(\\)+@/@g;
631 }
632
633 # reset per-doc stuff...
634 $self->{'aux_files'} = {};
635 $self->{'dir_num'} = 0;
636 $self->{'file_num'} = 0;
637
638 # process an HTML file where sections are divided by headings tags (H1, H2 ...)
639 # you can also include metadata in the format (X can be any number)
640 # <hX>Title<!--gsdl-metadata
641 # <Metadata name="name1">value1</Metadata>
642 # ...
643 # <Metadata name="nameN">valueN</Metadata>
644 #--></hX>
645 if ($self->{'sectionalise_using_h_tags'}) {
646 # description_tags should allways be activated because we convert headings to description tags
647 $self->{'description_tags'} = 1;
648
649 my $arrSections = [];
650 $$textref =~ s/<h([0-9]+)[^>]*>(.*?)<\/h[0-9]+>/$self->process_heading($1, $2, $arrSections, $file)/isge;
651
652 if (scalar(@$arrSections)) {
653 my $strMetadata = $self->update_section_data($arrSections, -1);
654 if (length($strMetadata)) {
655 $strMetadata = '<!--' . $strMetadata . "\n-->\n</body>";
656 $$textref =~ s/<\/body>/$strMetadata/ig;
657 }
658 }
659 }
660
661 my $cursection = $doc_obj->get_top_section();
662
663 $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection)
664 unless $self->{'no_metadata'} || $self->{'description_tags'};
665
666 # Store URL for page as metadata - this can be used for an
667 # altavista style search interface. The URL won't be valid
668 # unless the file structure contains the domain name (i.e.
669 # like when w3mir is used to download a website).
670
671 # URL metadata (even invalid ones) are used to support internal
672 # links, so even if 'file_is_url' is off, still need to store info
673
674 my ($tailname,$dirname,$suffix) = &File::Basename::fileparse($file, "\\.[^\\.]+\$");
675 my $utf8_file = $self->filename_to_utf8_metadata($file);
676 my $web_url = "http://";
677 if(defined $dirname) { # local directory
678 $web_url = $web_url.$dirname.$utf8_file;
679 } else {
680 $web_url = $web_url.$utf8_file;
681 }
682 $doc_obj->add_utf8_metadata($cursection, "URL", $web_url);
683
684 if ($self->{'file_is_url'}) {
685 $doc_obj->add_metadata($cursection, "weblink", "<a href=\"$web_url\">");
686 $doc_obj->add_metadata($cursection, "webicon", "_iconworld_");
687 $doc_obj->add_metadata($cursection, "/weblink", "</a>");
688 }
689
690 if ($self->{'description_tags'}) {
691 # remove the html header - note that doing this here means any
692 # sections defined within the header will be lost (so all <Section>
693 # tags must appear within the body of the HTML)
694 my ($head_keep) = ($$textref =~ m/^(.*?)<body[^>]*>/is);
695
696 $$textref =~ s/^.*?<body[^>]*>//is;
697 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
698
699 my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
700 my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
701
702 my $lt = '(?:<|&lt;)';
703 my $gt = '(?:>|&gt;)';
704 my $quot = '(?:"|&quot;|&rdquo;|&ldquo;)';
705
706 my $dont_strip = '';
707 if ($self->{'no_strip_metadata_html'}) {
708 ($dont_strip = $self->{'no_strip_metadata_html'}) =~ s{,}{|}g;
709 }
710
711 my $found_something = 0; my $top = 1;
712 while ($$textref =~ s/^(.*?)$opencom(.*?)$closecom//s) {
713 my $text = $1;
714 my $comment = $2;
715 if (defined $text) {
716 # text before a comment - note that getting to here
717 # doesn't necessarily mean there are Section tags in
718 # the document
719 $self->process_section(\$text, $base_dir, $file, $doc_obj, $cursection);
720 }
721 while ($comment =~ s/$lt(.*?)$gt//s) {
722 my $tag = $1;
723 if ($tag eq "Section") {
724 $found_something = 1;
725 $cursection = $doc_obj->insert_section($doc_obj->get_end_child($cursection)) unless $top;
726 $top = 0;
727 } elsif ($tag eq "/Section") {
728 $found_something = 1;
729 $cursection = $doc_obj->get_parent_section ($cursection);
730 } elsif ($tag =~ /^Metadata name=$quot(.*?)$quot/s) {
731 my $metaname = $1;
732 my $accumulate = $tag =~ /mode=${quot}accumulate${quot}/ ? 1 : 0;
733 $comment =~ s/^(.*?)$lt\/Metadata$gt//s;
734 my $metavalue = $1;
735 $metavalue =~ s/^\s+//;
736 $metavalue =~ s/\s+$//;
737 # assume that no metadata value intentionally includes
738 # carriage returns or HTML tags (if they're there they
739 # were probably introduced when converting to HTML from
740 # some other format).
741 # actually some people want to have html tags in their
742 # metadata.
743 $metavalue =~ s/[\cJ\cM]/ /sg;
744 $metavalue =~ s/<[^>]+>//sg
745 unless $dont_strip && ($dont_strip eq 'all' || $metaname =~ /^($dont_strip)$/);
746 $metavalue =~ s/\s+/ /sg;
747 if ($accumulate) {
748 $doc_obj->add_utf8_metadata($cursection, $metaname, $metavalue);
749 } else {
750 $doc_obj->set_utf8_metadata_element($cursection, $metaname, $metavalue);
751 }
752 } elsif ($tag eq "Description" || $tag eq "/Description") {
753 # do nothing with containing Description tags
754 } else {
755 # simple HTML tag (probably created by the conversion
756 # to HTML from some other format) - we'll ignore it and
757 # hope for the best ;-)
758 }
759 }
760 }
761 if ($cursection ne "") {
762 print $outhandle "HTMLPlugin: WARNING: $file contains unmatched <Section></Section> tags\n";
763 }
764
765 $$textref =~ s/^.*?<body[^>]*>//is;
766 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
767 if ($$textref =~ /\S/) {
768 if (!$found_something) {
769 if ($self->{'verbosity'} > 2) {
770 print $outhandle "HTMLPlugin: WARNING: $file appears to contain no Section tags so\n";
771 print $outhandle " will be processed as a single section document\n";
772 }
773
774 # go ahead and process single-section document
775 $self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
776
777 # if document contains no Section tags we'll go ahead
778 # and extract metadata (this won't have been done
779 # above as the -description_tags option prevents it)
780 my $complete_text = $head_keep.$doc_obj->get_text($cursection);
781 $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection)
782 unless $self->{'no_metadata'};
783
784 } else {
785 print $outhandle "HTMLPlugin: WARNING: $file contains the following text outside\n";
786 print $outhandle " of the final closing </Section> tag. This text will\n";
787 print $outhandle " be ignored.";
788
789 my ($text);
790 if (length($$textref) > 30) {
791 $text = substr($$textref, 0, 30) . "...";
792 } else {
793 $text = $$textref;
794 }
795 $text =~ s/\n/ /isg;
796 print $outhandle " ($text)\n";
797 }
798 } elsif (!$found_something) {
799
800 if ($self->{'verbosity'} > 2) {
801 # may get to here if document contained no valid Section
802 # tags but did contain some comments. The text will have
803 # been processed already but we should print the warning
804 # as above and extract metadata
805 print $outhandle "HTMLPlugin: WARNING: $file appears to contain no Section tags and\n";
806 print $outhandle " is blank or empty. Metadata will be assigned if present.\n";
807 }
808
809 my $complete_text = $head_keep.$doc_obj->get_text($cursection);
810 $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection)
811 unless $self->{'no_metadata'};
812 }
813
814 } else {
815
816 # remove header and footer
817 if (!$self->{'keep_head'} || $self->{'description_tags'}) {
818 $$textref =~ s/^.*?<body[^>]*>//is;
819 $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
820 }
821
822 # single section document
823 $self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
824 }
825 return 1;
826}
827
828
829sub process_heading
830{
831 my ($self, $nHeadNo, $strHeadingText, $arrSections, $file) = @_;
832 $strHeadingText = '' if (!defined($strHeadingText));
833
834 my $strMetadata = $self->update_section_data($arrSections, int($nHeadNo));
835
836 my $strSecMetadata = '';
837 while ($strHeadingText =~ s/<!--gsdl-metadata(.*?)-->//is)
838 {
839 $strSecMetadata .= $1;
840 }
841
842 $strHeadingText =~ s/^\s+//g;
843 $strHeadingText =~ s/\s+$//g;
844 $strSecMetadata =~ s/^\s+//g;
845 $strSecMetadata =~ s/\s+$//g;
846
847 $strMetadata .= "\n<Section>\n\t<Description>\n\t\t<Metadata name=\"Title\">" . $strHeadingText . "</Metadata>\n";
848
849 if (length($strSecMetadata)) {
850 $strMetadata .= "\t\t" . $strSecMetadata . "\n";
851 }
852
853 $strMetadata .= "\t</Description>\n";
854
855 return "<!--" . $strMetadata . "-->";
856}
857
858
859sub update_section_data
860{
861 my ($self, $arrSections, $nCurTocNo) = @_;
862 my ($strBuffer, $nLast, $nSections) = ('', 0, scalar(@$arrSections));
863
864 if ($nSections == 0) {
865 push @$arrSections, $nCurTocNo;
866 return $strBuffer;
867 }
868 $nLast = $arrSections->[$nSections - 1];
869 if ($nCurTocNo > $nLast) {
870 push @$arrSections, $nCurTocNo;
871 return $strBuffer;
872 }
873 for(my $i = $nSections - 1; $i >= 0; $i--) {
874 if ($nCurTocNo <= $arrSections->[$i]) {
875 $strBuffer .= "\n</Section>";
876 pop @$arrSections;
877 }
878 }
879 push @$arrSections, $nCurTocNo;
880 return $strBuffer;
881}
882
883
884# note that process_section may be called multiple times for a single
885# section (relying on the fact that add_utf8_text appends the text to any
886# that may exist already).
887sub process_section {
888 my $self = shift (@_);
889 my ($textref, $base_dir, $file, $doc_obj, $cursection) = @_;
890 # trap links
891 if (!$self->{'nolinks'}) {
892 # usemap="./#index" not handled correctly => change to "#index"
893 $$textref =~ s/(<img[^>]*?usemap\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/
894 $self->replace_usemap_links($1, $2, $3)/isge;
895
896 $$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/
897 $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
898 }
899
900 # trap images
901
902 # Previously, by default, HTMLPlugin would embed <img> tags inside anchor tags
903 # i.e. <a href="image><img src="image"></a> in order to overcome a problem that
904 # turned regular text succeeding images into links. That is, by embedding <imgs>
905 # inside <a href=""></a>, the text following images were no longer misbehaving.
906 # However, there would be many occasions whereby images were not meant to link
907 # to their source images but where the images would link to another web page.
908 # To allow this, the no_image_links option was introduced: it would prevent
909 # the behaviour of embedding images into links that referenced the source images.
910
911 # Somewhere along the line, the problem of normal text turning into links when
912 # such text followed images which were not embedded in <a href=""></a> ceased
913 # to occur. This is why the following lines have been commented out (as well as
914 # two lines in replace_images). They appear to no longer apply.
915
916 # If at any time, there is a need for having images embedded in <a> anchor tags,
917 # then it might be better to turn that into an HTMLPlugin option rather than make
918 # it the default behaviour. Also, eventually, no_image_links needs to become
919 # a deprecated option for HTMLPlugin as it has now become the default behaviour.
920
921 #if(!$self->{'no_image_links'}){
922 $$textref =~ s/(<(?:img|embed|table|tr|td)[^>]*?(?:src|background)\s*=\s*)((?:[\"][^\"]+[\"])|(?:[\'][^\']+[\'])|(?:[^\s\/>]+))([^>]*>)/
923 $self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
924 #}
925
926 # add text to document object
927 # turn \ into \\ so that the rest of greenstone doesn't think there
928 # is an escape code following. (Macro parsing loses them...)
929 $$textref =~ s/\\/\\\\/go;
930
931 $doc_obj->add_utf8_text($cursection, $$textref);
932}
933
934sub replace_images {
935 my $self = shift (@_);
936 my ($front, $link, $back, $base_dir,
937 $file, $doc_obj, $section) = @_;
938
939 # remove quotes from link at start and end if necessary
940 if ($link=~/^[\"\']/) {
941 $link=~s/^[\"\']//;
942 $link=~s/[\"\']$//;
943 $front.='"';
944 $back="\"$back";
945 }
946
947 $link =~ s/\n/ /g;
948
949 # Hack to overcome Windows wv 0.7.1 bug that causes embedded images to be broken
950 # If the Word file path has spaces in it, wv messes up and you end up with
951 # absolute paths for the images, and without the "file://" prefix
952 # So check for this special case and massage the data to be correct
953 if ($ENV{'GSDLOS'} =~ /^windows/i && $self->{'plugin_type'} eq "WordPlug" && $link =~ /^[A-Za-z]\:\\/) {
954 $link =~ s/^.*\\([^\\]+)$/$1/;
955 }
956
957 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
958
959 my $img_file = $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section);
960
961 print STDERR "**** link = $link\n";
962 print STDERR "**** href = $href\n";
963 print STDERR "**** img_file = $img_file\n";
964
965 my $anchor_name = $img_file;
966 #$anchor_name =~ s/^.*\///;
967 #$anchor_name = "<a name=\"$anchor_name\" ></a>";
968
969 my $image_link = $front . $img_file .$back;
970 return $image_link;
971
972 # The reasons for why the following two lines are no longer necessary can be
973 # found in subroutine process_section
974 #my $anchor_link = "<a href=\"$img_file\" >".$image_link."</a>";
975 #return $anchor_link;
976
977 #return $front . $img_file . $back . $anchor_name;
978}
979
980sub replace_href_links {
981 my $self = shift (@_);
982 my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;
983
984 # attempt to sort out targets - frames are not handled
985 # well in this plugin and some cases will screw things
986 # up - e.g. the _parent target (so we'll just remove
987 # them all ;-)
988 $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
989 $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
990 $front =~ s/target=\"?_parent\"?//is;
991 $back =~ s/target=\"?_parent\"?//is;
992
993 return $front . $link . $back if $link =~ /^\#/s;
994 $link =~ s/\n/ /g;
995
996 my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
997 # href may use '\'s where '/'s should be on Windows
998 $href =~ s/\\/\//g;
999
1000 my ($filename) = $href =~ /^(?:.*?):(?:\/\/)?(.*)/;
1001
1002
1003 ##### leave all these links alone (they won't be picked up by intermediate
1004 ##### pages). I think that's safest when dealing with frames, targets etc.
1005 ##### (at least until I think of a better way to do it). Problems occur with
1006 ##### mailto links from within small frames, the intermediate page is displayed
1007 ##### within that frame and can't be seen. There is still potential for this to
1008 ##### happen even with html pages - the solution seems to be to somehow tell
1009 ##### the browser from the server side to display the page being sent (i.e.
1010 ##### the intermediate page) in the top level window - I'm not sure if that's
1011 ##### possible - the following line should probably be deleted if that can be done
1012 return $front . $link . $back if $href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/is;
1013
1014
1015 if (($rl == 0) || ($filename =~ /$self->{'process_exp'}/) ||
1016 ($href =~ /\/$/) || ($href =~ /^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
1017 &ghtml::urlsafe ($href);
1018 return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
1019 } else {
1020 # link is to some other type of file (eg image) so we'll
1021 # need to associate that file
1022 return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
1023 }
1024}
1025
1026sub add_file {
1027 my $self = shift (@_);
1028 my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
1029 my ($newname);
1030
1031 my $filename = $href;
1032 if ($base_dir eq "") {
1033 # remove http:/ thereby leaving one slash at the start
1034 $filename =~ s/^[^:]*:\///;
1035 }
1036 else {
1037 # remove http://
1038 $filename =~ s/^[^:]*:\/\///;
1039 }
1040
1041 $filename = &util::filename_cat($base_dir, $filename);
1042
1043 # Replace %XX's in URL with decoded value if required.
1044 # Note that the filename may include the %XX in some situations
1045 if ($filename =~ m/\%[A-F0-9]{2}/i) {
1046 if (!-e $filename) {
1047 $filename =~ s/\%([A-F0-9]{2})/pack('C', hex($1))/ige;
1048 }
1049 }
1050
1051 my ($ext) = $filename =~ /(\.[^\.]*)$/;
1052
1053 if ($rl == 0) {
1054 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
1055 return "_httpextlink_&rl=0&el=prompt&href=" . $href . $hash_part;
1056 }
1057 else {
1058 return "_httpextlink_&rl=0&el=direct&href=" . $href . $hash_part;
1059 }
1060 }
1061
1062 if ((!defined $ext) || ($ext !~ /$self->{'assoc_files'}/)) {
1063 return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
1064 }
1065 if ($self->{'rename_assoc_files'}) {
1066 if (defined $self->{'aux_files'}->{$href}) {
1067 $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
1068 $self->{'aux_files'}->{$href}->{'file_num'} . $ext;
1069 } else {
1070 $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
1071 $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
1072 $self->inc_filecount ();
1073 }
1074 $doc_obj->associate_file($filename, $newname, undef, $section);
1075 return "_httpdocimg_/$newname";
1076 } else {
1077 ($newname) = $filename =~ /([^\/\\]*)$/;
1078 # Make sure this name is a valid utf8 filename
1079 ## &unicode::ensure_utf8(\$newname);
1080 $newname =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
1081
1082 $doc_obj->associate_file($filename, $newname, undef, $section);
1083
1084 my $newname_url = $newname;
1085 $newname_url =~ s/%/%25/g;
1086 return "_httpdocimg_/$newname_url";
1087 }
1088}
1089
1090
1091
1092sub format_link {
1093 my $self = shift (@_);
1094 my ($link, $base_dir, $file) = @_;
1095
1096 my ($before_hash, $hash_part) = $link =~ /^([^\#]*)(\#?.*)$/;
1097
1098 $hash_part = "" if !defined $hash_part;
1099 if (!defined $before_hash || $before_hash !~ /[\w\.\/]/) {
1100 my $outhandle = $self->{'outhandle'};
1101 print $outhandle "HTMLPlugin: ERROR - badly formatted tag ignored ($link)\n"
1102 if $self->{'verbosity'};
1103 return ($link, "", 0);
1104 }
1105
1106 if ($before_hash =~ s@^((?:http|ftp|file)://)@@i) {
1107 my $type = $1;
1108
1109 if ($link =~ /^(http|ftp):/i) {
1110 # Turn url (using /) into file name (possibly using \ on windows)
1111 my @http_dir_split = split('/', $before_hash);
1112 $before_hash = &util::filename_cat(@http_dir_split);
1113 }
1114
1115 $before_hash = $self->eval_dir_dots($before_hash);
1116
1117 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
1118
1119 my $rl = 0;
1120 $rl = 1 if (-e $linkfilename);
1121
1122 # make sure there's a slash on the end if it's a directory
1123 if ($before_hash !~ /\/$/) {
1124 $before_hash .= "/" if (-d $linkfilename);
1125 }
1126
1127 return ($type . $before_hash, $hash_part, $rl);
1128
1129 } elsif ($link !~ /^(mailto|news|gopher|nntp|telnet|javascript):/i && $link !~ /^\//) {
1130 if ($before_hash =~ s@^/@@ || $before_hash =~ /\\/) {
1131
1132 # the first directory will be the domain name if file_is_url
1133 # to generate archives, otherwise we'll assume all files are
1134 # from the same site and base_dir is the root
1135
1136 if ($self->{'file_is_url'}) {
1137 my @dirs = split /[\/\\]/, $file;
1138 my $domname = shift (@dirs);
1139 $before_hash = &util::filename_cat($domname, $before_hash);
1140 $before_hash =~ s@\\@/@g; # for windows
1141 }
1142 else
1143 {
1144 # see if link shares directory with source document
1145 # => turn into relative link if this is so!
1146
1147 if ($ENV{'GSDLOS'} =~ /^windows/i) {
1148 # too difficult doing a pattern match with embedded '\'s...
1149 my $win_before_hash=$before_hash;
1150 $win_before_hash =~ s@(\\)+@/@g;
1151 # $base_dir is already similarly "converted" on windows.
1152 if ($win_before_hash =~ s@^$base_dir/@@o) {
1153 # if this is true, we removed a prefix
1154 $before_hash=$win_before_hash;
1155 }
1156 }
1157 else {
1158 # before_hash has lost leading slash by this point,
1159 # -> add back in prior to substitution with $base_dir
1160 $before_hash = "/$before_hash";
1161
1162 $before_hash = &util::filename_cat("",$before_hash);
1163 $before_hash =~ s@^$base_dir/@@;
1164 }
1165 }
1166 } else {
1167 # Turn relative file path into full path
1168 my $dirname = &File::Basename::dirname($file);
1169 $before_hash = &util::filename_cat($dirname, $before_hash);
1170 $before_hash = $self->eval_dir_dots($before_hash);
1171 }
1172
1173 my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
1174 # make sure there's a slash on the end if it's a directory
1175 if ($before_hash !~ /\/$/) {
1176 $before_hash .= "/" if (-d $linkfilename);
1177 }
1178 return ("http://" . $before_hash, $hash_part, 1);
1179 } else {
1180 # mailto, news, nntp, telnet, javascript or gopher link
1181 return ($before_hash, "", 0);
1182 }
1183}
1184
1185sub extract_first_NNNN_characters {
1186 my $self = shift (@_);
1187 my ($textref, $doc_obj, $thissection) = @_;
1188
1189 foreach my $size (split /,/, $self->{'first'}) {
1190 my $tmptext = $$textref;
1191 # skip to the body
1192 $tmptext =~ s/.*<body[^>]*>//i;
1193 # remove javascript
1194 $tmptext =~ s@<script.*?</script>@ @sig;
1195 $tmptext =~ s/<[^>]*>/ /g;
1196 $tmptext =~ s/&nbsp;/ /g;
1197 $tmptext =~ s/^\s+//;
1198 $tmptext =~ s/\s+$//;
1199 $tmptext =~ s/\s+/ /gs;
1200 $tmptext = &unicode::substr ($tmptext, 0, $size);
1201 $tmptext =~ s/\s\S*$/&#8230;/; # adds an ellipse (...)
1202 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
1203 }
1204}
1205
1206
1207sub extract_metadata {
1208 my $self = shift (@_);
1209 my ($textref, $metadata, $doc_obj, $section) = @_;
1210 my $outhandle = $self->{'outhandle'};
1211 # if we don't want metadata, we may as well not be here ...
1212 return if (!defined $self->{'metadata_fields'});
1213
1214 # metadata fields to extract/save. 'key' is the (lowercase) name of the
1215 # html meta, 'value' is the metadata name for greenstone to use
1216 my %find_fields = ();
1217
1218 my %creator_fields = (); # short-cut for lookups
1219
1220
1221 foreach my $field (split /,/, $self->{'metadata_fields'}) {
1222 $field =~ s/^\s+//; # remove leading whitespace
1223 $field =~ s/\s+$//; # remove trailing whitespace
1224
1225 # support tag<tagname>
1226 if ($field =~ /^(.*?)<(.*?)>$/) {
1227 # "$2" is the user's preferred gs metadata name
1228 $find_fields{lc($1)}=$2; # lc = lowercase
1229 } else { # no <tagname> for mapping
1230 # "$field" is the user's preferred gs metadata name
1231 $find_fields{lc($field)}=$field; # lc = lowercase
1232 }
1233 }
1234
1235 if (defined $self->{'hunt_creator_metadata'} &&
1236 $self->{'hunt_creator_metadata'} == 1 ) {
1237 my @extra_fields =
1238 (
1239 'author',
1240 'author.email',
1241 'creator',
1242 'dc.creator',
1243 'dc.creator.corporatename',
1244 );
1245
1246 # add the creator_metadata fields to search for
1247 foreach my $field (@extra_fields) {
1248 $creator_fields{$field}=0; # add to lookup hash
1249 }
1250 }
1251
1252
1253 # find the header in the html file, which has the meta tags
1254 $$textref =~ m@<head>(.*?)</head>@si;
1255
1256 my $html_header=$1;
1257
1258 # go through every <meta... tag defined in the html and see if it is
1259 # one of the tags we want to match.
1260
1261 # special case for title - we want to remember if its been found
1262 my $found_title = 0;
1263 # this assumes that ">" won't appear. (I don't think it's allowed to...)
1264 $html_header =~ /^/; # match the start of the string, for \G assertion
1265
1266 while ($html_header =~ m/\G.*?<meta(.*?)>/sig) {
1267 my $metatag=$1;
1268 my ($tag, $value);
1269
1270 # find the tag name
1271 $metatag =~ /(?:name|http-equiv)\s*=\s*([\"\'])?(.*?)\1/is;
1272 $tag=$2;
1273 # in case they're not using " or ', but they should...
1274 if (! $tag) {
1275 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
1276 $tag=$1;
1277 }
1278
1279 if (!defined $tag) {
1280 print $outhandle "HTMLPlugin: can't find NAME in \"$metatag\"\n";
1281 next;
1282 }
1283
1284 # don't need to assign this field if it was passed in from a previous
1285 # (recursive) plugin
1286 if (defined $metadata->{$tag}) {next}
1287
1288 # find the tag content
1289 $metatag =~ /content\s*=\s*([\"\'])?(.*?)\1/is;
1290 $value=$2;
1291
1292 if (! $value) {
1293 $metatag =~ /(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
1294 $value=$1;
1295 }
1296 if (!defined $value) {
1297 print $outhandle "HTMLPlugin: can't find VALUE in \"$metatag\"\n";
1298 next;
1299 }
1300
1301 # clean up and add
1302 $value =~ s/\s+/ /gs;
1303 chomp($value); # remove trailing \n, if any
1304 if (exists $creator_fields{lc($tag)}) {
1305 # map this value onto greenstone's "Creator" metadata
1306 $tag='Creator';
1307 } elsif (!exists $find_fields{lc($tag)}) {
1308 next; # don't want this tag
1309 } else {
1310 # get the user's preferred capitalisation
1311 $tag = $find_fields{lc($tag)};
1312 }
1313 if (lc($tag) eq "title") {
1314 $found_title = 1;
1315 }
1316 print $outhandle " extracted \"$tag\" metadata \"$value\"\n"
1317 if ($self->{'verbosity'} > 2);
1318 if ($tag =~ /date.*/i){
1319 $tag = lc($tag);
1320 }
1321 $doc_obj->add_utf8_metadata($section, $tag, $value);
1322
1323 }
1324
1325 # TITLE: extract the document title
1326 if (exists $find_fields{'title'} && !$found_title) {
1327 # we want a title, and didn't find one in the meta tags
1328 # see if there's a <title> tag
1329 my $title;
1330 my $from = ""; # for debugging output only
1331 if ($html_header =~ /<title[^>]*>([^<]+)<\/title[^>]*>/is) {
1332 $title = $1;
1333 $from = "<title> tags";
1334 }
1335
1336 if (!defined $title) {
1337 $from = "first 100 chars";
1338 # if no title use first 100 or so characters
1339 $title = $$textref;
1340 $title =~ s/^\xFE\xFF//; # Remove unicode byte order mark
1341 $title =~ s/^.*?<body>//si;
1342 # ignore javascript!
1343 $title =~ s@<script.*?</script>@ @sig;
1344 $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
1345 $title =~ s/<[^>]*>/ /g; # remove all HTML tags
1346 $title = substr ($title, 0, 100);
1347 $title =~ s/\s\S*$/.../;
1348 }
1349 $title =~ s/<[^>]*>/ /g; # remove html tags
1350 $title =~ s/&nbsp;/ /g;
1351 $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
1352 $title =~ s/\s+/ /gs; # collapse multiple spaces
1353 $title =~ s/^\s*//; # remove leading spaces
1354 $title =~ s/\s*$//; # remove trailing spaces
1355
1356 $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
1357 $title =~ s/^\s+//s; # in case title_sub introduced any...
1358 $doc_obj->add_utf8_metadata ($section, 'Title', $title);
1359 print $outhandle " extracted Title metadata \"$title\" from $from\n"
1360 if ($self->{'verbosity'} > 2);
1361 }
1362
1363 # add FileFormat metadata
1364 $doc_obj->add_metadata($section,"FileFormat", "HTML");
1365
1366 # Special, for metadata names such as tagH1 - extracts
1367 # the text between the first <H1> and </H1> tags into "H1" metadata.
1368
1369 foreach my $field (keys %find_fields) {
1370 if ($field !~ /^tag([a-z0-9]+)$/i) {next}
1371 my $tag = $1;
1372 if ($$textref =~ m@<$tag[^>]*>(.*?)</$tag[^>]*>@g) {
1373 my $content = $1;
1374 $content =~ s/&nbsp;/ /g;
1375 $content =~ s/<[^>]*>/ /g;
1376 $content =~ s/^\s+//;
1377 $content =~ s/\s+$//;
1378 $content =~ s/\s+/ /gs;
1379 if ($content) {
1380 $tag=$find_fields{"tag$tag"}; # get the user's capitalisation
1381 $tag =~ s/^tag//i;
1382 $doc_obj->add_utf8_metadata ($section, $tag, $content);
1383 print $outhandle " extracted \"$tag\" metadata \"$content\"\n"
1384 if ($self->{'verbosity'} > 2);
1385 }
1386 }
1387 }
1388}
1389
1390
1391# evaluate any "../" to next directory up
1392# evaluate any "./" as here
1393sub eval_dir_dots {
1394 my $self = shift (@_);
1395 my ($filename) = @_;
1396 my $dirsep_os = &util::get_os_dirsep();
1397 my @dirsep = split(/$dirsep_os/,$filename);
1398
1399 my @eval_dirs = ();
1400 foreach my $d (@dirsep) {
1401 if ($d eq "..") {
1402 pop(@eval_dirs);
1403
1404 } elsif ($d eq ".") {
1405 # do nothing!
1406
1407 } else {
1408 push(@eval_dirs,$d);
1409 }
1410 }
1411
1412 # Need to fiddle with number of elements in @eval_dirs if the
1413 # first one is the empty string. This is because of a
1414 # modification to util::filename_cat that supresses the addition
1415 # of a leading '/' character (or \ if windows) (intended to help
1416 # filename cat with relative paths) if the first entry in the
1417 # array is the empty string. Making the array start with *two*
1418 # empty strings is a way to defeat this "smart" option.
1419 #
1420 if (scalar(@eval_dirs) > 0) {
1421 if ($eval_dirs[0] eq ""){
1422 unshift(@eval_dirs,"");
1423 }
1424 }
1425 return &util::filename_cat(@eval_dirs);
1426}
1427
1428sub replace_usemap_links {
1429 my $self = shift (@_);
1430 my ($front, $link, $back) = @_;
1431
1432 $link =~ s/^\.\///;
1433 return $front . $link . $back;
1434}
1435
1436sub inc_filecount {
1437 my $self = shift (@_);
1438
1439 if ($self->{'file_num'} == 1000) {
1440 $self->{'dir_num'} ++;
1441 $self->{'file_num'} = 0;
1442 } else {
1443 $self->{'file_num'} ++;
1444 }
1445}
1446
1447
1448# Extend read_file so that strings like &eacute; are
1449# converted to UTF8 internally.
1450#
1451# We don't convert &lt; or &gt; or &amp; or &quot; in case
1452# they interfere with the GML files
1453
1454sub read_file {
1455 my $self = shift(@_);
1456 my ($filename, $encoding, $language, $textref) = @_;
1457
1458 $self->SUPER::read_file($filename, $encoding, $language, $textref);
1459
1460 # Convert entities to their UTF8 equivalents
1461 $$textref =~ s/&(lt|gt|amp|quot|nbsp);/&z$1;/go;
1462 $$textref =~ s/&([^;]+);/&ghtml::getcharequiv($1,1)/gseo;
1463 $$textref =~ s/&z(lt|gt|amp|quot|nbsp);/&$1;/go;
1464}
1465
14661;
Note: See TracBrowser for help on using the repository browser.