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