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

Last change on this file since 14080 was 14080, checked in by lh92, 17 years ago

fix a bug in HTMLPlug for old style HDL

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