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

Last change on this file since 30022 was 30022, checked in by ak19, 9 years ago

Finally committing Dr Bainbridge's suggested fix (tested) to handle the updated Tudor collection when downloaded from the web. The HTML files link to themselves with the <link rel> tag, in which case the HTML files were blocked from being processed and 0 docs were processed. Now HTMLPlugin tests whether any of the linked associated files found are to the document itself, and in such cases, they are not blocked.

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