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