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);
221 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box.png";
223 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box\@$dpr.png";
226 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-nobox.jpg";
230 sub ensure_disk_location_exists {
232 my $dir = POSIX::floor($id / 256);
234 my $img_dir = $Sesse::pr0n::Config::image_base . "/images/$dir/";
236 log_info($r, "Need to create new image directory $img_dir");
237 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
240 my $cache_dir = $Sesse::pr0n::Config::image_base . "/cache/$dir/";
241 if (! -d $cache_dir) {
242 log_info($r, "Need to create new cache directory $cache_dir");
243 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
247 sub get_mipmap_location {
248 my ($r, $id, $width, $height) = @_;
249 my $dir = POSIX::floor($id / 256);
251 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-mipmap-$width-$height.jpg";
254 sub update_image_info {
255 my ($r, $id, $width, $height) = @_;
257 # Also find the date taken if appropriate (from the EXIF tag etc.)
258 my $exiftool = Image::ExifTool->new;
259 $exiftool->ExtractInfo(get_disk_location($r, $id));
260 my $info = $exiftool->GetInfo();
261 my $datetime = undef;
263 if (defined($info->{'DateTimeOriginal'})) {
264 # Parse the date and time over to ISO format
265 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
266 $datetime = "$1-$2-$3 $4:$5:$6";
271 local $dbh->{AutoCommit} = 0;
274 $dbh->do('DELETE FROM exif_info WHERE image=?',
276 or die "Couldn't delete old EXIF information in SQL: $!";
278 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
279 or die "Couldn't prepare inserting EXIF information: $!";
281 for my $key (keys %$info) {
282 next if ref $info->{$key};
283 $q->execute($id, $key, guess_charset($info->{$key}))
284 or die "Couldn't insert EXIF information in database: $!";
288 my $model = $exiftool->GetValue('Model', 'PrintConv');
289 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
290 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
294 $model = undef if (length($model) == 0);
298 $lens = undef if (length($lens) == 0);
300 # Now update the main table with the information we've got
301 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
302 undef, $width, $height, $datetime, $model, $lens, $id)
303 or die "Couldn't update width/height in SQL: $!";
305 # update the last_picture cache as well (this should of course be done
306 # via a trigger, but this is less complicated :-) )
307 $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=?)',
308 undef, $datetime, $id)
309 or die "Couldn't update last_picture in SQL: $!";
316 #return qw(sesse Sesse);
318 my $auth = $r->header('authorization');
319 if (!defined($auth)) {
322 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
323 return check_basic_auth($r, $1);
330 my $res = Plack::Response->new(401);
331 $res->content_type('text/plain; charset=utf-8');
333 $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
335 $res->body("Need authorization\n");
339 sub check_basic_auth {
342 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
343 my ($user, $takenby) = extract_takenby($raw_user);
345 my $ref = $dbh->selectrow_hashref('SELECT sha1password,cryptpassword FROM users WHERE username=? AND vhost=?',
346 undef, $user, Sesse::pr0n::Common::get_server_name($r));
347 my ($sha1_matches, $bcrypt_matches) = (0, 0);
348 if (defined($ref) && defined($ref->{'sha1password'})) {
349 $sha1_matches = (Digest::SHA::sha1_base64($pass) eq $ref->{'sha1password'});
351 if (defined($ref) && defined($ref->{'cryptpassword'})) {
352 $bcrypt_matches = (Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) eq $ref->{'cryptpassword'});
355 if (!defined($ref) || (!$sha1_matches && !$bcrypt_matches)) {
356 $r->content_type('text/plain; charset=utf-8');
357 log_warn($r, "Authentication failed for $user/$takenby");
360 log_info($r, "Authentication succeeded for $user/$takenby");
362 # Make sure we can use bcrypt authentication in the future with this password.
363 # Also remove old-style SHA1 password when we migrate.
364 if (!$bcrypt_matches) {
365 my $salt = get_pseudorandom_bytes(16); # Doesn't need to be cryptographically secur.
366 my $hash = "\$2a\$07\$" . Crypt::Eksblowfish::Bcrypt::en_base64($salt);
367 my $cryptpassword = Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $hash);
368 $dbh->do('UPDATE users SET sha1password=NULL,cryptpassword=? WHERE username=? AND vhost=?',
369 undef, $cryptpassword, $user, Sesse::pr0n::Common::get_server_name($r))
370 or die "Couldn't update: " . $dbh->errstr;
371 log_info($r, "Updated bcrypt hash for $user");
374 return ($user, $takenby);
377 sub get_pseudorandom_bytes {
378 my $num_left = shift;
380 open my $randfh, "<", "/dev/urandom"
381 or die "/dev/urandom: $!";
383 while ($num_left > 0) {
385 if (sysread($randfh, $tmp, $num_left) == -1) {
386 die "sysread(/dev/urandom): $!";
389 $num_left -= length($bytes);
395 sub extract_takenby {
398 # WinXP is stupid :-)
399 if ($user =~ /^.*\\(.*)$/) {
404 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
408 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
411 return ($user, $takenby);
415 my ($r, $event, $filename) = (@_);
416 my $ref = $dbh->selectrow_hashref(
417 'SELECT id FROM images WHERE event=? AND filename=?',
418 undef, $event, $filename);
419 if (!defined($ref)) {
420 return (undef, undef, undef);
422 return stat_image_from_id($r, $ref->{'id'});
425 sub stat_image_from_id {
428 my $fname = get_disk_location($r, $id);
429 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
430 or return (undef, undef, undef);
432 return ($fname, $size, $mtime);
435 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
436 # the smallest mipmap larger than the largest of them, as well as the original image
439 my ($r, $filename, $id, $dbwidth, $dbheight, @res) = @_;
440 my ($img, $mmimg, $width, $height);
442 my $physical_fname = get_disk_location($r, $id);
444 # If we don't know the size, we'll need to read it in anyway
445 if (!defined($dbwidth) || !defined($dbheight)) {
446 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
447 $width = $img->Get('columns');
448 $height = $img->Get('rows');
454 # Generate the list of mipmaps
457 my $mmwidth = $width;
458 my $mmheight = $height;
460 while ($mmwidth > 1 || $mmheight > 1) {
461 my $new_mmwidth = POSIX::floor($mmwidth / 2);
462 my $new_mmheight = POSIX::floor($mmheight / 2);
464 $new_mmwidth = 1 if ($new_mmwidth < 1);
465 $new_mmheight = 1 if ($new_mmheight < 1);
467 my $large_enough = 1;
468 for my $i (0..($#res/2)) {
469 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
470 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
476 last if (!$large_enough);
478 $mmwidth = $new_mmwidth;
479 $mmheight = $new_mmheight;
481 push @mmlist, [ $mmwidth, $mmheight ];
484 # Ensure that all of them are OK
485 my $last_good_mmlocation;
486 for my $i (0..$#mmlist) {
487 my $last = ($i == $#mmlist);
488 my $mmres = $mmlist[$i];
490 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
491 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
492 if (!defined($img)) {
493 if (defined($last_good_mmlocation)) {
494 $img = Sesse::pr0n::QscaleProxy->new;
495 $img->Read($last_good_mmlocation);
497 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
504 $cimg = $img->Clone();
506 log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
507 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
509 my $err = $cimg->write(
510 filename => $mmlocation,
512 'sampling-factor' => '1x1'
516 $last_good_mmlocation = $mmlocation;
518 if ($last && !defined($img)) {
519 # OK, read in the smallest one
520 $img = Sesse::pr0n::QscaleProxy->new;
521 my $err = $img->Read($mmlocation);
525 if (!defined($img)) {
526 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
527 $width = $img->Get('columns');
528 $height = $img->Get('rows');
530 return ($img, $width, $height);
533 sub read_original_image {
534 my ($r, $filename, $id, $dbwidth, $dbheight) = @_;
536 my $physical_fname = get_disk_location($r, $id);
538 # Read in the original image
540 if ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
541 $magick = Sesse::pr0n::QscaleProxy->new;
543 $magick = Image::Magick->new;
547 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
548 # The delegate support is rather broken and causes very odd stuff to happen when
549 # more than one thread does this at the same time. Thus, we simply do it ourselves.
550 if ($filename =~ /\.(nef|cr2)$/i) {
551 # this would suffice if ImageMagick gets to fix their handling
552 # $physical_fname = "NEF:$physical_fname";
554 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
555 or error("dcraw: $!");
556 $err = $magick->Read(file => \*DCRAW);
559 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
560 # RGB is slightly faster (no colorspace conversion needed) and works equally
561 # well for our uses, as long as we don't need to draw an information box,
562 # which trickles several ImageMagick bugs related to colorspace handling.
563 # (Ideally we'd be able to keep the image subsampled and
564 # planar, but that would probably be difficult for ImageMagick to expose.)
566 # $magick->Set(colorspace=>'YCbCr');
568 $err = $magick->Read($physical_fname);
572 log_warn($r, "$physical_fname: $err");
576 error($r, "$physical_fname: $err");
580 # If we use ->[0] unconditionally, text rendering (!) seems to crash
582 if (ref($magick) !~ /Image::Magick/) {
585 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
592 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
594 my ($new_dbwidth, $new_dbheight);
596 my $fname = get_disk_location($r, $id);
598 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
599 return ($fname, undef);
603 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
605 if (! -r $cachename or (-M $cachename > -M $fname)) {
606 # If we are in overload mode (aka Slashdot mode), refuse to generate
608 if (Sesse::pr0n::Overload::is_in_overload($r)) {
609 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
610 error($r, 'System is in overload mode, not doing any scaling');
613 # If we're being asked for the box, make a new image with it.
614 # We don't care about @otherres since each of these images are
615 # already pretty cheap to generate, but we need the exact width so we can make
616 # one in the right size.
618 my ($img, $width, $height);
620 # This is slow, but should fortunately almost never happen, so don't bother
622 if (!defined($dbwidth) || !defined($dbheight)) {
623 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
624 $new_dbwidth = $width = $img->Get('columns');
625 $new_dbheight = $height = $img->Get('rows');
628 $img = Image::Magick->new;
633 if (defined($xres) && defined($yres)) {
634 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
637 $img->Set(size=>($width . "x" . $height));
638 $img->Read('xc:white');
640 my $info = Image::ExifTool::ImageInfo($fname);
641 if (make_infobox($img, $info, $r, $dpr)) {
642 $img->Quantize(colors=>16, dither=>'False');
644 # Since the image is grayscale, ImageMagick overrides us and writes this
645 # as grayscale anyway, but at least we get rid of the alpha channel this
647 $img->Set(type=>'Palette');
649 # Not enough room for the text, make a tiny dummy transparent infobox
651 $img->Set(size=>"1x1");
658 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
659 log_info($r, "New infobox cache: $width x $height for $id.jpg");
661 return ($cachename, 'image/png');
665 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres);
667 while (defined($xres) && defined($yres)) {
668 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
669 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
672 if (defined($nxres) && defined($nyres)) {
673 # we have more resolutions to scale, so don't throw
675 $cimg = $img->Clone();
680 my $width = $img->Get('columns');
681 my $height = $img->Get('rows');
682 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
684 my $filter = 'Lanczos';
689 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
692 # Strip EXIF tags etc.
697 filename => $cachename,
700 if (($nwidth >= 640 && $nheight >= 480) ||
701 ($nwidth >= 480 && $nheight >= 640)) {
702 $parms{'interlace'} = 'Plane';
705 $parms{'sampling-factor'} = $sf;
707 $err = $cimg->write(%parms);
712 ($xres, $yres) = ($nxres, $nyres);
714 log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
719 log_warn($r, "$fname: $err");
723 error($r, "$fname: $err");
728 # Update the SQL database if it doesn't contain the required info
729 if (!defined($dbwidth) && defined($new_dbwidth)) {
730 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
731 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
734 return ($cachename, 'image/jpeg');
737 sub get_mimetype_from_filename {
738 my $filename = shift;
739 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
740 $type = "image/jpeg" if (!defined($type));
745 my ($img, $info, $r, $dpr) = @_;
747 # The infobox is of the form
748 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
749 # possibly with some parts omitted -- the middle part is known as the "classic
750 # fields"; note the comma separation. Every field has an associated "bold flag"
751 # in the second part.
753 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
754 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
755 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
756 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
757 if ($info->{'ExposureProgram'} =~ /manual/i) {
759 $manual_aperture = 1;
762 my @classic_fields = ();
763 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
764 push @classic_fields, [ $1 . "mm", 0 ];
765 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
766 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
769 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
770 my ($a, $b) = ($1, $2);
771 my $gcd = gcd($a, $b);
772 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
773 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
774 push @classic_fields, [ $1 . "s", $manual_shutter ];
777 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
780 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
782 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
784 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
785 my $f = $info->{'FNumber'};
787 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
789 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
793 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
796 if (defined($info->{'NikonD1-ISOSetting'})) {
797 $iso = $info->{'NikonD1-ISOSetting'};
798 } elsif (defined($info->{'ISO'})) {
799 $iso = $info->{'ISO'};
800 } elsif (defined($info->{'ISOSetting'})) {
801 $iso = $info->{'ISOSetting'};
803 if (defined($iso) && $iso =~ /(\d+)/) {
804 push @classic_fields, [ $1 . " ISO", 0 ];
807 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
808 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
809 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
810 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
813 # Now piece together the rest
816 if (defined($info->{'DateTimeOriginal'}) &&
817 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
819 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
822 if (defined($info->{'Model'})) {
823 my $model = $info->{'Model'};
827 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
828 push @parts, [ $model, 0 ];
832 if (scalar @classic_fields > 0) {
833 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
836 for my $field (@classic_fields) {
837 push @parts, [ ', ', 0 ] if (!$first_elem);
843 if (defined($info->{'Flash'})) {
844 if ($info->{'Flash'} =~ /did not fire/i ||
845 $info->{'Flash'} =~ /no flash/i ||
846 $info->{'Flash'} =~ /not fired/i ||
847 $info->{'Flash'} =~ /Off/) {
848 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
849 push @parts, [ "No flash", 0 ];
850 } elsif ($info->{'Flash'} =~ /fired/i ||
851 $info->{'Flash'} =~ /On/) {
852 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
853 push @parts, [ "Flash", 0 ];
855 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
856 push @parts, [ $info->{'Flash'}, 0 ];
860 return 0 if (scalar @parts == 0);
862 # Find the required width
866 for my $part (@parts) {
869 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
871 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
874 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
877 $th = $h if ($h > $th);
880 return 0 if ($tw > $img->Get('columns'));
883 my $y = $img->Get('rows') - 24*$dpr;
885 # Hit exact DCT blocks
888 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
889 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
890 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
891 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
893 # Start writing out the text
894 $x = ($img->Get('columns') - $tw) / 2;
896 my $room = ($img->Get('rows') - $dpr - $y - $th);
897 $y = ($img->Get('rows') - $dpr) - $room/2;
899 for my $part (@parts) {
902 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
904 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
906 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
907 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
915 return $a if ($b == 0);
916 return gcd($b, $a % $b);
920 my ($r, $res, $dbh, $id, $date, $desc) = @_;
923 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
924 push @errors, "Manglende eller ugyldig ID.";
926 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
927 push @errors, "Manglende eller ugyldig dato.";
929 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
930 push @errors, "Manglende eller ugyldig beskrivelse.";
933 if (scalar @errors > 0) {
937 my $vhost = Sesse::pr0n::Common::get_server_name($r);
938 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
939 undef, $id, $date, $desc, $vhost)
940 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
941 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
943 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
944 purge_cache($r, $res, "/");
954 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
957 $decoded = Encode::decode("iso8859-1", $text);
963 # Depending on your front-end cache, you might want to get creative somehow here.
964 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
965 # regex tacked onto a request into something useful. The elements given in
966 # should not be regexes, though, as e.g. Squid will not be able to handle that.
968 my ($r, $res, @elements) = @_;
969 return if (scalar @elements == 0);
972 for my $elem (@elements) {
973 log_info($r, "Purging $elem");
974 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
979 if (scalar @pe == 1) {
982 $regex .= "(" . join('|', @pe) . ")";
984 $regex .= "(\\?.*)?\$";
985 $res->header('X-Pr0n-Purge' => $regex);
988 # Find a list of all cache URLs for a given image, given what we have on disk.
989 sub get_all_cache_urls {
990 my ($r, $dbh, $id) = @_;
991 my $dir = POSIX::floor($id / 256);
994 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
995 or die "Couldn't prepare: " . $dbh->errstr;
997 or die "Couldn't find event and filename: " . $dbh->errstr;
998 my $ref = $q->fetchrow_hashref;
999 my $event = $ref->{'event'};
1000 my $filename = $ref->{'filename'};
1003 my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
1004 for my $file (<$base/$id-*>) {
1005 my $fname = File::Basename::basename($file);
1006 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1007 # Mipmaps don't have an URL, ignore
1008 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1009 push @ret, "/$event/$filename";
1010 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1011 push @ret, "/$event/$1x$2/$filename";
1012 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1013 push @ret, "/$event/$1x$2/nobox/$filename";
1014 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1015 push @ret, "/$event/box/$filename";
1016 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1017 push @ret, "/$event/$1x$2/box/$filename";
1019 log_warn($r, "Couldn't find a purging URL for $fname");
1026 sub set_last_modified {
1027 my ($res, $mtime) = @_;
1029 my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
1030 $res->headers({ 'Last-Modified' => $str });
1033 sub get_server_name {
1035 my $host = $r->env->{'HTTP_HOST'};
1042 if (defined($r->logger)) {
1043 $r->logger->({ level => 'info', message => $msg });
1045 print STDERR "[INFO] $msg\n";
1051 if (defined($r->logger)) {
1052 $r->logger->({ level => 'warn', message => $msg });
1054 print STDERR "[WARN] $msg\n";
1060 if (defined($r->logger)) {
1061 $r->logger->({ level => 'error', message => $msg });
1063 print STDERR "[ERROR] $msg\n";