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