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

Last change on this file since 22705 was 22689, checked in by mdewsnip, 14 years ago

Trac ticket #634: change so "ftp://" is used instead of "http://" in URLs when importing mirrored content where the domain name contains "ftp". By Richard Managh at DL Consulting Ltd.

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