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