1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
17 use Digest::HMAC_SHA1;
26 use Crypt::Eksblowfish::Bcrypt;
30 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
32 use Sesse::pr0n::Config;
34 require Sesse::pr0n::Config_local;
37 $VERSION = "v3.00-pre";
39 @EXPORT = qw(&error &dberror);
41 @EXPORT_OK = qw(&error &dberror);
43 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
44 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
45 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
46 our $mimetypes = new MIME::Types;
48 print STDERR "Initializing pr0n $VERSION\n";
55 our ($dbh, $mimetypes);
58 my ($r,$err,$status,$title) = @_;
60 if (!defined($status) || !defined($title)) {
62 $title = "Internal server error";
65 my $res = Plack::Response->new($status);
66 my $io = IO::String->new;
68 $r->content_type('text/html; charset=utf-8');
70 header($r, $io, $title);
71 $io->print(" <p>Error: $err</p>\n");
75 log_error($r, "Stack trace follows: " . Carp::longmess());
84 return error($r, "$err (DB error: " . $dbh->errstr . ")");
88 my ($r, $io, $title) = @_;
90 $r->content_type("text/html; charset=utf-8");
92 # Fetch quote if we're itk-bilder.samfundet.no
94 if (Sesse::pr0n::Common::get_server_name($r) eq 'itk-bilder.samfundet.no') {
95 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
96 $quote = "Error: Could not fetch quotes." if (!defined($quote));
98 Sesse::pr0n::Templates::print_template($r, $io, "header", { title => $title, quotes => $quote });
103 Sesse::pr0n::Templates::print_template($r, $io, "footer",
104 { version => $Sesse::pr0n::Common::VERSION });
108 my ($width, $height, $thumbxres, $thumbyres) = @_;
110 unless ($thumbxres >= $width &&
111 $thumbyres >= $height) {
112 my $sfh = $width / $thumbxres;
113 my $sfv = $height / $thumbyres;
121 $width = POSIX::floor($width);
122 $height = POSIX::floor($height);
125 return ($width, $height);
128 sub get_query_string {
129 my ($param, $defparam) = @_;
133 while (my ($key, $value) = each %$param) {
134 next unless defined($value);
135 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
137 $value = pretty_escape($value);
139 $str .= ($first) ? "?" : ';';
140 $str .= "$key=$value";
146 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
147 sub weird_space_encode {
150 return "_" x (length($val) * 2);
152 return "_" x (length($val) * 2 - 1);
156 sub weird_space_unencode {
158 if (length($val) % 2 == 0) {
159 return "_" x (length($val) / 2);
161 return " " x ((length($val) + 1) / 2);
168 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
169 $value = URI::Escape::uri_escape($value);
170 $value =~ s/%2F/\//g;
175 sub pretty_unescape {
178 # URI unescaping is already done for us
179 $value =~ s/(_+)/weird_space_unencode($1)/ge;
185 my ($io, $title, $baseurl, $param, $defparam, $accesskey) = @_;
186 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
187 if (defined($accesskey) && length($accesskey) == 1) {
188 $str .= " accesskey=\"$accesskey\"";
190 $str .= ">$title</a>";
195 # Check that we are alive
196 if (!(defined($dbh) && $dbh->ping)) {
198 print STDERR "Lost contact with PostgreSQL server, trying to reconnect...\n";
199 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
200 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
202 die "Couldn't connect to PostgreSQL database";
209 sub get_disk_location {
211 my $dir = POSIX::floor($id / 256);
212 return $Sesse::pr0n::Config::image_base . "images/$dir/$id.jpg";
215 sub get_cache_location {
216 my ($r, $id, $width, $height, $infobox, $dpr) = @_;
217 my $dir = POSIX::floor($id / 256);
219 if ($infobox eq 'both') {
220 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height.jpg";
221 } elsif ($infobox eq 'nobox') {
222 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-nobox.jpg";
225 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box.png";
227 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box\@$dpr.png";
232 sub ensure_disk_location_exists {
234 my $dir = POSIX::floor($id / 256);
236 my $img_dir = $Sesse::pr0n::Config::image_base . "/images/$dir/";
238 log_info($r, "Need to create new image directory $img_dir");
239 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
242 my $cache_dir = $Sesse::pr0n::Config::image_base . "/cache/$dir/";
243 if (! -d $cache_dir) {
244 log_info($r, "Need to create new cache directory $cache_dir");
245 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
249 sub get_mipmap_location {
250 my ($r, $id, $width, $height) = @_;
251 my $dir = POSIX::floor($id / 256);
253 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-mipmap-$width-$height.jpg";
256 sub update_image_info {
257 my ($r, $id, $width, $height) = @_;
259 # Also find the date taken if appropriate (from the EXIF tag etc.)
260 my $exiftool = Image::ExifTool->new;
261 $exiftool->ExtractInfo(get_disk_location($r, $id));
262 my $info = $exiftool->GetInfo();
263 my $datetime = undef;
265 if (defined($info->{'DateTimeOriginal'})) {
266 # Parse the date and time over to ISO format
267 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
268 $datetime = "$1-$2-$3 $4:$5:$6";
273 local $dbh->{AutoCommit} = 0;
276 $dbh->do('DELETE FROM exif_info WHERE image=?',
278 or die "Couldn't delete old EXIF information in SQL: $!";
280 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
281 or die "Couldn't prepare inserting EXIF information: $!";
283 for my $key (keys %$info) {
284 next if ref $info->{$key};
285 $q->execute($id, $key, guess_charset($info->{$key}))
286 or die "Couldn't insert EXIF information in database: $!";
290 my $model = $exiftool->GetValue('Model', 'PrintConv');
291 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
292 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
296 $model = undef if (length($model) == 0);
300 $lens = undef if (length($lens) == 0);
302 # Now update the main table with the information we've got
303 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
304 undef, $width, $height, $datetime, $model, $lens, $id)
305 or die "Couldn't update width/height in SQL: $!";
308 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
309 if (scalar @tags == 0) {
310 # This is XMP-dc:Subject, an RDF bag of tags.
311 @tags = $exiftool->GetValue('Subject', 'ValueConv');
313 $dbh->do('DELETE FROM tags WHERE image=?',
315 or die "Couldn't delete old tag information in SQL: $!";
317 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
318 or die "Couldn't prepare inserting tag information: $!";
321 for my $tag (@tags) {
322 $q->execute($id, guess_charset($tag))
323 or die "Couldn't insert tag information in database: $!";
326 # update the last_picture cache as well (this should of course be done
327 # via a trigger, but this is less complicated :-) )
328 $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=?)',
329 undef, $datetime, $id)
330 or die "Couldn't update last_picture in SQL: $!";
337 #return qw(sesse Sesse);
339 my $auth = $r->header('authorization');
340 if (!defined($auth)) {
343 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
344 return check_basic_auth($r, $1);
351 my $res = Plack::Response->new(401);
352 $res->content_type('text/plain; charset=utf-8');
354 $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
356 $res->body("Need authorization\n");
360 sub check_basic_auth {
363 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
364 my ($user, $takenby) = extract_takenby($raw_user);
366 my $ref = $dbh->selectrow_hashref('SELECT sha1password,cryptpassword FROM users WHERE username=? AND vhost=?',
367 undef, $user, Sesse::pr0n::Common::get_server_name($r));
368 my ($sha1_matches, $bcrypt_matches) = (0, 0);
369 if (defined($ref) && defined($ref->{'sha1password'})) {
370 $sha1_matches = (Digest::SHA::sha1_base64($pass) eq $ref->{'sha1password'});
372 if (defined($ref) && defined($ref->{'cryptpassword'})) {
373 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
376 if (!defined($ref) || (!$sha1_matches && !$bcrypt_matches)) {
377 $r->content_type('text/plain; charset=utf-8');
378 log_warn($r, "Authentication failed for $user/$takenby");
381 log_info($r, "Authentication succeeded for $user/$takenby");
383 # Make sure we can use bcrypt authentication in the future with this password.
384 # Also remove old-style SHA1 password when we migrate.
385 if (!$bcrypt_matches) {
386 my $salt = get_pseudorandom_bytes(16); # Doesn't need to be cryptographically secur.
387 my $hash = "\$2a\$07\$" . Crypt::Eksblowfish::Bcrypt::en_base64($salt);
388 my $cryptpassword = Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $hash);
389 $dbh->do('UPDATE users SET sha1password=NULL,cryptpassword=? WHERE username=? AND vhost=?',
390 undef, $cryptpassword, $user, Sesse::pr0n::Common::get_server_name($r))
391 or die "Couldn't update: " . $dbh->errstr;
392 log_info($r, "Updated bcrypt hash for $user");
395 return ($user, $takenby);
398 sub get_pseudorandom_bytes {
399 my $num_left = shift;
401 open my $randfh, "<", "/dev/urandom"
402 or die "/dev/urandom: $!";
404 while ($num_left > 0) {
406 if (sysread($randfh, $tmp, $num_left) == -1) {
407 die "sysread(/dev/urandom): $!";
410 $num_left -= length($bytes);
416 sub extract_takenby {
419 # WinXP is stupid :-)
420 if ($user =~ /^.*\\(.*)$/) {
425 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
429 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
432 return ($user, $takenby);
436 my ($r, $event, $filename) = (@_);
437 my $ref = $dbh->selectrow_hashref(
438 'SELECT id FROM images WHERE event=? AND filename=?',
439 undef, $event, $filename);
440 if (!defined($ref)) {
441 return (undef, undef, undef);
443 return stat_image_from_id($r, $ref->{'id'});
446 sub stat_image_from_id {
449 my $fname = get_disk_location($r, $id);
450 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
451 or return (undef, undef, undef);
453 return ($fname, $size, $mtime);
456 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
457 # the smallest mipmap larger than the largest of them, as well as the original image
460 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
461 my ($img, $mmimg, $width, $height);
463 my $physical_fname = get_disk_location($r, $id);
465 # If we don't know the size, we'll need to read it in anyway
466 if (!defined($dbwidth) || !defined($dbheight)) {
467 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
468 $width = $img->Get('columns');
469 $height = $img->Get('rows');
475 # Generate the list of mipmaps
478 my $mmwidth = $width;
479 my $mmheight = $height;
481 while ($mmwidth > 1 || $mmheight > 1) {
482 my $new_mmwidth = POSIX::floor($mmwidth / 2);
483 my $new_mmheight = POSIX::floor($mmheight / 2);
485 $new_mmwidth = 1 if ($new_mmwidth < 1);
486 $new_mmheight = 1 if ($new_mmheight < 1);
488 my $large_enough = 1;
489 for my $i (0..($#res/2)) {
490 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
491 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
497 last if (!$large_enough);
499 $mmwidth = $new_mmwidth;
500 $mmheight = $new_mmheight;
502 push @mmlist, [ $mmwidth, $mmheight ];
505 # Ensure that all of them are OK
506 my $last_good_mmlocation;
507 for my $i (0..$#mmlist) {
508 my $last = ($i == $#mmlist);
509 my $mmres = $mmlist[$i];
511 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
512 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
513 if (!defined($img)) {
514 if (defined($last_good_mmlocation)) {
515 if ($can_use_qscale) {
516 $img = Sesse::pr0n::QscaleProxy->new;
518 $img = Image::Magick->new;
520 $img->Read($last_good_mmlocation);
522 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
529 $cimg = $img->Clone();
531 log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
532 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
534 my $err = $cimg->write(
535 filename => $mmlocation,
537 'sampling-factor' => '1x1'
541 $last_good_mmlocation = $mmlocation;
543 if ($last && !defined($img)) {
544 # OK, read in the smallest one
545 if ($can_use_qscale) {
546 $img = Sesse::pr0n::QscaleProxy->new;
548 $img = Image::Magick->new;
550 my $err = $img->Read($mmlocation);
554 if (!defined($img)) {
555 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
556 $width = $img->Get('columns');
557 $height = $img->Get('rows');
559 return ($img, $width, $height);
562 sub read_original_image {
563 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
565 my $physical_fname = get_disk_location($r, $id);
567 # Read in the original image
569 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
570 $magick = Sesse::pr0n::QscaleProxy->new;
572 $magick = Image::Magick->new;
576 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
577 # The delegate support is rather broken and causes very odd stuff to happen when
578 # more than one thread does this at the same time. Thus, we simply do it ourselves.
579 if ($filename =~ /\.(nef|cr2)$/i) {
580 # this would suffice if ImageMagick gets to fix their handling
581 # $physical_fname = "NEF:$physical_fname";
583 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
584 or error("dcraw: $!");
585 $err = $magick->Read(file => \*DCRAW);
588 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
589 # RGB is slightly faster (no colorspace conversion needed) and works equally
590 # well for our uses, as long as we don't need to draw an information box,
591 # which trickles several ImageMagick bugs related to colorspace handling.
592 # (Ideally we'd be able to keep the image subsampled and
593 # planar, but that would probably be difficult for ImageMagick to expose.)
595 # $magick->Set(colorspace=>'YCbCr');
597 $err = $magick->Read($physical_fname);
601 log_warn($r, "$physical_fname: $err");
605 error($r, "$physical_fname: $err");
609 # If we use ->[0] unconditionally, text rendering (!) seems to crash
611 if (ref($magick) !~ /Image::Magick/) {
614 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
621 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
623 my ($new_dbwidth, $new_dbheight);
625 my $fname = get_disk_location($r, $id);
626 if ($infobox ne 'box') {
627 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
628 return ($fname, undef);
632 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
634 if (! -r $cachename or (-M $cachename > -M $fname)) {
635 # If we are in overload mode (aka Slashdot mode), refuse to generate
637 if (Sesse::pr0n::Overload::is_in_overload($r)) {
638 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
639 error($r, 'System is in overload mode, not doing any scaling');
642 # If we're being asked for just the box, make a new image with just the box.
643 # We don't care about @otherres since each of these images are
644 # already pretty cheap to generate, but we need the exact width so we can make
645 # one in the right size.
646 if ($infobox eq 'box') {
647 my ($img, $width, $height);
649 # This is slow, but should fortunately almost never happen, so don't bother
651 if (!defined($dbwidth) || !defined($dbheight)) {
652 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
653 $new_dbwidth = $width = $img->Get('columns');
654 $new_dbheight = $height = $img->Get('rows');
657 $img = Image::Magick->new;
662 if (defined($xres) && defined($yres)) {
663 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
666 $img->Set(size=>($width . "x" . $height));
667 $img->Read('xc:white');
669 my $info = Image::ExifTool::ImageInfo($fname);
670 if (make_infobox($img, $info, $r, $dpr)) {
671 $img->Quantize(colors=>16, dither=>'False');
673 # Since the image is grayscale, ImageMagick overrides us and writes this
674 # as grayscale anyway, but at least we get rid of the alpha channel this
676 $img->Set(type=>'Palette');
678 # Not enough room for the text, make a tiny dummy transparent infobox
680 $img->Set(size=>"1x1");
687 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
688 log_info($r, "New infobox cache: $width x $height for $id.jpg");
690 return ($cachename, 'image/png');
693 my $can_use_qscale = 0;
694 if ($infobox eq 'nobox') {
699 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
701 while (defined($xres) && defined($yres)) {
702 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
703 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
706 if (defined($nxres) && defined($nyres)) {
707 # we have more resolutions to scale, so don't throw
709 $cimg = $img->Clone();
714 my $width = $img->Get('columns');
715 my $height = $img->Get('rows');
716 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
718 my $filter = 'Lanczos';
723 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
726 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
727 my $info = Image::ExifTool::ImageInfo($fname);
728 make_infobox($cimg, $info, $r, 1);
731 # Strip EXIF tags etc.
736 filename => $cachename,
739 if (($nwidth >= 640 && $nheight >= 480) ||
740 ($nwidth >= 480 && $nheight >= 640)) {
741 $parms{'interlace'} = 'Plane';
744 $parms{'sampling-factor'} = $sf;
746 $err = $cimg->write(%parms);
751 ($xres, $yres) = ($nxres, $nyres);
753 log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
758 log_warn($r, "$fname: $err");
762 error($r, "$fname: $err");
767 # Update the SQL database if it doesn't contain the required info
768 if (!defined($dbwidth) && defined($new_dbwidth)) {
769 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
770 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
773 return ($cachename, 'image/jpeg');
776 sub get_mimetype_from_filename {
777 my $filename = shift;
778 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
779 $type = "image/jpeg" if (!defined($type));
784 my ($img, $info, $r, $dpr) = @_;
786 # The infobox is of the form
787 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
788 # possibly with some parts omitted -- the middle part is known as the "classic
789 # fields"; note the comma separation. Every field has an associated "bold flag"
790 # in the second part.
792 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
793 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
794 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
795 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
796 if ($info->{'ExposureProgram'} =~ /manual/i) {
798 $manual_aperture = 1;
801 my @classic_fields = ();
802 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
803 push @classic_fields, [ $1 . "mm", 0 ];
804 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
805 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
808 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
809 my ($a, $b) = ($1, $2);
810 my $gcd = gcd($a, $b);
811 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
812 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
813 push @classic_fields, [ $1 . "s", $manual_shutter ];
816 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
819 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
821 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
823 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
824 my $f = $info->{'FNumber'};
826 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
828 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
832 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
835 if (defined($info->{'NikonD1-ISOSetting'})) {
836 $iso = $info->{'NikonD1-ISOSetting'};
837 } elsif (defined($info->{'ISO'})) {
838 $iso = $info->{'ISO'};
839 } elsif (defined($info->{'ISOSetting'})) {
840 $iso = $info->{'ISOSetting'};
842 if (defined($iso) && $iso =~ /(\d+)/) {
843 push @classic_fields, [ $1 . " ISO", 0 ];
846 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
847 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
848 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
849 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
852 # Now piece together the rest
855 if (defined($info->{'DateTimeOriginal'}) &&
856 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
858 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
861 if (defined($info->{'Model'})) {
862 my $model = $info->{'Model'};
866 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
867 push @parts, [ $model, 0 ];
871 if (scalar @classic_fields > 0) {
872 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
875 for my $field (@classic_fields) {
876 push @parts, [ ', ', 0 ] if (!$first_elem);
882 if (defined($info->{'Flash'})) {
883 if ($info->{'Flash'} =~ /did not fire/i ||
884 $info->{'Flash'} =~ /no flash/i ||
885 $info->{'Flash'} =~ /not fired/i ||
886 $info->{'Flash'} =~ /Off/) {
887 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
888 push @parts, [ "No flash", 0 ];
889 } elsif ($info->{'Flash'} =~ /fired/i ||
890 $info->{'Flash'} =~ /On/) {
891 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
892 push @parts, [ "Flash", 0 ];
894 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
895 push @parts, [ $info->{'Flash'}, 0 ];
899 return 0 if (scalar @parts == 0);
901 # Find the required width
905 for my $part (@parts) {
908 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
910 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
913 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
916 $th = $h if ($h > $th);
919 return 0 if ($tw > $img->Get('columns'));
922 my $y = $img->Get('rows') - 24*$dpr;
924 # Hit exact DCT blocks
927 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
928 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
929 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
930 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
932 # Start writing out the text
933 $x = ($img->Get('columns') - $tw) / 2;
935 my $room = ($img->Get('rows') - $dpr - $y - $th);
936 $y = ($img->Get('rows') - $dpr) - $room/2;
938 for my $part (@parts) {
941 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
943 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
945 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
946 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
954 return $a if ($b == 0);
955 return gcd($b, $a % $b);
959 my ($r, $res, $dbh, $id, $date, $desc) = @_;
962 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
963 push @errors, "Manglende eller ugyldig ID.";
965 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
966 push @errors, "Manglende eller ugyldig dato.";
968 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
969 push @errors, "Manglende eller ugyldig beskrivelse.";
972 if (scalar @errors > 0) {
976 my $vhost = Sesse::pr0n::Common::get_server_name($r);
977 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
978 undef, $id, $date, $desc, $vhost)
979 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
980 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
982 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
983 purge_cache($r, $res, "/");
993 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
996 $decoded = Encode::decode("iso8859-1", $text);
1002 # Depending on your front-end cache, you might want to get creative somehow here.
1003 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
1004 # regex tacked onto a request into something useful. The elements given in
1005 # should not be regexes, though, as e.g. Squid will not be able to handle that.
1007 my ($r, $res, @elements) = @_;
1008 return if (scalar @elements == 0);
1011 for my $elem (@elements) {
1012 log_info($r, "Purging $elem");
1013 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1018 if (scalar @pe == 1) {
1021 $regex .= "(" . join('|', @pe) . ")";
1023 $regex .= "(\\?.*)?\$";
1024 $res->header('X-Pr0n-Purge' => $regex);
1027 # Find a list of all cache URLs for a given image, given what we have on disk.
1028 sub get_all_cache_urls {
1029 my ($r, $dbh, $id) = @_;
1030 my $dir = POSIX::floor($id / 256);
1033 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1034 or die "Couldn't prepare: " . $dbh->errstr;
1036 or die "Couldn't find event and filename: " . $dbh->errstr;
1037 my $ref = $q->fetchrow_hashref;
1038 my $event = $ref->{'event'};
1039 my $filename = $ref->{'filename'};
1042 my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
1043 for my $file (<$base/$id-*>) {
1044 my $fname = File::Basename::basename($file);
1045 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1046 # Mipmaps don't have an URL, ignore
1047 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1048 push @ret, "/$event/$filename";
1049 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1050 push @ret, "/$event/$1x$2/$filename";
1051 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1052 push @ret, "/$event/$1x$2/nobox/$filename";
1053 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1054 push @ret, "/$event/box/$filename";
1055 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1056 push @ret, "/$event/$1x$2/box/$filename";
1058 log_warn($r, "Couldn't find a purging URL for $fname");
1065 sub set_last_modified {
1066 my ($res, $mtime) = @_;
1068 my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S %Z", localtime($mtime));
1069 $res->headers({ 'Last-Modified' => $str });
1072 sub get_server_name {
1074 my $host = $r->env->{'HTTP_HOST'};
1081 if (defined($r->logger)) {
1082 $r->logger->({ level => 'info', message => $msg });
1084 print STDERR "[INFO] $msg\n";
1090 if (defined($r->logger)) {
1091 $r->logger->({ level => 'warn', message => $msg });
1093 print STDERR "[WARN] $msg\n";
1099 if (defined($r->logger)) {
1100 $r->logger->({ level => 'error', message => $msg });
1102 print STDERR "[ERROR] $msg\n";