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