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

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

Corrected error I made in regex expression used to call replace_images: removed additional parentheses separating | operands

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