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