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: $!";
307 # update the last_picture cache as well (this should of course be done
308 # via a trigger, but this is less complicated :-) )
309 $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=?)',
310 undef, $datetime, $id)
311 or die "Couldn't update last_picture in SQL: $!";
318 #return qw(sesse Sesse);
320 my $auth = $r->header('authorization');
321 if (!defined($auth)) {
324 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
325 return check_basic_auth($r, $1);
332 my $res = Plack::Response->new(401);
333 $res->content_type('text/plain; charset=utf-8');
335 $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
337 $res->body("Need authorization\n");
341 sub check_basic_auth {
344 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
345 my ($user, $takenby) = extract_takenby($raw_user);
347 my $ref = $dbh->selectrow_hashref('SELECT sha1password,cryptpassword FROM users WHERE username=? AND vhost=?',
348 undef, $user, Sesse::pr0n::Common::get_server_name($r));
349 my ($sha1_matches, $bcrypt_matches) = (0, 0);
350 if (defined($ref) && defined($ref->{'sha1password'})) {
351 $sha1_matches = (Digest::SHA::sha1_base64($pass) eq $ref->{'sha1password'});
353 if (defined($ref) && defined($ref->{'cryptpassword'})) {
354 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
357 if (!defined($ref) || (!$sha1_matches && !$bcrypt_matches)) {
358 $r->content_type('text/plain; charset=utf-8');
359 log_warn($r, "Authentication failed for $user/$takenby");
362 log_info($r, "Authentication succeeded for $user/$takenby");
364 # Make sure we can use bcrypt authentication in the future with this password.
365 # Also remove old-style SHA1 password when we migrate.
366 if (!$bcrypt_matches) {
367 my $salt = get_pseudorandom_bytes(16); # Doesn't need to be cryptographically secur.
368 my $hash = "\$2a\$07\$" . Crypt::Eksblowfish::Bcrypt::en_base64($salt);
369 my $cryptpassword = Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $hash);
370 $dbh->do('UPDATE users SET sha1password=NULL,cryptpassword=? WHERE username=? AND vhost=?',
371 undef, $cryptpassword, $user, Sesse::pr0n::Common::get_server_name($r))
372 or die "Couldn't update: " . $dbh->errstr;
373 log_info($r, "Updated bcrypt hash for $user");
376 return ($user, $takenby);
379 sub get_pseudorandom_bytes {
380 my $num_left = shift;
382 open my $randfh, "<", "/dev/urandom"
383 or die "/dev/urandom: $!";
385 while ($num_left > 0) {
387 if (sysread($randfh, $tmp, $num_left) == -1) {
388 die "sysread(/dev/urandom): $!";
391 $num_left -= length($bytes);
397 sub extract_takenby {
400 # WinXP is stupid :-)
401 if ($user =~ /^.*\\(.*)$/) {
406 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
410 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
413 return ($user, $takenby);
417 my ($r, $event, $filename) = (@_);
418 my $ref = $dbh->selectrow_hashref(
419 'SELECT id FROM images WHERE event=? AND filename=?',
420 undef, $event, $filename);
421 if (!defined($ref)) {
422 return (undef, undef, undef);
424 return stat_image_from_id($r, $ref->{'id'});
427 sub stat_image_from_id {
430 my $fname = get_disk_location($r, $id);
431 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
432 or return (undef, undef, undef);
434 return ($fname, $size, $mtime);
437 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
438 # the smallest mipmap larger than the largest of them, as well as the original image
441 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
442 my ($img, $mmimg, $width, $height);
444 my $physical_fname = get_disk_location($r, $id);
446 # If we don't know the size, we'll need to read it in anyway
447 if (!defined($dbwidth) || !defined($dbheight)) {
448 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
449 $width = $img->Get('columns');
450 $height = $img->Get('rows');
456 # Generate the list of mipmaps
459 my $mmwidth = $width;
460 my $mmheight = $height;
462 while ($mmwidth > 1 || $mmheight > 1) {
463 my $new_mmwidth = POSIX::floor($mmwidth / 2);
464 my $new_mmheight = POSIX::floor($mmheight / 2);
466 $new_mmwidth = 1 if ($new_mmwidth < 1);
467 $new_mmheight = 1 if ($new_mmheight < 1);
469 my $large_enough = 1;
470 for my $i (0..($#res/2)) {
471 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
472 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
478 last if (!$large_enough);
480 $mmwidth = $new_mmwidth;
481 $mmheight = $new_mmheight;
483 push @mmlist, [ $mmwidth, $mmheight ];
486 # Ensure that all of them are OK
487 my $last_good_mmlocation;
488 for my $i (0..$#mmlist) {
489 my $last = ($i == $#mmlist);
490 my $mmres = $mmlist[$i];
492 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
493 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
494 if (!defined($img)) {
495 if (defined($last_good_mmlocation)) {
496 if ($can_use_qscale) {
497 $img = Sesse::pr0n::QscaleProxy->new;
499 $img = Image::Magick->new;
501 $img->Read($last_good_mmlocation);
503 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
510 $cimg = $img->Clone();
512 log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
513 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
515 my $err = $cimg->write(
516 filename => $mmlocation,
518 'sampling-factor' => '1x1'
522 $last_good_mmlocation = $mmlocation;
524 if ($last && !defined($img)) {
525 # OK, read in the smallest one
526 if ($can_use_qscale) {
527 $img = Sesse::pr0n::QscaleProxy->new;
529 $img = Image::Magick->new;
531 my $err = $img->Read($mmlocation);
535 if (!defined($img)) {
536 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
537 $width = $img->Get('columns');
538 $height = $img->Get('rows');
540 return ($img, $width, $height);
543 sub read_original_image {
544 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
546 my $physical_fname = get_disk_location($r, $id);
548 # Read in the original image
550 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
551 $magick = Sesse::pr0n::QscaleProxy->new;
553 $magick = Image::Magick->new;
557 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
558 # The delegate support is rather broken and causes very odd stuff to happen when
559 # more than one thread does this at the same time. Thus, we simply do it ourselves.
560 if ($filename =~ /\.(nef|cr2)$/i) {
561 # this would suffice if ImageMagick gets to fix their handling
562 # $physical_fname = "NEF:$physical_fname";
564 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
565 or error("dcraw: $!");
566 $err = $magick->Read(file => \*DCRAW);
569 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
570 # RGB is slightly faster (no colorspace conversion needed) and works equally
571 # well for our uses, as long as we don't need to draw an information box,
572 # which trickles several ImageMagick bugs related to colorspace handling.
573 # (Ideally we'd be able to keep the image subsampled and
574 # planar, but that would probably be difficult for ImageMagick to expose.)
576 # $magick->Set(colorspace=>'YCbCr');
578 $err = $magick->Read($physical_fname);
582 log_warn($r, "$physical_fname: $err");
586 error($r, "$physical_fname: $err");
590 # If we use ->[0] unconditionally, text rendering (!) seems to crash
592 if (ref($magick) !~ /Image::Magick/) {
595 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
602 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
604 my ($new_dbwidth, $new_dbheight);
606 my $fname = get_disk_location($r, $id);
607 if ($infobox ne 'box') {
608 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
609 return ($fname, undef);
613 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
615 if (! -r $cachename or (-M $cachename > -M $fname)) {
616 # If we are in overload mode (aka Slashdot mode), refuse to generate
618 if (Sesse::pr0n::Overload::is_in_overload($r)) {
619 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
620 error($r, 'System is in overload mode, not doing any scaling');
623 # If we're being asked for just the box, make a new image with just the box.
624 # We don't care about @otherres since each of these images are
625 # already pretty cheap to generate, but we need the exact width so we can make
626 # one in the right size.
627 if ($infobox eq 'box') {
628 my ($img, $width, $height);
630 # This is slow, but should fortunately almost never happen, so don't bother
632 if (!defined($dbwidth) || !defined($dbheight)) {
633 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
634 $new_dbwidth = $width = $img->Get('columns');
635 $new_dbheight = $height = $img->Get('rows');
638 $img = Image::Magick->new;
643 if (defined($xres) && defined($yres)) {
644 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
647 $img->Set(size=>($width . "x" . $height));
648 $img->Read('xc:white');
650 my $info = Image::ExifTool::ImageInfo($fname);
651 if (make_infobox($img, $info, $r, $dpr)) {
652 $img->Quantize(colors=>16, dither=>'False');
654 # Since the image is grayscale, ImageMagick overrides us and writes this
655 # as grayscale anyway, but at least we get rid of the alpha channel this
657 $img->Set(type=>'Palette');
659 # Not enough room for the text, make a tiny dummy transparent infobox
661 $img->Set(size=>"1x1");
668 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
669 log_info($r, "New infobox cache: $width x $height for $id.jpg");
671 return ($cachename, 'image/png');
674 my $can_use_qscale = 0;
675 if ($infobox eq 'nobox') {
680 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
682 while (defined($xres) && defined($yres)) {
683 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
684 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
687 if (defined($nxres) && defined($nyres)) {
688 # we have more resolutions to scale, so don't throw
690 $cimg = $img->Clone();
695 my $width = $img->Get('columns');
696 my $height = $img->Get('rows');
697 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
699 my $filter = 'Lanczos';
704 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
707 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
708 my $info = Image::ExifTool::ImageInfo($fname);
709 make_infobox($cimg, $info, $r, 1);
712 # Strip EXIF tags etc.
717 filename => $cachename,
720 if (($nwidth >= 640 && $nheight >= 480) ||
721 ($nwidth >= 480 && $nheight >= 640)) {
722 $parms{'interlace'} = 'Plane';
725 $parms{'sampling-factor'} = $sf;
727 $err = $cimg->write(%parms);
732 ($xres, $yres) = ($nxres, $nyres);
734 log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
739 log_warn($r, "$fname: $err");
743 error($r, "$fname: $err");
748 # Update the SQL database if it doesn't contain the required info
749 if (!defined($dbwidth) && defined($new_dbwidth)) {
750 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
751 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
754 return ($cachename, 'image/jpeg');
757 sub get_mimetype_from_filename {
758 my $filename = shift;
759 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
760 $type = "image/jpeg" if (!defined($type));
765 my ($img, $info, $r, $dpr) = @_;
767 # The infobox is of the form
768 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
769 # possibly with some parts omitted -- the middle part is known as the "classic
770 # fields"; note the comma separation. Every field has an associated "bold flag"
771 # in the second part.
773 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
774 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
775 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
776 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
777 if ($info->{'ExposureProgram'} =~ /manual/i) {
779 $manual_aperture = 1;
782 my @classic_fields = ();
783 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
784 push @classic_fields, [ $1 . "mm", 0 ];
785 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
786 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
789 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
790 my ($a, $b) = ($1, $2);
791 my $gcd = gcd($a, $b);
792 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
793 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
794 push @classic_fields, [ $1 . "s", $manual_shutter ];
797 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
800 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
802 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
804 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
805 my $f = $info->{'FNumber'};
807 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
809 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
813 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
816 if (defined($info->{'NikonD1-ISOSetting'})) {
817 $iso = $info->{'NikonD1-ISOSetting'};
818 } elsif (defined($info->{'ISO'})) {
819 $iso = $info->{'ISO'};
820 } elsif (defined($info->{'ISOSetting'})) {
821 $iso = $info->{'ISOSetting'};
823 if (defined($iso) && $iso =~ /(\d+)/) {
824 push @classic_fields, [ $1 . " ISO", 0 ];
827 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
828 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
829 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
830 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
833 # Now piece together the rest
836 if (defined($info->{'DateTimeOriginal'}) &&
837 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
839 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
842 if (defined($info->{'Model'})) {
843 my $model = $info->{'Model'};
847 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
848 push @parts, [ $model, 0 ];
852 if (scalar @classic_fields > 0) {
853 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
856 for my $field (@classic_fields) {
857 push @parts, [ ', ', 0 ] if (!$first_elem);
863 if (defined($info->{'Flash'})) {
864 if ($info->{'Flash'} =~ /did not fire/i ||
865 $info->{'Flash'} =~ /no flash/i ||
866 $info->{'Flash'} =~ /not fired/i ||
867 $info->{'Flash'} =~ /Off/) {
868 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
869 push @parts, [ "No flash", 0 ];
870 } elsif ($info->{'Flash'} =~ /fired/i ||
871 $info->{'Flash'} =~ /On/) {
872 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
873 push @parts, [ "Flash", 0 ];
875 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
876 push @parts, [ $info->{'Flash'}, 0 ];
880 return 0 if (scalar @parts == 0);
882 # Find the required width
886 for my $part (@parts) {
889 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
891 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
894 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
897 $th = $h if ($h > $th);
900 return 0 if ($tw > $img->Get('columns'));
903 my $y = $img->Get('rows') - 24*$dpr;
905 # Hit exact DCT blocks
908 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
909 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
910 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
911 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
913 # Start writing out the text
914 $x = ($img->Get('columns') - $tw) / 2;
916 my $room = ($img->Get('rows') - $dpr - $y - $th);
917 $y = ($img->Get('rows') - $dpr) - $room/2;
919 for my $part (@parts) {
922 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
924 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
926 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
927 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
935 return $a if ($b == 0);
936 return gcd($b, $a % $b);
940 my ($r, $res, $dbh, $id, $date, $desc) = @_;
943 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
944 push @errors, "Manglende eller ugyldig ID.";
946 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
947 push @errors, "Manglende eller ugyldig dato.";
949 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
950 push @errors, "Manglende eller ugyldig beskrivelse.";
953 if (scalar @errors > 0) {
957 my $vhost = Sesse::pr0n::Common::get_server_name($r);
958 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
959 undef, $id, $date, $desc, $vhost)
960 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
961 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
963 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
964 purge_cache($r, $res, "/");
974 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
977 $decoded = Encode::decode("iso8859-1", $text);
983 # Depending on your front-end cache, you might want to get creative somehow here.
984 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
985 # regex tacked onto a request into something useful. The elements given in
986 # should not be regexes, though, as e.g. Squid will not be able to handle that.
988 my ($r, $res, @elements) = @_;
989 return if (scalar @elements == 0);
992 for my $elem (@elements) {
993 log_info($r, "Purging $elem");
994 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
999 if (scalar @pe == 1) {
1002 $regex .= "(" . join('|', @pe) . ")";
1004 $regex .= "(\\?.*)?\$";
1005 $res->header('X-Pr0n-Purge' => $regex);
1008 # Find a list of all cache URLs for a given image, given what we have on disk.
1009 sub get_all_cache_urls {
1010 my ($r, $dbh, $id) = @_;
1011 my $dir = POSIX::floor($id / 256);
1014 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1015 or die "Couldn't prepare: " . $dbh->errstr;
1017 or die "Couldn't find event and filename: " . $dbh->errstr;
1018 my $ref = $q->fetchrow_hashref;
1019 my $event = $ref->{'event'};
1020 my $filename = $ref->{'filename'};
1023 my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
1024 for my $file (<$base/$id-*>) {
1025 my $fname = File::Basename::basename($file);
1026 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1027 # Mipmaps don't have an URL, ignore
1028 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1029 push @ret, "/$event/$filename";
1030 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1031 push @ret, "/$event/$1x$2/$filename";
1032 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1033 push @ret, "/$event/$1x$2/nobox/$filename";
1034 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1035 push @ret, "/$event/box/$filename";
1036 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1037 push @ret, "/$event/$1x$2/box/$filename";
1039 log_warn($r, "Couldn't find a purging URL for $fname");
1046 sub set_last_modified {
1047 my ($res, $mtime) = @_;
1049 my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S %Z", localtime($mtime));
1050 $res->headers({ 'Last-Modified' => $str });
1053 sub get_server_name {
1055 my $host = $r->env->{'HTTP_HOST'};
1062 if (defined($r->logger)) {
1063 $r->logger->({ level => 'info', message => $msg });
1065 print STDERR "[INFO] $msg\n";
1071 if (defined($r->logger)) {
1072 $r->logger->({ level => 'warn', message => $msg });
1074 print STDERR "[WARN] $msg\n";
1080 if (defined($r->logger)) {
1081 $r->logger->({ level => 'error', message => $msg });
1083 print STDERR "[ERROR] $msg\n";