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';
22 use Digest::HMAC_SHA1;
31 use Crypt::Eksblowfish::Bcrypt;
35 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
37 use Sesse::pr0n::Config;
39 require Sesse::pr0n::Config_local;
44 @EXPORT = qw(&error &dberror);
46 @EXPORT_OK = qw(&error &dberror);
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;
53 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
60 our ($dbh, $mimetypes);
63 my ($r,$err,$status,$title) = @_;
65 if (!defined($status) || !defined($title)) {
67 $title = "Internal server error";
70 $r->content_type('text/html; charset=utf-8');
74 $r->print(" <p>Error: $err</p>\n");
78 $r->log->error("Stack trace follows: " . Carp::longmess());
80 ModPerl::Util::exit();
85 error($r, "$err (DB error: " . $dbh->errstr . ")");
91 $r->content_type("text/html; charset=utf-8");
93 # Fetch quote if we're itk-bilder.samfundet.no
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));
99 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
104 Sesse::pr0n::Templates::print_template($r, "footer",
105 { version => $Sesse::pr0n::Common::VERSION });
109 my ($width, $height, $thumbxres, $thumbyres) = @_;
111 unless ($thumbxres >= $width &&
112 $thumbyres >= $height) {
113 my $sfh = $width / $thumbxres;
114 my $sfv = $height / $thumbyres;
122 $width = POSIX::floor($width);
123 $height = POSIX::floor($height);
126 return ($width, $height);
129 sub get_query_string {
130 my ($param, $defparam) = @_;
134 while (my ($key, $value) = each %$param) {
135 next unless defined($value);
136 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
138 $value = pretty_escape($value);
140 $str .= ($first) ? "?" : ';';
141 $str .= "$key=$value";
147 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
148 sub weird_space_encode {
151 return "_" x (length($val) * 2);
153 return "_" x (length($val) * 2 - 1);
157 sub weird_space_unencode {
159 if (length($val) % 2 == 0) {
160 return "_" x (length($val) / 2);
162 return " " x ((length($val) + 1) / 2);
169 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
170 $value = URI::Escape::uri_escape($value);
171 $value =~ s/%2F/\//g;
176 sub pretty_unescape {
179 # URI unescaping is already done for us
180 $value =~ s/(_+)/weird_space_unencode($1)/ge;
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\"";
191 $str .= ">$title</a>";
196 # Check that we are alive
197 if (!(defined($dbh) && $dbh->ping)) {
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)) {
203 die "Couldn't connect to PostgreSQL database";
212 return $r->dir_config('ImageBase');
215 sub get_disk_location {
217 my $dir = POSIX::floor($id / 256);
218 return get_base($r) . "images/$dir/$id.jpg";
221 sub get_cache_location {
222 my ($r, $id, $width, $height, $infobox, $dpr) = @_;
223 my $dir = POSIX::floor($id / 256);
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";
231 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
233 return get_base($r) . "cache/$dir/$id-$width-$height-box\@$dpr.png";
238 sub ensure_disk_location_exists {
240 my $dir = POSIX::floor($id / 256);
242 my $img_dir = get_base($r) . "/images/$dir/";
244 $r->log->info("Need to create new image directory $img_dir");
245 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
248 my $cache_dir = get_base($r) . "/cache/$dir/";
249 if (! -d $cache_dir) {
250 $r->log->info("Need to create new cache directory $cache_dir");
251 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
255 sub get_mipmap_location {
256 my ($r, $id, $width, $height) = @_;
257 my $dir = POSIX::floor($id / 256);
259 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
262 sub update_image_info {
263 my ($r, $id, $width, $height) = @_;
265 # Also find the date taken if appropriate (from the EXIF tag etc.)
266 my $exiftool = Image::ExifTool->new;
267 $exiftool->ExtractInfo(get_disk_location($r, $id));
268 my $info = $exiftool->GetInfo();
269 my $datetime = undef;
271 if (defined($info->{'DateTimeOriginal'})) {
272 # Parse the date and time over to ISO format
273 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
274 $datetime = "$1-$2-$3 $4:$5:$6";
279 local $dbh->{AutoCommit} = 0;
282 $dbh->do('DELETE FROM exif_info WHERE image=?',
284 or die "Couldn't delete old EXIF information in SQL: $!";
286 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
287 or die "Couldn't prepare inserting EXIF information: $!";
289 for my $key (keys %$info) {
290 next if ref $info->{$key};
291 $q->execute($id, $key, guess_charset($info->{$key}))
292 or die "Couldn't insert EXIF information in database: $!";
296 my $model = $exiftool->GetValue('Model', 'PrintConv');
297 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
298 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
302 $model = undef if (length($model) == 0);
306 $lens = undef if (length($lens) == 0);
308 # Now update the main table with the information we've got
309 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
310 undef, $width, $height, $datetime, $model, $lens, $id)
311 or die "Couldn't update width/height in SQL: $!";
314 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
315 if (scalar @tags == 0) {
316 # This is XMP-dc:Subject, an RDF bag of tags.
317 @tags = $exiftool->GetValue('Subject', 'ValueConv');
319 $dbh->do('DELETE FROM tags WHERE image=?',
321 or die "Couldn't delete old tag information in SQL: $!";
323 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
324 or die "Couldn't prepare inserting tag information: $!";
327 for my $tag (@tags) {
328 $q->execute($id, guess_charset($tag))
329 or die "Couldn't insert tag information in database: $!";
332 # update the last_picture cache as well (this should of course be done
333 # via a trigger, but this is less complicated :-) )
334 $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=?)',
335 undef, $datetime, $id)
336 or die "Couldn't update last_picture in SQL: $!";
343 #return qw(sesse Sesse);
345 my $auth = $r->headers_in->{'authorization'};
346 if (!defined($auth)) {
350 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
351 return check_basic_auth($r, $1);
358 my ($r, %options) = @_;
359 $r->content_type('text/plain; charset=utf-8');
361 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
363 $r->print("Need authorization\n");
366 sub check_basic_auth {
369 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
370 my ($user, $takenby) = extract_takenby($raw_user);
372 my $ref = $dbh->selectrow_hashref('SELECT sha1password,cryptpassword FROM users WHERE username=? AND vhost=?',
373 undef, $user, $r->get_server_name);
374 my ($sha1_matches, $bcrypt_matches) = (0, 0);
375 if (defined($ref) && defined($ref->{'sha1password'})) {
376 $sha1_matches = (Digest::SHA::sha1_base64($pass) eq $ref->{'sha1password'});
378 if (defined($ref) && defined($ref->{'cryptpassword'})) {
379 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
382 if (!defined($ref) || (!$sha1_matches && !$bcrypt_matches)) {
383 $r->content_type('text/plain; charset=utf-8');
384 $r->log->warn("Authentication failed for $user/$takenby");
388 $r->log->info("Authentication succeeded for $user/$takenby");
390 # Make sure we can use bcrypt authentication in the future with this password.
391 # Also remove old-style SHA1 password when we migrate.
392 if (!$bcrypt_matches) {
393 my $salt = get_pseudorandom_bytes(16); # Doesn't need to be cryptographically secur.
394 my $hash = "\$2a\$07\$" . Crypt::Eksblowfish::Bcrypt::en_base64($salt);
395 my $cryptpassword = Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $hash);
396 $dbh->do('UPDATE users SET sha1password=NULL,cryptpassword=? WHERE username=? AND vhost=?',
397 undef, $cryptpassword, $user, $r->get_server_name)
398 or die "Couldn't update: " . $dbh->errstr;
399 $r->log->info("Updated bcrypt hash for $user");
402 return ($user, $takenby);
405 sub get_pseudorandom_bytes {
406 my $num_left = shift;
408 open my $randfh, "<", "/dev/urandom"
409 or die "/dev/urandom: $!";
411 while ($num_left > 0) {
413 if (sysread($randfh, $tmp, $num_left) == -1) {
414 die "sysread(/dev/urandom): $!";
417 $num_left -= length($bytes);
423 sub extract_takenby {
426 # WinXP is stupid :-)
427 if ($user =~ /^.*\\(.*)$/) {
432 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
436 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
439 return ($user, $takenby);
443 my ($r, $event, $filename) = (@_);
444 my $ref = $dbh->selectrow_hashref(
445 'SELECT id FROM images WHERE event=? AND filename=?',
446 undef, $event, $filename);
447 if (!defined($ref)) {
448 return (undef, undef, undef);
450 return stat_image_from_id($r, $ref->{'id'});
453 sub stat_image_from_id {
456 my $fname = get_disk_location($r, $id);
457 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
458 or return (undef, undef, undef);
460 return ($fname, $size, $mtime);
463 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
464 # the smallest mipmap larger than the largest of them, as well as the original image
467 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
468 my ($img, $mmimg, $width, $height);
470 my $physical_fname = get_disk_location($r, $id);
472 # If we don't know the size, we'll need to read it in anyway
473 if (!defined($dbwidth) || !defined($dbheight)) {
474 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
475 $width = $img->Get('columns');
476 $height = $img->Get('rows');
482 # Generate the list of mipmaps
485 my $mmwidth = $width;
486 my $mmheight = $height;
488 while ($mmwidth > 1 || $mmheight > 1) {
489 my $new_mmwidth = POSIX::floor($mmwidth / 2);
490 my $new_mmheight = POSIX::floor($mmheight / 2);
492 $new_mmwidth = 1 if ($new_mmwidth < 1);
493 $new_mmheight = 1 if ($new_mmheight < 1);
495 my $large_enough = 1;
496 for my $i (0..($#res/2)) {
497 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
498 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
504 last if (!$large_enough);
506 $mmwidth = $new_mmwidth;
507 $mmheight = $new_mmheight;
509 push @mmlist, [ $mmwidth, $mmheight ];
512 # Ensure that all of them are OK
513 my $last_good_mmlocation;
514 for my $i (0..$#mmlist) {
515 my $last = ($i == $#mmlist);
516 my $mmres = $mmlist[$i];
518 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
519 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
520 if (!defined($img)) {
521 if (defined($last_good_mmlocation)) {
522 if ($can_use_qscale) {
523 $img = Sesse::pr0n::QscaleProxy->new;
525 $img = Image::Magick->new;
527 $img->Read($last_good_mmlocation);
529 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
536 $cimg = $img->Clone();
538 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
539 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
541 my $err = $cimg->write(
542 filename => $mmlocation,
544 'sampling-factor' => '1x1'
548 $last_good_mmlocation = $mmlocation;
550 if ($last && !defined($img)) {
551 # OK, read in the smallest one
552 if ($can_use_qscale) {
553 $img = Sesse::pr0n::QscaleProxy->new;
555 $img = Image::Magick->new;
557 my $err = $img->Read($mmlocation);
561 if (!defined($img)) {
562 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
563 $width = $img->Get('columns');
564 $height = $img->Get('rows');
566 return ($img, $width, $height);
569 sub read_original_image {
570 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
572 my $physical_fname = get_disk_location($r, $id);
574 # Read in the original image
576 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
577 $magick = Sesse::pr0n::QscaleProxy->new;
579 $magick = Image::Magick->new;
583 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
584 # The delegate support is rather broken and causes very odd stuff to happen when
585 # more than one thread does this at the same time. Thus, we simply do it ourselves.
586 if ($filename =~ /\.(nef|cr2)$/i) {
587 # this would suffice if ImageMagick gets to fix their handling
588 # $physical_fname = "NEF:$physical_fname";
590 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
591 or error("dcraw: $!");
592 $err = $magick->Read(file => \*DCRAW);
595 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
596 # RGB is slightly faster (no colorspace conversion needed) and works equally
597 # well for our uses, as long as we don't need to draw an information box,
598 # which trickles several ImageMagick bugs related to colorspace handling.
599 # (Ideally we'd be able to keep the image subsampled and
600 # planar, but that would probably be difficult for ImageMagick to expose.)
602 # $magick->Set(colorspace=>'YCbCr');
604 $err = $magick->Read($physical_fname);
608 $r->log->warn("$physical_fname: $err");
612 error($r, "$physical_fname: $err");
616 # If we use ->[0] unconditionally, text rendering (!) seems to crash
618 if (ref($magick) !~ /Image::Magick/) {
621 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
628 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
630 my ($new_dbwidth, $new_dbheight);
632 my $fname = get_disk_location($r, $id);
633 if ($infobox ne 'box') {
634 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
635 return ($fname, undef);
639 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
641 if (! -r $cachename or (-M $cachename > -M $fname)) {
642 # If we are in overload mode (aka Slashdot mode), refuse to generate
644 if (Sesse::pr0n::Overload::is_in_overload($r)) {
645 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
646 error($r, 'System is in overload mode, not doing any scaling');
649 # If we're being asked for just the box, make a new image with just the box.
650 # We don't care about @otherres since each of these images are
651 # already pretty cheap to generate, but we need the exact width so we can make
652 # one in the right size.
653 if ($infobox eq 'box') {
654 my ($img, $width, $height);
656 # This is slow, but should fortunately almost never happen, so don't bother
658 if (!defined($dbwidth) || !defined($dbheight)) {
659 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
660 $new_dbwidth = $width = $img->Get('columns');
661 $new_dbheight = $height = $img->Get('rows');
664 $img = Image::Magick->new;
669 if (defined($xres) && defined($yres)) {
670 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
673 $img->Set(size=>($width . "x" . $height));
674 $img->Read('xc:white');
676 my $info = Image::ExifTool::ImageInfo($fname);
677 if (make_infobox($img, $info, $r, $dpr)) {
678 $img->Quantize(colors=>16, dither=>'False');
680 # Since the image is grayscale, ImageMagick overrides us and writes this
681 # as grayscale anyway, but at least we get rid of the alpha channel this
683 $img->Set(type=>'Palette');
685 # Not enough room for the text, make a tiny dummy transparent infobox
687 $img->Set(size=>"1x1");
694 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
695 $r->log->info("New infobox cache: $width x $height for $id.jpg");
697 return ($cachename, 'image/png');
700 my $can_use_qscale = 0;
701 if ($infobox eq 'nobox') {
706 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
708 while (defined($xres) && defined($yres)) {
709 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
710 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
713 if (defined($nxres) && defined($nyres)) {
714 # we have more resolutions to scale, so don't throw
716 $cimg = $img->Clone();
721 my $width = $img->Get('columns');
722 my $height = $img->Get('rows');
723 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
725 my $filter = 'Lanczos';
730 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
733 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
734 my $info = Image::ExifTool::ImageInfo($fname);
735 make_infobox($cimg, $info, $r, 1);
738 # Strip EXIF tags etc.
743 filename => $cachename,
746 if (($nwidth >= 640 && $nheight >= 480) ||
747 ($nwidth >= 480 && $nheight >= 640)) {
748 $parms{'interlace'} = 'Plane';
751 $parms{'sampling-factor'} = $sf;
753 $err = $cimg->write(%parms);
758 ($xres, $yres) = ($nxres, $nyres);
760 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
765 $r->log->warn("$fname: $err");
769 error($r, "$fname: $err");
774 # Update the SQL database if it doesn't contain the required info
775 if (!defined($dbwidth) && defined($new_dbwidth)) {
776 $r->log->info("Updating width/height for $id: $new_dbwidth x $new_dbheight");
777 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
780 return ($cachename, 'image/jpeg');
783 sub get_mimetype_from_filename {
784 my $filename = shift;
785 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
786 $type = "image/jpeg" if (!defined($type));
791 my ($img, $info, $r, $dpr) = @_;
793 # The infobox is of the form
794 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
795 # possibly with some parts omitted -- the middle part is known as the "classic
796 # fields"; note the comma separation. Every field has an associated "bold flag"
797 # in the second part.
799 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
800 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
801 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
802 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
803 if ($info->{'ExposureProgram'} =~ /manual/i) {
805 $manual_aperture = 1;
808 my @classic_fields = ();
809 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
810 push @classic_fields, [ $1 . "mm", 0 ];
811 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
812 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
815 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
816 my ($a, $b) = ($1, $2);
817 my $gcd = gcd($a, $b);
818 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
819 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
820 push @classic_fields, [ $1 . "s", $manual_shutter ];
823 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
826 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
828 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
830 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
831 my $f = $info->{'FNumber'};
833 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
835 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
839 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
842 if (defined($info->{'NikonD1-ISOSetting'})) {
843 $iso = $info->{'NikonD1-ISOSetting'};
844 } elsif (defined($info->{'ISO'})) {
845 $iso = $info->{'ISO'};
846 } elsif (defined($info->{'ISOSetting'})) {
847 $iso = $info->{'ISOSetting'};
849 if (defined($iso) && $iso =~ /(\d+)/) {
850 push @classic_fields, [ $1 . " ISO", 0 ];
853 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
854 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
855 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
856 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
859 # Now piece together the rest
862 if (defined($info->{'DateTimeOriginal'}) &&
863 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
865 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
868 if (defined($info->{'Model'})) {
869 my $model = $info->{'Model'};
873 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
874 push @parts, [ $model, 0 ];
878 if (scalar @classic_fields > 0) {
879 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
882 for my $field (@classic_fields) {
883 push @parts, [ ', ', 0 ] if (!$first_elem);
889 if (defined($info->{'Flash'})) {
890 if ($info->{'Flash'} =~ /did not fire/i ||
891 $info->{'Flash'} =~ /no flash/i ||
892 $info->{'Flash'} =~ /not fired/i ||
893 $info->{'Flash'} =~ /Off/) {
894 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
895 push @parts, [ "No flash", 0 ];
896 } elsif ($info->{'Flash'} =~ /fired/i ||
897 $info->{'Flash'} =~ /On/) {
898 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
899 push @parts, [ "Flash", 0 ];
901 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
902 push @parts, [ $info->{'Flash'}, 0 ];
906 return 0 if (scalar @parts == 0);
908 # Find the required width
912 for my $part (@parts) {
915 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
917 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
920 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
923 $th = $h if ($h > $th);
926 return 0 if ($tw > $img->Get('columns'));
929 my $y = $img->Get('rows') - 24*$dpr;
931 # Hit exact DCT blocks
934 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
935 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
936 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
937 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
939 # Start writing out the text
940 $x = ($img->Get('columns') - $tw) / 2;
942 my $room = ($img->Get('rows') - $dpr - $y - $th);
943 $y = ($img->Get('rows') - $dpr) - $room/2;
945 for my $part (@parts) {
948 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
950 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
952 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
953 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
961 return $a if ($b == 0);
962 return gcd($b, $a % $b);
966 my ($r, $dbh, $id, $date, $desc) = @_;
969 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
970 push @errors, "Manglende eller ugyldig ID.";
972 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
973 push @errors, "Manglende eller ugyldig dato.";
975 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
976 push @errors, "Manglende eller ugyldig beskrivelse.";
979 if (scalar @errors > 0) {
983 my $vhost = $r->get_server_name;
984 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
985 undef, $id, $date, $desc, $vhost)
986 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
987 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
989 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
990 purge_cache($r, "/");
1000 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
1003 $decoded = Encode::decode("iso8859-1", $text);
1009 # Depending on your front-end cache, you might want to get creative somehow here.
1010 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
1011 # regex tacked onto a request into something useful. The elements given in
1012 # should not be regexes, though, as e.g. Squid will not be able to handle that.
1014 my ($r, @elements) = @_;
1015 return if (scalar @elements == 0);
1018 for my $elem (@elements) {
1019 $r->log->info("Purging $elem");
1020 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1025 if (scalar @pe == 1) {
1028 $regex .= "(" . join('|', @pe) . ")";
1030 $regex .= "(\\?.*)?\$";
1031 $r->headers_out->{'X-Pr0n-Purge'} = $regex;
1034 # Find a list of all cache URLs for a given image, given what we have on disk.
1035 sub get_all_cache_urls {
1036 my ($r, $dbh, $id) = @_;
1037 my $dir = POSIX::floor($id / 256);
1040 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1041 or die "Couldn't prepare: " . $dbh->errstr;
1043 or die "Couldn't find event and filename: " . $dbh->errstr;
1044 my $ref = $q->fetchrow_hashref;
1045 my $event = $ref->{'event'};
1046 my $filename = $ref->{'filename'};
1049 my $base = get_base($r) . "cache/$dir";
1050 for my $file (<$base/$id-*>) {
1051 my $fname = File::Basename::basename($file);
1052 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1053 # Mipmaps don't have an URL, ignore
1054 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1055 push @ret, "/$event/$filename";
1056 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1057 push @ret, "/$event/$1x$2/$filename";
1058 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1059 push @ret, "/$event/$1x$2/nobox/$filename";
1060 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1061 push @ret, "/$event/box/$filename";
1062 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1063 push @ret, "/$event/$1x$2/box/$filename";
1065 $r->log->warn("Couldn't find a purging URL for $fname");