]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Fix a missing purging URL.
[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::MD5;
22 use Digest::SHA1;
23 use Digest::HMAC_SHA1;
24 use MIME::Base64;
25 use MIME::Types;
26 use LWP::Simple;
27 # use Image::Info;
28 use Image::ExifTool;
29 use HTML::Entities;
30 use URI::Escape;
31 use File::Basename;
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.70";
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 => Encode::decode_utf8($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) = @_;
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                 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
231         }
232 }
233
234 sub get_mipmap_location {
235         my ($r, $id, $width, $height) = @_;
236         my $dir = POSIX::floor($id / 256);
237
238         return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
239 }
240
241 sub update_image_info {
242         my ($r, $id, $width, $height) = @_;
243
244         # Also find the date taken if appropriate (from the EXIF tag etc.)
245         my $exiftool = Image::ExifTool->new;
246         $exiftool->ExtractInfo(get_disk_location($r, $id));
247         my $info = $exiftool->GetInfo();
248         my $datetime = undef;
249                         
250         if (defined($info->{'DateTimeOriginal'})) {
251                 # Parse the date and time over to ISO format
252                 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
253                         $datetime = "$1-$2-$3 $4:$5:$6";
254                 }
255         }
256
257         {
258                 local $dbh->{AutoCommit} = 0;
259
260                 # EXIF information
261                 $dbh->do('DELETE FROM exif_info WHERE image=?',
262                         undef, $id)
263                         or die "Couldn't delete old EXIF information in SQL: $!";
264
265                 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
266                         or die "Couldn't prepare inserting EXIF information: $!";
267
268                 for my $key (keys %$info) {
269                         next if ref $info->{$key};
270                         $q->execute($id, $key, guess_charset($info->{$key}))
271                                 or die "Couldn't insert EXIF information in database: $!";
272                 }
273
274                 # Model/Lens
275                 my $model = $exiftool->GetValue('Model', 'PrintConv');
276                 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
277                 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
278
279                 $model =~ s/^\s*//;
280                 $model =~ s/\s*$//;
281                 $model = undef if (length($model) == 0);
282
283                 $lens =~ s/^\s*//;
284                 $lens =~ s/\s*$//;
285                 $lens = undef if (length($lens) == 0);
286                 
287                 # Now update the main table with the information we've got
288                 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
289                          undef, $width, $height, $datetime, $model, $lens, $id)
290                         or die "Couldn't update width/height in SQL: $!";
291                 
292                 # Tags
293                 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
294                 $dbh->do('DELETE FROM tags WHERE image=?',
295                         undef, $id)
296                         or die "Couldn't delete old tag information in SQL: $!";
297
298                 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
299                         or die "Couldn't prepare inserting tag information: $!";
300
301
302                 for my $tag (@tags) {
303                         $q->execute($id, guess_charset($tag))
304                                 or die "Couldn't insert tag information in database: $!";
305                 }
306
307                 # update the last_picture cache as well (this should of course be done
308                 # via a trigger, but this is less complicated :-) )
309                 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
310                         undef, $datetime, $id)
311                         or die "Couldn't update last_picture in SQL: $!";
312         }
313 }
314
315 sub check_access {
316         my $r = shift;
317         
318         #return qw(sesse Sesse);
319
320         my $auth = $r->headers_in->{'authorization'};
321         if (!defined($auth)) {
322                 output_401($r);
323                 return undef;
324         } 
325         if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
326                 return check_basic_auth($r, $1);
327         }       
328         if ($auth =~ /^Digest (.*)$/) {
329                 return check_digest_auth($r, $1);
330         }
331         output_401($r);
332         return undef;
333 }
334
335 sub output_401 {
336         my ($r, %options) = @_;
337         $r->content_type('text/plain; charset=utf-8');
338         $r->status(401);
339         $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
340
341         if ($options{'DigestAuth'} // 1) {
342                 # We make our nonce similar to the scheme of RFC2069 section 2.1.1,
343                 # with some changes: We don't care about client IP (these have a nasty
344                 # tendency to change from request to request when load-balancing
345                 # proxies etc. are being used), and we use HMAC instead of simple
346                 # hashing simply because that's a better signing method.
347                 #
348                 # NOTE: For some weird reason, Digest::HMAC_SHA1 doesn't like taking
349                 # the output from time directly (it gives a different response), so we
350                 # forcefully stringify the argument.
351                 my $ts = time;
352                 my $nonce = Digest::HMAC_SHA1->hmac_sha1_hex($ts . "", $Sesse::pr0n::Config::db_password);
353                 my $stale_nonce_text = "";
354                 $stale_nonce_text = ", stale=\"true\"" if ($options{'StaleNonce'} // 0);
355
356                 $r->headers_out->{'www-authenticate'} =
357                         "Digest realm=\"pr0n.sesse.net\", " .
358                         "nonce=\"$nonce\", " .
359                         "opaque=\"$ts\", " .
360                         "qop=\"auth\"" . $stale_nonce_text;  # FIXME: support auth-int
361         }
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,digest_ha1_hex FROM users WHERE username=? AND vhost=?',
373                 undef, $user, $r->get_server_name);
374         if (!defined($ref) || $ref->{'sha1password'} ne Digest::SHA1::sha1_base64($pass)) {
375                 $r->content_type('text/plain; charset=utf-8');
376                 $r->log->warn("Authentication failed for $user/$takenby");
377                 output_401($r);
378                 return undef;
379         }
380         $r->log->info("Authentication succeeded for $user/$takenby");
381
382         # Make sure we can use Digest authentication in the future with this password.
383         my $ha1 = Digest::MD5::md5_hex($user . ':pr0n.sesse.net:' . $pass);
384         if (!defined($ref->{'digest_ha1_hex'}) || $ref->{'digest_ha1_hex'} ne $ha1) {
385                 $dbh->do('UPDATE users SET digest_ha1_hex=? WHERE username=? AND vhost=?',
386                         undef, $ha1, $user, $r->get_server_name)
387                         or die "Couldn't update: " . $dbh->errstr;
388                 $r->log->info("Updated Digest auth hash for for $user");
389         }
390
391         return ($user, $takenby);
392 }
393
394 sub check_digest_auth {
395         my ($r, $auth) = @_;    
396
397         # We're a bit more liberal than RFC2069 in the parsing here, allowing
398         # quoted strings everywhere.
399         my %auth = ();
400         while ($auth =~ s/^ ([a-zA-Z]+)                # key
401                          =                 
402                          (                            
403                            [^",]*                     # either something that doesn't contain comma or quotes
404                          |
405                            " ( [^"\\] | \\ . ) * "    # or a full quoted string
406                          )
407                          (?: (?: , \s* ) + | $ )      # delimiter(s), or end of string
408                         //x) {
409                 my ($key, $value) = ($1, $2);
410                 if ($value =~ /^"(.*)"$/) {
411                         $value = $1;
412                         $value =~ s/\\(.)/$1/g;
413                 }
414                 $auth{$key} = $value;
415         }
416         unless (exists($auth{'username'}) &&
417                 exists($auth{'uri'}) &&
418                 exists($auth{'nonce'}) &&
419                 exists($auth{'opaque'}) &&
420                 exists($auth{'response'})) {
421                 output_401($r);
422                 return undef;
423         }
424         if ($r->uri ne $auth{'uri'}) {  
425                 output_401($r);
426                 return undef;
427         }
428         
429         # Verify that the opaque data does indeed look like a timestamp, and that the nonce
430         # is indeed a signed version of it.
431         if ($auth{'opaque'} !~ /^\d+$/) {
432                 output_401($r);
433                 return undef;
434         }
435         my $compare_nonce = Digest::HMAC_SHA1->hmac_sha1_hex($auth{'opaque'}, $Sesse::pr0n::Config::db_password);
436         if ($auth{'nonce'} ne $compare_nonce) {
437                 output_401($r);
438                 return undef;
439         }
440
441         # Now look up the user's HA1 from the database, and calculate HA2.      
442         my ($user, $takenby) = extract_takenby($auth{'username'});
443         my $ref = $dbh->selectrow_hashref('SELECT digest_ha1_hex FROM users WHERE username=? AND vhost=?',
444                 undef, $user, $r->get_server_name);
445         if (!defined($ref)) {
446                 output_401($r);
447                 return undef;
448         }
449         if (!defined($ref->{'digest_ha1_hex'}) || $ref->{'digest_ha1_hex'} !~ /^[0-9a-f]{32}$/) {
450                 # A user that exists but has empty HA1 is a user that's not
451                 # ready for digest auth, so we hack it and resend 401,
452                 # only this time without digest auth.
453                 output_401($r, DigestAuth => 0);
454                 return undef;
455         }
456         my $ha1 = $ref->{'digest_ha1_hex'};
457         my $ha2 = Digest::MD5::md5_hex($r->method . ':' . $auth{'uri'});
458         my $response;
459         if (exists($auth{'qop'}) && $auth{'qop'} eq 'auth') {
460                 unless (exists($auth{'nc'}) && exists($auth{'cnonce'})) {
461                         output_401($r);
462                         return undef;
463                 }       
464
465                 $response = $ha1;
466                 $response .= ':' . $auth{'nonce'};
467                 $response .= ':' . $auth{'nc'};
468                 $response .= ':' . $auth{'cnonce'};
469                 $response .= ':' . $auth{'qop'};
470                 $response .= ':' . $ha2;
471         } else {
472                 $response = $ha1;
473                 $response .= ':' . $auth{'nonce'};
474                 $response .= ':' . $ha2;
475         }
476         if ($auth{'response'} ne Digest::MD5::md5_hex($response)) {     
477                 output_401($r);
478                 return undef;
479         }
480
481         # OK, everything is good, and there's only one thing we need to check: That the nonce
482         # isn't too old. If it is, but everything else is ok, we tell the browser that and it
483         # will re-encrypt with the new nonce.
484         my $timediff = time - $auth{'opaque'};
485         if ($timediff < 0 || $timediff > 300) {
486                 output_401($r, StaleNonce => 1);
487                 return undef;
488         }
489
490         return ($user, $takenby);
491 }
492
493 sub extract_takenby {
494         my ($user) = shift;
495
496         # WinXP is stupid :-)
497         if ($user =~ /^.*\\(.*)$/) {
498                 $user = $1;
499         }
500
501         my $takenby;
502         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
503                 $user = $1;
504                 $takenby = $2;
505         } else {
506                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
507         }
508
509         return ($user, $takenby);
510 }
511         
512 sub stat_image {
513         my ($r, $event, $filename) = (@_);
514         my $ref = $dbh->selectrow_hashref(
515                 'SELECT id FROM images WHERE event=? AND filename=?',
516                 undef, $event, $filename);
517         if (!defined($ref)) {
518                 return (undef, undef, undef);
519         }
520         return stat_image_from_id($r, $ref->{'id'});
521 }
522
523 sub stat_image_from_id {
524         my ($r, $id) = @_;
525
526         my $fname = get_disk_location($r, $id);
527         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
528                 or return (undef, undef, undef);
529
530         return ($fname, $size, $mtime);
531 }
532
533 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
534 # the smallest mipmap larger than the largest of them.
535 sub make_mipmap {
536         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
537         my ($img, $mmimg, $width, $height);
538         
539         my $physical_fname = get_disk_location($r, $id);
540
541         # If we don't know the size, we'll need to read it in anyway
542         if (!defined($dbwidth) || !defined($dbheight)) {
543                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
544                 $width = $img->Get('columns');
545                 $height = $img->Get('rows');
546         } else {
547                 $width = $dbwidth;
548                 $height = $dbheight;
549         }
550
551         # Generate the list of mipmaps
552         my @mmlist = ();
553         
554         my $mmwidth = $width;
555         my $mmheight = $height;
556
557         while ($mmwidth > 1 || $mmheight > 1) {
558                 my $new_mmwidth = POSIX::floor($mmwidth / 2);           
559                 my $new_mmheight = POSIX::floor($mmheight / 2);         
560
561                 $new_mmwidth = 1 if ($new_mmwidth < 1);
562                 $new_mmheight = 1 if ($new_mmheight < 1);
563
564                 my $large_enough = 1;
565                 for my $i (0..($#res/2)) {
566                         my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
567                         if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
568                                 $large_enough = 0;
569                                 last;
570                         }
571                 }
572                                 
573                 last if (!$large_enough);
574
575                 $mmwidth = $new_mmwidth;
576                 $mmheight = $new_mmheight;
577
578                 push @mmlist, [ $mmwidth, $mmheight ];
579         }
580                 
581         # Ensure that all of them are OK
582         my $last_good_mmlocation;
583         for my $i (0..$#mmlist) {
584                 my $last = ($i == $#mmlist);
585                 my $mmres = $mmlist[$i];
586
587                 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
588                 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
589                         if (!defined($img)) {
590                                 if (defined($last_good_mmlocation)) {
591                                         if ($can_use_qscale) {
592                                                 $img = Sesse::pr0n::QscaleProxy->new;
593                                         } else {
594                                                 $img = Image::Magick->new;
595                                         }
596                                         $img->Read($last_good_mmlocation);
597                                 } else {
598                                         $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
599                                 }
600                         }
601                         my $cimg;
602                         if ($last) {
603                                 $cimg = $img;
604                         } else {
605                                 $cimg = $img->Clone();
606                         }
607                         $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
608                         $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
609                         $cimg->Strip();
610                         my $err = $cimg->write(
611                                 filename => $mmlocation,
612                                 quality => 95,
613                                 'sampling-factor' => '1x1'
614                         );
615                         $img = $cimg;
616                 } else {
617                         $last_good_mmlocation = $mmlocation;
618                 }
619                 if ($last && !defined($img)) {
620                         # OK, read in the smallest one
621                         if ($can_use_qscale) {
622                                 $img = Sesse::pr0n::QscaleProxy->new;
623                         } else {
624                                 $img = Image::Magick->new;
625                         }
626                         my $err = $img->Read($mmlocation);
627                 }
628         }
629
630         if (!defined($img)) {
631                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
632         }
633         return $img;
634 }
635
636 sub read_original_image {
637         my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
638
639         my $physical_fname = get_disk_location($r, $id);
640
641         # Read in the original image
642         my $magick;
643         if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
644                 $magick = Sesse::pr0n::QscaleProxy->new;
645         } else {
646                 $magick = Image::Magick->new;
647         }
648         my $err;
649
650         # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
651         # The delegate support is rather broken and causes very odd stuff to happen when
652         # more than one thread does this at the same time. Thus, we simply do it ourselves.
653         if ($filename =~ /\.(nef|cr2)$/i) {
654                 # this would suffice if ImageMagick gets to fix their handling
655                 # $physical_fname = "NEF:$physical_fname";
656                 
657                 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
658                         or error("dcraw: $!");
659                 $err = $magick->Read(file => \*DCRAW);
660                 close(DCRAW);
661         } else {
662                 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
663                 # RGB is slightly faster (no colorspace conversion needed) and works equally
664                 # well for our uses, as long as we don't need to draw an information box,
665                 # which trickles several ImageMagick bugs related to colorspace handling.
666                 # (Ideally we'd be able to keep the image subsampled and
667                 # planar, but that would probably be difficult for ImageMagick to expose.)
668                 #if (!$infobox) {
669                 #       $magick->Set(colorspace=>'YCbCr');
670                 #}
671                 $err = $magick->Read($physical_fname);
672         }
673         
674         if ($err) {
675                 $r->log->warn("$physical_fname: $err");
676                 $err =~ /(\d+)/;
677                 if ($1 >= 400) {
678                         undef $magick;
679                         error($r, "$physical_fname: $err");
680                 }
681         }
682
683         # If we use ->[0] unconditionally, text rendering (!) seems to crash
684         my $img;
685         if (ref($magick)) {
686                 $img = $magick;
687         } else {
688                 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
689         }
690
691         my $width = $img->Get('columns');
692         my $height = $img->Get('rows');
693
694         # Update the SQL database if it doesn't contain the required info
695         if (!defined($dbwidth) || !defined($dbheight)) {
696                 $r->log->info("Updating width/height for $id: $width x $height");
697                 update_image_info($r, $id, $width, $height);
698         }
699
700         return $img;
701 }
702
703 sub ensure_cached {
704         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
705
706         my $fname = get_disk_location($r, $id);
707         if ($infobox ne 'box') {
708                 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
709                         return ($fname, undef);
710                 }
711         }
712
713         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
714         my $err;
715         if (! -r $cachename or (-M $cachename > -M $fname)) {
716                 # If we are in overload mode (aka Slashdot mode), refuse to generate
717                 # new thumbnails.
718                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
719                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
720                         error($r, 'System is in overload mode, not doing any scaling');
721                 }
722
723                 # If we're being asked for just the box, make a new image with just the box.
724                 # We don't care about @otherres since each of these images are
725                 # already pretty cheap to generate, but we need the exact width so we can make
726                 # one in the right size.
727                 if ($infobox eq 'box') {
728                         my ($img, $width, $height);
729
730                         # This is slow, but should fortunately almost never happen, so don't bother
731                         # special-casing it.
732                         if (!defined($dbwidth) || !defined($dbheight)) {
733                                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
734                                 $width = $img->Get('columns');
735                                 $height = $img->Get('rows');
736                                 @$img = ();
737                         } else {
738                                 $img = Image::Magick->new;
739                                 $width = $dbwidth;
740                                 $height = $dbheight;
741                         }
742                         
743                         if (defined($xres) && defined($yres)) {
744                                 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
745                         }
746                         $height = 24;
747                         $img->Set(size=>($width . "x" . $height));
748                         $img->Read('xc:white');
749                                 
750                         my $info = Image::ExifTool::ImageInfo($fname);
751                         if (make_infobox($img, $info, $r)) {
752                                 $img->Quantize(colors=>16, dither=>'False');
753
754                                 # Since the image is grayscale, ImageMagick overrides us and writes this
755                                 # as grayscale anyway, but at least we get rid of the alpha channel this
756                                 # way.
757                                 $img->Set(type=>'Palette');
758                         } else {
759                                 # Not enough room for the text, make a tiny dummy transparent infobox
760                                 @$img = ();
761                                 $img->Set(size=>"1x1");
762                                 $img->Read('null:');
763
764                                 $width = 1;
765                                 $height = 1;
766                         }
767                                 
768                         $err = $img->write(filename => $cachename, quality => 90, depth => 8);
769                         $r->log->info("New infobox cache: $width x $height for $id.jpg");
770                         
771                         return ($cachename, 'image/png');
772                 }
773
774                 my $can_use_qscale = 0;
775                 if ($infobox eq 'nobox') {
776                         $can_use_qscale = 1;
777                 }
778
779                 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
780
781                 while (defined($xres) && defined($yres)) {
782                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
783                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
784                         
785                         my $cimg;
786                         if (defined($nxres) && defined($nyres)) {
787                                 # we have more resolutions to scale, so don't throw
788                                 # the image away
789                                 $cimg = $img->Clone();
790                         } else {
791                                 $cimg = $img;
792                         }
793                 
794                         my $width = $img->Get('columns');
795                         my $height = $img->Get('rows');
796                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
797
798                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
799                         my $filter = 'Mitchell';
800                         my $quality = 90;
801                         my $sf = undef;
802
803                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
804                                 $filter = 'Lanczos';
805                                 $quality = 85;
806                                 $sf = "1x1";
807                         }
808
809                         if ($xres != -1) {
810                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
811                         }
812
813                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
814                                 my $info = Image::ExifTool::ImageInfo($fname);
815                                 make_infobox($cimg, $info, $r);
816                         }
817
818                         # Strip EXIF tags etc.
819                         $cimg->Strip();
820
821                         {
822                                 my %parms = (
823                                         filename => $cachename,
824                                         quality => $quality
825                                 );
826                                 if (($nwidth >= 640 && $nheight >= 480) ||
827                                     ($nwidth >= 480 && $nheight >= 640)) {
828                                         $parms{'interlace'} = 'Plane';
829                                 }
830                                 if (defined($sf)) {
831                                         $parms{'sampling-factor'} = $sf;
832                                 }
833                                 $err = $cimg->write(%parms);
834                         }
835
836                         undef $cimg;
837
838                         ($xres, $yres) = ($nxres, $nyres);
839
840                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
841                 }
842                 
843                 undef $img;
844                 if ($err) {
845                         $r->log->warn("$fname: $err");
846                         $err =~ /(\d+)/;
847                         if ($1 >= 400) {
848                                 #@$magick = ();
849                                 error($r, "$fname: $err");
850                         }
851                 }
852         }
853         return ($cachename, 'image/jpeg');
854 }
855
856 sub get_mimetype_from_filename {
857         my $filename = shift;
858         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
859         $type = "image/jpeg" if (!defined($type));
860         return $type;
861 }
862
863 sub make_infobox {
864         my ($img, $info, $r) = @_;
865
866         # The infobox is of the form
867         # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
868         # possibly with some parts omitted -- the middle part is known as the "classic
869         # fields"; note the comma separation. Every field has an associated "bold flag"
870         # in the second part.
871         
872         my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
873                 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
874         my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
875                 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
876
877         my @classic_fields = ();
878         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
879                 push @classic_fields, [ $1 . "mm", 0 ];
880         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
881                 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
882         }
883
884         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
885                 my ($a, $b) = ($1, $2);
886                 my $gcd = gcd($a, $b);
887                 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
888         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+))$/) {
889                 push @classic_fields, [ $1 . "s", $shutter_priority ];
890         }
891
892         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
893                 my $f = $1/$2;
894                 if ($f >= 10) {
895                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
896                 } else {
897                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
898                 }
899         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
900                 my $f = $info->{'FNumber'};
901                 if ($f >= 10) {
902                         push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
903                 } else {
904                         push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
905                 }
906         }
907
908 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
909
910         my $iso = undef;
911         if (defined($info->{'NikonD1-ISOSetting'})) {
912                 $iso = $info->{'NikonD1-ISOSetting'};
913         } elsif (defined($info->{'ISO'})) {
914                 $iso = $info->{'ISO'};
915         } elsif (defined($info->{'ISOSetting'})) {
916                 $iso = $info->{'ISOSetting'};
917         }
918         if (defined($iso) && $iso =~ /(\d+)/) {
919                 push @classic_fields, [ $1 . " ISO", 0 ];
920         }
921
922         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
923                 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
924         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
925                 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
926         }
927
928         # Now piece together the rest
929         my @parts = ();
930         
931         if (defined($info->{'DateTimeOriginal'}) &&
932             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
933             && $1 >= 1990) {
934                 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
935         }
936
937         if (defined($info->{'Model'})) {
938                 my $model = $info->{'Model'}; 
939                 $model =~ s/^\s+//;
940                 $model =~ s/\s+$//;
941
942                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
943                 push @parts, [ $model, 0 ];
944         }
945         
946         # classic fields
947         if (scalar @classic_fields > 0) {
948                 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
949
950                 my $first_elem = 1;
951                 for my $field (@classic_fields) {
952                         push @parts, [ ', ', 0 ] if (!$first_elem);
953                         $first_elem = 0;
954                         push @parts, $field;
955                 }
956         }
957
958         if (defined($info->{'Flash'})) {
959                 if ($info->{'Flash'} =~ /did not fire/i ||
960                     $info->{'Flash'} =~ /no flash/i ||
961                     $info->{'Flash'} =~ /not fired/i ||
962                     $info->{'Flash'} =~ /Off/)  {
963                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
964                         push @parts, [ "No flash", 0 ];
965                 } elsif ($info->{'Flash'} =~ /fired/i ||
966                          $info->{'Flash'} =~ /On/) {
967                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
968                         push @parts, [ "Flash", 0 ];
969                 } else {
970                         push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
971                         push @parts, [ $info->{'Flash'}, 0 ];
972                 }
973         }
974
975         return 0 if (scalar @parts == 0);
976
977         # Find the required width
978         my $th = 0;
979         my $tw = 0;
980
981         for my $part (@parts) {
982                 my $font;
983                 if ($part->[1]) {
984                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
985                 } else {
986                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
987                 }
988
989                 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
990
991                 $tw += $w;
992                 $th = $h if ($h > $th);
993         }
994
995         return 0 if ($tw > $img->Get('columns'));
996
997         my $x = 0;
998         my $y = $img->Get('rows') - 24;
999
1000         # Hit exact DCT blocks
1001         $y -= ($y % 8);
1002
1003         my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
1004         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
1005         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
1006         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
1007
1008         # Start writing out the text
1009         $x = ($img->Get('columns') - $tw) / 2;
1010
1011         my $room = ($img->Get('rows') - 1 - $y - $th);
1012         $y = ($img->Get('rows') - 1) - $room/2;
1013         
1014         for my $part (@parts) {
1015                 my $font;
1016                 if ($part->[1]) {
1017                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
1018                 } else {
1019                         $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
1020                 }
1021                 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
1022                 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
1023         }
1024
1025         return 1;
1026 }
1027
1028 sub gcd {
1029         my ($a, $b) = @_;
1030         return $a if ($b == 0);
1031         return gcd($b, $a % $b);
1032 }
1033
1034 sub add_new_event {
1035         my ($r, $dbh, $id, $date, $desc) = @_;
1036         my @errors = ();
1037
1038         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
1039                 push @errors, "Manglende eller ugyldig ID.";
1040         }
1041         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
1042                 push @errors, "Manglende eller ugyldig dato.";
1043         }
1044         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
1045                 push @errors, "Manglende eller ugyldig beskrivelse.";
1046         }
1047         
1048         if (scalar @errors > 0) {
1049                 return @errors;
1050         }
1051                 
1052         my $vhost = $r->get_server_name;
1053         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
1054                 undef, $id, $date, $desc, $vhost)
1055                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
1056         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
1057                 undef, $vhost, $id)
1058                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
1059         purge_cache($r, "/");
1060
1061         return ();
1062 }
1063
1064 sub guess_charset {
1065         my $text = shift;
1066         my $decoded;
1067
1068         eval {
1069                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
1070         };
1071         if ($@) {
1072                 $decoded = Encode::decode("iso8859-1", $text);
1073         }
1074
1075         return $decoded;
1076 }
1077
1078 # Depending on your front-end cache, you might want to get creative somehow here.
1079 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
1080 # regex tacked onto a request into something useful. The elements given in
1081 # should not be regexes, though, as e.g. Squid will not be able to handle that.
1082 sub purge_cache {
1083         my ($r, @elements) = @_;
1084         return if (scalar @elements == 0);
1085
1086         my @pe = ();
1087         for my $elem (@elements) {
1088                 $r->log->info("Purging $elem");
1089                 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1090                 push @pe, $e;
1091         }
1092
1093         my $regex = "^";
1094         if (scalar @pe == 1) {
1095                 $regex .= $pe[0];
1096         } else {
1097                 $regex .= "(" . join('|', @pe) . ")";
1098         }
1099         $regex .= "(\\?.*)?\$";
1100         $r->headers_out->{'X-Pr0n-Purge'} = $regex;
1101
1102         $r->log->info($r->headers_out->{'X-Pr0n-Purge'});
1103 }
1104                                 
1105 # Find a list of all cache URLs for a given image, given what we have on disk.
1106 sub get_all_cache_urls {
1107         my ($r, $dbh, $id) = @_;
1108         my $dir = POSIX::floor($id / 256);
1109         my @ret = ();
1110
1111         my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1112                 or die "Couldn't prepare: " . $dbh->errstr;
1113         $q->execute($id)
1114                 or die "Couldn't find event and filename: " . $dbh->errstr;
1115         my $ref = $q->fetchrow_hashref; 
1116         my $event = $ref->{'event'};
1117         my $filename = $ref->{'filename'};
1118         $q->finish;
1119
1120         my $base = get_base($r) . "cache/$dir";
1121         for my $file (<$base/$id-*>) {
1122                 my $fname = File::Basename::basename($file);
1123                 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1124                         # Mipmaps don't have an URL, ignore
1125                 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1126                         push @ret, "/$event/$filename";
1127                 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1128                         push @ret, "/$event/$1x$2/$filename";
1129                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1130                         push @ret, "/$event/$1x$2/nobox/$filename";
1131                 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1132                         push @ret, "/$event/box/$filename";
1133                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1134                         push @ret, "/$event/$1x$2/box/$filename";
1135                 } else {
1136                         $r->log->warn("Couldn't find a purging URL for $fname");
1137                 }
1138         }
1139
1140         return @ret;
1141 }
1142
1143 1;
1144
1145