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

Last change on this file since 14012 was 14012, checked in by cvs_anon, 17 years ago

modify HTMLPlug to convert old HDL section style to new HDL section style

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