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