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