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

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

fix HTMLPlug bug for the Page turning application

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