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