source: gsdl/trunk/perllib/plugins/HTMLPlugin.pm@ 20791

Last change on this file since 20791 was 20791, checked in by kjdon, 15 years ago

new option -processing_tmp_files - if set, then don't store the assicated files using associate_source_file - we don't want to store tmp files in the archivesinf databases

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