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