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

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

A few further additions to help windows keep track of c\... and C:\... filenames

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