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

Last change on this file since 21800 was 21800, checked in by kjdon, 14 years ago

added a new option, metadata_field_separator, which specifies what to split on for multi-valued metadata

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