root/main/trunk/greenstone2/perllib/plugins/HTMLPlugin.pm @ 32325

Revision 32325, 70.9 KB (checked in by ak19, 13 months ago)

Dr Bainbridge worked out the solution to HTMLPlugin not handling embedded base64 encoded images. Fixed!

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