source: trunk/gsdl/perllib/plugins/W3ImgPlug.pm@ 6138

Last change on this file since 6138 was 5924, checked in by kjdon, 21 years ago

changed the new metadata to eg WordPlug instead of Word, cos a clash with Image

  • Property svn:keywords set to Author Date Id Revision
File size: 40.9 KB
Line 
1###########################################################################
2#
3# W3ImgPlug.pm -- Context-based image indexing plugin for HTML documents
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) 2001 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# DESCRIPTION:
28#
29# Extracts images and associated text and metadata from
30# web pages as individual documents for indexing. Thumbnails
31# are created from each image for browsing purposes.
32#
33# Options are available for configuring the aggressiveness of the
34# associated text extraction mechanisms. A higher level of
35# aggressiveness will extract more text and consequently
36# may mean lower accuracy (precision); however, it may also
37# retrieve more of the relevant images from the collection (recall).
38# Lower levels of aggressiveness maybe result in slightly faster
39# collection builds at the import stage.
40#
41# W3ImgPlug is a subclass of HTMLPlug (i.e. it will index pages also
42# if required). It can be used in place of HTMLPlug to index both
43# pages and their images.
44#
45# REQUIREMENTS:
46#
47# The ImageMagick image manipulation is used to create
48# thumbnails and extract some image metadata. (Available
49# from http://www.imagemagick.org/)
50#
51# Unix:
52# Many Linux distributions contain ImageMagick.
53#
54# Windows:
55# ImageMagick can be downloaded from the website above.
56# Make sure the system path includes the ImageMagick binaries
57# before using W3ImgPlug.
58#
59# NOTE: NT/2000/XP contain a filesystem utility 'convert.exe'
60# with the same name as the image conversion utility. The
61# ImageMagick FAQ recommends renaming the filesystem
62# utility (e.g. to 'fsconvert.exe') to avoid this clash.
63#
64# USAGE:
65#
66# An image document consists of metadata elements:
67#
68# OriginalFilename, FilePath, Filename, FileExt, FileSize,
69# Width, Height, URL, PageURL, ThumbURL, CacheURL, CachePageURL
70# ImageText, PageTitle
71#
72# Most of these are only useful in format strings (e.g. ThumbURL,
73# Filename, URL, PageURL, CachePageURL).
74#
75# ImageText, as the name suggests contains the indexable text.
76# (unless using the -document_text plugin option)
77#
78# Since image documents are made up of metadata elements
79# alone, format strings are needed to display them properly.
80# NOTE: The receptionist will only display results (e.g. thumbnails)
81# in 4 columns if the format string begins with "<td><table>".
82#
83# The example below takes the user to the image within the
84# source HTML document rather than using a format string
85# on DocumentText to display the image document itself.
86#
87# Example collect.cfg:
88#
89# ...
90#
91# indexes document:ImageText document:text
92# defaultindex document:ImageText
93#
94# collectionmeta .document:ImageText "images"
95# collectionmeta .document:text "documents"
96#
97# ...
98#
99# plugin W3ImgPlug -index_pages -aggressiveness 6
100#
101# ...
102#
103# format SearchVList '<td>{If}{[Title],[link][icon]&nbsp;[Title][[/link],
104# <table><tr><td align="center"><a href="[CachePageURL]">
105# <img src="[ThumbURL]"></a></td></tr><tr><td align="center">
106# <a href="[CachePageURL]"><font size="-1">[OriginalFilename]</font></a>
107# <br>[Width]x[Height]</td></tr></table>}</td>'
108#
109# ...
110#
111
112package W3ImgPlug;
113
114use HTMLPlug;
115use ghtml;
116use unicode;
117use util;
118use parsargv;
119use strict 'subs';
120
121sub BEGIN {
122 @ISA = qw( HTMLPlug );
123}
124
125my $aggressiveness_list =
126 [ { 'name' => "1",
127 'desc' => "{W3ImgPlug.aggressiveness.1}" },
128 { 'name' => "2",
129 'desc' => "{W3ImgPlug.aggressiveness.2}" },
130 { 'name' => "3",
131 'desc' => "{W3ImgPlug.aggressiveness.3}" },
132 { 'name' => "4",
133 'desc' => "{W3ImgPlug.aggressiveness.4}" },
134 { 'name' => "5",
135 'desc' => "{W3ImgPlug.aggressiveness.5}" },
136 { 'name' => "6",
137 'desc' => "{W3ImgPlug.aggressiveness.6}" },
138 { 'name' => "7",
139 'desc' => "{W3ImgPlug.aggressiveness.7}" },
140 { 'name' => "8",
141 'desc' => "{W3ImgPlug.aggressiveness.8}" },
142 { 'name' => "9",
143 'desc' => "{W3ImgPlug.aggressiveness.9}" } ];
144
145my $arguments =
146 [ { 'name' => "aggressiveness",
147 'desc' => "{W3ImgPlug.aggressiveness}",
148 'type' => "int",
149 'list' => $aggressiveness_list,
150 'deft' => "3",
151 'reqd' => "no" },
152 { 'name' => "index_pages",
153 'desc' => "{W3ImgPlug.index_pages}",
154 'type' => "flag",
155 'reqd' => "no" },
156 { 'name' => "no_cache_images",
157 'desc' => "{W3ImgPlug.no_cache_images}",
158 'type' => "flag",
159 'reqd' => "no" },
160 { 'name' => "min_size",
161 'desc' => "{W3ImgPlug.min_size}",
162 'type' => "int",
163 'deft' => "2000",
164 'reqd' => "no" },
165 { 'name' => "min_width",
166 'desc' => "{W3ImgPlug.min_width}",
167 'type' => "int",
168 'deft' => "50",
169 'reqd' => "no" },
170 { 'name' => "min_height",
171 'desc' => "{W3ImgPlug.min_height}",
172 'type' => "int",
173 'deft' => "50",
174 'reqd' => "no" },
175 { 'name' => "thumb_size",
176 'desc' => "{W3ImgPlug.thumb_size}",
177 'type' => "int",
178 'deft' => "100",
179 'reqd' => "no" },
180 { 'name' => "convert_params",
181 'desc' => "{W3ImgPlug.convert_params}",
182 'type' => "string",
183 'deft' => "",
184 'reqd' => "no" },
185 { 'name' => "min_near_text",
186 'desc' => "{W3ImgPlug.min_near_text}",
187 'type' => "int",
188 'deft' => "10",
189 'reqd' => "no" },
190 { 'name' => "max_near_text",
191 'desc' => "{W3ImgPlug.max_near_text}",
192 'type' => "int",
193 'deft' => "400",
194 'reqd' => "no" },
195 { 'name' => "smallpage_threshold",
196 'desc' => "{W3ImgPlug.smallpage_threshold}",
197 'type' => "int",
198 'deft' => "2048",
199 'reqd' => "no" },
200 { 'name' => "textrefs_threshold",
201 'desc' => "{W3ImgPlug.textrefs_threshold}",
202 'type' => "int",
203 'deft' => "2",
204 'reqd' => "no" },
205 { 'name' => "caption_length",
206 'desc' => "{W3ImgPlug.caption_length}",
207 'type' => "int",
208 'deft' => "80",
209 'reqd' => "no" },
210 { 'name' => "neartext_length",
211 'desc' => "{W3ImgPlug.neartext_length}",
212 'type' => "int",
213 'deft' => "300",
214 'reqd' => "no" },
215 { 'name' => "document_text",
216 'desc' => "{W3ImgPlug.document_text}",
217 'type' => "flag",
218 'reqd' => "no" } ];
219
220my $options = { 'name' => "W3ImgPlug",
221 'desc' => "{W3ImgPlug.desc}",
222 'inherits' => "yes",
223 'args' => $arguments };
224
225
226# sub print_usage {
227# print STDERR "\nUsage: plugin W3ImgPlug [options]\n\n";
228# print STDERR " options:\n";
229# print STDERR " -aggressiveness Range of related text extraction techniques to use [4]\n";
230# print STDERR " 1: Filename, path, ALT text only\n";
231# print STDERR " 2: All of 1, plus caption where available\n";
232# print STDERR " 3: All of 2, plus near paragraphs where available\n";
233# print STDERR " 4: All of 3, plus previous headers (<h1>, <h2>...)\n";
234# print STDERR " where available\n";
235# print STDERR " 5: All of 4, plus textual references where available\n";
236# print STDERR " 6: All of 4, plus page metatags (title, keywords, etc)\n";
237# print STDERR " 7: All of 6, 5 and 4 combined\n";
238# print STDERR " 8: All of 7, plus repeat caption, filename, etc (raise \n";
239# print STDERR " ranking of more relevant results)\n";
240# print STDERR " 10: All of 1, plus full text of source page\n";
241# print STDERR "\n";
242# print STDERR " -no_cache_images Don't cache images (point to URL of original)\n";
243# print STDERR " -index_pages Index the pages along with the images.\n";
244# print STDERR " Otherwise reference the pages at the source URL\n";
245# print STDERR " -min_size Bytes. Skip images smaller than this [2000]\n";
246# print STDERR " -min_width Pixels. Skip images narrower than this [50 pixels]\n";
247# print STDERR " -min_height Pixels. Skip images shorter than this [50 pixels]\n";
248# print STDERR " -thumb_size Max thumbnail size. Both width and height [100 pixels]\n";
249# print STDERR " -convert_params Additional parameters for ImageMagicK convert on\n";
250# print STDERR " thumbnail creation. For example, '-raise' will give\n";
251# print STDERR " a three dimensional effect to thumbnail images.\n";
252# print STDERR " -document_text Add image text as document:text (otherwise IndexedText\n";
253# print STDERR " metadata field)\n";
254# print STDERR "\n";
255# print STDERR " Advanced Options (applicability depends on aggressiveness level)\n";
256# print STDERR " -smallpage_threshold Images on pages smaller than this (bytes) will have\n";
257# print STDERR " the page (title, keywords, etc) meta-data added [2048]\n";
258# print STDERR " -textrefs_threshold Threshold for textual references. Lower values mean\n";
259# print STDERR " the algorithm is less strict [2]\n";
260# print STDERR " -caption_length Maximum length of captions (in characters) [100]\n";
261# print STDERR " -neartext_length Target length of near text (in characters) [300]\n";
262# print STDERR " -max_near_text Maximum characters near images to extract [400]\n";
263# print STDERR " -min_near_text Minimum characters of near text or caption to extract [10]\n";
264# print STDERR "\n";
265# print STDERR " Tag set configuration file (XML format):\n";
266# print STDERR " <collectionpath>/etc/W3ImgPlug.cfg \n";
267# print STDERR "\n";
268# print STDERR "\n";
269# print STDERR "W3ImgPlug inherits all of HTMLPlug's functionality and options:\n";
270# HTMLPlug::print_usage();
271# print STDERR "\n";
272# }
273
274sub new {
275 my $class = shift (@_);
276 my $self = new HTMLPlug ($class, @_);
277 $self->{'plugin_type'} = "W3ImgPlug";
278 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
279 my $option_list = $self->{'option_list'};
280 push( @{$option_list}, $options );
281
282 if (!parsargv::parse(\@_,
283 q^aggressiveness/\d/3^, \$self->{'aggressiveness'},
284 q^index_pages^, \$self->{'index_pages'},
285 q^no_cache_images^, \$self->{'no_cache_images'},
286 q^min_size/\d*/2000^, \$self->{'min_img_filesize'},
287 q^min_width/\d*/50^, \$self->{'min_img_width'},
288 q^min_height/\d*/50^, \$self->{'min_img_height'},
289 q^thumb_size/\d*/100^, \$self->{'thumbnail_size'},
290 q^convert_params/.*/ ^, \$self->{'img_convert_param'},
291 q^max_near_text/\d*/400^, \$self->{'maxtext'},
292 q^min_near_text/\d*/10^, \$self->{'mintext'},
293 q^smallpage_threshold/\d*/2048^, \$self->{'smallpage_threshold'},
294 q^textrefs_threshold/\d*/2^, \$self->{'textref_threshold'},
295 q^caption_length/\d*/80^, \$self->{'caption_len'},
296 q^neartext_length/\d*/300^, \$self->{'neartext_len'},
297 q^document_text^, \$self->{'document_text'},
298 "allow_extra_options"
299 )) {
300
301 print STDERR "\nIncorrect options passed to W3ImgPlug, check your collect.cfg configuration file\n";
302 $self->print_txt_usage(""); # Use default resource bundle
303 die "\n";
304 }
305
306 # init class variables
307 $self->{'textref'} = undef; # init by read_file fn
308 $self->{'htdoc_obj'} = undef; # init by process fn
309 $self->{'htpath'} = undef; # init by process fn
310 $self->{'hturl'} = undef; # init by process fn
311 $self->{'plaintext'} = undef; # HTML stripped version - only init if needed by raw_neartext sub
312 $self->{'smallpage'} = 0; # set by process fn
313 $self->{'images_indexed'} = undef; # num of images indexed - if 1 or 2 then we know page is small
314 $self->{'initialised'} = undef; # flag (see set_extraction_options())
315
316 return bless $self, $class;
317}
318
319# if indexing pages, let HTMLPlug do it's stuff
320# image extraction done through read()
321sub process {
322 my ($self, $textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
323 $self->{'imglist'} = ();
324 if ( $self->{'index_pages'} ) {
325 my $ok = $self->SUPER::process($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj);
326 if ( ! $ok ) { return $ok }
327 $self->{'htdoc_obj'} = $doc_obj;
328 }
329 # else use URL for referencing
330 #if ( $file =~ /(.*)[\/\\]/ ) { $self->{'htpath'} = $1; } else { $self->{'htpath'} = $file; }
331
332 $self->{'htpath'} = $base_dir if (-d $base_dir);
333 if ( $file =~ /(.*)[\/\\]/ ) { $self->{'htpath'} .= "/$1"; }
334 $self->{'htpath'} =~ s/\\/\//g; # replace \ with /
335
336 $self->{'hturl'} = "http://$file";
337 $self->{'hturl'} =~ s/\\/\//g; # for windows
338 ($self->{'filename'}) = $file =~ /.*[\/\\](.*)/;
339 ($self->{'base_path'}) = $file =~ /(.*)[\/\\]/i;
340 if ( ( -s "$base_dir/$file") <= $self->{'smallpage_threshold'} ) {
341 $self->{'smallpage'} = 1;
342 } else { $self->{'smallpage'} = 0; }
343
344 if ( defined($self->{'initialised'}) ) { return 1; }
345 else {
346 $self->{'initialised'} = $self->set_extraction_options($base_dir =~ /^(.*?)\/import/i);
347 return $self->{'initialised'};
348 }
349}
350
351# get complex configuration options from configuration files
352# -- $GSDLCOLLECTION/etc/W3ImgPlug.cfg (tag sets for aggr 2+)
353# -- $GSDLHOME/etc/packages/phind/stopword/en/brown.sw (stopwords for aggr 5+)
354
355# If there's no W3ImgPlug.cfg file we'll use the following default values
356my $defaultcfg = '
357<delimitertagset>
358 <setname>Caption</setname>
359 <taggroup>font</taggroup>
360 <taggroup>tt</taggroup>
361 <taggroup>small</taggroup>
362 <taggroup>b</taggroup>
363 <taggroup>i</taggroup>
364 <taggroup>u</taggroup>
365 <taggroup>em</taggroup>
366 <taggroup>td</taggroup>
367 <taggroup>li</taggroup>
368 <taggroup>a</taggroup>
369 <taggroup>p</taggroup>
370 <taggroup>tr</taggroup>
371 <taggroup>center</taggroup>
372 <taggroup>div</taggroup>
373 <taggroup>caption</taggroup>
374 <taggroup>br</taggroup>
375 <taggroup>ul</taggroup>
376 <taggroup>ol</taggroup>
377 <taggroup>table</taggroup>
378 <taggroup>hr</taggroup>
379</delimitertagset>
380
381<delimitertagset>
382 <setname>Neartext</setname>
383 <taggroup>tr|hr|table|h\d|img|body</taggroup>
384 <taggroup>td|tr|hr|table|h\d|img|body</taggroup>
385 <taggroup>p|br|td|tr|hr|table|h\d|img|body</taggroup>
386 <taggroup>font|p|i|b|em|img</taggroup>
387</delimitertagset>
388';
389
390sub set_extraction_options() {
391 my ($self, $collpath) = @_;
392 my ($filepath);
393
394 print {$self->{'outhandle'}} "W3ImgPlug: Initialising\n"
395 if $self->{'verbosity'} > 1;
396 # etc/W3ImgPlug.cfg (XML)
397 # tag sets for captions and neartext
398 if ( $self->{'aggressiveness'} > 1 && $self->{'aggressiveness'} != 9 ) {
399 $self->{'delims'} = [];
400 $self->{'cdelims'} = [];
401 my ($cfg, @tagsets, $tagset, $type, @delims);
402
403 $filepath = "$collpath/etc/W3ImgPlug.cfg";
404 if ( open CFG, "<$filepath" ) {
405 while (<CFG>) { $cfg .= $_ }
406 close CFG;
407 } else {
408 $cfg = $defaultcfg;
409 }
410
411 (@tagsets) =
412 $cfg =~ /<delimitertagset>(.*?)<\/delimitertagset>/igs;
413 foreach $tagset ( @tagsets ) {
414 ($type) = $tagset =~ /<setname>(.*?)<\/setname>/i;
415 if ( lc($type) eq "caption" ) {
416 (@{$self->{'cdelims'}}) = $tagset =~ /<taggroup>(.*?)<\/taggroup>/igs;
417 }
418 elsif ( lc($type) eq "neartext" ) {
419 (@{$self->{'delims'}}) = $tagset =~ /<taggroup>(.*?)<\/taggroup>/igs;
420 }
421 }
422
423 # output a warning if there seem to be no delimiters
424 if ( scalar(@{$self->{'cdelims'}} == 0)) {
425 print {$self->{'outhandle'}} "W3ImgPlug: Warning: no caption delimiters found in $filepath\n";
426 }
427 if ( scalar(@{$self->{'delims'}} == 0)) {
428 print {$self->{'outhandle'}} "W3ImgPlug: Warning: no neartext delimiters found in $filepath\n";
429 }
430 }
431
432 # get stop words for textual reference extraction
433 # TODO: warnings scroll off. Would be best to output them again at end of import
434 if ( $self->{'aggressiveness'} >=5 && $self->{'aggressiveness'} != 9 ) {
435 $self->{'stopwords'} = ();
436 $filepath = &util::filename_cat($ENV{'GSDLHOME'}, "etc", "packages", "phind", "stopword", "en", "brown.sw");
437 if ( open STOPWORDS, "<$filepath" ) {
438 while ( <STOPWORDS> ) {
439 chomp;
440 $self->{'stopwords'}{$_} = 1;
441 }
442 close STOPWORDS;
443 } else {
444 print {$self->{'outhandle'}} "W3ImgPlug: Warning: couldn't open stopwords file at $filepath ($!)\n";
445 }
446
447 }
448
449 if ( $self->{'neartext_len'} > $self->{'maxtext'} ) {
450 $self->{'maxtext'} = $self->{'neartext_len'} * 1.33;
451 print {$self->{'outhandle'}} "W3ImgPlug: Warning: adjusted max_text to $self->{'maxtext'}\n";
452 }
453 if ( $self->{'caption_len'} > $self->{'maxtext'} ) {
454 $self->{'maxtext'} = $self->{'caption_len'} * 1.33;
455 print {$self->{'outhandle'}} "W3ImgPlug: Warning: adjusted max_text to $self->{'maxtext'}\n";
456 }
457
458 return 1;
459}
460
461# return number of files processed, undef if can't process
462# Note that $base_dir might be "" and that $file might
463# include directories
464sub read {
465 my ($self, $pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs) = (@_);
466 my ($doc_obj, $section, $filepath, $imgtag, $pos, $context, $numdocs, $tndir, $imgs);
467 # forward normal read (runs HTMLPlug if index_pages T)
468 my $ok = $self->SUPER::read($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs);
469 if ( ! $ok ) { return $ok }
470
471 my $outhandle = $self->{'outhandle'};
472 my $textref = $self->{'textref'};
473 my $htdoc_obj = $self->{'htdoc_obj'};
474 $numdocs = 0;
475 $base_dir =~ /(.*)\/.*/;
476 $tndir = "$1/archives/thumbnails"; # TODO: this path shouldn't be hardcoded?
477 &util::mk_all_dir($tndir) unless -e "$tndir";
478
479 $imgs = \%{$self->{'imglist'}};
480 my $nimgs = $self->get_img_list($textref);
481 $self->{'images_indexed'} = $nimgs;
482 if ( $nimgs > 0 ) {
483 my @fplist = (sort { $imgs->{$a}{'pos'} <=> $imgs->{$b}{'pos'} } keys %{$imgs});
484 my $i = 0;
485 foreach $filepath ( @fplist ) {
486 $pos = $imgs->{$filepath}{'pos'};
487 $context = substr ($$textref, $pos - 50, $pos + 50); # grab context (quicker)
488 ($imgtag) = ($context =~ /(<(?:img|a|body)\s[^>]*$filepath[^>]*>)/is );
489 if (! defined($imgtag)) { $imgtag = $filepath }
490 print $outhandle "W3ImgPlug: extracting $filepath\n"
491 if ( $self->{'verbosity'} > 1 );
492 $doc_obj = new doc ("", "indexed_doc");
493 $section = $doc_obj->get_top_section();
494 $prevpos = ( $i == 0 ? 0 : $imgs->{$fplist[$i - 1]}{'pos'});
495 $nextpos = ( $i >= ($nimgs -1) ? -1 : $imgs->{$fplist[$i + 1]}{'pos'} );
496
497 $self->extract_image_info($imgtag, $filepath, $textref, $doc_obj, $section, $tndir, $prevpos, $nextpos);
498 $processor->process($doc_obj);
499 $numdocs++;
500 $i++;
501 }
502 return $numdocs;
503 } else {
504 print $outhandle "W3ImgPlug: No images from $file indexed\n"
505 if ( $self->{'verbosity'} > 2 );
506 return 1;
507 }
508
509}
510
511# for every valid image tag
512# 1. extract related text and image metadata
513# 2. add this as document meta-data
514# 3. add assoc image(s) as files
515#
516sub extract_image_info {
517 my $self = shift (@_);
518 my ($tag, $id, $textref, $doc_obj, $section, $tndir, $prevpos, $nextpos) = (@_);
519 my ($filename, $orig_fp, $fn, $ext, $reltext, $relreltext, $crcid, $imgs,
520 $thumbfp, $pagetitle, $alttext, $filepath, $aggr);
521 $aggr = $self->{'aggressiveness'};
522 $imgs = \%{$self->{'imglist'}};
523 $filepath = $imgs->{$id}{'relpath'};
524 ($filename) = $filepath =~ /([^\/\\]+)$/s;
525 ($orig_fp) = "$self->{'base_path'}/$filepath";
526 $orig_fp =~ tr/+/ /;
527 $orig_fp =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; # translate %2E to space, etc
528 $orig_fp =~ s/\\/\//g;
529 $filepath = "$self->{'htpath'}/$filepath";
530 ($onlyfn) = $filename =~ /([^\\\/]*)$/;
531 ($fn, $ext) = $onlyfn =~ /(.*)\.(.*)/;
532 $fn = lc $fn; $ext = lc $ext;
533 ($reltext) = "<tr><td>GifComment</td><td>" . `identify $filepath -ping -format "%c"` . "</td></tr>\n"
534 if ($ext eq "gif");
535 $reltext .= "<tr><td>FilePath</td><td>$orig_fp</td></tr>\n";
536
537 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
538 $crcid = "$fn.$ext." . $self->{'next_crcid'}++;
539 } else { ($crcid) = `cksum $filepath` =~ /^(\d+)/; }
540 $thumbfp = "$tndir/tn_$crcid.jpg";
541 `convert -flatten -filter Hanning $self->{'img_convert_param'} -geometry "$self->{'thumbnail_size'}x$self->{'thumbnail_size'}>" $filepath $thumbfp` unless -e $thumbfp;
542 if ( ! (-e $thumbfp) ) {
543 print STDERR "W3ImgPlug: 'convert' failed. Check ImageMagicK binaries are installed and working correctly\n"; return 0;
544 }
545
546 # shove in full text (tag stripped or unstripped) if settings require it
547 if ( $aggr == 10) {
548 $reltext = "<tr><td>AllPage</td><td>" . $$textref . "</td><tr>\n"; # level 10 (all text, verbatim)
549 } else {
550 $pagetitle = $self->get_meta_value("title", $textref);
551 ($alttext) = $tag =~ /\salt\s*=\s*(?:\"|\')(.+?)(?:\"|\')/is;
552 if ( defined($alttext) && length($alttext) > 1) {
553 $reltext .= "<tr><td>ALTtext</td><td>$alttext</td></tr>\n"; }
554 $reltext .= "<tr><td>SplitCapitalisation</td><td>" .
555 $self->split_filepath($orig_fp) . "</td></tr>\n";
556
557 # get caption/tag based near text (if appropriate)
558 if ( $aggr > 1 ) {
559 if ( $aggr >= 2 ) {
560 $reltext .=
561 $self->extract_caption_text($tag, $textref, $prevpos, $imgs->{$id}{'pos'}, $nextpos);
562 $relreltext = $reltext;
563 }
564 # repeat the filepath, alt-text, caption, etc
565 if ( $aggr == 8 ) {
566 $reltext .= $relreltext;
567 }
568 if ( $aggr >= 3 ) {
569 $reltext .=
570 $self->extract_near_text($tag, $textref, $prevpos, $imgs->{$id}{'pos'}, $nextpos);
571 }
572
573 # get page metadata (if appropriate)
574 if ( $aggr >= 6 || ( $aggr >= 2 &&
575 ( $self->{'images_indexed'} < 2 ||
576 ($self->{'smallpage'} == 1 && $self->{'images_indexed'} < 6 )))) {
577 $reltext .= $self->get_page_metadata($textref);
578 }
579 # textual references
580 if ( $aggr == 5 || $aggr >= 7) {
581 if ( length($relreltext) > ($self->{'caption_len'} * 2) ) {
582 $reltext .= $self->get_textrefs($relreltext, $textref, $prevpos, $imgs->{$id}{'pos'}, $nextpos); }
583 else {
584 $reltext .= $self->get_textrefs($reltext, $textref, $prevpos, $imgs->{$id}{'pos'}, $nextpos);
585 }
586 }
587 } # aggr > 1
588 } # aggr != 10
589
590 $doc_obj->set_OID($crcid);
591 $doc_obj->associate_file($thumbfp, "$fn.thumb.jpg", undef, $section);
592 $doc_obj->add_metadata($section, "OriginalFilename", $filename);
593 $doc_obj->add_metadata($section, "FilePath", $orig_fp);
594 $doc_obj->add_metadata($section, "Filename", $fn);
595 $doc_obj->add_metadata($section, "FileExt", $ext);
596 $doc_obj->add_metadata($section, "FileSize", $imgs->{$id}{'filesize'});
597 $doc_obj->add_metadata($section, "Width", $imgs->{$id}{'width'});
598 $doc_obj->add_metadata($section, "Height", $imgs->{$id}{'height'});
599 $doc_obj->add_metadata($section, "URL", "http://$orig_fp");
600 $doc_obj->add_metadata($section, "PageURL", $self->{'hturl'});
601 $doc_obj->add_metadata($section, "PageTitle", $pagetitle);
602 $doc_obj->add_metadata($section, "ThumbURL",
603 "_httpcollection_/index/assoc/[archivedir]/$fn.thumb.jpg");
604
605 if ( $self->{'document_text'} ) {
606 $doc_obj->add_utf8_text($section, "<table border=1>\n$reltext</table>");
607 } else {
608 $doc_obj->add_metadata($section, "ImageText", "<table border=1>\n$reltext</table>\n");
609 }
610
611 if ( $self->{'index_pages'} ) {
612 my ($cache_url) = "_httpdoc_&d=" . $self->{'htdoc_obj'}->get_OID();
613 if ( $imgs->{$id}{'anchored'} ) {
614 my $a_name = $id;
615 $a_name =~ s/[\/\\\:\&]/_/g;
616 $cache_url .= "#gsdl_$a_name" ;
617 }
618 $doc_obj->add_utf8_metadata($section, "CachePageURL", $cache_url);
619 }
620 if ( ! $self->{'no_cache_images'} ) {
621 $onlyfn = lc $onlyfn;
622 $doc_obj->associate_file($filepath, $onlyfn, undef, $section);
623 $doc_obj->add_utf8_metadata($section, "CacheURL",
624 "_httpcollection_/index/assoc/[archivedir]/$onlyfn");
625 }
626 return 1;
627}
628
629sub get_page_metadata {
630 my ($self, $textref) = (@_);
631 my (@rval);
632 $rval[0] = $self->get_meta_value("title", $textref);
633 $rval[1] = $self->get_meta_value("keywords", $textref);
634 $rval[2] = $self->get_meta_value("description", $textref);
635 $rval[3] = $self->{'filename'};
636
637 return wantarray ? @rval : "<tr><td>PageMeta</td><td>@rval</td></tr>\n" ;
638}
639
640# turns LargeCatFish into Large,Cat,Fish so MG sees the separate words
641sub split_filepath {
642 my ($self, $filepath) = (@_);
643 my (@words) = $filepath =~ /([A-Z][a-z]+)/g;
644 return join(',', @words);
645}
646
647# finds and extracts sentences
648# that seem to be on the same topic
649# as other related text (correlations)
650# and textual references (e.g. in figure 3 ...)
651sub get_textrefs {
652 my ($self, $reltext, $textref, $prevpos, $pos, $nextpos) = (@_);
653 my ($maxtext, $mintext, $startpos, $context_size, $context);
654
655 my (@relwords, @refwords, %sentences, @pagemeta);
656
657 # extract larger context
658 $maxtext = $self->{'maxtext'};
659 $startpos = $pos - ($maxtext * 4);
660 $context_size = $maxtext*10;
661 if ($startpos < $prevpos ) { $startpos = $prevpos }
662 if ($nextpos != -1 && $context_size > ( $nextpos - $startpos )) { $context_size = ($nextpos - $startpos) }
663 $context = substr ( $$textref, $startpos, $context_size );
664 $context =~ s/<.*?>//gs;
665 $context =~ s/^.*>(.*)/$1/gs;
666 $context =~ s/(.*)<.*$/$1/gs;
667
668 # get page meta-data (if not already included)
669 if ( $self->{'aggressiveness'} == 5 && ! $self->{'smallpage'} ) {
670 @pagemeta = $self->get_page_metadata($textref);
671 foreach $value ( @pagemeta ) {
672 $context .= "$value."; # make each into psuedo-sentence
673 }
674 }
675
676 # TODO: this list is not exhaustive
677 @refwords = ( '(?:is|are)? ?(?:show(?:s|n)|demonstrate(?:d|s)|explains|features) (?:in|by|below|above|here)',
678 '(?:see)? (?:figure|table)? (?:below|above)');
679
680 # extract general references
681 foreach $rw ( @refwords ) {
682 while ( $context =~ /[\.\?\!\,](.*?$rw\W.*?[\.\?\!\,])/ig ) {
683 $sentence = $1;
684 $sentence =~ s/\s+/ /g;
685 $sentences{$sentence}+=2;
686 }
687 }
688 # extract specific (figure, table) references by number
689 my ($fignum) = $context =~ /[\.\?\!].*?(?:figure|table)s?[\-\_\ \.](\d+\w*)\W.*?[\.\?\!]/ig;
690 if ( $fignum ) {
691 foreach $rw ( @refwords ) {
692 while ( $context =~ /[\.\?\!](.*?(figure|table)[\-\_\ \.]$fignum\W.*?[\.\?\!])/ig ) {
693 $sentence = $1;
694 $sentence =~ s/\s+/ /g;
695 $sentences{$sentence}+=4;
696 }
697 }
698 }
699
700 # sentences with occurances of important words
701 @relwords = $reltext =~ /([a-zA-Z]{4,})/g; # take out small words
702 foreach $word ( @relwords ) {
703 if ( $self->{'stopwords'}{$word} ) { next } # skip stop words
704 while ( $context =~ /([^\.\?\!]*?$word\W.*?[\.\?\!])/ig ) {
705 $sentence = $1;
706 $sentence =~ s/\s+/ /g;
707 $sentences{$sentence}++;
708 }
709 }
710 foreach $sentence ( keys %sentences ) {
711 if ($sentences{$sentence} < $self->{'textref_threshold'}) {
712 delete $sentences{$sentence};
713 }
714 }
715 my ($rval) = join "<br>\n", (keys %sentences);
716 if ( $rval && length($rval) > 5 ) {
717 return ( "<tr><td>TextualReferences</td><td>" . $rval . "</td></tr>\n") }
718 else { return "" }
719}
720
721# handles caption extraction
722# calling the extractor with different
723# tags and choosing the best candidate caption
724sub extract_caption_text {
725 my ($self, $tag, $textref, $prevpos, $pos, $nextpos) = (@_);
726 my (@neartext, $len, $hdelim, $goodlen,
727 $startpos, $context, $context_size);
728
729 $mintext = $self->{'mintext'};
730 $goodlen = $self->{'caption_len'};
731
732 # extract a context to extract near text from (faster)
733 $context_size = $self->{'maxtext'}*3;
734 $startpos = $pos - ($context_size / 2);
735 if ($startpos < $prevpos ) { $startpos = $prevpos }
736 if ($nextpos != -1 && $context_size > ( $nextpos - $startpos ))
737 { $context_size = ($nextpos - $startpos) }
738
739 $context = substr ( $$textref, $startpos, $context_size );
740 $context =~ s/<!--.*?-->//gs;
741 $context =~ s/^.*-->(.*)/$1/gs;
742 $context =~ s/(.*)<!--.*$/$1/gs;
743
744 # try stepping through markup delimiter sets
745 # and selecting the best one
746 foreach $hdelim ( @{ $self->{'cdelims'} } ) {
747 @neartext = $self->extract_caption($tag, $hdelim, \$context);
748 $len = length(join("", @neartext));
749 last if ($len >= $mintext && $len <= $goodlen);
750 }
751 # reject if well over reasonable length
752 if ( $len > $goodlen ) {
753 @neartext = [];
754 }
755 $neartext[0] = " " if (! defined $neartext[0]);
756 $neartext[1] = " " if (! defined $neartext[1]);
757 return "<tr><td>Caption</td><td>" . (join ",", @neartext) . "</td></tr>\n"; # TODO: the | is for testing purposes
758} # end extract_caption_text
759
760# the previous section header often gives a bit
761# of context to the section that the image is
762# in (invariably the header is before/above the image)
763# so extract the text of the closest header above the image
764#
765# this fn just gets all the headers above the image, within the context window
766sub get_prev_header {
767 my ($self, $pos, $textref) = (@_);
768 my ($rhtext);
769 while ( $$textref =~ /<h\d>(.*?)<\/h\d>/sig ) {
770 # only headers before image
771 if ((pos $$textref) < $pos) {
772 $rhtext .= "$1, ";
773 }
774 }
775 if ( $rhtext ) { return "Header($rhtext)" }
776 else { return "" }
777}
778
779# not the most robust tag stripping
780# regexps (see perl.com FAQ) but good enough
781#
782# used by caption & tag-based near text algorithms
783sub strip_tags {
784 my ( $self, $value ) = @_;
785 if ( ! defined($value) ) { $value = "" } # handle nulls
786 else {
787 $value =~ s/<.*?>//gs; # strip all html tags
788 $value =~ s/\s+/\ /g; # remove extra whitespace
789 $value =~ s/\&\w+\;//g; # remove &nbsp; etc
790 }
791 return $value;
792}
793
794# uses the given tag(s) to identify
795# the caption near to the image
796# (below, above or both below and above)
797sub extract_caption {
798 my ($self, $tag, $bound_tag, $contextref) = (@_);
799 my (@nt, $n, $etag, $gotcap);
800 return ("", "") if ( ! ($$contextref =~ /\Q$tag/) );
801
802 $nt[0] = $`;
803 $nt[1] = $';
804 $gotcap = 0;
805
806 # look before the image for a boundary tag
807 ($etag, $nt[0]) = $nt[0] =~ /<($bound_tag)[\s]?.*?>(.*?)$/is;
808 # if bound_tag too far from the image, then prob not caption
809 # (note: have to allow for tags, so multiply by 3
810 if ( $etag && length($nt[0]) < ($self->{'caption_len'} * 3) ) {
811 if ( $nt[0] =~ /<\/$etag>/si ) {
812 # the whole caption is above the image: <tag>text</tag><img>
813 ($nt[0]) =~ /<(?:$etag)[\s]?.*?>(.*?)<\/$etag>/is;
814 $nt[0] = $self->strip_tags($nt[0]);
815 if ( length($nt[0]) > $self->{'mintext'} ) {
816 $gotcap = 1;
817 $nt[1] = "";
818 }
819
820 } elsif ( $nt[1] =~ /<\/$etag>/si) {
821 # the caption tag covers image: <tag>text?<img>text?</tag>
822 ($nt[1]) = $nt[1] =~ /(.*?)<\/$etag>/si;
823 $nt[0] = $self->strip_tags($nt[0] . $nt[1]);
824 if ( length($nt[0]) > $self->{'mintext'} ) {
825 $gotcap = 2;
826 $nt[1] = "";
827 }
828 }
829 }
830 # else try below the image
831 if ( ! $gotcap ) {
832 # the caption is after the image: <img><tag>text</tag>
833 ($etag, $nt[1]) = $nt[1] =~ /^.*?<($bound_tag)[\s]?.*?>(.*)/is;
834 if ( $etag && $nt[1] =~ /<\/$etag>/s) {
835 ($nt[1]) = $nt[1] =~ /(.*?)<\/$etag>/si;
836 $gotcap = 3;
837 $nt[0] = "";
838 $nt[1] = $self->strip_tags($nt[1]);
839 }
840 }
841 if ( ! $gotcap ) { $nt[0] = $nt[1] = "" }
842 else {
843 # strip part-tags
844 $nt[0] =~ s/^.*>//s;
845 $nt[1] =~ s/<.*$//s;
846 }
847 my ($type);
848 if ( $gotcap == 0 ) { return ("nocaption", "") }
849 elsif ( $gotcap == 1 ) { $type = "captionabove:" }
850 elsif ( $gotcap == 2 ) { $type = "captioncovering:" }
851 elsif ( $gotcap == 3 ) { $type = "captionbelow:" }
852 return ($type, $nt[0], $nt[1]);
853}
854
855# tag-based near text
856#
857# tries different tag sets
858# and chooses the best one
859sub extract_near_text {
860 my ($self, $tag, $textref, $prevpos, $pos, $nextpos) = (@_);
861 my (@neartext, $len, $hdelim, $maxtext, $mintext, $goodlen,
862 @bestlen, @best, $startpos, $context, $context_size,
863 $dist, $bdist, $best1, $i, $nt);
864 $bestlen[0] = $bestlen[1] = 0; $bestlen[2] = $bdist = 999999;
865 $best[0] = $best[1] = $best[2] = "";
866 $maxtext = $self->{'maxtext'};
867 $mintext = $self->{'mintext'};
868 $goodlen = $self->{'neartext_len'};
869
870 # extract a context to extract near text from (faster)
871 $context_size = $maxtext*4;
872 $startpos = $pos - ($context_size / 2);
873 if ($startpos < $prevpos ) { $startpos = $prevpos }
874 if ($nextpos != -1 && $context_size > ( $nextpos - $startpos ))
875 { $context_size = ($nextpos - $startpos) }
876 $context = substr ( $$textref, $startpos, $context_size );
877 $context =~ s/<!--.*?-->//gs;
878 $context =~ s/^.*-->(.*)/$1/gs;
879 $context =~ s/(.*)<!--.*$/$1/gs;
880
881 # try stepping through markup delimiter sets
882 # and selecting the best one
883 foreach $hdelim ( @{ $self->{'delims'} } ) {
884 @neartext = $self->extract_tagged_neartext($tag, $hdelim, \$context);
885 $nt = join("", @neartext);
886 $len = length($nt);
887 # Priorities:
888 # 1. Greater than mintext
889 # 2. Less than maxtext
890 # 3. Closest to goodlen
891 if ( $len <= $goodlen && $len > $bestlen[0] ) {
892 $bestlen[0] = $len;
893 $best[0] = $hdelim;
894 } elsif ( $len >= $maxtext && $len < $bestlen[2] ) {
895 $bestlen[2] = $len;
896 $best[2] = $hdelim;
897 } elsif ( $len >= $bestlen[0] && $len <= $bestlen[2] ) {
898 $dist = abs($goodlen - $len);
899 if ( $dist < $bdist ) {
900 $bestlen[1] = $len;
901 $best[1] = $hdelim;
902 $bdist = $dist;
903 }
904 }
905 }
906 $best1 = 2;
907 foreach $i ( 0..2 ) {
908 if ( $bestlen[$i] == 999999 ) { $bestlen[$i] = 0 }
909 $dist = abs($goodlen - $bestlen[$i]);
910 if ( $bestlen[$i] > $mintext && $dist <= $bdist ) {
911 $best1 = $i;
912 $bdist = $dist;
913 }
914 }
915 @neartext = $self->extract_tagged_neartext($tag, $best[$best1], \$context);
916 if ( $bestlen[$best1] > $maxtext ) {
917 # truncate on word boundary if too much text
918 my $hmax = $maxtext / 2;
919 ($neartext[0]) = $neartext[0] =~ /([^\s]*.{1,$hmax})$/s;
920 ($neartext[1]) = $neartext[1] =~ /^(.{1,$hmax}[^\s]*)/s;
921 } elsif ( $bestlen[$best1] < $mintext ) {
922 # use plain text extraction if tags failed (e.g. usable tag outside context)
923 print {$self->{'outhandle'}} "W3ImgPlug: Fallback to plain-text extraction for $tag\n"
924 if $self->{'verbosity'} > 2;
925 $neartext[0] = "<tr><td>RawNeartext</td><td>" . $self->extract_raw_neartext($tag, $textref) . "</td></tr>";
926 $neartext[1] = "";
927 }
928 # get previous header if available
929 $neartext[0] .= "<br>\n" .
930 $self->get_prev_header($pos, \$context) if ( $self->{'aggressiveness'} >= 4 );
931 $neartext[0] = " " if (! defined $neartext[0]);
932 $neartext[1] = " " if (! defined $neartext[1]);
933
934 return "<tr><td>NearText</td><td>" . (join "|", @neartext) . "</td></tr>\n"; # TODO: the | is for testing purposes
935} # end extract_near_text
936
937# actually captures tag-based
938# near-text given a tag set
939sub extract_tagged_neartext {
940 my ($self, $tag, $bound_tag, $textref) = (@_);
941 return "" if ( ! ($$textref =~ /\Q$tag/) );
942 my (@nt, $delim, $pre_tag, $n);
943 $nt[0] = $`;
944 $nt[1] = $';
945
946 # get text after previous image tag
947 $nt[0] =~ s/.*<($bound_tag)[^>]*>(.*)/$2/is; # get rid of preceding text
948 if (defined($1)) { $delim = $1 }
949 $pre_tag = $bound_tag;
950
951 if (defined($delim)) {
952 # we want to try and use the end tag of the previous delimiter
953 # (put it on the front of the list)
954 $pre_tag =~ s/(^|\|)($delim)($|\|)//i; # take it out
955 $pre_tag =~ s/\|\|/\|/i; # replace || with |
956 $pre_tag = $delim . "|" . $pre_tag; # put it on the front
957 }
958
959 # get text before next image tag
960 $nt[1] =~ s/<\/?(?:$pre_tag)[^>]*>.*//is; # get rid of stuff after first delimiter
961
962 # process related text
963 for $n (0..1) {
964 if ( defined($nt[$n]) ) {
965 $nt[$n] =~ s/<.*?>//gs; # strip all html tags
966 $nt[$n] =~ s/\s+/\ /gs; # remove extra whitespace
967 $nt[$n] =~ s/\&\w+\;//sg; # remove &nbsp; etc
968 # strip part-tags
969 if ( $n == 0 ) { $nt[0] =~ s/^.*>//s }
970 if ( $n == 1 ) { $nt[1] =~ s/<.*$//s }
971 } else { $nt[$n] = ""; } # handle nulls
972 }
973 return @nt;
974}
975
976# this function is fall-back
977# if tags aren't suitable.
978#
979# extracts a fixed length of characters
980# either side of image tag (on word boundary)
981sub extract_raw_neartext {
982 my ($self, $tag, $textref) = (@_);
983 my ($rawtext, $startpos, $fp);
984 my $imgs = \%{$self->{'imglist'}};
985 ($fp) = $tag =~ /([\w\\\/]+\.(?:gif|jpe?g|png))/is;
986 if (! $fp) { return " " };
987 # if the cached, plain-text version isn't there, then create it
988 $self->init_plaintext($textref) unless defined($self->{'plaintext'});
989
990 # take the closest maxtext/2 characters
991 # either side of the tag (by word boundary)
992 return "" if ( ! exists $imgs->{$fp}{'rawpos'} );
993 $startpos = $imgs->{$fp}{'rawpos'} - (($self->{'maxtext'} / 2) + 20);
994 if ( $startpos < 0 ) { $startpos = 0 }
995 $rawtext = substr $self->{'plaintext'}, $startpos, $self->{'maxtext'} + 20;
996 $rawtext =~ s/\s\s/ /g;
997
998 return $rawtext;
999}
1000
1001# init plaintext variable for HTML-stripped version
1002# (for full text index/raw assoc text extraction)
1003sub init_plaintext {
1004 my ($self, $textref) = (@_);
1005 my ($page, $fp);
1006 my $imgs = \%{$self->{'imglist'}};
1007 $page = $$textref; # make a copy of original
1008
1009 # strip tags around image filenames so they don't get zapped
1010 $page =~ s/<\w+\s+.*?([\w\/\\]+\.(?:gif|jpe?g|png))[^>]*>/\"$1\"/gsi;
1011 $page =~ s/<.*?>//gs;
1012 $page =~ s/&nbsp;/ /gs;
1013 $page =~ s/&amp;/&/gs; #TODO: more &zzz; replacements (except &lt;, $gt;)
1014
1015 # get positions and strip images
1016 while ( $page =~ /([^\s\'\"]+\.(jpe?g|gif|png))/ig ) {
1017 $fp = $1;
1018 if ( $imgs->{$fp}{'exists'} ) {
1019 $imgs->{$fp}{'rawpos'} = pos $page;
1020 }
1021 $page =~ s/\"$fp\"//gs;
1022 }
1023 $self->{'plaintext'} = $page;
1024}
1025
1026# finds and filters images based on size
1027# (dimensions, height, filesize) and existence
1028#
1029# looks for image filenames (.jpg, .gif, etc)
1030# and checks for existence on disk
1031# (hence supports most JavaScript images)
1032sub get_img_list {
1033 my $self = shift (@_);
1034 my ($textref) = (@_);
1035 my ($filepath, $relpath, $abspath, $pos, $num, $width, $height, $filesize);
1036 my $imgs = \%{$self->{'imglist'}};
1037 while ( $$textref =~ /([^\s\'\"]+\.(jpe?g|gif|png))/ig ) {
1038 $filepath = $1;
1039 $pos = pos $$textref;
1040 next if ( $imgs->{$filepath}{'relpath'} );
1041 $relpath = $filepath;
1042 $relpath =~ s/^http\:\/\///; # remove http:// in case we have mirrored it
1043 $relpath =~ s/\\/\//g; # replace \ with /
1044 $relpath =~ s/^\.\///s; # make "./filepath" into "filepath"
1045 $imgs->{$filepath}{'relpath'} = $relpath;
1046 $abspath = "$self->{'htpath'}/$relpath";
1047
1048 if (! -e $abspath) { next }
1049
1050 # can't modify real filepath var because it
1051 # then can't be located in the page for tag recognition later
1052 ($width, $height) =
1053 `identify $abspath -ping -format "%wx%h"` =~ /^(\d*)x(\d*)$/m;
1054 if (! ($width && $height)) {
1055 print STDERR "W3ImgPlug: ($abspath) 'identify' failed. Check ImageMagicK binaries are installed and working correctly\n"; next;
1056 }
1057 $filesize = (-s $abspath);
1058 if ( $filesize >= $self->{'min_img_filesize'}
1059 && ( $width >= $self->{'min_img_width'} )
1060 && ( $height >= $self->{'min_img_height'} ) ) {
1061
1062 $imgs->{$filepath}{'exists'} = 1;
1063 $imgs->{$filepath}{'pos'} = $pos;
1064 $imgs->{$filepath}{'width'} = $width;
1065 $imgs->{$filepath}{'height'} = $height;
1066 $imgs->{$filepath}{'filesize'} = $filesize;
1067 } else {
1068 print {$self->{'outhandle'}} "W3ImgPlug: skipping $self->{'base_path'}/$relpath: $filesize, $width x $height\n"
1069 if $self->{'verbosity'} > 2;
1070 }
1071 }
1072 $num = 0;
1073 foreach $i ( keys %{$imgs} ) {
1074 if ( $imgs->{$i}{'pos'} ) {
1075 $num++;
1076 } else { delete $imgs->{$i} }
1077 }
1078 return $num;
1079}
1080
1081# make the text available to the read function
1082# by making it an object variable
1083sub read_file {
1084 my ($self, $filename, $encoding, $language, $textref) = @_;
1085 $self->SUPER::read_file($filename, $encoding, $language, $textref);
1086
1087 # if HTMLplug has run through, then it will
1088 # have replaced references so we have to
1089 # make a copy of the text before processing
1090 if ( $self->{'index_pages'} ) {
1091 $self->{'text'} = $$textref;
1092 $self->{'textref'} = \($self->{'text'});
1093 } else {
1094 $self->{'textref'} = $textref;
1095 }
1096 $self->{'plaintext'} = undef;
1097}
1098
1099# HTMLPlug only extracts meta-data if it is specified in plugin options
1100# hence a special function to do it here
1101sub get_meta_value {
1102 my ($self, $name, $textref) = @_;
1103 my ($value);
1104 $name = lc $name;
1105 if ($name eq "title") {
1106 ($value) = $$textref =~ /<title>(.*?)<\/title>/is
1107 } else {
1108 my $qm = "(?:\"|\')";
1109 ($value) = $$textref =~ /<meta name\s*=\s*$qm?$name$qm?\s+content\s*=\s*$qm?(.*?)$qm?\s*>/is
1110 }
1111 $value = "" unless $value;
1112 return $value;
1113}
1114
1115# make filename an anchor reference
1116# so we can go straight to the image
1117# within the cached version of the source page
1118# (augment's HTMLPlug sub)
1119sub replace_images {
1120 my $self = shift (@_);
1121 my ($front, $link, $back, $base_dir,
1122 $file, $doc_obj, $section) = @_;
1123 $link =~ s/\"//g;
1124 my ($a_name) = $link;
1125 $a_name =~ s/[\/\\\:\&]/_/g;
1126 # keep a list so we don't repeat the same anchor
1127 if ( ! $self->{'imglist'}{$link}{'anchored'} ) {
1128 $front = "<a name=\"gsdl_$a_name\">$front";
1129 $back = "$back</a>";
1130 $self->{'imglist'}{$link}{'anchored'} = 1;
1131 }
1132 return $self->SUPER::replace_images($front, $link, $back, $base_dir,
1133 $file, $doc_obj, $section);
1134}
1135
11361;
Note: See TracBrowser for help on using the repository browser.