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