Muster/Hook/Img.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Muster/Assemble.pm ↑ Summary
1 package Muster::Hook::Img;
2 $Muster::Hook::Img::VERSION = '0.96';
3 =head1 NAME
4  
5 Muster::Hook::Img - Muster image and thumbnailing directive
6  
7 =head1 VERSION
8  
9 version 0.96
10  
11 =head1 DESCRIPTION
12  
13 L<Muster::Hook::Img> links to images and makes thumbnails for the links.
14  
15 =cut
16  
17 1 ▶use Mojo::Base 'Muster::Hook::Directives';
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use Muster::LeafFile;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Muster::Hooks;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Muster::Hook::Links;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use File::Slurper 'write_binary';
Subroutine BEGIN: called CC=1 SCAR=0.0
24 0 ▶use Image::Magick;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use YAML::Any;
26  
27 use Carp 'croak';
28  
29 =head1 METHODS
30  
31 L<Muster::Hook::Img> inherits all methods from L<Muster::Hook::Directives>.
32  
33 =head2 register
34  
35 Do some intialization.
36  
37 =cut
38 sub register {
39 my $self = shift;
40 my $hookmaster = shift;
41 my $conf = shift;
42  
43 $self->{metadb} = $hookmaster->{metadb};
44  
45 # place to store and serve cached thumbnails
46 $self->{cache_dir} = $conf->{cache_dir};
47 $self->{img_dir} = File::Spec->catdir($self->{cache_dir}, 'images');
48 if (!-d $self->{img_dir})
49 {
50 mkdir $self->{img_dir};
51 }
52 $self->{img_url} = 'images/';
53  
54 $hookmaster->add_hook('img' => sub {
55 my %args = @_;
56  
57 return $self->do_directives(
58 directive=>'img',
59 call=>sub {
60 my %args2 = @_;
61  
62 return $self->process(%args2);
63 },
64 %args,
65 );
66 },
67 );
68 return $self;
69 } # register
70  
71 =head2 process
72  
73 Image directive: link to image, with a thumbnail.
74  
75 =cut
76 sub process {
77 my $self = shift;
78 my %args = @_;
79  
80 my $directive = $args{directive};
81 my $leaf = $args{leaf};
82 my $phase = $args{phase};
83 my @p = @{$args{params}};
84 my $image = $p[0]; # the first argument is the image
85 my %params = @p;
86 my $pagename = $leaf->pagename;
87  
88 # We don't display anything if:
89 # - we are scanning
90 # - this is the "defaults" directive
91 # But if we are scanning the "defaults" directive, we want to remember it.
92 if ($image eq 'defaults' or $phase eq $Muster::Hooks::PHASE_SCAN)
93 {
94 if ($image eq 'defaults' and $phase eq $Muster::Hooks::PHASE_SCAN)
95 {
96 $leaf->{meta}->{_img_defaults} = Dump(@p);
97 }
98 return "";
99 }
100 # ---------------------------------------------------------
101 # Not Scanning
102 # ---------------------------------------------------------
103  
104 # Image defaults
105 if (exists $leaf->{meta}->{_img_defaults}
106 and defined $leaf->{meta}->{_img_defaults})
107 {
108 my @d = Load($leaf->{meta}->{_img_defaults});
109 my %d = @d;
110 foreach my $key (keys %d)
111 {
112 if ($key ne 'defaults' and !exists $params{$key})
113 {
114 $params{$key} = $d{$key};
115 }
116 }
117 }
118 if (! exists $params{size} || ! length $params{size})
119 {
120 $params{size}='full';
121 }
122  
123 my $imgpage = $self->{metadb}->bestlink($pagename, $image);
124 if (!$imgpage)
125 {
126 return "[[$image]]"; # link to the unknown image
127 }
128 my $img_info = $self->{metadb}->page_or_file_info($imgpage);
129  
130 my $extension = $img_info->{extension};
131 my $format;
132  
133 # Never interpret well-known file extensions as any other format,
134 # in case the wiki configuration unwisely allows attaching
135 # arbitrary files named *.jpg, etc.
136 my $magic;
137 my $offset = 0;
138 open(my $in, '<', $img_info->{filename}) or croak sprintf("A. failed to read %s: %s", $imgpage, $!);
139 binmode($in);
140  
141 if ($extension =~ m/^(jpeg|jpg)$/is)
142 {
143 $format = 'jpeg';
144 $magic = "\377\330\377";
145 }
146 elsif ($extension =~ m/^(png)$/is)
147 {
148 $format = 'png';
149 $magic = "\211PNG\r\n\032\n";
150 }
151 elsif ($extension =~ m/^(gif)$/is)
152 {
153 $format = 'gif';
154 $magic = "GIF8";
155 }
156 elsif ($extension =~ m/^(svg)$/is)
157 {
158 $format = 'svg';
159 }
160 else {
161 # allow ImageMagick to auto-detect (potentially dangerous)
162 $format = '';
163 }
164 # Try harder to protect ImageMagick from itself
165 if (defined $magic)
166 {
167 my $content;
168 read($in, $content, length $magic) or croak sprintf("B. failed to read %s: %s", $imgpage, $!);
169 if ($magic ne $content) {
170 croak sprintf(("\"%s\" does not seem to be a valid %s file"), $imgpage, $format);
171 }
172 }
173 close($in);
174  
175 # give it a long flat name
176 my $thumb_base = $img_info->{pagesrcname};
177 $thumb_base =~ s!/!-!g;
178 my $imglink;
179 my ($dwidth, $dheight);
180  
181 my ($w, $h);
182 if ($params{size} ne 'full')
183 {
184 ($w, $h) = ($params{size} =~ /^(\d*)x(\d*)$/);
185 }
186  
187 if ($format eq 'svg')
188 {
189 # svg images are not scaled using ImageMagick because the
190 # pipeline is complex. Instead, the image size is simply
191 # set to the provided values.
192 #
193 # Aspect ratio will be preserved automatically when
194 # only a width or only a height is specified.
195 # When both are specified, aspect ratio will not be
196 # preserved.
197 $imglink = $img_info->{pagesrcname};
198 $dwidth = $w if length $w;
199 $dheight = $h if length $h;
200 }
201 else
202 {
203 my $im = Image::Magick->new();
204 my $r = $im->Read(filename=>$img_info->{filename});
205 croak sprintf(("C. failed to read %s: %s"), $imgpage, $r) if $r;
206  
207 if (! defined $im->Get("width") || ! defined $im->Get("height"))
208 {
209 croak sprintf('failed to get dimensions of %s', $imgpage);
210 }
211  
212 if (! length $w && ! length $h)
213 {
214 $dwidth = $im->Get("width");
215 $dheight = $im->Get("height");
216 }
217 else
218 {
219 croak sprintf('wrong size format "%s" (should be WxH)', $params{size})
220 unless (defined $w && defined $h &&
221 (length $w || length $h));
222  
223 if ($im->Get("width") == 0 || $im->Get("height") == 0)
224 {
225 ($dwidth, $dheight)=(0, 0);
226 } elsif (! length $w || (length $h && $im->Get("height")*$w > $h * $im->Get("width")))
227 {
228 # using height because only height is given or ...
229 # because original image is more portrait than $w/$h
230 # ... slimness of $im > $h/w
231 # ... $im->Get("height")/$im->Get("width") > $h/$w
232 # ... $im->Get("height")*$w > $h * $im->Get("width")
233  
234 $dheight=$h;
235 $dwidth=$h / $im->Get("height") * $im->Get("width");
236 }
237 else
238 { # (! length $h) or $w is what determines the resized size
239 $dwidth=$w;
240 $dheight=$w / $im->Get("width") * $im->Get("height");
241 }
242 }
243 # thumbnail?
244 if ($dwidth < $im->Get("width"))
245 {
246 # resize down, or resize to pixels at all
247 my $outfile = File::Spec->catfile($self->{img_dir}, $params{size} . '-' . $thumb_base);
248 $imglink = $self->{img_url} . $params{size} . '-' . $thumb_base;
249  
250 if (-e $outfile && (-M $img_info->{filename} >= -M $outfile))
251 {
252 $im = Image::Magick->new;
253 $r = $im->Read($outfile);
254 croak sprintf("D. failed to read %s: %s", $outfile, $r) if $r;
255 }
256 else
257 {
258 $r = $im->Resize(geometry => "${dwidth}x${dheight}");
259 croak sprintf("failed to resize: %s", $r) if $r;
260  
261 my @blob = $im->ImageToBlob();
262 write_binary($outfile, $blob[0]);
263 }
264  
265 # always get the true size of the resized image (it could be
266 # that imagemagick did its calculations differently)
267  
268 $dwidth = $im->Get("width");
269 $dheight = $im->Get("height");
270 }
271 else
272 {
273 $imglink = $img_info->{pagesrcname};
274 }
275  
276 if (! defined($dwidth) || ! defined($dheight))
277 {
278 croak sprintf("failed to determine size of image %s", $imgpage)
279 }
280  
281 # link needs to be relative to this page
282 $imglink = File::Spec->abs2rel($imglink, $leaf->pagename);
283 }
284  
285 if (! exists $params{class})
286 {
287 $params{class}="img";
288 }
289  
290 my $attrs='';
291 foreach my $attr (qw{alt title class id style})
292 {
293 if (exists $params{$attr})
294 {
295 $attrs.=" $attr=\"$params{$attr}\"";
296 }
297 }
298
299 my $imgtag='<img src="'.$imglink.'"';
300 $imgtag.=' width="'.$dwidth.'"' if defined $dwidth;
301 $imgtag.=' height="'.$dheight.'"' if defined $dheight;
302 $imgtag.= $attrs.
303 (exists $params{align} && ! exists $params{caption} ? ' align="'.$params{align}.'"' : '').
304 ' />';
305  
306 my $link;
307 if (! defined $params{link})
308 {
309 $link = File::Spec->abs2rel($img_info->{pagesrcname}, $leaf->{pagename});
310 }
311 elsif ($params{link} =~ /^\w+:\/\//)
312 {
313 $link=$params{link};
314 }
315  
316 if (defined $link)
317 {
318 $imgtag='<a href="'.$link.'">'.$imgtag.'</a>';
319 }
320 if (!exists $params{caption} and exists $img_info->{description})
321 {
322 $params{caption} = $img_info->{description};
323 }
324  
325 if (exists $params{caption} and $params{caption})
326 {
327 my $style = '';
328 $style = sprintf('width: %dpx;', $dwidth + 6) if defined $dwidth; # give it a bit of a margin
329  
330 return <<EOT;
331 <div style="$style" class="$params{class}">
332 $imgtag<br/>
333 <span class="caption">$params{caption}</span>
334 </div>
335 EOT
336 }
337 else
338 {
339 return $imgtag;
340 }
341 } # process
342  
343 1;
« Muster/Assemble.pm ↑ Summary