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';
33 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
35 use Sesse::pr0n::Config;
37 require Sesse::pr0n::Config_local;
42 @EXPORT = qw(&error &dberror);
44 @EXPORT_OK = qw(&error &dberror);
46 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
47 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
48 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
49 our $mimetypes = new MIME::Types;
51 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
58 our ($dbh, $mimetypes);
61 my ($r,$err,$status,$title) = @_;
63 if (!defined($status) || !defined($title)) {
65 $title = "Internal server error";
68 $r->content_type('text/html; charset=utf-8');
72 $r->print(" <p>Error: $err</p>\n");
76 $r->log->error("Stack trace follows: " . Carp::longmess());
78 ModPerl::Util::exit();
83 error($r, "$err (DB error: " . $dbh->errstr . ")");
89 $r->content_type("text/html; charset=utf-8");
91 # Fetch quote if we're itk-bilder.samfundet.no
93 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
94 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
95 $quote = "Error: Could not fetch quotes." if (!defined($quote));
97 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
102 Sesse::pr0n::Templates::print_template($r, "footer",
103 { version => $Sesse::pr0n::Common::VERSION });
107 my ($width, $height, $thumbxres, $thumbyres) = @_;
109 unless ($thumbxres >= $width &&
110 $thumbyres >= $height) {
111 my $sfh = $width / $thumbxres;
112 my $sfv = $height / $thumbyres;
120 $width = POSIX::floor($width);
121 $height = POSIX::floor($height);
124 return ($width, $height);
127 sub get_query_string {
128 my ($param, $defparam) = @_;
132 while (my ($key, $value) = each %$param) {
133 next unless defined($value);
134 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
136 $value = pretty_escape($value);
138 $str .= ($first) ? "?" : ';';
139 $str .= "$key=$value";
145 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
146 sub weird_space_encode {
149 return "_" x (length($val) * 2);
151 return "_" x (length($val) * 2 - 1);
155 sub weird_space_unencode {
157 if (length($val) % 2 == 0) {
158 return "_" x (length($val) / 2);
160 return " " x ((length($val) + 1) / 2);
167 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
168 $value = URI::Escape::uri_escape($value);
169 $value =~ s/%2F/\//g;
174 sub pretty_unescape {
177 # URI unescaping is already done for us
178 $value =~ s/(_+)/weird_space_unencode($1)/ge;
184 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
185 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
186 if (defined($accesskey) && length($accesskey) == 1) {
187 $str .= " accesskey=\"$accesskey\"";
189 $str .= ">$title</a>";
194 # Check that we are alive
195 if (!(defined($dbh) && $dbh->ping)) {
197 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
198 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
199 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
201 die "Couldn't connect to PostgreSQL database";
210 return $r->dir_config('ImageBase');
213 sub get_disk_location {
215 my $dir = POSIX::floor($id / 256);
216 return get_base($r) . "images/$dir/$id.jpg";
219 sub get_cache_location {
220 my ($r, $id, $width, $height, $infobox) = @_;
221 my $dir = POSIX::floor($id / 256);
223 if ($infobox eq 'both') {
224 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
225 } elsif ($infobox eq 'nobox') {
226 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
228 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
232 sub get_mipmap_location {
233 my ($r, $id, $width, $height) = @_;
234 my $dir = POSIX::floor($id / 256);
236 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
239 sub update_image_info {
240 my ($r, $id, $width, $height) = @_;
242 # Also find the date taken if appropriate (from the EXIF tag etc.)
243 my $exiftool = Image::ExifTool->new;
244 $exiftool->ExtractInfo(get_disk_location($r, $id));
245 my $info = $exiftool->GetInfo();
246 my $datetime = undef;
248 if (defined($info->{'DateTimeOriginal'})) {
249 # Parse the date and time over to ISO format
250 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
251 $datetime = "$1-$2-$3 $4:$5:$6";
256 local $dbh->{AutoCommit} = 0;
259 $dbh->do('DELETE FROM exif_info WHERE image=?',
261 or die "Couldn't delete old EXIF information in SQL: $!";
263 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
264 or die "Couldn't prepare inserting EXIF information: $!";
266 for my $key (keys %$info) {
267 next if ref $info->{$key};
268 $q->execute($id, $key, guess_charset($info->{$key}))
269 or die "Couldn't insert EXIF information in database: $!";
273 my $model = $exiftool->GetValue('Model', 'PrintConv');
274 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
275 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
279 $model = undef if (length($model) == 0);
283 $lens = undef if (length($lens) == 0);
285 # Now update the main table with the information we've got
286 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
287 undef, $width, $height, $datetime, $model, $lens, $id)
288 or die "Couldn't update width/height in SQL: $!";
291 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
292 $dbh->do('DELETE FROM tags WHERE image=?',
294 or die "Couldn't delete old tag information in SQL: $!";
296 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
297 or die "Couldn't prepare inserting tag information: $!";
300 for my $tag (@tags) {
301 $q->execute($id, guess_charset($tag))
302 or die "Couldn't insert tag information in database: $!";
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, ?) 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 my $auth = $r->headers_in->{'authorization'};
317 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
318 $r->content_type('text/plain; charset=utf-8');
320 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
321 $r->print("Need authorization\n");
325 #return qw(sesse Sesse);
327 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
328 # WinXP is stupid :-)
329 if ($user =~ /^.*\\(.*)$/) {
334 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
338 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
342 $pass = Digest::SHA1::sha1_base64($pass);
343 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
344 undef, $user, $pass, $r->get_server_name);
345 if ($ref->{'auth'} != 1) {
346 $r->content_type('text/plain; charset=utf-8');
347 warn "No user exists, only $auth";
349 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
350 $r->print("Authorization failed");
351 $r->log->warn("Authentication failed for $user/$takenby");
355 $r->log->info("Authentication succeeded for $user/$takenby");
357 return ($user, $takenby);
361 my ($r, $event, $filename) = (@_);
362 my $ref = $dbh->selectrow_hashref(
363 'SELECT id FROM images WHERE event=? AND filename=?',
364 undef, $event, $filename);
365 if (!defined($ref)) {
366 return (undef, undef, undef);
368 return stat_image_from_id($r, $ref->{'id'});
371 sub stat_image_from_id {
374 my $fname = get_disk_location($r, $id);
375 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
376 or return (undef, undef, undef);
378 return ($fname, $size, $mtime);
381 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
382 # the smallest mipmap larger than the largest of them.
384 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
385 my ($img, $mmimg, $width, $height);
387 my $physical_fname = get_disk_location($r, $id);
389 # If we don't know the size, we'll need to read it in anyway
390 if (!defined($dbwidth) || !defined($dbheight)) {
391 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
392 $width = $img->Get('columns');
393 $height = $img->Get('rows');
399 # Generate the list of mipmaps
402 my $mmwidth = $width;
403 my $mmheight = $height;
405 while ($mmwidth > 1 || $mmheight > 1) {
406 my $new_mmwidth = POSIX::floor($mmwidth / 2);
407 my $new_mmheight = POSIX::floor($mmheight / 2);
409 $new_mmwidth = 1 if ($new_mmwidth < 1);
410 $new_mmheight = 1 if ($new_mmheight < 1);
412 my $large_enough = 1;
413 for my $i (0..($#res/2)) {
414 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
415 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
421 last if (!$large_enough);
423 $mmwidth = $new_mmwidth;
424 $mmheight = $new_mmheight;
426 push @mmlist, [ $mmwidth, $mmheight ];
429 # Ensure that all of them are OK
430 my $last_good_mmlocation;
431 for my $i (0..$#mmlist) {
432 my $last = ($i == $#mmlist);
433 my $mmres = $mmlist[$i];
435 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
436 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
437 if (!defined($img)) {
438 if (defined($last_good_mmlocation)) {
439 if ($can_use_qscale) {
440 $img = Sesse::pr0n::QscaleProxy->new;
442 $img = Image::Magick->new;
444 $img->Read($last_good_mmlocation);
446 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
453 $cimg = $img->Clone();
455 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
456 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
458 my $err = $cimg->write(
459 filename => $mmlocation,
461 'sampling-factor' => '1x1'
465 $last_good_mmlocation = $mmlocation;
467 if ($last && !defined($img)) {
468 # OK, read in the smallest one
469 if ($can_use_qscale) {
470 $img = Sesse::pr0n::QscaleProxy->new;
472 $img = Image::Magick->new;
474 my $err = $img->Read($mmlocation);
478 if (!defined($img)) {
479 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
484 sub read_original_image {
485 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
487 my $physical_fname = get_disk_location($r, $id);
489 # Read in the original image
491 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
492 $magick = Sesse::pr0n::QscaleProxy->new;
494 $magick = Image::Magick->new;
498 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
499 # The delegate support is rather broken and causes very odd stuff to happen when
500 # more than one thread does this at the same time. Thus, we simply do it ourselves.
501 if ($filename =~ /\.(nef|cr2)$/i) {
502 # this would suffice if ImageMagick gets to fix their handling
503 # $physical_fname = "NEF:$physical_fname";
505 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
506 or error("dcraw: $!");
507 $err = $magick->Read(file => \*DCRAW);
510 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
511 # RGB is slightly faster (no colorspace conversion needed) and works equally
512 # well for our uses, as long as we don't need to draw an information box,
513 # which trickles several ImageMagick bugs related to colorspace handling.
514 # (Ideally we'd be able to keep the image subsampled and
515 # planar, but that would probably be difficult for ImageMagick to expose.)
517 # $magick->Set(colorspace=>'YCbCr');
519 $err = $magick->Read($physical_fname);
523 $r->log->warn("$physical_fname: $err");
527 error($r, "$physical_fname: $err");
531 # If we use ->[0] unconditionally, text rendering (!) seems to crash
536 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
539 my $width = $img->Get('columns');
540 my $height = $img->Get('rows');
542 # Update the SQL database if it doesn't contain the required info
543 if (!defined($dbwidth) || !defined($dbheight)) {
544 $r->log->info("Updating width/height for $id: $width x $height");
545 update_image_info($r, $id, $width, $height);
552 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
554 my $fname = get_disk_location($r, $id);
555 if ($infobox ne 'box') {
556 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
557 return ($fname, undef);
561 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
563 if (! -r $cachename or (-M $cachename > -M $fname)) {
564 # If we are in overload mode (aka Slashdot mode), refuse to generate
566 if (Sesse::pr0n::Overload::is_in_overload($r)) {
567 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
568 error($r, 'System is in overload mode, not doing any scaling');
571 # If we're being asked for just the box, make a new image with just the box.
572 # We don't care about @otherres since each of these images are
573 # already pretty cheap to generate, but we need the exact width so we can make
574 # one in the right size.
575 if ($infobox eq 'box') {
576 my ($img, $width, $height);
578 # This is slow, but should fortunately almost never happen, so don't bother
580 if (!defined($dbwidth) || !defined($dbheight)) {
581 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
582 $width = $img->Get('columns');
583 $height = $img->Get('rows');
586 $img = Image::Magick->new;
591 if (defined($xres) && defined($yres)) {
592 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
595 $img->Set(size=>($width . "x" . $height));
596 $img->Read('xc:white');
598 my $info = Image::ExifTool::ImageInfo($fname);
599 if (make_infobox($img, $info, $r)) {
600 $img->Quantize(colors=>16, dither=>'False');
602 # Since the image is grayscale, ImageMagick overrides us and writes this
603 # as grayscale anyway, but at least we get rid of the alpha channel this
605 $img->Set(type=>'Palette');
607 # Not enough room for the text, make a tiny dummy transparent infobox
609 $img->Set(size=>"1x1");
616 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
617 $r->log->info("New infobox cache: $width x $height for $id.jpg");
619 return ($cachename, 'image/png');
622 my $can_use_qscale = 0;
623 if ($infobox eq 'nobox') {
627 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
629 while (defined($xres) && defined($yres)) {
630 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
631 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
634 if (defined($nxres) && defined($nyres)) {
635 # we have more resolutions to scale, so don't throw
637 $cimg = $img->Clone();
642 my $width = $img->Get('columns');
643 my $height = $img->Get('rows');
644 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
646 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
647 my $filter = 'Mitchell';
651 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
658 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
661 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
662 my $info = Image::ExifTool::ImageInfo($fname);
663 make_infobox($cimg, $info, $r);
666 # Strip EXIF tags etc.
671 filename => $cachename,
674 if (($nwidth >= 640 && $nheight >= 480) ||
675 ($nwidth >= 480 && $nheight >= 640)) {
676 $parms{'interlace'} = 'Plane';
679 $parms{'sampling-factor'} = $sf;
681 $err = $cimg->write(%parms);
686 ($xres, $yres) = ($nxres, $nyres);
688 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
693 $r->log->warn("$fname: $err");
697 error($r, "$fname: $err");
701 return ($cachename, 'image/jpeg');
704 sub get_mimetype_from_filename {
705 my $filename = shift;
706 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
707 $type = "image/jpeg" if (!defined($type));
712 my ($img, $info, $r) = @_;
714 # The infobox is of the form
715 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
716 # possibly with some parts omitted -- the middle part is known as the "classic
717 # fields"; note the comma separation. Every field has an associated "bold flag"
718 # in the second part.
720 my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
721 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
722 my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
723 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
725 my @classic_fields = ();
726 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
727 push @classic_fields, [ $1 . "mm", 0 ];
728 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
729 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
732 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
733 my ($a, $b) = ($1, $2);
734 my $gcd = gcd($a, $b);
735 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
736 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+))$/) {
737 push @classic_fields, [ $1 . "s", $shutter_priority ];
740 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
743 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
745 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
747 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
748 my $f = $info->{'FNumber'};
750 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
752 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
756 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
759 if (defined($info->{'NikonD1-ISOSetting'})) {
760 $iso = $info->{'NikonD1-ISOSetting'};
761 } elsif (defined($info->{'ISO'})) {
762 $iso = $info->{'ISO'};
763 } elsif (defined($info->{'ISOSetting'})) {
764 $iso = $info->{'ISOSetting'};
766 if (defined($iso) && $iso =~ /(\d+)/) {
767 push @classic_fields, [ $1 . " ISO", 0 ];
770 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
771 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
772 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
773 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
776 # Now piece together the rest
779 if (defined($info->{'DateTimeOriginal'}) &&
780 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
782 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
785 if (defined($info->{'Model'})) {
786 my $model = $info->{'Model'};
790 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
791 push @parts, [ $model, 0 ];
795 if (scalar @classic_fields > 0) {
796 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
799 for my $field (@classic_fields) {
800 push @parts, [ ', ', 0 ] if (!$first_elem);
806 if (defined($info->{'Flash'})) {
807 if ($info->{'Flash'} =~ /did not fire/i ||
808 $info->{'Flash'} =~ /no flash/i ||
809 $info->{'Flash'} =~ /not fired/i ||
810 $info->{'Flash'} =~ /Off/) {
811 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
812 push @parts, [ "No flash", 0 ];
813 } elsif ($info->{'Flash'} =~ /fired/i ||
814 $info->{'Flash'} =~ /On/) {
815 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
816 push @parts, [ "Flash", 0 ];
818 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
819 push @parts, [ $info->{'Flash'}, 0 ];
823 return 0 if (scalar @parts == 0);
825 # Find the required width
829 for my $part (@parts) {
832 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
834 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
837 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
840 $th = $h if ($h > $th);
843 return 0 if ($tw > $img->Get('columns'));
846 my $y = $img->Get('rows') - 24;
848 # Hit exact DCT blocks
851 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
852 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
853 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
854 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
856 # Start writing out the text
857 $x = ($img->Get('columns') - $tw) / 2;
859 my $room = ($img->Get('rows') - 1 - $y - $th);
860 $y = ($img->Get('rows') - 1) - $room/2;
862 for my $part (@parts) {
865 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
867 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
869 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
870 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
878 return $a if ($b == 0);
879 return gcd($b, $a % $b);
883 my ($r, $dbh, $id, $date, $desc) = @_;
886 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
887 push @errors, "Manglende eller ugyldig ID.";
889 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
890 push @errors, "Manglende eller ugyldig dato.";
892 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
893 push @errors, "Manglende eller ugyldig beskrivelse.";
896 if (scalar @errors > 0) {
900 my $vhost = $r->get_server_name;
901 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
902 undef, $id, $date, $desc, $vhost)
903 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
904 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
906 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
907 purge_cache($r, "/");
917 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
920 $decoded = Encode::decode("iso8859-1", $text);
926 # Depending on your front-end cache, you might want to get creative somehow here.
927 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
928 # regex tacked onto a request into something useful. The elements given in
929 # should not be regexes, though, as e.g. Squid will not be able to handle that.
931 my ($r, @elements) = @_;
932 return if (scalar @elements == 0);
935 for my $elem (@elements) {
936 $r->log->info("Purging $elem");
937 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
942 if (scalar @pe == 1) {
945 $regex .= "(" . join('|', @pe) . ")";
947 $regex .= "(\\?.*)?\$";
948 $r->headers_out->{'X-Pr0n-Purge'} = $regex;
950 $r->log->info($r->headers_out->{'X-Pr0n-Purge'});
953 # Find a list of all cache URLs for a given image, given what we have on disk.
954 sub get_all_cache_urls {
955 my ($r, $dbh, $id) = @_;
956 my $dir = POSIX::floor($id / 256);
959 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
960 or die "Couldn't prepare: " . $dbh->errstr;
962 or die "Couldn't find event and filename: " . $dbh->errstr;
963 my $ref = $q->fetchrow_hashref;
964 my $event = $ref->{'event'};
965 my $filename = $ref->{'filename'};
968 my $base = get_base($r) . "cache/$dir";
969 for my $file (<$base/$id-*>) {
970 my $fname = File::Basename::basename($file);
971 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
972 # Mipmaps don't have an URL, ignore
973 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
974 push @ret, "/$event/$filename";
975 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
976 push @ret, "/$event/$1x$2/$filename";
977 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
978 push @ret, "/$event/$1x$2/nobox/$filename";
979 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
980 push @ret, "/$event/$1x$2/box/$filename";
982 $r->log->warning("Couldn't find a purging URL for $fname");