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 #return qw(sesse Sesse);
318 my $auth = $r->headers_in->{'authorization'};
319 if (!defined($auth)) {
323 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
324 return check_basic_auth($r, $1);
332 $r->content_type('text/plain; charset=utf-8');
334 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
335 $r->print("Need authorization\n");
338 sub check_basic_auth {
341 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
343 # WinXP is stupid :-)
344 if ($user =~ /^.*\\(.*)$/) {
349 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
353 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
357 $pass = Digest::SHA1::sha1_base64($pass);
358 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
359 undef, $user, $pass, $r->get_server_name);
360 if ($ref->{'auth'} != 1) {
361 $r->content_type('text/plain; charset=utf-8');
362 $r->log->warn("Authentication failed for $user/$takenby");
367 $r->log->info("Authentication succeeded for $user/$takenby");
369 return ($user, $takenby);
373 my ($r, $event, $filename) = (@_);
374 my $ref = $dbh->selectrow_hashref(
375 'SELECT id FROM images WHERE event=? AND filename=?',
376 undef, $event, $filename);
377 if (!defined($ref)) {
378 return (undef, undef, undef);
380 return stat_image_from_id($r, $ref->{'id'});
383 sub stat_image_from_id {
386 my $fname = get_disk_location($r, $id);
387 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
388 or return (undef, undef, undef);
390 return ($fname, $size, $mtime);
393 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
394 # the smallest mipmap larger than the largest of them.
396 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
397 my ($img, $mmimg, $width, $height);
399 my $physical_fname = get_disk_location($r, $id);
401 # If we don't know the size, we'll need to read it in anyway
402 if (!defined($dbwidth) || !defined($dbheight)) {
403 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
404 $width = $img->Get('columns');
405 $height = $img->Get('rows');
411 # Generate the list of mipmaps
414 my $mmwidth = $width;
415 my $mmheight = $height;
417 while ($mmwidth > 1 || $mmheight > 1) {
418 my $new_mmwidth = POSIX::floor($mmwidth / 2);
419 my $new_mmheight = POSIX::floor($mmheight / 2);
421 $new_mmwidth = 1 if ($new_mmwidth < 1);
422 $new_mmheight = 1 if ($new_mmheight < 1);
424 my $large_enough = 1;
425 for my $i (0..($#res/2)) {
426 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
427 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
433 last if (!$large_enough);
435 $mmwidth = $new_mmwidth;
436 $mmheight = $new_mmheight;
438 push @mmlist, [ $mmwidth, $mmheight ];
441 # Ensure that all of them are OK
442 my $last_good_mmlocation;
443 for my $i (0..$#mmlist) {
444 my $last = ($i == $#mmlist);
445 my $mmres = $mmlist[$i];
447 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
448 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
449 if (!defined($img)) {
450 if (defined($last_good_mmlocation)) {
451 if ($can_use_qscale) {
452 $img = Sesse::pr0n::QscaleProxy->new;
454 $img = Image::Magick->new;
456 $img->Read($last_good_mmlocation);
458 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
465 $cimg = $img->Clone();
467 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
468 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
470 my $err = $cimg->write(
471 filename => $mmlocation,
473 'sampling-factor' => '1x1'
477 $last_good_mmlocation = $mmlocation;
479 if ($last && !defined($img)) {
480 # OK, read in the smallest one
481 if ($can_use_qscale) {
482 $img = Sesse::pr0n::QscaleProxy->new;
484 $img = Image::Magick->new;
486 my $err = $img->Read($mmlocation);
490 if (!defined($img)) {
491 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
496 sub read_original_image {
497 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
499 my $physical_fname = get_disk_location($r, $id);
501 # Read in the original image
503 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
504 $magick = Sesse::pr0n::QscaleProxy->new;
506 $magick = Image::Magick->new;
510 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
511 # The delegate support is rather broken and causes very odd stuff to happen when
512 # more than one thread does this at the same time. Thus, we simply do it ourselves.
513 if ($filename =~ /\.(nef|cr2)$/i) {
514 # this would suffice if ImageMagick gets to fix their handling
515 # $physical_fname = "NEF:$physical_fname";
517 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
518 or error("dcraw: $!");
519 $err = $magick->Read(file => \*DCRAW);
522 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
523 # RGB is slightly faster (no colorspace conversion needed) and works equally
524 # well for our uses, as long as we don't need to draw an information box,
525 # which trickles several ImageMagick bugs related to colorspace handling.
526 # (Ideally we'd be able to keep the image subsampled and
527 # planar, but that would probably be difficult for ImageMagick to expose.)
529 # $magick->Set(colorspace=>'YCbCr');
531 $err = $magick->Read($physical_fname);
535 $r->log->warn("$physical_fname: $err");
539 error($r, "$physical_fname: $err");
543 # If we use ->[0] unconditionally, text rendering (!) seems to crash
548 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
551 my $width = $img->Get('columns');
552 my $height = $img->Get('rows');
554 # Update the SQL database if it doesn't contain the required info
555 if (!defined($dbwidth) || !defined($dbheight)) {
556 $r->log->info("Updating width/height for $id: $width x $height");
557 update_image_info($r, $id, $width, $height);
564 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
566 my $fname = get_disk_location($r, $id);
567 if ($infobox ne 'box') {
568 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
569 return ($fname, undef);
573 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
575 if (! -r $cachename or (-M $cachename > -M $fname)) {
576 # If we are in overload mode (aka Slashdot mode), refuse to generate
578 if (Sesse::pr0n::Overload::is_in_overload($r)) {
579 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
580 error($r, 'System is in overload mode, not doing any scaling');
583 # If we're being asked for just the box, make a new image with just the box.
584 # We don't care about @otherres since each of these images are
585 # already pretty cheap to generate, but we need the exact width so we can make
586 # one in the right size.
587 if ($infobox eq 'box') {
588 my ($img, $width, $height);
590 # This is slow, but should fortunately almost never happen, so don't bother
592 if (!defined($dbwidth) || !defined($dbheight)) {
593 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
594 $width = $img->Get('columns');
595 $height = $img->Get('rows');
598 $img = Image::Magick->new;
603 if (defined($xres) && defined($yres)) {
604 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
607 $img->Set(size=>($width . "x" . $height));
608 $img->Read('xc:white');
610 my $info = Image::ExifTool::ImageInfo($fname);
611 if (make_infobox($img, $info, $r)) {
612 $img->Quantize(colors=>16, dither=>'False');
614 # Since the image is grayscale, ImageMagick overrides us and writes this
615 # as grayscale anyway, but at least we get rid of the alpha channel this
617 $img->Set(type=>'Palette');
619 # Not enough room for the text, make a tiny dummy transparent infobox
621 $img->Set(size=>"1x1");
628 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
629 $r->log->info("New infobox cache: $width x $height for $id.jpg");
631 return ($cachename, 'image/png');
634 my $can_use_qscale = 0;
635 if ($infobox eq 'nobox') {
639 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
641 while (defined($xres) && defined($yres)) {
642 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
643 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
646 if (defined($nxres) && defined($nyres)) {
647 # we have more resolutions to scale, so don't throw
649 $cimg = $img->Clone();
654 my $width = $img->Get('columns');
655 my $height = $img->Get('rows');
656 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
658 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
659 my $filter = 'Mitchell';
663 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
670 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
673 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
674 my $info = Image::ExifTool::ImageInfo($fname);
675 make_infobox($cimg, $info, $r);
678 # Strip EXIF tags etc.
683 filename => $cachename,
686 if (($nwidth >= 640 && $nheight >= 480) ||
687 ($nwidth >= 480 && $nheight >= 640)) {
688 $parms{'interlace'} = 'Plane';
691 $parms{'sampling-factor'} = $sf;
693 $err = $cimg->write(%parms);
698 ($xres, $yres) = ($nxres, $nyres);
700 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
705 $r->log->warn("$fname: $err");
709 error($r, "$fname: $err");
713 return ($cachename, 'image/jpeg');
716 sub get_mimetype_from_filename {
717 my $filename = shift;
718 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
719 $type = "image/jpeg" if (!defined($type));
724 my ($img, $info, $r) = @_;
726 # The infobox is of the form
727 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
728 # possibly with some parts omitted -- the middle part is known as the "classic
729 # fields"; note the comma separation. Every field has an associated "bold flag"
730 # in the second part.
732 my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
733 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
734 my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
735 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
737 my @classic_fields = ();
738 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
739 push @classic_fields, [ $1 . "mm", 0 ];
740 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
741 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
744 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
745 my ($a, $b) = ($1, $2);
746 my $gcd = gcd($a, $b);
747 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
748 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+))$/) {
749 push @classic_fields, [ $1 . "s", $shutter_priority ];
752 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
755 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
757 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
759 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
760 my $f = $info->{'FNumber'};
762 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
764 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
768 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
771 if (defined($info->{'NikonD1-ISOSetting'})) {
772 $iso = $info->{'NikonD1-ISOSetting'};
773 } elsif (defined($info->{'ISO'})) {
774 $iso = $info->{'ISO'};
775 } elsif (defined($info->{'ISOSetting'})) {
776 $iso = $info->{'ISOSetting'};
778 if (defined($iso) && $iso =~ /(\d+)/) {
779 push @classic_fields, [ $1 . " ISO", 0 ];
782 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
783 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
784 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
785 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
788 # Now piece together the rest
791 if (defined($info->{'DateTimeOriginal'}) &&
792 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
794 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
797 if (defined($info->{'Model'})) {
798 my $model = $info->{'Model'};
802 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
803 push @parts, [ $model, 0 ];
807 if (scalar @classic_fields > 0) {
808 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
811 for my $field (@classic_fields) {
812 push @parts, [ ', ', 0 ] if (!$first_elem);
818 if (defined($info->{'Flash'})) {
819 if ($info->{'Flash'} =~ /did not fire/i ||
820 $info->{'Flash'} =~ /no flash/i ||
821 $info->{'Flash'} =~ /not fired/i ||
822 $info->{'Flash'} =~ /Off/) {
823 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
824 push @parts, [ "No flash", 0 ];
825 } elsif ($info->{'Flash'} =~ /fired/i ||
826 $info->{'Flash'} =~ /On/) {
827 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
828 push @parts, [ "Flash", 0 ];
830 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
831 push @parts, [ $info->{'Flash'}, 0 ];
835 return 0 if (scalar @parts == 0);
837 # Find the required width
841 for my $part (@parts) {
844 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
846 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
849 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
852 $th = $h if ($h > $th);
855 return 0 if ($tw > $img->Get('columns'));
858 my $y = $img->Get('rows') - 24;
860 # Hit exact DCT blocks
863 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
864 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
865 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
866 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
868 # Start writing out the text
869 $x = ($img->Get('columns') - $tw) / 2;
871 my $room = ($img->Get('rows') - 1 - $y - $th);
872 $y = ($img->Get('rows') - 1) - $room/2;
874 for my $part (@parts) {
877 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
879 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
881 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
882 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
890 return $a if ($b == 0);
891 return gcd($b, $a % $b);
895 my ($r, $dbh, $id, $date, $desc) = @_;
898 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
899 push @errors, "Manglende eller ugyldig ID.";
901 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
902 push @errors, "Manglende eller ugyldig dato.";
904 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
905 push @errors, "Manglende eller ugyldig beskrivelse.";
908 if (scalar @errors > 0) {
912 my $vhost = $r->get_server_name;
913 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
914 undef, $id, $date, $desc, $vhost)
915 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
916 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
918 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
919 purge_cache($r, "/");
929 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
932 $decoded = Encode::decode("iso8859-1", $text);
938 # Depending on your front-end cache, you might want to get creative somehow here.
939 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
940 # regex tacked onto a request into something useful. The elements given in
941 # should not be regexes, though, as e.g. Squid will not be able to handle that.
943 my ($r, @elements) = @_;
944 return if (scalar @elements == 0);
947 for my $elem (@elements) {
948 $r->log->info("Purging $elem");
949 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
954 if (scalar @pe == 1) {
957 $regex .= "(" . join('|', @pe) . ")";
959 $regex .= "(\\?.*)?\$";
960 $r->headers_out->{'X-Pr0n-Purge'} = $regex;
962 $r->log->info($r->headers_out->{'X-Pr0n-Purge'});
965 # Find a list of all cache URLs for a given image, given what we have on disk.
966 sub get_all_cache_urls {
967 my ($r, $dbh, $id) = @_;
968 my $dir = POSIX::floor($id / 256);
971 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
972 or die "Couldn't prepare: " . $dbh->errstr;
974 or die "Couldn't find event and filename: " . $dbh->errstr;
975 my $ref = $q->fetchrow_hashref;
976 my $event = $ref->{'event'};
977 my $filename = $ref->{'filename'};
980 my $base = get_base($r) . "cache/$dir";
981 for my $file (<$base/$id-*>) {
982 my $fname = File::Basename::basename($file);
983 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
984 # Mipmaps don't have an URL, ignore
985 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
986 push @ret, "/$event/$filename";
987 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
988 push @ret, "/$event/$1x$2/$filename";
989 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
990 push @ret, "/$event/$1x$2/nobox/$filename";
991 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
992 push @ret, "/$event/$1x$2/box/$filename";
994 $r->log->warning("Couldn't find a purging URL for $fname");