]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Move from mod_perl to being a PSGI app.
[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                 # Tags
308                 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
309                 if (scalar @tags == 0) {
310                         # This is XMP-dc:Subject, an RDF bag of tags.
311                         @tags = $exiftool->GetValue('Subject', 'ValueConv');
312                 }
313                 $dbh->do('DELETE FROM tags WHERE image=?',
314                         undef, $id)
315                         or die "Couldn't delete old tag information in SQL: $!";
316
317                 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
318                         or die "Couldn't prepare inserting tag information: $!";
319
320
321                 for my $tag (@tags) {
322                         $q->execute($id, guess_charset($tag))
323                                 or die "Couldn't insert tag information in database: $!";
324                 }
325
326                 # update the last_picture cache as well (this should of course be done
327                 # via a trigger, but this is less complicated :-) )
328                 $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=?)',
329                         undef, $datetime, $id)
330                         or die "Couldn't update last_picture in SQL: $!";
331         }
332 }
333
334 sub check_access {
335         my $r = shift;
336         
337         #return qw(sesse Sesse);
338
339         my $auth = $r->header('authorization');
340         if (!defined($auth)) {
341                 return undef;
342         } 
343         if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
344                 return check_basic_auth($r, $1);
345         }       
346         return undef;
347 }
348
349 sub generate_401 {
350         my ($r) = @_;
351         my $res = Plack::Response->new(401);
352         $res->content_type('text/plain; charset=utf-8');
353         $res->status(401);
354         $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
355
356         $res->body("Need authorization\n");
357         return $res;
358 }
359
360 sub check_basic_auth {
361         my ($r, $auth) = @_;    
362
363         my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
364         my ($user, $takenby) = extract_takenby($raw_user);
365
366         my $ref = $dbh->selectrow_hashref('SELECT sha1password,cryptpassword FROM users WHERE username=? AND vhost=?',
367                 undef, $user, Sesse::pr0n::Common::get_server_name($r));
368         my ($sha1_matches, $bcrypt_matches) = (0, 0);
369         if (defined($ref) && defined($ref->{'sha1password'})) {
370                 $sha1_matches = (Digest::SHA::sha1_base64($pass) eq $ref->{'sha1password'});
371         }
372         if (defined($ref) && defined($ref->{'cryptpassword'})) {
373                 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
374         }
375
376         if (!defined($ref) || (!$sha1_matches && !$bcrypt_matches)) {
377                 $r->content_type('text/plain; charset=utf-8');
378                 log_warn($r, "Authentication failed for $user/$takenby");
379                 return undef;
380         }
381         log_info($r, "Authentication succeeded for $user/$takenby");
382
383         # Make sure we can use bcrypt authentication in the future with this password.
384         # Also remove old-style SHA1 password when we migrate.
385         if (!$bcrypt_matches) {
386                 my $salt = get_pseudorandom_bytes(16);  # Doesn't need to be cryptographically secur.
387                 my $hash = "\$2a\$07\$" . Crypt::Eksblowfish::Bcrypt::en_base64($salt);
388                 my $cryptpassword = Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $hash);
389                 $dbh->do('UPDATE users SET sha1password=NULL,cryptpassword=? WHERE username=? AND vhost=?',
390                         undef, $cryptpassword, $user, Sesse::pr0n::Common::get_server_name($r))
391                         or die "Couldn't update: " . $dbh->errstr;
392                 log_info($r, "Updated bcrypt hash for $user");
393         }
394
395         return ($user, $takenby);
396 }
397
398 sub get_pseudorandom_bytes {
399         my $num_left = shift;
400         my $bytes = "";
401         open my $randfh, "<", "/dev/urandom"
402                 or die "/dev/urandom: $!";
403         binmode $randfh;
404         while ($num_left > 0) {
405                 my $tmp;
406                 if (sysread($randfh, $tmp, $num_left) == -1) {
407                         die "sysread(/dev/urandom): $!";
408                 }
409                 $bytes .= $tmp;
410                 $num_left -= length($bytes);
411         }
412         close $randfh;
413         return $bytes;
414 }
415
416 sub extract_takenby {
417         my ($user) = shift;
418
419         # WinXP is stupid :-)
420         if ($user =~ /^.*\\(.*)$/) {
421                 $user = $1;
422         }
423
424         my $takenby;
425         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
426                 $user = $1;
427                 $takenby = $2;
428         } else {
429                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
430         }
431
432         return ($user, $takenby);
433 }
434         
435 sub stat_image {
436         my ($r, $event, $filename) = (@_);
437         my $ref = $dbh->selectrow_hashref(
438                 'SELECT id FROM images WHERE event=? AND filename=?',
439                 undef, $event, $filename);
440         if (!defined($ref)) {
441                 return (undef, undef, undef);
442         }
443         return stat_image_from_id($r, $ref->{'id'});
444 }
445
446 sub stat_image_from_id {
447         my ($r, $id) = @_;
448
449         my $fname = get_disk_location($r, $id);
450         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
451                 or return (undef, undef, undef);
452
453         return ($fname, $size, $mtime);
454 }
455
456 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
457 # the smallest mipmap larger than the largest of them, as well as the original image
458 # dimensions.
459 sub make_mipmap {
460         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
461         my ($img, $mmimg, $width, $height);
462         
463         my $physical_fname = get_disk_location($r, $id);
464
465         # If we don't know the size, we'll need to read it in anyway
466         if (!defined($dbwidth) || !defined($dbheight)) {
467                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
468                 $width = $img->Get('columns');
469                 $height = $img->Get('rows');
470         } else {
471                 $width = $dbwidth;
472                 $height = $dbheight;
473         }
474
475         # Generate the list of mipmaps
476         my @mmlist = ();
477         
478         my $mmwidth = $width;
479         my $mmheight = $height;
480
481         while ($mmwidth > 1 || $mmheight > 1) {
482                 my $new_mmwidth = POSIX::floor($mmwidth / 2);           
483                 my $new_mmheight = POSIX::floor($mmheight / 2);         
484
485                 $new_mmwidth = 1 if ($new_mmwidth < 1);
486                 $new_mmheight = 1 if ($new_mmheight < 1);
487
488                 my $large_enough = 1;
489                 for my $i (0..($#res/2)) {
490                         my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
491                         if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
492                                 $large_enough = 0;
493                                 last;
494                         }
495                 }
496                                 
497                 last if (!$large_enough);
498
499                 $mmwidth = $new_mmwidth;
500                 $mmheight = $new_mmheight;
501
502                 push @mmlist, [ $mmwidth, $mmheight ];
503         }
504                 
505         # Ensure that all of them are OK
506         my $last_good_mmlocation;
507         for my $i (0..$#mmlist) {
508                 my $last = ($i == $#mmlist);
509                 my $mmres = $mmlist[$i];
510
511                 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
512                 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
513                         if (!defined($img)) {
514                                 if (defined($last_good_mmlocation)) {
515                                         if ($can_use_qscale) {
516                                                 $img = Sesse::pr0n::QscaleProxy->new;
517                                         } else {
518                                                 $img = Image::Magick->new;
519                                         }
520                                         $img->Read($last_good_mmlocation);
521                                 } else {
522                                         $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
523                                 }
524                         }
525                         my $cimg;
526                         if ($last) {
527                                 $cimg = $img;
528                         } else {
529                                 $cimg = $img->Clone();
530                         }
531                         log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
532                         $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
533                         $cimg->Strip();
534                         my $err = $cimg->write(
535                                 filename => $mmlocation,
536                                 quality => 95,
537                                 'sampling-factor' => '1x1'
538                         );
539                         $img = $cimg;
540                 } else {
541                         $last_good_mmlocation = $mmlocation;
542                 }
543                 if ($last && !defined($img)) {
544                         # OK, read in the smallest one
545                         if ($can_use_qscale) {
546                                 $img = Sesse::pr0n::QscaleProxy->new;
547                         } else {
548                                 $img = Image::Magick->new;
549                         }
550                         my $err = $img->Read($mmlocation);
551                 }
552         }
553
554         if (!defined($img)) {
555                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
556                 $width = $img->Get('columns');
557                 $height = $img->Get('rows');
558         }
559         return ($img, $width, $height);
560 }
561
562 sub read_original_image {
563         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
564
565         my $physical_fname = get_disk_location($r, $id);
566
567         # Read in the original image
568         my $magick;
569         if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
570                 $magick = Sesse::pr0n::QscaleProxy->new;
571         } else {
572                 $magick = Image::Magick->new;
573         }
574         my $err;
575
576         # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
577         # The delegate support is rather broken and causes very odd stuff to happen when
578         # more than one thread does this at the same time. Thus, we simply do it ourselves.
579         if ($filename =~ /\.(nef|cr2)$/i) {
580                 # this would suffice if ImageMagick gets to fix their handling
581                 # $physical_fname = "NEF:$physical_fname";
582                 
583                 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
584                         or error("dcraw: $!");
585                 $err = $magick->Read(file => \*DCRAW);
586                 close(DCRAW);
587         } else {
588                 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
589                 # RGB is slightly faster (no colorspace conversion needed) and works equally
590                 # well for our uses, as long as we don't need to draw an information box,
591                 # which trickles several ImageMagick bugs related to colorspace handling.
592                 # (Ideally we'd be able to keep the image subsampled and
593                 # planar, but that would probably be difficult for ImageMagick to expose.)
594                 #if (!$infobox) {
595                 #       $magick->Set(colorspace=>'YCbCr');
596                 #}
597                 $err = $magick->Read($physical_fname);
598         }
599         
600         if ($err) {
601                 log_warn($r, "$physical_fname: $err");
602                 $err =~ /(\d+)/;
603                 if ($1 >= 400) {
604                         undef $magick;
605                         error($r, "$physical_fname: $err");
606                 }
607         }
608
609         # If we use ->[0] unconditionally, text rendering (!) seems to crash
610         my $img;
611         if (ref($magick) !~ /Image::Magick/) {
612                 $img = $magick;
613         } else {
614                 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
615         }
616
617         return $img;
618 }
619
620 sub ensure_cached {
621         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
622
623         my ($new_dbwidth, $new_dbheight);
624
625         my $fname = get_disk_location($r, $id);
626         if ($infobox ne 'box') {
627                 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
628                         return ($fname, undef);
629                 }
630         }
631
632         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
633         my $err;
634         if (! -r $cachename or (-M $cachename > -M $fname)) {
635                 # If we are in overload mode (aka Slashdot mode), refuse to generate
636                 # new thumbnails.
637                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
638                         log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
639                         error($r, 'System is in overload mode, not doing any scaling');
640                 }
641
642                 # If we're being asked for just the box, make a new image with just the box.
643                 # We don't care about @otherres since each of these images are
644                 # already pretty cheap to generate, but we need the exact width so we can make
645                 # one in the right size.
646                 if ($infobox eq 'box') {
647                         my ($img, $width, $height);
648
649                         # This is slow, but should fortunately almost never happen, so don't bother
650                         # special-casing it.
651                         if (!defined($dbwidth) || !defined($dbheight)) {
652                                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
653                                 $new_dbwidth = $width = $img->Get('columns');
654                                 $new_dbheight = $height = $img->Get('rows');
655                                 @$img = ();
656                         } else {
657                                 $img = Image::Magick->new;
658                                 $width = $dbwidth;
659                                 $height = $dbheight;
660                         }
661                         
662                         if (defined($xres) && defined($yres)) {
663                                 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
664                         }
665                         $height = 24 * $dpr;
666                         $img->Set(size=>($width . "x" . $height));
667                         $img->Read('xc:white');
668                                 
669                         my $info = Image::ExifTool::ImageInfo($fname);
670                         if (make_infobox($img, $info, $r, $dpr)) {
671                                 $img->Quantize(colors=>16, dither=>'False');
672
673                                 # Since the image is grayscale, ImageMagick overrides us and writes this
674                                 # as grayscale anyway, but at least we get rid of the alpha channel this
675                                 # way.
676                                 $img->Set(type=>'Palette');
677                         } else {
678                                 # Not enough room for the text, make a tiny dummy transparent infobox
679                                 @$img = ();
680                                 $img->Set(size=>"1x1");
681                                 $img->Read('null:');
682
683                                 $width = 1;
684                                 $height = 1;
685                         }
686                                 
687                         $err = $img->write(filename => $cachename, quality => 90, depth => 8);
688                         log_info($r, "New infobox cache: $width x $height for $id.jpg");
689                         
690                         return ($cachename, 'image/png');
691                 }
692
693                 my $can_use_qscale = 0;
694                 if ($infobox eq 'nobox') {
695                         $can_use_qscale = 1;
696                 }
697
698                 my $img;
699                 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
700
701                 while (defined($xres) && defined($yres)) {
702                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
703                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
704                         
705                         my $cimg;
706                         if (defined($nxres) && defined($nyres)) {
707                                 # we have more resolutions to scale, so don't throw
708                                 # the image away
709                                 $cimg = $img->Clone();
710                         } else {
711                                 $cimg = $img;
712                         }
713                 
714                         my $width = $img->Get('columns');
715                         my $height = $img->Get('rows');
716                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
717
718                         my $filter = 'Lanczos';
719                         my $quality = 87;
720                         my $sf = "1x1";
721
722                         if ($xres != -1) {
723                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
724                         }
725
726                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
727                                 my $info = Image::ExifTool::ImageInfo($fname);
728                                 make_infobox($cimg, $info, $r, 1);
729                         }
730
731                         # Strip EXIF tags etc.
732                         $cimg->Strip();
733
734                         {
735                                 my %parms = (
736                                         filename => $cachename,
737                                         quality => $quality
738                                 );
739                                 if (($nwidth >= 640 && $nheight >= 480) ||
740                                     ($nwidth >= 480 && $nheight >= 640)) {
741                                         $parms{'interlace'} = 'Plane';
742                                 }
743                                 if (defined($sf)) {
744                                         $parms{'sampling-factor'} = $sf;
745                                 }
746                                 $err = $cimg->write(%parms);
747                         }
748
749                         undef $cimg;
750
751                         ($xres, $yres) = ($nxres, $nyres);
752
753                         log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
754                 }
755                 
756                 undef $img;
757                 if ($err) {
758                         log_warn($r, "$fname: $err");
759                         $err =~ /(\d+)/;
760                         if ($1 >= 400) {
761                                 #@$magick = ();
762                                 error($r, "$fname: $err");
763                         }
764                 }
765         }
766         
767         # Update the SQL database if it doesn't contain the required info
768         if (!defined($dbwidth) && defined($new_dbwidth)) {
769                 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
770                 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
771         }
772
773         return ($cachename, 'image/jpeg');
774 }
775
776 sub get_mimetype_from_filename {
777         my $filename = shift;
778         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
779         $type = "image/jpeg" if (!defined($type));
780         return $type;
781 }
782
783 sub make_infobox {
784         my ($img, $info, $r, $dpr) = @_;
785
786         # The infobox is of the form
787         # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
788         # possibly with some parts omitted -- the middle part is known as the "classic
789         # fields"; note the comma separation. Every field has an associated "bold flag"
790         # in the second part.
791         
792         my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
793                 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
794         my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
795                 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
796         if ($info->{'ExposureProgram'} =~ /manual/i) {
797                 $manual_shutter = 1;
798                 $manual_aperture = 1;
799         }
800
801         my @classic_fields = ();
802         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
803                 push @classic_fields, [ $1 . "mm", 0 ];
804         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
805                 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
806         }
807
808         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
809                 my ($a, $b) = ($1, $2);
810                 my $gcd = gcd($a, $b);
811                 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
812         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
813                 push @classic_fields, [ $1 . "s", $manual_shutter ];
814         }
815
816         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
817                 my $f = $1/$2;
818                 if ($f >= 10) {
819                         push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
820                 } else {
821                         push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
822                 }
823         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
824                 my $f = $info->{'FNumber'};
825                 if ($f >= 10) {
826                         push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
827                 } else {
828                         push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
829                 }
830         }
831
832 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
833
834         my $iso = undef;
835         if (defined($info->{'NikonD1-ISOSetting'})) {
836                 $iso = $info->{'NikonD1-ISOSetting'};
837         } elsif (defined($info->{'ISO'})) {
838                 $iso = $info->{'ISO'};
839         } elsif (defined($info->{'ISOSetting'})) {
840                 $iso = $info->{'ISOSetting'};
841         }
842         if (defined($iso) && $iso =~ /(\d+)/) {
843                 push @classic_fields, [ $1 . " ISO", 0 ];
844         }
845
846         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
847                 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
848         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
849                 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
850         }
851
852         # Now piece together the rest
853         my @parts = ();
854         
855         if (defined($info->{'DateTimeOriginal'}) &&
856             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
857             && $1 >= 1990) {
858                 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
859         }
860
861         if (defined($info->{'Model'})) {
862                 my $model = $info->{'Model'}; 
863                 $model =~ s/^\s+//;
864                 $model =~ s/\s+$//;
865
866                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
867                 push @parts, [ $model, 0 ];
868         }
869         
870         # classic fields
871         if (scalar @classic_fields > 0) {
872                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
873
874                 my $first_elem = 1;
875                 for my $field (@classic_fields) {
876                         push @parts, [ ', ', 0 ] if (!$first_elem);
877                         $first_elem = 0;
878                         push @parts, $field;
879                 }
880         }
881
882         if (defined($info->{'Flash'})) {
883                 if ($info->{'Flash'} =~ /did not fire/i ||
884                     $info->{'Flash'} =~ /no flash/i ||
885                     $info->{'Flash'} =~ /not fired/i ||
886                     $info->{'Flash'} =~ /Off/)  {
887                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
888                         push @parts, [ "No flash", 0 ];
889                 } elsif ($info->{'Flash'} =~ /fired/i ||
890                          $info->{'Flash'} =~ /On/) {
891                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
892                         push @parts, [ "Flash", 0 ];
893                 } else {
894                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
895                         push @parts, [ $info->{'Flash'}, 0 ];
896                 }
897         }
898
899         return 0 if (scalar @parts == 0);
900
901         # Find the required width
902         my $th = 0;
903         my $tw = 0;
904
905         for my $part (@parts) {
906                 my $font;
907                 if ($part->[1]) {
908                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
909                 } else {
910                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
911                 }
912
913                 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
914
915                 $tw += $w;
916                 $th = $h if ($h > $th);
917         }
918
919         return 0 if ($tw > $img->Get('columns'));
920
921         my $x = 0;
922         my $y = $img->Get('rows') - 24*$dpr;
923
924         # Hit exact DCT blocks
925         $y -= ($y % 8);
926
927         my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
928         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
929         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
930         $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
931
932         # Start writing out the text
933         $x = ($img->Get('columns') - $tw) / 2;
934
935         my $room = ($img->Get('rows') - $dpr - $y - $th);
936         $y = ($img->Get('rows') - $dpr) - $room/2;
937         
938         for my $part (@parts) {
939                 my $font;
940                 if ($part->[1]) {
941                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
942                 } else {
943                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
944                 }
945                 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
946                 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
947         }
948
949         return 1;
950 }
951
952 sub gcd {
953         my ($a, $b) = @_;
954         return $a if ($b == 0);
955         return gcd($b, $a % $b);
956 }
957
958 sub add_new_event {
959         my ($r, $res, $dbh, $id, $date, $desc) = @_;
960         my @errors = ();
961
962         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
963                 push @errors, "Manglende eller ugyldig ID.";
964         }
965         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
966                 push @errors, "Manglende eller ugyldig dato.";
967         }
968         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
969                 push @errors, "Manglende eller ugyldig beskrivelse.";
970         }
971         
972         if (scalar @errors > 0) {
973                 return @errors;
974         }
975                 
976         my $vhost = Sesse::pr0n::Common::get_server_name($r);
977         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
978                 undef, $id, $date, $desc, $vhost)
979                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
980         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
981                 undef, $vhost, $id)
982                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
983         purge_cache($r, $res, "/");
984
985         return ();
986 }
987
988 sub guess_charset {
989         my $text = shift;
990         my $decoded;
991
992         eval {
993                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
994         };
995         if ($@) {
996                 $decoded = Encode::decode("iso8859-1", $text);
997         }
998
999         return $decoded;
1000 }
1001
1002 # Depending on your front-end cache, you might want to get creative somehow here.
1003 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
1004 # regex tacked onto a request into something useful. The elements given in
1005 # should not be regexes, though, as e.g. Squid will not be able to handle that.
1006 sub purge_cache {
1007         my ($r, $res, @elements) = @_;
1008         return if (scalar @elements == 0);
1009
1010         my @pe = ();
1011         for my $elem (@elements) {
1012                 log_info($r, "Purging $elem");
1013                 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1014                 push @pe, $e;
1015         }
1016
1017         my $regex = "^";
1018         if (scalar @pe == 1) {
1019                 $regex .= $pe[0];
1020         } else {
1021                 $regex .= "(" . join('|', @pe) . ")";
1022         }
1023         $regex .= "(\\?.*)?\$";
1024         $res->header('X-Pr0n-Purge' => $regex);
1025 }
1026                                 
1027 # Find a list of all cache URLs for a given image, given what we have on disk.
1028 sub get_all_cache_urls {
1029         my ($r, $dbh, $id) = @_;
1030         my $dir = POSIX::floor($id / 256);
1031         my @ret = ();
1032
1033         my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1034                 or die "Couldn't prepare: " . $dbh->errstr;
1035         $q->execute($id)
1036                 or die "Couldn't find event and filename: " . $dbh->errstr;
1037         my $ref = $q->fetchrow_hashref; 
1038         my $event = $ref->{'event'};
1039         my $filename = $ref->{'filename'};
1040         $q->finish;
1041
1042         my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
1043         for my $file (<$base/$id-*>) {
1044                 my $fname = File::Basename::basename($file);
1045                 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1046                         # Mipmaps don't have an URL, ignore
1047                 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1048                         push @ret, "/$event/$filename";
1049                 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1050                         push @ret, "/$event/$1x$2/$filename";
1051                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1052                         push @ret, "/$event/$1x$2/nobox/$filename";
1053                 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1054                         push @ret, "/$event/box/$filename";
1055                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1056                         push @ret, "/$event/$1x$2/box/$filename";
1057                 } else {
1058                         log_warn($r, "Couldn't find a purging URL for $fname");
1059                 }
1060         }
1061
1062         return @ret;
1063 }
1064
1065 sub set_last_modified {
1066         my ($res, $mtime) = @_;
1067
1068         my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S %Z", localtime($mtime));
1069         $res->headers({ 'Last-Modified' => $str });
1070 }
1071
1072 sub get_server_name {
1073         my $r = shift;
1074         my $host = $r->env->{'HTTP_HOST'};
1075         $host =~ s/:.*//;
1076         return $host;
1077 }
1078
1079 sub log_info {
1080         my ($r, $msg) = @_;
1081         if (defined($r->logger)) {
1082                 $r->logger->({ level => 'info', message => $msg });
1083         } else {
1084                 print STDERR "[INFO] $msg\n";
1085         }
1086 }
1087
1088 sub log_warn {
1089         my ($r, $msg) = @_;
1090         if (defined($r->logger)) {
1091                 $r->logger->({ level => 'warn', message => $msg });
1092         } else {
1093                 print STDERR "[WARN] $msg\n";
1094         }
1095 }
1096
1097 sub log_error {
1098         my ($r, $msg) = @_;
1099         if (defined($r->logger)) {
1100                 $r->logger->({ level => 'error', message => $msg });
1101         } else {
1102                 print STDERR "[ERROR] $msg\n";
1103         }
1104 }
1105
1106 1;
1107
1108