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