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