source: main/branches/64_bit_Greenstone/greenstone2/perllib/plugins/HTMLPlugin.pm@ 23580

Last change on this file since 23580 was 23580, checked in by sjm84, 13 years ago

Merging the latest trunk changes into this branch

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