1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
9 use Apache2::RequestRec (); # for $r->content_type
10 use Apache2::RequestIO (); # for $r->print
11 use Apache2::Const -compile => ':common';
23 use Digest::HMAC_SHA1;
32 use Crypt::Eksblowfish::Bcrypt;
36 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
38 use Sesse::pr0n::Config;
40 require Sesse::pr0n::Config_local;
45 @EXPORT = qw(&error &dberror);
47 @EXPORT_OK = qw(&error &dberror);
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;
54 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
61 our ($dbh, $mimetypes);
64 my ($r,$err,$status,$title) = @_;
66 if (!defined($status) || !defined($title)) {
68 $title = "Internal server error";
71 $r->content_type('text/html; charset=utf-8');
75 $r->print(" <p>Error: $err</p>\n");
79 $r->log->error("Stack trace follows: " . Carp::longmess());
81 ModPerl::Util::exit();
86 error($r, "$err (DB error: " . $dbh->errstr . ")");
92 $r->content_type("text/html; charset=utf-8");
94 # Fetch quote if we're itk-bilder.samfundet.no
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));
100 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
105 Sesse::pr0n::Templates::print_template($r, "footer",
106 { version => $Sesse::pr0n::Common::VERSION });
110 my ($width, $height, $thumbxres, $thumbyres) = @_;
112 unless ($thumbxres >= $width &&
113 $thumbyres >= $height) {
114 my $sfh = $width / $thumbxres;
115 my $sfv = $height / $thumbyres;
123 $width = POSIX::floor($width);
124 $height = POSIX::floor($height);
127 return ($width, $height);
130 sub get_query_string {
131 my ($param, $defparam) = @_;
135 while (my ($key, $value) = each %$param) {
136 next unless defined($value);
137 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
139 $value = pretty_escape($value);
141 $str .= ($first) ? "?" : ';';
142 $str .= "$key=$value";
148 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
149 sub weird_space_encode {
152 return "_" x (length($val) * 2);
154 return "_" x (length($val) * 2 - 1);
158 sub weird_space_unencode {
160 if (length($val) % 2 == 0) {
161 return "_" x (length($val) / 2);
163 return " " x ((length($val) + 1) / 2);
170 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
171 $value = URI::Escape::uri_escape($value);
172 $value =~ s/%2F/\//g;
177 sub pretty_unescape {
180 # URI unescaping is already done for us
181 $value =~ s/(_+)/weird_space_unencode($1)/ge;
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\"";
192 $str .= ">$title</a>";
197 # Check that we are alive
198 if (!(defined($dbh) && $dbh->ping)) {
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)) {
204 die "Couldn't connect to PostgreSQL database";
213 return $r->dir_config('ImageBase');
216 sub get_disk_location {
218 my $dir = POSIX::floor($id / 256);
219 return get_base($r) . "images/$dir/$id.jpg";
222 sub get_cache_location {
223 my ($r, $id, $width, $height, $infobox, $dpr) = @_;
224 my $dir = POSIX::floor($id / 256);
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";
232 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
234 return get_base($r) . "cache/$dir/$id-$width-$height-box\@$dpr.png";
239 sub ensure_disk_location_exists {
241 my $dir = POSIX::floor($id / 256);
243 my $img_dir = get_base($r) . "/images/$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";
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";
256 sub get_mipmap_location {
257 my ($r, $id, $width, $height) = @_;
258 my $dir = POSIX::floor($id / 256);
260 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
263 sub update_image_info {
264 my ($r, $id, $width, $height) = @_;
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;
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";
280 local $dbh->{AutoCommit} = 0;
283 $dbh->do('DELETE FROM exif_info WHERE image=?',
285 or die "Couldn't delete old EXIF information in SQL: $!";
287 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
288 or die "Couldn't prepare inserting EXIF information: $!";
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: $!";
297 my $model = $exiftool->GetValue('Model', 'PrintConv');
298 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
299 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
303 $model = undef if (length($model) == 0);
307 $lens = undef if (length($lens) == 0);
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: $!";
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');
320 $dbh->do('DELETE FROM tags WHERE image=?',
322 or die "Couldn't delete old tag information in SQL: $!";
324 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
325 or die "Couldn't prepare inserting tag information: $!";
328 for my $tag (@tags) {
329 $q->execute($id, guess_charset($tag))
330 or die "Couldn't insert tag information in database: $!";
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: $!";
344 #return qw(sesse Sesse);
346 my $auth = $r->headers_in->{'authorization'};
347 if (!defined($auth)) {
351 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
352 return check_basic_auth($r, $1);
354 if ($auth =~ /^Digest (.*)$/) {
355 return check_digest_auth($r, $1);
362 my ($r, %options) = @_;
363 $r->content_type('text/plain; charset=utf-8');
365 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
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.
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.
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);
383 $r->headers_out->{'www-authenticate'} =
384 "Digest realm=\"pr0n.sesse.net\", " .
385 "nonce=\"$nonce\", " .
387 "qop=\"auth\"" . $stale_nonce_text; # FIXME: support auth-int
390 $r->print("Need authorization\n");
393 sub check_basic_auth {
396 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
397 my ($user, $takenby) = extract_takenby($raw_user);
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'});
405 if (defined($ref) && defined($ref->{'cryptpassword'})) {
406 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
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");
415 $r->log->info("Authentication succeeded for $user/$takenby");
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");
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");
438 return ($user, $takenby);
441 sub get_pseudorandom_bytes {
442 my $num_left = shift;
444 open my $randfh, "<", "/dev/urandom"
445 or die "/dev/urandom: $!";
447 while ($num_left > 0) {
449 if (sysread($randfh, $tmp, $num_left) == -1) {
450 die "sysread(/dev/urandom): $!";
453 $num_left -= length($bytes);
459 sub check_digest_auth {
462 # We're a bit more liberal than RFC2069 in the parsing here, allowing
463 # quoted strings everywhere.
465 while ($auth =~ s/^ ([a-zA-Z]+) # key
468 [^",]* # either something that doesn't contain comma or quotes
470 " ( [^"\\] | \\ . ) * " # or a full quoted string
472 (?: (?: , \s* ) + | $ ) # delimiter(s), or end of string
474 my ($key, $value) = ($1, $2);
475 if ($value =~ /^"(.*)"$/) {
477 $value =~ s/\\(.)/$1/g;
479 $auth{$key} = $value;
481 unless (exists($auth{'username'}) &&
482 exists($auth{'uri'}) &&
483 exists($auth{'nonce'}) &&
484 exists($auth{'opaque'}) &&
485 exists($auth{'response'})) {
489 if ($r->uri ne $auth{'uri'}) {
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+$/) {
500 my $compare_nonce = Digest::HMAC_SHA1->hmac_sha1_hex($auth{'opaque'}, $Sesse::pr0n::Config::db_password);
501 if ($auth{'nonce'} ne $compare_nonce) {
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)) {
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);
521 my $ha1 = $ref->{'digest_ha1_hex'};
522 my $ha2 = Digest::MD5::md5_hex($r->method . ':' . $auth{'uri'});
524 if (exists($auth{'qop'}) && $auth{'qop'} eq 'auth') {
525 unless (exists($auth{'nc'}) && exists($auth{'cnonce'})) {
531 $response .= ':' . $auth{'nonce'};
532 $response .= ':' . $auth{'nc'};
533 $response .= ':' . $auth{'cnonce'};
534 $response .= ':' . $auth{'qop'};
535 $response .= ':' . $ha2;
538 $response .= ':' . $auth{'nonce'};
539 $response .= ':' . $ha2;
541 if ($auth{'response'} ne Digest::MD5::md5_hex($response)) {
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);
555 return ($user, $takenby);
558 sub extract_takenby {
561 # WinXP is stupid :-)
562 if ($user =~ /^.*\\(.*)$/) {
567 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
571 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
574 return ($user, $takenby);
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);
585 return stat_image_from_id($r, $ref->{'id'});
588 sub stat_image_from_id {
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);
595 return ($fname, $size, $mtime);
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
602 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
603 my ($img, $mmimg, $width, $height);
605 my $physical_fname = get_disk_location($r, $id);
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');
617 # Generate the list of mipmaps
620 my $mmwidth = $width;
621 my $mmheight = $height;
623 while ($mmwidth > 1 || $mmheight > 1) {
624 my $new_mmwidth = POSIX::floor($mmwidth / 2);
625 my $new_mmheight = POSIX::floor($mmheight / 2);
627 $new_mmwidth = 1 if ($new_mmwidth < 1);
628 $new_mmheight = 1 if ($new_mmheight < 1);
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) {
639 last if (!$large_enough);
641 $mmwidth = $new_mmwidth;
642 $mmheight = $new_mmheight;
644 push @mmlist, [ $mmwidth, $mmheight ];
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];
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;
660 $img = Image::Magick->new;
662 $img->Read($last_good_mmlocation);
664 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
671 $cimg = $img->Clone();
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');
676 my $err = $cimg->write(
677 filename => $mmlocation,
679 'sampling-factor' => '1x1'
683 $last_good_mmlocation = $mmlocation;
685 if ($last && !defined($img)) {
686 # OK, read in the smallest one
687 if ($can_use_qscale) {
688 $img = Sesse::pr0n::QscaleProxy->new;
690 $img = Image::Magick->new;
692 my $err = $img->Read($mmlocation);
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');
701 return ($img, $width, $height);
704 sub read_original_image {
705 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
707 my $physical_fname = get_disk_location($r, $id);
709 # Read in the original image
711 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
712 $magick = Sesse::pr0n::QscaleProxy->new;
714 $magick = Image::Magick->new;
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";
725 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
726 or error("dcraw: $!");
727 $err = $magick->Read(file => \*DCRAW);
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.)
737 # $magick->Set(colorspace=>'YCbCr');
739 $err = $magick->Read($physical_fname);
743 $r->log->warn("$physical_fname: $err");
747 error($r, "$physical_fname: $err");
751 # If we use ->[0] unconditionally, text rendering (!) seems to crash
753 if (ref($magick) !~ /Image::Magick/) {
756 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
763 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
765 my ($new_dbwidth, $new_dbheight);
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);
774 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
776 if (! -r $cachename or (-M $cachename > -M $fname)) {
777 # If we are in overload mode (aka Slashdot mode), refuse to generate
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');
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);
791 # This is slow, but should fortunately almost never happen, so don't bother
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');
799 $img = Image::Magick->new;
804 if (defined($xres) && defined($yres)) {
805 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
808 $img->Set(size=>($width . "x" . $height));
809 $img->Read('xc:white');
811 my $info = Image::ExifTool::ImageInfo($fname);
812 if (make_infobox($img, $info, $r, $dpr)) {
813 $img->Quantize(colors=>16, dither=>'False');
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
818 $img->Set(type=>'Palette');
820 # Not enough room for the text, make a tiny dummy transparent infobox
822 $img->Set(size=>"1x1");
829 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
830 $r->log->info("New infobox cache: $width x $height for $id.jpg");
832 return ($cachename, 'image/png');
835 my $can_use_qscale = 0;
836 if ($infobox eq 'nobox') {
841 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
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);
848 if (defined($nxres) && defined($nyres)) {
849 # we have more resolutions to scale, so don't throw
851 $cimg = $img->Clone();
856 my $width = $img->Get('columns');
857 my $height = $img->Get('rows');
858 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
860 my $filter = 'Lanczos';
865 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
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);
873 # Strip EXIF tags etc.
878 filename => $cachename,
881 if (($nwidth >= 640 && $nheight >= 480) ||
882 ($nwidth >= 480 && $nheight >= 640)) {
883 $parms{'interlace'} = 'Plane';
886 $parms{'sampling-factor'} = $sf;
888 $err = $cimg->write(%parms);
893 ($xres, $yres) = ($nxres, $nyres);
895 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
900 $r->log->warn("$fname: $err");
904 error($r, "$fname: $err");
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);
915 return ($cachename, 'image/jpeg');
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));
926 my ($img, $info, $r, $dpr) = @_;
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.
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) {
940 $manual_aperture = 1;
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 ];
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 ];
958 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
961 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
963 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
965 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
966 my $f = $info->{'FNumber'};
968 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
970 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
974 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
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'};
984 if (defined($iso) && $iso =~ /(\d+)/) {
985 push @classic_fields, [ $1 . " ISO", 0 ];
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 ];
994 # Now piece together the rest
997 if (defined($info->{'DateTimeOriginal'}) &&
998 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
1000 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
1003 if (defined($info->{'Model'})) {
1004 my $model = $info->{'Model'};
1008 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
1009 push @parts, [ $model, 0 ];
1013 if (scalar @classic_fields > 0) {
1014 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
1017 for my $field (@classic_fields) {
1018 push @parts, [ ', ', 0 ] if (!$first_elem);
1020 push @parts, $field;
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 ];
1036 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
1037 push @parts, [ $info->{'Flash'}, 0 ];
1041 return 0 if (scalar @parts == 0);
1043 # Find the required width
1047 for my $part (@parts) {
1050 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
1052 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
1055 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
1058 $th = $h if ($h > $th);
1061 return 0 if ($tw > $img->Get('columns'));
1064 my $y = $img->Get('rows') - 24*$dpr;
1066 # Hit exact DCT blocks
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);
1074 # Start writing out the text
1075 $x = ($img->Get('columns') - $tw) / 2;
1077 my $room = ($img->Get('rows') - $dpr - $y - $th);
1078 $y = ($img->Get('rows') - $dpr) - $room/2;
1080 for my $part (@parts) {
1083 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
1085 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
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];
1096 return $a if ($b == 0);
1097 return gcd($b, $a % $b);
1101 my ($r, $dbh, $id, $date, $desc) = @_;
1104 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
1105 push @errors, "Manglende eller ugyldig ID.";
1107 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
1108 push @errors, "Manglende eller ugyldig dato.";
1110 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
1111 push @errors, "Manglende eller ugyldig beskrivelse.";
1114 if (scalar @errors > 0) {
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)",
1124 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
1125 purge_cache($r, "/");
1135 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
1138 $decoded = Encode::decode("iso8859-1", $text);
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.
1149 my ($r, @elements) = @_;
1150 return if (scalar @elements == 0);
1153 for my $elem (@elements) {
1154 $r->log->info("Purging $elem");
1155 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1160 if (scalar @pe == 1) {
1163 $regex .= "(" . join('|', @pe) . ")";
1165 $regex .= "(\\?.*)?\$";
1166 $r->headers_out->{'X-Pr0n-Purge'} = $regex;
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);
1175 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1176 or die "Couldn't prepare: " . $dbh->errstr;
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'};
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";
1200 $r->log->warn("Couldn't find a purging URL for $fname");