2 # Ikiwiki enhanced image handling plugin
3 # Christian Mock cm@tahina.priv.at 20061002
4 package IkiWiki::Plugin::img;
13 hook(type => "getsetup", id => "img", call => \&getsetup);
14 hook(type => "preprocess", id => "img", call => \&preprocess, scan => 1);
24 img_allowed_formats => {
26 default => [qw(jpeg png gif svg)],
27 description => "Image formats to process (jpeg, png, gif, svg, pdf or 'everything' to accept all)",
28 # ImageMagick has had arbitrary code execution flaws,
29 # and the whole delegates mechanism is scary from
38 my $allowed = $config{img_allowed_formats};
39 $allowed = ['jpeg', 'png', 'gif', 'svg'] unless defined $allowed && @$allowed;
41 foreach my $a (@$allowed) {
42 return 1 if lc($a) eq $format || lc($a) eq 'everything';
49 my ($image) = $_[0] =~ /$config{wiki_file_regexp}/; # untaint
52 if (! defined $image) {
53 error("bad image filename");
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};
64 if (! exists $params{size} || ! length $params{size}) {
68 if ($image eq 'defaults') {
69 $imgdefaults{$params{page}} = \%params;
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) {
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);
87 my $dir = $params{page};
88 my $base = IkiWiki::basename($file);
92 if ($base =~ m/\.([a-z0-9]+)$/is) {
96 error gettext("Unable to detect image type from extension");
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.
104 open(my $in, '<', $srcfile) or error sprintf(gettext("failed to read %s: %s"), $file, $!);
107 if ($extension =~ m/^(jpeg|jpg)$/is) {
109 $magic = "\377\330\377";
111 elsif ($extension =~ m/^(png)$/is) {
113 $magic = "\211PNG\r\n\032\n";
115 elsif ($extension =~ m/^(gif)$/is) {
119 elsif ($extension =~ m/^(svg)$/is) {
122 elsif ($extension =~ m/^(pdf)$/is) {
127 # allow ImageMagick to auto-detect (potentially dangerous)
128 my $im = Image::Magick->new();
129 my $r = $im->Ping(file => $in);
134 error sprintf(gettext("failed to determine format of %s"), $file);
138 error sprintf(gettext("%s image processing disabled in img_allowed_formats configuration"), $format ? $format : "\"$extension\"") unless allowed($format ? $format : "everything");
140 # Try harder to protect ImageMagick from itself
141 if (defined $magic) {
143 read($in, $content, length $magic) or error sprintf(gettext("failed to read %s: %s"), $file, $!);
144 if ($magic ne $content) {
145 error sprintf(gettext("\"%s\" does not seem to be a valid %s file"), $file, $format);
149 my $ispdf = $base=~s/\.pdf$/.png/i;
150 my $pagenumber = exists($params{pagenumber}) ? int($params{pagenumber}) : 0;
151 if ($pagenumber != 0) {
152 $base = "p$pagenumber-$base";
157 my ($dwidth, $dheight);
160 if ($params{size} ne 'full') {
161 ($w, $h) = ($params{size} =~ /^(\d*)x(\d*)$/);
164 if ($format eq 'svg') {
165 # svg images are not scaled using ImageMagick because the
166 # pipeline is complex. Instead, the image size is simply
167 # set to the provided values.
169 # Aspect ratio will be preserved automatically when
170 # only a width or only a height is specified.
171 # When both are specified, aspect ratio will not be
174 $dwidth = $w if length $w;
175 $dheight = $h if length $h;
178 eval q{use Image::Magick};
179 error gettext("Image::Magick is not installed") if $@;
180 my $im = Image::Magick->new();
181 my $r = $im->Read("$format:$srcfile\[$pagenumber]");
182 error sprintf(gettext("failed to read %s: %s"), $file, $r) if $r;
184 if ($config{deterministic}) {
185 $im->Set('date:create' => 0);
186 $im->Set('date:modify' => 0);
187 $im->Set('option' => 'png:exclude-chunk=time');
190 if (! defined $im->Get("width") || ! defined $im->Get("height")) {
191 error sprintf(gettext("failed to get dimensions of %s"), $file);
194 if (! length $w && ! length $h) {
195 $dwidth = $im->Get("width");
196 $dheight = $im->Get("height");
198 error sprintf(gettext('wrong size format "%s" (should be WxH)'), $params{size})
199 unless (defined $w && defined $h &&
200 (length $w || length $h));
202 if ($im->Get("width") == 0 || $im->Get("height") == 0) {
203 ($dwidth, $dheight)=(0, 0);
204 } elsif (! length $w || (length $h && $im->Get("height")*$w > $h * $im->Get("width"))) {
205 # using height because only height is given or ...
206 # because original image is more portrait than $w/$h
207 # ... slimness of $im > $h/w
208 # ... $im->Get("height")/$im->Get("width") > $h/$w
209 # ... $im->Get("height")*$w > $h * $im->Get("width")
212 $dwidth=$h / $im->Get("height") * $im->Get("width");
213 } else { # (! length $h) or $w is what determines the resized size
215 $dheight=$w / $im->Get("width") * $im->Get("height");
219 if ($dwidth < $im->Get("width") || $ispdf) {
220 # resize down, or resize to pixels at all
222 my $outfile = "$config{destdir}/$dir/$params{size}-$base";
223 $imglink = "$dir/$params{size}-$base";
225 will_render($params{page}, $imglink);
227 if (-e $outfile && (-M $srcfile >= -M $outfile)) {
228 $im = Image::Magick->new;
229 $r = $im->Read($outfile);
230 error sprintf(gettext("failed to read %s: %s"), $outfile, $r) if $r;
233 $r = $im->Resize(geometry => "${dwidth}x${dheight}");
234 error sprintf(gettext("failed to resize: %s"), $r) if $r;
236 $im->set($ispdf ? (magick => 'png') : ());
237 my @blob = $im->ImageToBlob();
238 # don't actually write resized file in preview mode;
239 # rely on width and height settings
240 if (! $params{preview}) {
241 writefile($imglink, $config{destdir}, $blob[0], 1);
244 eval q{use MIME::Base64};
246 $imgdatalink = "data:image/".$im->Get("magick").";base64,".encode_base64($blob[0]);
250 # always get the true size of the resized image (it could be
251 # that imagemagick did its calculations differently)
252 $dwidth = $im->Get("width");
253 $dheight = $im->Get("height");
258 if (! defined($dwidth) || ! defined($dheight)) {
259 error sprintf(gettext("failed to determine size of image %s"), $file)
263 my ($fileurl, $imgurl);
264 my $urltobase = $params{preview} ? undef : $params{destpage};
265 $fileurl=urlto($file, $urltobase);
266 $imgurl=$imgdatalink ? $imgdatalink : urlto($imglink, $urltobase);
268 if (! exists $params{class}) {
269 $params{class}="img";
273 foreach my $attr (qw{alt title class id hspace vspace}) {
274 if (exists $params{$attr}) {
275 $attrs.=" $attr=\"$params{$attr}\"";
279 my $imgtag='<img src="'.$imgurl.'"';
280 $imgtag.=' width="'.$dwidth.'"' if defined $dwidth;
281 $imgtag.=' height="'.$dheight.'"' if defined $dheight;
283 (exists $params{align} && ! exists $params{caption} ? ' align="'.$params{align}.'"' : '').
287 if (! defined $params{link}) {
290 elsif ($params{link} =~ /^\w+:\/\//) {
295 $imgtag='<a href="'.$link.'">'.$imgtag.'</a>';
298 my $b = bestlink($params{page}, $params{link});
301 add_depends($params{page}, $b, deptype("presence"));
302 $imgtag=htmllink($params{page}, $params{destpage},
303 $params{link}, linktext => $imgtag,
309 if (exists $params{caption}) {
310 return '<table class="img'.
311 (exists $params{align} ? " align-$params{align}" : "").
313 '<caption>'.$params{caption}.'</caption>'.
314 '<tr><td>'.$imgtag.'</td></tr>'.