]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/img.pm
img: check magic number before giving common formats to ImageMagick
[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         my $magic;
103         my $offset = 0;
104         open(my $in, '<', $srcfile) or error sprintf(gettext("failed to read %s: %s"), $file, $!);
105         binmode($in);
107         if ($extension =~ m/^(jpeg|jpg)$/is) {
108                 $format = 'jpeg';
109                 $magic = "\377\330\377";
110         }
111         elsif ($extension =~ m/^(png)$/is) {
112                 $format = 'png';
113                 $magic = "\211PNG\r\n\032\n";
114         }
115         elsif ($extension =~ m/^(gif)$/is) {
116                 $format = 'gif';
117                 $magic = "GIF8";
118         }
119         elsif ($extension =~ m/^(svg)$/is) {
120                 $format = 'svg';
121         }
122         elsif ($extension =~ m/^(pdf)$/is) {
123                 $format = 'pdf';
124                 $magic = "%PDF-";
125         }
126         else {
127                 # allow ImageMagick to auto-detect (potentially dangerous)
128                 $format = '';
129         }
131         error sprintf(gettext("%s image processing disabled in img_allowed_formats configuration"), $format ? $format : "\"$extension\"") unless allowed($format ? $format : "everything");
133         # Try harder to protect ImageMagick from itself
134         if ($format eq 'svg') {
135                 my $content;
136                 read($in, $content, 5) or error sprintf(gettext("failed to read %s: %s"), $file, $!);
137                 # This is an over-simplification, but ?xml is the check that
138                 # ImageMagick uses. We also accept <svg for the simplest
139                 # possible SVGs.
140                 if ($content !~ m/^(.\?xml|<svg)/is) {
141                         error sprintf(gettext("\"%s\" does not seem to be a valid %s file"), $file, $format);
142                 }
143         }
144         elsif ($magic) {
145                 my $content;
146                 read($in, $content, length $magic) or error sprintf(gettext("failed to read %s: %s"), $file, $!);
147                 if ($magic ne $content) {
148                         error sprintf(gettext("\"%s\" does not seem to be a valid %s file"), $file, $format);
149                 }
150         }
152         my $issvg = $base=~s/\.svg$/.png/i;
153         my $ispdf = $base=~s/\.pdf$/.png/i;
154         my $pagenumber = exists($params{pagenumber}) ? int($params{pagenumber}) : 0;
155         if ($pagenumber != 0) {
156                 $base = "p$pagenumber-$base";
157         }
159         eval q{use Image::Magick};
160         error gettext("Image::Magick is not installed") if $@;
161         my $im = Image::Magick->new();
162         my $imglink;
163         my $imgdatalink;
164         my $r = $im->Read("$format:$srcfile\[$pagenumber]");
165         error sprintf(gettext("failed to read %s: %s"), $file, $r) if $r;
167         if (! defined $im->Get("width") || ! defined $im->Get("height")) {
168                 error sprintf(gettext("failed to get dimensions of %s"), $file);
169         }
171         my ($dwidth, $dheight);
173         if ($params{size} eq 'full') {
174                 $dwidth = $im->Get("width");
175                 $dheight = $im->Get("height");
176         } else {
177                 my ($w, $h) = ($params{size} =~ /^(\d*)x(\d*)$/);
178                 error sprintf(gettext('wrong size format "%s" (should be WxH)'), $params{size})
179                         unless (defined $w && defined $h &&
180                                 (length $w || length $h));
182                 if ($im->Get("width") == 0 || $im->Get("height") == 0) {
183                         ($dwidth, $dheight)=(0, 0);
184                 } elsif (! length $w || (length $h && $im->Get("height")*$w > $h * $im->Get("width"))) {
185                         # using height because only height is given or ...
186                         # because original image is more portrait than $w/$h
187                         # ... slimness of $im > $h/w
188                         # ... $im->Get("height")/$im->Get("width") > $h/$w
189                         # ... $im->Get("height")*$w > $h * $im->Get("width")
191                         $dheight=$h;
192                         $dwidth=$h / $im->Get("height") * $im->Get("width");
193                 } else { # (! length $h) or $w is what determines the resized size
194                         $dwidth=$w;
195                         $dheight=$w / $im->Get("width") * $im->Get("height");
196                 }
197         }
199         if ($dwidth < $im->Get("width") || $ispdf) {
200                 # resize down, or resize to pixels at all
202                 my $outfile = "$config{destdir}/$dir/$params{size}-$base";
203                 $imglink = "$dir/$params{size}-$base";
205                 will_render($params{page}, $imglink);
207                 if (-e $outfile && (-M $srcfile >= -M $outfile)) {
208                         $im = Image::Magick->new;
209                         $r = $im->Read($outfile);
210                         error sprintf(gettext("failed to read %s: %s"), $outfile, $r) if $r;
211                 }
212                 else {
213                         $r = $im->Resize(geometry => "${dwidth}x${dheight}");
214                         error sprintf(gettext("failed to resize: %s"), $r) if $r;
216                         $im->set(($issvg || $ispdf) ? (magick => 'png') : ());
217                         my @blob = $im->ImageToBlob();
218                         # don't actually write resized file in preview mode;
219                         # rely on width and height settings
220                         if (! $params{preview}) {
221                                 writefile($imglink, $config{destdir}, $blob[0], 1);
222                         }
223                         else {
224                                 eval q{use MIME::Base64};
225                                 error($@) if $@;
226                                 $imgdatalink = "data:image/".$im->Get("magick").";base64,".encode_base64($blob[0]);
227                         }
228                 }
230                 # always get the true size of the resized image (it could be
231                 # that imagemagick did its calculations differently)
232                 $dwidth  = $im->Get("width");
233                 $dheight = $im->Get("height");
234         } else {
235                 $imglink = $file;
236         }
237         
238         if (! defined($dwidth) || ! defined($dheight)) {
239                 error sprintf(gettext("failed to determine size of image %s"), $file)
240         }
242         my ($fileurl, $imgurl);
243         my $urltobase = $params{preview} ? undef : $params{destpage};
244         $fileurl=urlto($file, $urltobase);
245         $imgurl=$imgdatalink ? $imgdatalink : urlto($imglink, $urltobase);
247         if (! exists $params{class}) {
248                 $params{class}="img";
249         }
251         my $attrs='';
252         foreach my $attr (qw{alt title class id hspace vspace}) {
253                 if (exists $params{$attr}) {
254                         $attrs.=" $attr=\"$params{$attr}\"";
255                 }
256         }
257         
258         my $imgtag='<img src="'.$imgurl.
259                 '" width="'.$dwidth.
260                 '" height="'.$dheight.'"'.
261                 $attrs.
262                 (exists $params{align} && ! exists $params{caption} ? ' align="'.$params{align}.'"' : '').
263                 ' />';
265         my $link;
266         if (! defined $params{link}) {
267                 $link=$fileurl;
268         }
269         elsif ($params{link} =~ /^\w+:\/\//) {
270                 $link=$params{link};
271         }
273         if (defined $link) {
274                 $imgtag='<a href="'.$link.'">'.$imgtag.'</a>';
275         }
276         else {
277                 my $b = bestlink($params{page}, $params{link});
278         
279                 if (length $b) {
280                         add_depends($params{page}, $b, deptype("presence"));
281                         $imgtag=htmllink($params{page}, $params{destpage},
282                                 $params{link}, linktext => $imgtag,
283                                 noimageinline => 1,
284                         );
285                 }
286         }
288         if (exists $params{caption}) {
289                 return '<table class="img'.
290                         (exists $params{align} ? " align-$params{align}" : "").
291                         '">'.
292                         '<caption>'.$params{caption}.'</caption>'.
293                         '<tr><td>'.$imgtag.'</td></tr>'.
294                         '</table>';
295         }
296         else {
297                 return $imgtag;
298         }