source: main/trunk/greenstone2/perllib/plugins/HTMLPlugin.pm@ 22348

Last change on this file since 22348 was 22348, checked in by kjdon, 14 years ago

store any extracted metadata that has a namespace as ex.ns.meta

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