]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
95faead21de0e44d1005ba2000b5b4e89214ffc8
[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.65";
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                                         $img = Sesse::pr0n::QscaleProxy->new;
439                                         $img->Read($last_good_mmlocation);
440                                 } else {
441                                         $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
442                                 }
443                         }
444                         my $cimg;
445                         if ($last) {
446                                 $cimg = $img;
447                         } else {
448                                 $cimg = $img->Clone();
449                         }
450                         $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
451                         $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
452                         $cimg->Strip();
453                         my $err = $cimg->write(
454                                 filename => $mmlocation,
455                                 quality => 95,
456                                 'sampling-factor' => '1x1'
457                         );
458                         $img = $cimg;
459                 } else {
460                         $last_good_mmlocation = $mmlocation;
461                 }
462                 if ($last && !defined($img)) {
463                         # OK, read in the smallest one
464                         $img = Sesse::pr0n::QscaleProxy->new;
465                         my $err = $img->Read($mmlocation);
466                 }
467         }
468
469         if (!defined($img)) {
470                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
471         }
472         return $img;
473 }
474
475 sub read_original_image {
476         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
477
478         my $physical_fname = get_disk_location($r, $id);
479
480         # Read in the original image
481         my $magick;
482         if ($can_use_qscale && $filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
483                 $magick = Sesse::pr0n::QscaleProxy->new;
484         } else {
485                 $magick = Image::Magick->new;
486         }
487         my $err;
488
489         # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
490         # The delegate support is rather broken and causes very odd stuff to happen when
491         # more than one thread does this at the same time. Thus, we simply do it ourselves.
492         if ($filename =~ /\.nef$/i) {
493                 # this would suffice if ImageMagick gets to fix their handling
494                 # $physical_fname = "NEF:$physical_fname";
495                 
496                 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
497                         or error("dcraw: $!");
498                 $err = $magick->Read(file => \*DCRAW);
499                 close(DCRAW);
500         } else {
501                 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
502                 # RGB is slightly faster (no colorspace conversion needed) and works equally
503                 # well for our uses, as long as we don't need to draw an information box,
504                 # which trickles several ImageMagick bugs related to colorspace handling.
505                 # (Ideally we'd be able to keep the image subsampled and
506                 # planar, but that would probably be difficult for ImageMagick to expose.)
507                 #if (!$infobox) {
508                 #       $magick->Set(colorspace=>'YCbCr');
509                 #}
510                 $err = $magick->Read($physical_fname);
511         }
512         
513         if ($err) {
514                 $r->log->warn("$physical_fname: $err");
515                 $err =~ /(\d+)/;
516                 if ($1 >= 400) {
517                         undef $magick;
518                         error($r, "$physical_fname: $err");
519                 }
520         }
521
522         # If we use ->[0] unconditionally, text rendering (!) seems to crash
523         my $img;
524         if (ref($magick)) {
525                 $img = $magick;
526         } else {
527                 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
528         }
529
530         my $width = $img->Get('columns');
531         my $height = $img->Get('rows');
532
533         # Update the SQL database if it doesn't contain the required info
534         if (!defined($dbwidth) || !defined($dbheight)) {
535                 $r->log->info("Updating width/height for $id: $width x $height");
536                 update_image_info($r, $id, $width, $height);
537         }
538
539         return $img;
540 }
541
542 sub ensure_cached {
543         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
544
545         my $fname = get_disk_location($r, $id);
546         if ($infobox ne 'box') {
547                 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
548                         return ($fname, undef);
549                 }
550         }
551
552         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
553         my $err;
554         if (! -r $cachename or (-M $cachename > -M $fname)) {
555                 # If we are in overload mode (aka Slashdot mode), refuse to generate
556                 # new thumbnails.
557                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
558                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
559                         error($r, 'System is in overload mode, not doing any scaling');
560                 }
561
562                 # If we're being asked for just the box, make a new image with just the box.
563                 # We don't care about @otherres since each of these images are
564                 # already pretty cheap to generate, but we need the exact width so we can make
565                 # one in the right size.
566                 if ($infobox eq 'box') {
567                         my ($img, $width, $height);
568
569                         # This is slow, but should fortunately almost never happen, so don't bother
570                         # special-casing it.
571                         if (!defined($dbwidth) || !defined($dbheight)) {
572                                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
573                                 $width = $img->Get('columns');
574                                 $height = $img->Get('rows');
575                                 @$img = ();
576                         } else {
577                                 $img = Image::Magick->new;
578                                 $width = $dbwidth;
579                                 $height = $dbheight;
580                         }
581                         
582                         if (defined($xres) && defined($yres)) {
583                                 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
584                         }
585                         $height = 24;
586                         $img->Set(size=>($width . "x" . $height));
587                         $img->Read('xc:white');
588                                 
589                         my $info = Image::ExifTool::ImageInfo($fname);
590                         if (make_infobox($img, $info, $r)) {
591                                 $img->Quantize(colors=>16, dither=>'False');
592
593                                 # Since the image is grayscale, ImageMagick overrides us and writes this
594                                 # as grayscale anyway, but at least we get rid of the alpha channel this
595                                 # way.
596                                 $img->Set(type=>'Palette');
597                         } else {
598                                 # Not enough room for the text, make a tiny dummy transparent infobox
599                                 @$img = ();
600                                 $img->Set(size=>"1x1");
601                                 $img->Read('null:');
602
603                                 $width = 1;
604                                 $height = 1;
605                         }
606                                 
607                         $err = $img->write(filename => $cachename, quality => 90, depth => 8);
608                         $r->log->info("New infobox cache: $width x $height for $id.jpg");
609                         
610                         return ($cachename, 'image/png');
611                 }
612
613                 my $can_use_qscale = 0;
614                 if ($infobox eq 'nobox') {
615                         $can_use_qscale = 1;
616                 }
617
618                 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
619
620                 while (defined($xres) && defined($yres)) {
621                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
622                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
623                         
624                         my $cimg;
625                         if (defined($nxres) && defined($nyres)) {
626                                 # we have more resolutions to scale, so don't throw
627                                 # the image away
628                                 $cimg = $img->Clone();
629                         } else {
630                                 $cimg = $img;
631                         }
632                 
633                         my $width = $img->Get('columns');
634                         my $height = $img->Get('rows');
635                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
636
637                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
638                         my $filter = 'Mitchell';
639                         my $quality = 90;
640                         my $sf = undef;
641
642                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
643                                 $filter = 'Lanczos';
644                                 $quality = 85;
645                                 $sf = "1x1";
646                         }
647
648                         if ($xres != -1) {
649                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
650                         }
651
652                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
653                                 my $info = Image::ExifTool::ImageInfo($fname);
654                                 make_infobox($cimg, $info, $r);
655                         }
656
657                         # Strip EXIF tags etc.
658                         $cimg->Strip();
659
660                         {
661                                 my %parms = (
662                                         filename => $cachename,
663                                         quality => $quality
664                                 );
665                                 if (($nwidth >= 640 && $nheight >= 480) ||
666                                     ($nwidth >= 480 && $nheight >= 640)) {
667                                         $parms{'interlace'} = 'Plane';
668                                 }
669                                 if (defined($sf)) {
670                                         $parms{'sampling-factor'} = $sf;
671                                 }
672                                 $err = $cimg->write(%parms);
673                         }
674
675                         undef $cimg;
676
677                         ($xres, $yres) = ($nxres, $nyres);
678
679                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
680                 }
681                 
682                 undef $img;
683                 if ($err) {
684                         $r->log->warn("$fname: $err");
685                         $err =~ /(\d+)/;
686                         if ($1 >= 400) {
687                                 #@$magick = ();
688                                 error($r, "$fname: $err");
689                         }
690                 }
691         }
692         return ($cachename, 'image/jpeg');
693 }
694
695 sub get_mimetype_from_filename {
696         my $filename = shift;
697         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
698         $type = "image/jpeg" if (!defined($type));
699         return $type;
700 }
701
702 sub make_infobox {
703         my ($img, $info, $r) = @_;
704
705         # The infobox is of the form
706         # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
707         # possibly with some parts omitted -- the middle part is known as the "classic
708         # fields"; note the comma separation. Every field has an associated "bold flag"
709         # in the second part.
710         
711         my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
712                 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
713         my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
714                 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
715
716         my @classic_fields = ();
717         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
718                 push @classic_fields, [ $1 . "mm", 0 ];
719         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
720                 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
721         }
722
723         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
724                 my ($a, $b) = ($1, $2);
725                 my $gcd = gcd($a, $b);
726                 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
727         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
728                 push @classic_fields, [ $1 . "s", $shutter_priority ];
729         }
730
731         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
732                 my $f = $1/$2;
733                 if ($f >= 10) {
734                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
735                 } else {
736                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
737                 }
738         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
739                 my $f = $info->{'FNumber'};
740                 if ($f >= 10) {
741                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
742                 } else {
743                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
744                 }
745         }
746
747 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
748
749         my $iso = undef;
750         if (defined($info->{'NikonD1-ISOSetting'})) {
751                 $iso = $info->{'NikonD1-ISOSetting'};
752         } elsif (defined($info->{'ISO'})) {
753                 $iso = $info->{'ISO'};
754         } elsif (defined($info->{'ISOSetting'})) {
755                 $iso = $info->{'ISOSetting'};
756         }
757         if (defined($iso) && $iso =~ /(\d+)/) {
758                 push @classic_fields, [ $1 . " ISO", 0 ];
759         }
760
761         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
762                 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
763         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
764                 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
765         }
766
767         # Now piece together the rest
768         my @parts = ();
769         
770         if (defined($info->{'DateTimeOriginal'}) &&
771             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
772             && $1 >= 1990) {
773                 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
774         }
775
776         if (defined($info->{'Model'})) {
777                 my $model = $info->{'Model'}; 
778                 $model =~ s/^\s+//;
779                 $model =~ s/\s+$//;
780
781                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
782                 push @parts, [ $model, 0 ];
783         }
784         
785         # classic fields
786         if (scalar @classic_fields > 0) {
787                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
788
789                 my $first_elem = 1;
790                 for my $field (@classic_fields) {
791                         push @parts, [ ', ', 0 ] if (!$first_elem);
792                         $first_elem = 0;
793                         push @parts, $field;
794                 }
795         }
796
797         if (defined($info->{'Flash'})) {
798                 if ($info->{'Flash'} =~ /did not fire/i ||
799                     $info->{'Flash'} =~ /no flash/i ||
800                     $info->{'Flash'} =~ /not fired/i ||
801                     $info->{'Flash'} =~ /Off/)  {
802                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
803                         push @parts, [ "No flash", 0 ];
804                 } elsif ($info->{'Flash'} =~ /fired/i ||
805                          $info->{'Flash'} =~ /On/) {
806                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
807                         push @parts, [ "Flash", 0 ];
808                 } else {
809                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
810                         push @parts, [ $info->{'Flash'}, 0 ];
811                 }
812         }
813
814         return 0 if (scalar @parts == 0);
815
816         # Find the required width
817         my $th = 0;
818         my $tw = 0;
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
828                 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
829
830                 $tw += $w;
831                 $th = $h if ($h > $th);
832         }
833
834         return 0 if ($tw > $img->Get('columns'));
835
836         my $x = 0;
837         my $y = $img->Get('rows') - 24;
838
839         # Hit exact DCT blocks
840         $y -= ($y % 8);
841
842         my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
843         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
844         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
845         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
846
847         # Start writing out the text
848         $x = ($img->Get('columns') - $tw) / 2;
849
850         my $room = ($img->Get('rows') - 1 - $y - $th);
851         $y = ($img->Get('rows') - 1) - $room/2;
852         
853         for my $part (@parts) {
854                 my $font;
855                 if ($part->[1]) {
856                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
857                 } else {
858                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
859                 }
860                 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
861                 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
862         }
863
864         return 1;
865 }
866
867 sub gcd {
868         my ($a, $b) = @_;
869         return $a if ($b == 0);
870         return gcd($b, $a % $b);
871 }
872
873 sub add_new_event {
874         my ($dbh, $id, $date, $desc, $vhost) = @_;
875         my @errors = ();
876
877         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
878                 push @errors, "Manglende eller ugyldig ID.";
879         }
880         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
881                 push @errors, "Manglende eller ugyldig dato.";
882         }
883         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
884                 push @errors, "Manglende eller ugyldig beskrivelse.";
885         }
886         
887         if (scalar @errors > 0) {
888                 return @errors;
889         }
890                 
891         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
892                 undef, $id, $date, $desc, $vhost)
893                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
894         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
895                 undef, $vhost, $id)
896                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
897
898         return ();
899 }
900
901 sub guess_charset {
902         my $text = shift;
903         my $decoded;
904
905         eval {
906                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
907         };
908         if ($@) {
909                 $decoded = Encode::decode("iso8859-1", $text);
910         }
911
912         return $decoded;
913 }
914
915 1;
916
917