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

Last change on this file since 23760 was 23760, checked in by davidb, 13 years ago

Whitespace tidy up

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