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