]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Unbroke infobox=0 for fullscreen mode.
[pr0n] / perl / Sesse / pr0n / Common.pm
1 package Sesse::pr0n::Common;
2 use strict;
3 use warnings;
4
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
8
9 use Apache2::RequestRec (); # for $r->content_type
10 use Apache2::RequestIO ();  # for $r->print
11 use Apache2::Const -compile => ':common';
12 use Apache2::Log;
13 use ModPerl::Util;
14
15 use Carp;
16 use Encode;
17 use DBI;
18 use DBD::Pg;
19 use Image::Magick;
20 use POSIX;
21 use Digest::SHA1;
22 use MIME::Base64;
23 use MIME::Types;
24 use LWP::Simple;
25 # use Image::Info;
26 use Image::ExifTool;
27 use HTML::Entities;
28 use URI::Escape;
29 use File::Basename;
30
31 BEGIN {
32         use Exporter ();
33         our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
34
35         use Sesse::pr0n::Config;
36         eval {
37                 require Sesse::pr0n::Config_local;
38         };
39
40         $VERSION     = "v2.70";
41         @ISA         = qw(Exporter);
42         @EXPORT      = qw(&error &dberror);
43         %EXPORT_TAGS = qw();
44         @EXPORT_OK   = qw(&error &dberror);
45
46         our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
47                 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
48                 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
49         our $mimetypes = new MIME::Types;
50         
51         Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
52 }
53 END {
54         our $dbh;
55         $dbh->disconnect;
56 }
57
58 our ($dbh, $mimetypes);
59
60 sub error {
61         my ($r,$err,$status,$title) = @_;
62
63         if (!defined($status) || !defined($title)) {
64                 $status = 500;
65                 $title = "Internal server error";
66         }
67         
68         $r->content_type('text/html; charset=utf-8');
69         $r->status($status);
70
71         header($r, $title);
72         $r->print("    <p>Error: $err</p>\n");
73         footer($r);
74
75         $r->log->error($err);
76         $r->log->error("Stack trace follows: " . Carp::longmess());
77
78         ModPerl::Util::exit();
79 }
80
81 sub dberror {
82         my ($r,$err) = @_;
83         error($r, "$err (DB error: " . $dbh->errstr . ")");
84 }
85
86 sub header {
87         my ($r,$title) = @_;
88
89         $r->content_type("text/html; charset=utf-8");
90
91         # Fetch quote if we're itk-bilder.samfundet.no
92         my $quote = "";
93         if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
94                 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
95                 $quote = "Error: Could not fetch quotes." if (!defined($quote));
96         }
97         Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
98 }
99
100 sub footer {
101         my ($r) = @_;
102         Sesse::pr0n::Templates::print_template($r, "footer",
103                 { version => $Sesse::pr0n::Common::VERSION });
104 }
105
106 sub scale_aspect {
107         my ($width, $height, $thumbxres, $thumbyres) = @_;
108
109         unless ($thumbxres >= $width &&
110                 $thumbyres >= $height) {
111                 my $sfh = $width / $thumbxres;
112                 my $sfv = $height / $thumbyres;
113                 if ($sfh > $sfv) {
114                         $width  /= $sfh;
115                         $height /= $sfh;
116                 } else {
117                         $width  /= $sfv;
118                         $height /= $sfv;
119                 }
120                 $width = POSIX::floor($width);
121                 $height = POSIX::floor($height);
122         }
123
124         return ($width, $height);
125 }
126
127 sub get_query_string {
128         my ($param, $defparam) = @_;
129         my $first = 1;
130         my $str = "";
131
132         while (my ($key, $value) = each %$param) {
133                 next unless defined($value);
134                 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
135
136                 $value = pretty_escape($value);
137         
138                 $str .= ($first) ? "?" : ';';
139                 $str .= "$key=$value";
140                 $first = 0;
141         }
142         return $str;
143 }
144
145 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
146 sub weird_space_encode {
147         my $val = shift;
148         if ($val =~ /_/) {
149                 return "_" x (length($val) * 2);
150         } else {
151                 return "_" x (length($val) * 2 - 1);
152         }
153 }
154
155 sub weird_space_unencode {
156         my $val = shift;
157         if (length($val) % 2 == 0) {
158                 return "_" x (length($val) / 2);
159         } else {
160                 return " " x ((length($val) + 1) / 2);
161         }
162 }
163                 
164 sub pretty_escape {
165         my $value = shift;
166
167         $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
168         $value = URI::Escape::uri_escape($value);
169         $value =~ s/%2F/\//g;
170
171         return $value;
172 }
173
174 sub pretty_unescape {
175         my $value = shift;
176
177         # URI unescaping is already done for us
178         $value =~ s/(_+)/weird_space_unencode($1)/ge;
179
180         return $value;
181 }
182
183 sub print_link {
184         my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
185         my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
186         if (defined($accesskey) && length($accesskey) == 1) {
187                 $str .= " accesskey=\"$accesskey\"";
188         }
189         $str .= ">$title</a>";
190         $r->print($str);
191 }
192
193 sub get_dbh {
194         # Check that we are alive
195         if (!(defined($dbh) && $dbh->ping)) {
196                 # Try to reconnect
197                 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
198                 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
199                         $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
200                         $dbh = undef;
201                         die "Couldn't connect to PostgreSQL database";
202                 }
203         }
204
205         return $dbh;
206 }
207
208 sub get_base {
209         my $r = shift;
210         return $r->dir_config('ImageBase');
211 }
212
213 sub get_disk_location {
214         my ($r, $id) = @_;
215         my $dir = POSIX::floor($id / 256);
216         return get_base($r) . "images/$dir/$id.jpg";
217 }
218
219 sub get_cache_location {
220         my ($r, $id, $width, $height, $infobox) = @_;
221         my $dir = POSIX::floor($id / 256);
222
223         if ($infobox eq 'both') {
224                 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
225         } elsif ($infobox eq 'nobox') {
226                 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
227         } else {
228                 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
229         }
230 }
231
232 sub get_mipmap_location {
233         my ($r, $id, $width, $height) = @_;
234         my $dir = POSIX::floor($id / 256);
235
236         return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
237 }
238
239 sub update_image_info {
240         my ($r, $id, $width, $height) = @_;
241
242         # Also find the date taken if appropriate (from the EXIF tag etc.)
243         my $exiftool = Image::ExifTool->new;
244         $exiftool->ExtractInfo(get_disk_location($r, $id));
245         my $info = $exiftool->GetInfo();
246         my $datetime = undef;
247                         
248         if (defined($info->{'DateTimeOriginal'})) {
249                 # Parse the date and time over to ISO format
250                 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
251                         $datetime = "$1-$2-$3 $4:$5:$6";
252                 }
253         }
254
255         {
256                 local $dbh->{AutoCommit} = 0;
257
258                 # EXIF information
259                 $dbh->do('DELETE FROM exif_info WHERE image=?',
260                         undef, $id)
261                         or die "Couldn't delete old EXIF information in SQL: $!";
262
263                 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
264                         or die "Couldn't prepare inserting EXIF information: $!";
265
266                 for my $key (keys %$info) {
267                         next if ref $info->{$key};
268                         $q->execute($id, $key, guess_charset($info->{$key}))
269                                 or die "Couldn't insert EXIF information in database: $!";
270                 }
271
272                 # Model/Lens
273                 my $model = $exiftool->GetValue('Model', 'PrintConv');
274                 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
275                 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
276
277                 $model =~ s/^\s*//;
278                 $model =~ s/\s*$//;
279                 $model = undef if (length($model) == 0);
280
281                 $lens =~ s/^\s*//;
282                 $lens =~ s/\s*$//;
283                 $lens = undef if (length($lens) == 0);
284                 
285                 # Now update the main table with the information we've got
286                 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
287                          undef, $width, $height, $datetime, $model, $lens, $id)
288                         or die "Couldn't update width/height in SQL: $!";
289                 
290                 # Tags
291                 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
292                 $dbh->do('DELETE FROM tags WHERE image=?',
293                         undef, $id)
294                         or die "Couldn't delete old tag information in SQL: $!";
295
296                 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
297                         or die "Couldn't prepare inserting tag information: $!";
298
299
300                 for my $tag (@tags) {
301                         $q->execute($id, guess_charset($tag))
302                                 or die "Couldn't insert tag information in database: $!";
303                 }
304
305                 # update the last_picture cache as well (this should of course be done
306                 # via a trigger, but this is less complicated :-) )
307                 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
308                         undef, $datetime, $id)
309                         or die "Couldn't update last_picture in SQL: $!";
310         }
311 }
312
313 sub check_access {
314         my $r = shift;
315
316         my $auth = $r->headers_in->{'authorization'};
317         if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
318                 $r->content_type('text/plain; charset=utf-8');
319                 $r->status(401);
320                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
321                 $r->print("Need authorization\n");
322                 return undef;
323         }
324         
325         #return qw(sesse Sesse);
326
327         my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
328         # WinXP is stupid :-)
329         if ($user =~ /^.*\\(.*)$/) {
330                 $user = $1;
331         }
332
333         my $takenby;
334         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
335                 $user = $1;
336                 $takenby = $2;
337         } else {
338                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
339         }
340         
341         my $oldpass = $pass;
342         $pass = Digest::SHA1::sha1_base64($pass);
343         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
344                 undef, $user, $pass, $r->get_server_name);
345         if ($ref->{'auth'} != 1) {
346                 $r->content_type('text/plain; charset=utf-8');
347                 warn "No user exists, only $auth";
348                 $r->status(401);
349                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
350                 $r->print("Authorization failed");
351                 $r->log->warn("Authentication failed for $user/$takenby");
352                 return undef;
353         }
354
355         $r->log->info("Authentication succeeded for $user/$takenby");
356
357         return ($user, $takenby);
358 }
359         
360 sub stat_image {
361         my ($r, $event, $filename) = (@_);
362         my $ref = $dbh->selectrow_hashref(
363                 'SELECT id FROM images WHERE event=? AND filename=?',
364                 undef, $event, $filename);
365         if (!defined($ref)) {
366                 return (undef, undef, undef);
367         }
368         return stat_image_from_id($r, $ref->{'id'});
369 }
370
371 sub stat_image_from_id {
372         my ($r, $id) = @_;
373
374         my $fname = get_disk_location($r, $id);
375         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
376                 or return (undef, undef, undef);
377
378         return ($fname, $size, $mtime);
379 }
380
381 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
382 # the smallest mipmap larger than the largest of them.
383 sub make_mipmap {
384         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
385         my ($img, $mmimg, $width, $height);
386         
387         my $physical_fname = get_disk_location($r, $id);
388
389         # If we don't know the size, we'll need to read it in anyway
390         if (!defined($dbwidth) || !defined($dbheight)) {
391                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
392                 $width = $img->Get('columns');
393                 $height = $img->Get('rows');
394         } else {
395                 $width = $dbwidth;
396                 $height = $dbheight;
397         }
398
399         # Generate the list of mipmaps
400         my @mmlist = ();
401         
402         my $mmwidth = $width;
403         my $mmheight = $height;
404
405         while ($mmwidth > 1 || $mmheight > 1) {
406                 my $new_mmwidth = POSIX::floor($mmwidth / 2);           
407                 my $new_mmheight = POSIX::floor($mmheight / 2);         
408
409                 $new_mmwidth = 1 if ($new_mmwidth < 1);
410                 $new_mmheight = 1 if ($new_mmheight < 1);
411
412                 my $large_enough = 1;
413                 for my $i (0..($#res/2)) {
414                         my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
415                         if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
416                                 $large_enough = 0;
417                                 last;
418                         }
419                 }
420                                 
421                 last if (!$large_enough);
422
423                 $mmwidth = $new_mmwidth;
424                 $mmheight = $new_mmheight;
425
426                 push @mmlist, [ $mmwidth, $mmheight ];
427         }
428                 
429         # Ensure that all of them are OK
430         my $last_good_mmlocation;
431         for my $i (0..$#mmlist) {
432                 my $last = ($i == $#mmlist);
433                 my $mmres = $mmlist[$i];
434
435                 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
436                 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
437                         if (!defined($img)) {
438                                 if (defined($last_good_mmlocation)) {
439                                         if ($can_use_qscale) {
440                                                 $img = Sesse::pr0n::QscaleProxy->new;
441                                         } else {
442                                                 $img = Image::Magick->new;
443                                         }
444                                         $img->Read($last_good_mmlocation);
445                                 } else {
446                                         $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
447                                 }
448                         }
449                         my $cimg;
450                         if ($last) {
451                                 $cimg = $img;
452                         } else {
453                                 $cimg = $img->Clone();
454                         }
455                         $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
456                         $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
457                         $cimg->Strip();
458                         my $err = $cimg->write(
459                                 filename => $mmlocation,
460                                 quality => 95,
461                                 'sampling-factor' => '1x1'
462                         );
463                         $img = $cimg;
464                 } else {
465                         $last_good_mmlocation = $mmlocation;
466                 }
467                 if ($last && !defined($img)) {
468                         # OK, read in the smallest one
469                         if ($can_use_qscale) {
470                                 $img = Sesse::pr0n::QscaleProxy->new;
471                         } else {
472                                 $img = Image::Magick->new;
473                         }
474                         my $err = $img->Read($mmlocation);
475                 }
476         }
477
478         if (!defined($img)) {
479                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
480         }
481         return $img;
482 }
483
484 sub read_original_image {
485         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
486
487         my $physical_fname = get_disk_location($r, $id);
488
489         # Read in the original image
490         my $magick;
491         if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
492                 $magick = Sesse::pr0n::QscaleProxy->new;
493         } else {
494                 $magick = Image::Magick->new;
495         }
496         my $err;
497
498         # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
499         # The delegate support is rather broken and causes very odd stuff to happen when
500         # more than one thread does this at the same time. Thus, we simply do it ourselves.
501         if ($filename =~ /\.(nef|cr2)$/i) {
502                 # this would suffice if ImageMagick gets to fix their handling
503                 # $physical_fname = "NEF:$physical_fname";
504                 
505                 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
506                         or error("dcraw: $!");
507                 $err = $magick->Read(file => \*DCRAW);
508                 close(DCRAW);
509         } else {
510                 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
511                 # RGB is slightly faster (no colorspace conversion needed) and works equally
512                 # well for our uses, as long as we don't need to draw an information box,
513                 # which trickles several ImageMagick bugs related to colorspace handling.
514                 # (Ideally we'd be able to keep the image subsampled and
515                 # planar, but that would probably be difficult for ImageMagick to expose.)
516                 #if (!$infobox) {
517                 #       $magick->Set(colorspace=>'YCbCr');
518                 #}
519                 $err = $magick->Read($physical_fname);
520         }
521         
522         if ($err) {
523                 $r->log->warn("$physical_fname: $err");
524                 $err =~ /(\d+)/;
525                 if ($1 >= 400) {
526                         undef $magick;
527                         error($r, "$physical_fname: $err");
528                 }
529         }
530
531         # If we use ->[0] unconditionally, text rendering (!) seems to crash
532         my $img;
533         if (ref($magick)) {
534                 $img = $magick;
535         } else {
536                 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
537         }
538
539         my $width = $img->Get('columns');
540         my $height = $img->Get('rows');
541
542         # Update the SQL database if it doesn't contain the required info
543         if (!defined($dbwidth) || !defined($dbheight)) {
544                 $r->log->info("Updating width/height for $id: $width x $height");
545                 update_image_info($r, $id, $width, $height);
546         }
547
548         return $img;
549 }
550
551 sub ensure_cached {
552         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
553
554         my $fname = get_disk_location($r, $id);
555         if ($infobox ne 'box') {
556                 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
557                         return ($fname, undef);
558                 }
559         }
560
561         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
562         my $err;
563         if (! -r $cachename or (-M $cachename > -M $fname)) {
564                 # If we are in overload mode (aka Slashdot mode), refuse to generate
565                 # new thumbnails.
566                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
567                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
568                         error($r, 'System is in overload mode, not doing any scaling');
569                 }
570
571                 # If we're being asked for just the box, make a new image with just the box.
572                 # We don't care about @otherres since each of these images are
573                 # already pretty cheap to generate, but we need the exact width so we can make
574                 # one in the right size.
575                 if ($infobox eq 'box') {
576                         my ($img, $width, $height);
577
578                         # This is slow, but should fortunately almost never happen, so don't bother
579                         # special-casing it.
580                         if (!defined($dbwidth) || !defined($dbheight)) {
581                                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
582                                 $width = $img->Get('columns');
583                                 $height = $img->Get('rows');
584                                 @$img = ();
585                         } else {
586                                 $img = Image::Magick->new;
587                                 $width = $dbwidth;
588                                 $height = $dbheight;
589                         }
590                         
591                         if (defined($xres) && defined($yres)) {
592                                 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
593                         }
594                         $height = 24;
595                         $img->Set(size=>($width . "x" . $height));
596                         $img->Read('xc:white');
597                                 
598                         my $info = Image::ExifTool::ImageInfo($fname);
599                         if (make_infobox($img, $info, $r)) {
600                                 $img->Quantize(colors=>16, dither=>'False');
601
602                                 # Since the image is grayscale, ImageMagick overrides us and writes this
603                                 # as grayscale anyway, but at least we get rid of the alpha channel this
604                                 # way.
605                                 $img->Set(type=>'Palette');
606                         } else {
607                                 # Not enough room for the text, make a tiny dummy transparent infobox
608                                 @$img = ();
609                                 $img->Set(size=>"1x1");
610                                 $img->Read('null:');
611
612                                 $width = 1;
613                                 $height = 1;
614                         }
615                                 
616                         $err = $img->write(filename => $cachename, quality => 90, depth => 8);
617                         $r->log->info("New infobox cache: $width x $height for $id.jpg");
618                         
619                         return ($cachename, 'image/png');
620                 }
621
622                 my $can_use_qscale = 0;
623                 if ($infobox eq 'nobox') {
624                         $can_use_qscale = 1;
625                 }
626
627                 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
628
629                 while (defined($xres) && defined($yres)) {
630                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
631                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
632                         
633                         my $cimg;
634                         if (defined($nxres) && defined($nyres)) {
635                                 # we have more resolutions to scale, so don't throw
636                                 # the image away
637                                 $cimg = $img->Clone();
638                         } else {
639                                 $cimg = $img;
640                         }
641                 
642                         my $width = $img->Get('columns');
643                         my $height = $img->Get('rows');
644                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
645
646                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
647                         my $filter = 'Mitchell';
648                         my $quality = 90;
649                         my $sf = undef;
650
651                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
652                                 $filter = 'Lanczos';
653                                 $quality = 85;
654                                 $sf = "1x1";
655                         }
656
657                         if ($xres != -1) {
658                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
659                         }
660
661                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
662                                 my $info = Image::ExifTool::ImageInfo($fname);
663                                 make_infobox($cimg, $info, $r);
664                         }
665
666                         # Strip EXIF tags etc.
667                         $cimg->Strip();
668
669                         {
670                                 my %parms = (
671                                         filename => $cachename,
672                                         quality => $quality
673                                 );
674                                 if (($nwidth >= 640 && $nheight >= 480) ||
675                                     ($nwidth >= 480 && $nheight >= 640)) {
676                                         $parms{'interlace'} = 'Plane';
677                                 }
678                                 if (defined($sf)) {
679                                         $parms{'sampling-factor'} = $sf;
680                                 }
681                                 $err = $cimg->write(%parms);
682                         }
683
684                         undef $cimg;
685
686                         ($xres, $yres) = ($nxres, $nyres);
687
688                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
689                 }
690                 
691                 undef $img;
692                 if ($err) {
693                         $r->log->warn("$fname: $err");
694                         $err =~ /(\d+)/;
695                         if ($1 >= 400) {
696                                 #@$magick = ();
697                                 error($r, "$fname: $err");
698                         }
699                 }
700         }
701         return ($cachename, 'image/jpeg');
702 }
703
704 sub get_mimetype_from_filename {
705         my $filename = shift;
706         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
707         $type = "image/jpeg" if (!defined($type));
708         return $type;
709 }
710
711 sub make_infobox {
712         my ($img, $info, $r) = @_;
713
714         # The infobox is of the form
715         # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
716         # possibly with some parts omitted -- the middle part is known as the "classic
717         # fields"; note the comma separation. Every field has an associated "bold flag"
718         # in the second part.
719         
720         my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
721                 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
722         my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
723                 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
724
725         my @classic_fields = ();
726         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
727                 push @classic_fields, [ $1 . "mm", 0 ];
728         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
729                 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
730         }
731
732         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
733                 my ($a, $b) = ($1, $2);
734                 my $gcd = gcd($a, $b);
735                 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
736         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+))$/) {
737                 push @classic_fields, [ $1 . "s", $shutter_priority ];
738         }
739
740         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
741                 my $f = $1/$2;
742                 if ($f >= 10) {
743                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
744                 } else {
745                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
746                 }
747         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
748                 my $f = $info->{'FNumber'};
749                 if ($f >= 10) {
750                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
751                 } else {
752                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
753                 }
754         }
755
756 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
757
758         my $iso = undef;
759         if (defined($info->{'NikonD1-ISOSetting'})) {
760                 $iso = $info->{'NikonD1-ISOSetting'};
761         } elsif (defined($info->{'ISO'})) {
762                 $iso = $info->{'ISO'};
763         } elsif (defined($info->{'ISOSetting'})) {
764                 $iso = $info->{'ISOSetting'};
765         }
766         if (defined($iso) && $iso =~ /(\d+)/) {
767                 push @classic_fields, [ $1 . " ISO", 0 ];
768         }
769
770         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
771                 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
772         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
773                 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
774         }
775
776         # Now piece together the rest
777         my @parts = ();
778         
779         if (defined($info->{'DateTimeOriginal'}) &&
780             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
781             && $1 >= 1990) {
782                 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
783         }
784
785         if (defined($info->{'Model'})) {
786                 my $model = $info->{'Model'}; 
787                 $model =~ s/^\s+//;
788                 $model =~ s/\s+$//;
789
790                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
791                 push @parts, [ $model, 0 ];
792         }
793         
794         # classic fields
795         if (scalar @classic_fields > 0) {
796                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
797
798                 my $first_elem = 1;
799                 for my $field (@classic_fields) {
800                         push @parts, [ ', ', 0 ] if (!$first_elem);
801                         $first_elem = 0;
802                         push @parts, $field;
803                 }
804         }
805
806         if (defined($info->{'Flash'})) {
807                 if ($info->{'Flash'} =~ /did not fire/i ||
808                     $info->{'Flash'} =~ /no flash/i ||
809                     $info->{'Flash'} =~ /not fired/i ||
810                     $info->{'Flash'} =~ /Off/)  {
811                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
812                         push @parts, [ "No flash", 0 ];
813                 } elsif ($info->{'Flash'} =~ /fired/i ||
814                          $info->{'Flash'} =~ /On/) {
815                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
816                         push @parts, [ "Flash", 0 ];
817                 } else {
818                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
819                         push @parts, [ $info->{'Flash'}, 0 ];
820                 }
821         }
822
823         return 0 if (scalar @parts == 0);
824
825         # Find the required width
826         my $th = 0;
827         my $tw = 0;
828
829         for my $part (@parts) {
830                 my $font;
831                 if ($part->[1]) {
832                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
833                 } else {
834                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
835                 }
836
837                 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
838
839                 $tw += $w;
840                 $th = $h if ($h > $th);
841         }
842
843         return 0 if ($tw > $img->Get('columns'));
844
845         my $x = 0;
846         my $y = $img->Get('rows') - 24;
847
848         # Hit exact DCT blocks
849         $y -= ($y % 8);
850
851         my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
852         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
853         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
854         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
855
856         # Start writing out the text
857         $x = ($img->Get('columns') - $tw) / 2;
858
859         my $room = ($img->Get('rows') - 1 - $y - $th);
860         $y = ($img->Get('rows') - 1) - $room/2;
861         
862         for my $part (@parts) {
863                 my $font;
864                 if ($part->[1]) {
865                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
866                 } else {
867                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
868                 }
869                 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
870                 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
871         }
872
873         return 1;
874 }
875
876 sub gcd {
877         my ($a, $b) = @_;
878         return $a if ($b == 0);
879         return gcd($b, $a % $b);
880 }
881
882 sub add_new_event {
883         my ($r, $dbh, $id, $date, $desc) = @_;
884         my @errors = ();
885
886         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
887                 push @errors, "Manglende eller ugyldig ID.";
888         }
889         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
890                 push @errors, "Manglende eller ugyldig dato.";
891         }
892         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
893                 push @errors, "Manglende eller ugyldig beskrivelse.";
894         }
895         
896         if (scalar @errors > 0) {
897                 return @errors;
898         }
899                 
900         my $vhost = $r->get_server_name;
901         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
902                 undef, $id, $date, $desc, $vhost)
903                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
904         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
905                 undef, $vhost, $id)
906                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
907         purge_cache($r, "/");
908
909         return ();
910 }
911
912 sub guess_charset {
913         my $text = shift;
914         my $decoded;
915
916         eval {
917                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
918         };
919         if ($@) {
920                 $decoded = Encode::decode("iso8859-1", $text);
921         }
922
923         return $decoded;
924 }
925
926 # Depending on your front-end cache, you might want to get creative somehow here.
927 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
928 # regex tacked onto a request into something useful. The elements given in
929 # should not be regexes, though, as e.g. Squid will not be able to handle that.
930 sub purge_cache {
931         my ($r, @elements) = @_;
932         return if (scalar @elements == 0);
933
934         my @pe = ();
935         for my $elem (@elements) {
936                 $r->log->info("Purging $elem");
937                 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
938                 push @pe, $e;
939         }
940
941         my $regex = "^";
942         if (scalar @pe == 1) {
943                 $regex .= $pe[0];
944         } else {
945                 $regex .= "(" . join('|', @pe) . ")";
946         }
947         $regex .= "(\\?.*)?\$";
948         $r->headers_out->{'X-Pr0n-Purge'} = $regex;
949
950         $r->log->info($r->headers_out->{'X-Pr0n-Purge'});
951 }
952                                 
953 # Find a list of all cache URLs for a given image, given what we have on disk.
954 sub get_all_cache_urls {
955         my ($r, $dbh, $id) = @_;
956         my $dir = POSIX::floor($id / 256);
957         my @ret = ();
958
959         my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
960                 or die "Couldn't prepare: " . $dbh->errstr;
961         $q->execute($id)
962                 or die "Couldn't find event and filename: " . $dbh->errstr;
963         my $ref = $q->fetchrow_hashref; 
964         my $event = $ref->{'event'};
965         my $filename = $ref->{'filename'};
966         $q->finish;
967
968         my $base = get_base($r) . "cache/$dir";
969         for my $file (<$base/$id-*>) {
970                 my $fname = File::Basename::basename($file);
971                 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
972                         # Mipmaps don't have an URL, ignore
973                 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
974                         push @ret, "/$event/$filename";
975                 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
976                         push @ret, "/$event/$1x$2/$filename";
977                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
978                         push @ret, "/$event/$1x$2/nobox/$filename";
979                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
980                         push @ret, "/$event/$1x$2/box/$filename";
981                 } else {
982                         $r->log->warning("Couldn't find a purging URL for $fname");
983                 }
984         }
985
986         return @ret;
987 }
988
989 1;
990
991