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