]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/img.pm
53d963425eb1dade14cdb5e8406457b20b2916f7
[git.ikiwiki.info.git] / IkiWiki / Plugin / img.pm
1 #!/usr/bin/perl
2 # Ikiwiki enhanced image handling plugin
3 # Christian Mock cm@tahina.priv.at 20061002
4 package IkiWiki::Plugin::img;
6 use warnings;
7 use strict;
8 use IkiWiki 3.00;
10 my %imgdefaults;
12 sub import {
13         hook(type => "getsetup", id => "img", call => \&getsetup);
14         hook(type => "preprocess", id => "img", call => \&preprocess, scan => 1);
15 }
17 sub getsetup () {
18         return
19                 plugin => {
20                         safe => 1,
21                         rebuild => undef,
22                         section => "widget",
23                 },
24                 img_allowed_formats => {
25                         type => "string",
26                         default => [qw(jpeg png gif)],
27                         description => "Image formats to process (jpeg, png, gif, pdf, svg or 'everything' to accept all)",
28                         # ImageMagick has had arbitrary code execution flaws,
29                         # and the whole delegates mechanism is scary from
30                         # that perspective
31                         safe => 0,
32                         rebuild => 0,
33                 },
34 }
36 sub allowed {
37         my $format = shift;
38         my $allowed = $config{img_allowed_formats};
39         $allowed = ['jpeg', 'png'] unless defined $allowed && @$allowed;
41         foreach my $a (@$allowed) {
42                 return 1 if $a eq $format || $a eq 'everything';
43         }
45         return 0;
46 }
48 sub preprocess (@) {
49         my ($image) = $_[0] =~ /$config{wiki_file_regexp}/; # untaint
50         my %params=@_;
52         if (! defined $image) {
53                 error("bad image filename");
54         }
56         if (exists $imgdefaults{$params{page}}) {
57                 foreach my $key (keys %{$imgdefaults{$params{page}}}) {
58                         if (! exists $params{$key}) {
59                                 $params{$key}=$imgdefaults{$params{page}}->{$key};
60                         }
61                 }
62         }
64         if (! exists $params{size} || ! length $params{size}) {
65                 $params{size}='full';
66         }
68         if ($image eq 'defaults') {
69                 $imgdefaults{$params{page}} = \%params;
70                 return '';
71         }
73         add_link($params{page}, $image);
74         add_depends($params{page}, $image);
76         # optimisation: detect scan mode, and avoid generating the image
77         if (! defined wantarray) {
78                 return;
79         }
81         my $file = bestlink($params{page}, $image);
82         my $srcfile = srcfile($file, 1);
83         if (! length $file || ! defined $srcfile) {
84                 return htmllink($params{page}, $params{destpage}, $image);
85         }
87         my $dir = $params{page};
88         my $base = IkiWiki::basename($file);
89         my $extension;
90         my $format;
92         if ($base =~ m/\.([a-z0-9]+)$/) {
93                 $extension = $1;
94         }
95         else {
96                 error gettext("Unable to detect image type from extension");
97         }
99         # Never interpret well-known file extensions as any other format,
100         # in case the wiki configuration unwisely allows attaching
101         # arbitrary files named *.jpg, etc.
102         if ($extension =~ m/^(jpeg|jpg)$/is) {
103                 $format = 'jpeg';
104         }
105         elsif ($extension =~ m/^(png)$/is) {
106                 $format = 'png';
107         }
108         elsif ($extension =~ m/^(gif)$/is) {
109                 $format = 'gif';
110         }
111         elsif ($extension =~ m/^(svg)$/is) {
112                 $format = 'svg';
113         }
114         elsif ($extension =~ m/^(pdf)$/is) {
115                 $format = 'pdf';
116         }
117         else {
118                 # allow ImageMagick to auto-detect (potentially dangerous)
119                 $format = '';
120         }
122         error sprintf(gettext("%s image processing disabled in img_allowed_formats configuration"), $format ? $format : "\"$extension\"") unless allowed($format ? $format : "everything");
124         my $issvg = $base=~s/\.svg$/.png/i;
125         my $ispdf = $base=~s/\.pdf$/.png/i;
126         my $pagenumber = exists($params{pagenumber}) ? int($params{pagenumber}) : 0;
127         if ($pagenumber != 0) {
128                 $base = "p$pagenumber-$base";
129         }
131         eval q{use Image::Magick};
132         error gettext("Image::Magick is not installed") if $@;
133         my $im = Image::Magick->new();
134         my $imglink;
135         my $imgdatalink;
136         my $r = $im->Read("$format:$srcfile\[$pagenumber]");
137         error sprintf(gettext("failed to read %s: %s"), $file, $r) if $r;
139         if (! defined $im->Get("width") || ! defined $im->Get("height")) {
140                 error sprintf(gettext("failed to get dimensions of %s"), $file);
141         }
143         my ($dwidth, $dheight);
145         if ($params{size} eq 'full') {
146                 $dwidth = $im->Get("width");
147                 $dheight = $im->Get("height");
148         } else {
149                 my ($w, $h) = ($params{size} =~ /^(\d*)x(\d*)$/);
150                 error sprintf(gettext('wrong size format "%s" (should be WxH)'), $params{size})
151                         unless (defined $w && defined $h &&
152                                 (length $w || length $h));
154                 if ($im->Get("width") == 0 || $im->Get("height") == 0) {
155                         ($dwidth, $dheight)=(0, 0);
156                 } elsif (! length $w || (length $h && $im->Get("height")*$w > $h * $im->Get("width"))) {
157                         # using height because only height is given or ...
158                         # because original image is more portrait than $w/$h
159                         # ... slimness of $im > $h/w
160                         # ... $im->Get("height")/$im->Get("width") > $h/$w
161                         # ... $im->Get("height")*$w > $h * $im->Get("width")
163                         $dheight=$h;
164                         $dwidth=$h / $im->Get("height") * $im->Get("width");
165                 } else { # (! length $h) or $w is what determines the resized size
166                         $dwidth=$w;
167                         $dheight=$w / $im->Get("width") * $im->Get("height");
168                 }
169         }
171         if ($dwidth < $im->Get("width") || $ispdf) {
172                 # resize down, or resize to pixels at all
174                 my $outfile = "$config{destdir}/$dir/$params{size}-$base";
175                 $imglink = "$dir/$params{size}-$base";
177                 will_render($params{page}, $imglink);
179                 if (-e $outfile && (-M $srcfile >= -M $outfile)) {
180                         $im = Image::Magick->new;
181                         $r = $im->Read($outfile);
182                         error sprintf(gettext("failed to read %s: %s"), $outfile, $r) if $r;
183                 }
184                 else {
185                         $r = $im->Resize(geometry => "${dwidth}x${dheight}");
186                         error sprintf(gettext("failed to resize: %s"), $r) if $r;
188                         $im->set(($issvg || $ispdf) ? (magick => 'png') : ());
189                         my @blob = $im->ImageToBlob();
190                         # don't actually write resized file in preview mode;
191                         # rely on width and height settings
192                         if (! $params{preview}) {
193                                 writefile($imglink, $config{destdir}, $blob[0], 1);
194                         }
195                         else {
196                                 eval q{use MIME::Base64};
197                                 error($@) if $@;
198                                 $imgdatalink = "data:image/".$im->Get("magick").";base64,".encode_base64($blob[0]);
199                         }
200                 }
202                 # always get the true size of the resized image (it could be
203                 # that imagemagick did its calculations differently)
204                 $dwidth  = $im->Get("width");
205                 $dheight = $im->Get("height");
206         } else {
207                 $imglink = $file;
208         }
209         
210         if (! defined($dwidth) || ! defined($dheight)) {
211                 error sprintf(gettext("failed to determine size of image %s"), $file)
212         }
214         my ($fileurl, $imgurl);
215         my $urltobase = $params{preview} ? undef : $params{destpage};
216         $fileurl=urlto($file, $urltobase);
217         $imgurl=$imgdatalink ? $imgdatalink : urlto($imglink, $urltobase);
219         if (! exists $params{class}) {
220                 $params{class}="img";
221         }
223         my $attrs='';
224         foreach my $attr (qw{alt title class id hspace vspace}) {
225                 if (exists $params{$attr}) {
226                         $attrs.=" $attr=\"$params{$attr}\"";
227                 }
228         }
229         
230         my $imgtag='<img src="'.$imgurl.
231                 '" width="'.$dwidth.
232                 '" height="'.$dheight.'"'.
233                 $attrs.
234                 (exists $params{align} && ! exists $params{caption} ? ' align="'.$params{align}.'"' : '').
235                 ' />';
237         my $link;
238         if (! defined $params{link}) {
239                 $link=$fileurl;
240         }
241         elsif ($params{link} =~ /^\w+:\/\//) {
242                 $link=$params{link};
243         }
245         if (defined $link) {
246                 $imgtag='<a href="'.$link.'">'.$imgtag.'</a>';
247         }
248         else {
249                 my $b = bestlink($params{page}, $params{link});
250         
251                 if (length $b) {
252                         add_depends($params{page}, $b, deptype("presence"));
253                         $imgtag=htmllink($params{page}, $params{destpage},
254                                 $params{link}, linktext => $imgtag,
255                                 noimageinline => 1,
256                         );
257                 }
258         }
260         if (exists $params{caption}) {
261                 return '<table class="img'.
262                         (exists $params{align} ? " align-$params{align}" : "").
263                         '">'.
264                         '<caption>'.$params{caption}.'</caption>'.
265                         '<tr><td>'.$imgtag.'</td></tr>'.
266                         '</table>';
267         }
268         else {
269                 return $imgtag;
270         }