1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
24 use Crypt::Eksblowfish::Bcrypt;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
30 use Sesse::pr0n::Config;
32 require Sesse::pr0n::Config_local;
37 @EXPORT = qw(&error &dberror);
39 @EXPORT_OK = qw(&error &dberror);
41 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
42 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
43 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
44 our $mimetypes = new MIME::Types;
46 print STDERR "Initializing pr0n $VERSION\n";
53 our ($dbh, $mimetypes);
56 my ($r,$err,$status,$title) = @_;
58 if (!defined($status) || !defined($title)) {
60 $title = "Internal server error";
63 my $res = Plack::Response->new($status);
64 my $io = IO::String->new;
66 $r->content_type('text/html; charset=utf-8');
68 header($r, $io, $title);
69 $io->print(" <p>Error: $err</p>\n");
73 log_error($r, "Stack trace follows: " . Carp::longmess());
82 return error($r, "$err (DB error: " . $dbh->errstr . ")");
86 my ($r, $io, $title) = @_;
88 $r->content_type("text/html; charset=utf-8");
90 # Fetch quote if we're itk-bilder.samfundet.no
92 if (Sesse::pr0n::Common::get_server_name($r) eq 'itk-bilder.samfundet.no') {
93 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
94 $quote = "Error: Could not fetch quotes." if (!defined($quote));
96 Sesse::pr0n::Templates::print_template($r, $io, "header", { title => $title, quotes => $quote });
101 Sesse::pr0n::Templates::print_template($r, $io, "footer",
102 { version => $Sesse::pr0n::Common::VERSION });
106 my ($width, $height, $thumbxres, $thumbyres) = @_;
108 unless ($thumbxres >= $width &&
109 $thumbyres >= $height) {
110 my $sfh = $width / $thumbxres;
111 my $sfv = $height / $thumbyres;
119 $width = POSIX::floor($width);
120 $height = POSIX::floor($height);
123 return ($width, $height);
126 sub get_query_string {
127 my ($param, $defparam) = @_;
131 while (my ($key, $value) = each %$param) {
132 next unless defined($value);
133 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
135 $value = pretty_escape($value);
137 $str .= ($first) ? "?" : ';';
138 $str .= "$key=$value";
144 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
145 sub weird_space_encode {
148 return "_" x (length($val) * 2);
150 return "_" x (length($val) * 2 - 1);
154 sub weird_space_unencode {
156 if (length($val) % 2 == 0) {
157 return "_" x (length($val) / 2);
159 return " " x ((length($val) + 1) / 2);
166 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
167 $value = URI::Escape::uri_escape($value);
168 $value =~ s/%2F/\//g;
173 sub pretty_unescape {
176 # URI unescaping is already done for us
177 $value =~ s/(_+)/weird_space_unencode($1)/ge;
183 my ($io, $title, $baseurl, $param, $defparam, $accesskey) = @_;
184 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
185 if (defined($accesskey) && length($accesskey) == 1) {
186 $str .= " accesskey=\"$accesskey\"";
188 $str .= ">$title</a>";
193 # Check that we are alive
194 if (!(defined($dbh) && $dbh->ping)) {
196 print STDERR "Lost contact with PostgreSQL server, trying to reconnect...\n";
197 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
198 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
200 die "Couldn't connect to PostgreSQL database";
207 sub get_disk_location {
209 my $dir = POSIX::floor($id / 256);
210 return $Sesse::pr0n::Config::image_base . "images/$dir/$id.jpg";
213 sub get_cache_location {
214 my ($r, $id, $width, $height, $infobox, $dpr) = @_;
215 my $dir = POSIX::floor($id / 256);
219 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box.png";
221 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box\@$dpr.png";
224 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-nobox.jpg";
228 sub ensure_disk_location_exists {
230 my $dir = POSIX::floor($id / 256);
232 my $img_dir = $Sesse::pr0n::Config::image_base . "/images/$dir/";
234 log_info($r, "Need to create new image directory $img_dir");
235 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
238 my $cache_dir = $Sesse::pr0n::Config::image_base . "/cache/$dir/";
239 if (! -d $cache_dir) {
240 log_info($r, "Need to create new cache directory $cache_dir");
241 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
245 sub get_mipmap_location {
246 my ($r, $id, $width, $height) = @_;
247 my $dir = POSIX::floor($id / 256);
249 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-mipmap-$width-$height.jpg";
252 sub update_image_info {
253 my ($r, $id, $width, $height) = @_;
255 # Also find the date taken if appropriate (from the EXIF tag etc.)
256 my $exiftool = Image::ExifTool->new;
257 $exiftool->ExtractInfo(get_disk_location($r, $id));
258 my $info = $exiftool->GetInfo();
259 my $datetime = undef;
261 if (defined($info->{'DateTimeOriginal'})) {
262 # Parse the date and time over to ISO format
263 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
264 $datetime = "$1-$2-$3 $4:$5:$6";
269 local $dbh->{AutoCommit} = 0;
272 $dbh->do('DELETE FROM exif_info WHERE image=?',
274 or die "Couldn't delete old EXIF information in SQL: $!";
276 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
277 or die "Couldn't prepare inserting EXIF information: $!";
279 for my $key (keys %$info) {
280 next if ref $info->{$key};
281 $q->execute($id, $key, guess_charset($info->{$key}))
282 or die "Couldn't insert EXIF information in database: $!";
286 my $model = $exiftool->GetValue('Model', 'PrintConv');
287 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
288 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
292 $model = undef if (length($model) == 0);
296 $lens = undef if (length($lens) == 0);
298 # Now update the main table with the information we've got
299 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
300 undef, $width, $height, $datetime, $model, $lens, $id)
301 or die "Couldn't update width/height in SQL: $!";
303 # update the last_picture cache as well (this should of course be done
304 # via a trigger, but this is less complicated :-) )
305 $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=?)',
306 undef, $datetime, $id)
307 or die "Couldn't update last_picture in SQL: $!";
314 #return qw(sesse Sesse);
316 my $auth = $r->header('authorization');
317 if (!defined($auth)) {
320 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
321 return check_basic_auth($r, $1);
328 my $res = Plack::Response->new(401);
329 $res->content_type('text/plain; charset=utf-8');
331 $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
333 $res->body("Need authorization\n");
337 sub check_basic_auth {
340 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
341 my ($user, $takenby) = extract_takenby($raw_user);
343 my $ref = $dbh->selectrow_hashref('SELECT cryptpassword FROM users WHERE username=? AND vhost=?',
344 undef, $user, Sesse::pr0n::Common::get_server_name($r));
345 my $bcrypt_matches = 0;
346 if (!defined($ref) || Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) ne $ref->{'cryptpassword'}) {
347 $r->content_type('text/plain; charset=utf-8');
348 log_warn($r, "Authentication failed for $user/$takenby");
351 log_info($r, "Authentication succeeded for $user/$takenby");
353 return ($user, $takenby);
356 sub get_pseudorandom_bytes {
357 my $num_left = shift;
359 open my $randfh, "<", "/dev/urandom"
360 or die "/dev/urandom: $!";
362 while ($num_left > 0) {
364 if (sysread($randfh, $tmp, $num_left) == -1) {
365 die "sysread(/dev/urandom): $!";
368 $num_left -= length($bytes);
374 sub extract_takenby {
377 # WinXP is stupid :-)
378 if ($user =~ /^.*\\(.*)$/) {
383 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
387 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
390 return ($user, $takenby);
394 my ($r, $event, $filename) = (@_);
395 my $ref = $dbh->selectrow_hashref(
396 'SELECT id FROM images WHERE event=? AND filename=?',
397 undef, $event, $filename);
398 if (!defined($ref)) {
399 return (undef, undef, undef);
401 return stat_image_from_id($r, $ref->{'id'});
404 sub stat_image_from_id {
407 my $fname = get_disk_location($r, $id);
408 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
409 or return (undef, undef, undef);
411 return ($fname, $size, $mtime);
414 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
415 # the smallest mipmap larger than the largest of them, as well as the original image
418 my ($r, $filename, $id, $dbwidth, $dbheight, @res) = @_;
419 my ($img, $mmimg, $width, $height);
421 my $physical_fname = get_disk_location($r, $id);
423 # If we don't know the size, we'll need to read it in anyway
424 if (!defined($dbwidth) || !defined($dbheight)) {
425 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
426 $width = $img->Get('columns');
427 $height = $img->Get('rows');
433 # Generate the list of mipmaps
436 my $mmwidth = $width;
437 my $mmheight = $height;
439 while ($mmwidth > 1 || $mmheight > 1) {
440 my $new_mmwidth = POSIX::floor($mmwidth / 2);
441 my $new_mmheight = POSIX::floor($mmheight / 2);
443 $new_mmwidth = 1 if ($new_mmwidth < 1);
444 $new_mmheight = 1 if ($new_mmheight < 1);
446 my $large_enough = 1;
447 for my $i (0..($#res/2)) {
448 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
449 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
455 last if (!$large_enough);
457 $mmwidth = $new_mmwidth;
458 $mmheight = $new_mmheight;
460 push @mmlist, [ $mmwidth, $mmheight ];
463 # Ensure that all of them are OK
464 my $last_good_mmlocation;
465 for my $i (0..$#mmlist) {
466 my $last = ($i == $#mmlist);
467 my $mmres = $mmlist[$i];
469 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
470 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
471 if (!defined($img)) {
472 if (defined($last_good_mmlocation)) {
473 $img = Sesse::pr0n::QscaleProxy->new;
474 $img->Read($last_good_mmlocation);
476 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
483 $cimg = $img->Clone();
485 log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
486 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
488 my $err = $cimg->write(
489 filename => $mmlocation,
491 'sampling-factor' => '1x1'
495 $last_good_mmlocation = $mmlocation;
497 if ($last && !defined($img)) {
498 # OK, read in the smallest one
499 $img = Sesse::pr0n::QscaleProxy->new;
500 my $err = $img->Read($mmlocation);
504 if (!defined($img)) {
505 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
506 $width = $img->Get('columns');
507 $height = $img->Get('rows');
509 return ($img, $width, $height);
512 sub read_original_image {
513 my ($r, $filename, $id, $dbwidth, $dbheight) = @_;
515 my $physical_fname = get_disk_location($r, $id);
517 # Read in the original image
519 if ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
520 $magick = Sesse::pr0n::QscaleProxy->new;
522 $magick = Image::Magick->new;
526 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
527 # The delegate support is rather broken and causes very odd stuff to happen when
528 # more than one thread does this at the same time. Thus, we simply do it ourselves.
529 if ($filename =~ /\.(nef|cr2)$/i) {
530 # this would suffice if ImageMagick gets to fix their handling
531 # $physical_fname = "NEF:$physical_fname";
533 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
534 or error("dcraw: $!");
535 $err = $magick->Read(file => \*DCRAW);
538 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
539 # RGB is slightly faster (no colorspace conversion needed) and works equally
540 # well for our uses, as long as we don't need to draw an information box,
541 # which trickles several ImageMagick bugs related to colorspace handling.
542 # (Ideally we'd be able to keep the image subsampled and
543 # planar, but that would probably be difficult for ImageMagick to expose.)
545 # $magick->Set(colorspace=>'YCbCr');
547 $err = $magick->Read($physical_fname);
551 log_warn($r, "$physical_fname: $err");
555 error($r, "$physical_fname: $err");
559 # If we use ->[0] unconditionally, text rendering (!) seems to crash
561 if (ref($magick) !~ /Image::Magick/) {
564 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
571 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $dpr, $xres, $yres, @otherres) = @_;
573 my ($new_dbwidth, $new_dbheight);
575 my $fname = get_disk_location($r, $id);
577 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
578 return ($fname, undef);
582 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
584 if (! -r $cachename or (-M $cachename > -M $fname)) {
585 # If we are in overload mode (aka Slashdot mode), refuse to generate
587 if (Sesse::pr0n::Overload::is_in_overload($r)) {
588 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
589 error($r, 'System is in overload mode, not doing any scaling');
592 # If we're being asked for the box, make a new image with it.
593 # We don't care about @otherres since each of these images are
594 # already pretty cheap to generate, but we need the exact width so we can make
595 # one in the right size.
597 my ($img, $width, $height);
599 # This is slow, but should fortunately almost never happen, so don't bother
601 if (!defined($dbwidth) || !defined($dbheight)) {
602 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
603 $new_dbwidth = $width = $img->Get('columns');
604 $new_dbheight = $height = $img->Get('rows');
607 $img = Image::Magick->new;
612 if (defined($xres) && defined($yres)) {
613 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
616 $img->Set(size=>($width . "x" . $height));
617 $img->Read('xc:white');
619 my $info = Image::ExifTool::ImageInfo($fname);
620 if (make_infobox($img, $info, $r, $dpr)) {
621 $img->Quantize(colors=>16, dither=>'False');
623 # Since the image is grayscale, ImageMagick overrides us and writes this
624 # as grayscale anyway, but at least we get rid of the alpha channel this
626 $img->Set(type=>'Palette');
628 # Not enough room for the text, make a tiny dummy transparent infobox
630 $img->Set(size=>"1x1");
637 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
638 log_info($r, "New infobox cache: $width x $height for $id.jpg");
640 return ($cachename, 'image/png');
644 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres);
646 while (defined($xres) && defined($yres)) {
647 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
648 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox, $dpr);
651 if (defined($nxres) && defined($nyres)) {
652 # we have more resolutions to scale, so don't throw
654 $cimg = $img->Clone();
659 my $width = $img->Get('columns');
660 my $height = $img->Get('rows');
661 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
663 my $filter = 'Lanczos';
668 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
671 # Strip EXIF tags etc.
676 filename => $cachename,
679 if (($nwidth >= 640 && $nheight >= 480) ||
680 ($nwidth >= 480 && $nheight >= 640)) {
681 $parms{'interlace'} = 'Plane';
684 $parms{'sampling-factor'} = $sf;
686 $err = $cimg->write(%parms);
691 ($xres, $yres) = ($nxres, $nyres);
693 log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
698 log_warn($r, "$fname: $err");
702 error($r, "$fname: $err");
707 # Update the SQL database if it doesn't contain the required info
708 if (!defined($dbwidth) && defined($new_dbwidth)) {
709 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
710 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
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, $dpr) = @_;
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 $manual_shutter = (defined($info->{'ExposureProgram'}) &&
733 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
734 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
735 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
736 if ($info->{'ExposureProgram'} =~ /manual/i) {
738 $manual_aperture = 1;
741 my @classic_fields = ();
742 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
743 push @classic_fields, [ $1 . "mm", 0 ];
744 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
745 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
748 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
749 my ($a, $b) = ($1, $2);
750 my $gcd = gcd($a, $b);
751 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
752 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
753 push @classic_fields, [ $1 . "s", $manual_shutter ];
756 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
759 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
761 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
763 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
764 my $f = $info->{'FNumber'};
766 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
768 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
772 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
775 if (defined($info->{'NikonD1-ISOSetting'})) {
776 $iso = $info->{'NikonD1-ISOSetting'};
777 } elsif (defined($info->{'ISO'})) {
778 $iso = $info->{'ISO'};
779 } elsif (defined($info->{'ISOSetting'})) {
780 $iso = $info->{'ISOSetting'};
782 if (defined($iso) && $iso =~ /(\d+)/) {
783 push @classic_fields, [ $1 . " ISO", 0 ];
786 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
787 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
788 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
789 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
792 # Now piece together the rest
795 if (defined($info->{'DateTimeOriginal'}) &&
796 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
798 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
801 if (defined($info->{'Model'})) {
802 my $model = $info->{'Model'};
806 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
807 push @parts, [ $model, 0 ];
811 if (scalar @classic_fields > 0) {
812 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
815 for my $field (@classic_fields) {
816 push @parts, [ ', ', 0 ] if (!$first_elem);
822 if (defined($info->{'Flash'})) {
823 if ($info->{'Flash'} =~ /did not fire/i ||
824 $info->{'Flash'} =~ /no flash/i ||
825 $info->{'Flash'} =~ /not fired/i ||
826 $info->{'Flash'} =~ /Off/) {
827 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
828 push @parts, [ "No flash", 0 ];
829 } elsif ($info->{'Flash'} =~ /fired/i ||
830 $info->{'Flash'} =~ /On/) {
831 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
832 push @parts, [ "Flash", 0 ];
834 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
835 push @parts, [ $info->{'Flash'}, 0 ];
839 return 0 if (scalar @parts == 0);
841 # Find the required width
845 for my $part (@parts) {
848 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
850 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
853 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
856 $th = $h if ($h > $th);
859 return 0 if ($tw > $img->Get('columns'));
862 my $y = $img->Get('rows') - 24*$dpr;
864 # Hit exact DCT blocks
867 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
868 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
869 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
870 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
872 # Start writing out the text
873 $x = ($img->Get('columns') - $tw) / 2;
875 my $room = ($img->Get('rows') - $dpr - $y - $th);
876 $y = ($img->Get('rows') - $dpr) - $room/2;
878 for my $part (@parts) {
881 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
883 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
885 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
886 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
894 return $a if ($b == 0);
895 return gcd($b, $a % $b);
899 my ($r, $res, $dbh, $id, $date, $desc) = @_;
902 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
903 push @errors, "Manglende eller ugyldig ID.";
905 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
906 push @errors, "Manglende eller ugyldig dato.";
908 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
909 push @errors, "Manglende eller ugyldig beskrivelse.";
912 if (scalar @errors > 0) {
916 my $vhost = Sesse::pr0n::Common::get_server_name($r);
917 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
918 undef, $id, $date, $desc, $vhost)
919 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
920 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
922 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
923 purge_cache($r, $res, "/");
933 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
936 $decoded = Encode::decode("iso8859-1", $text);
942 # Depending on your front-end cache, you might want to get creative somehow here.
943 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
944 # regex tacked onto a request into something useful. The elements given in
945 # should not be regexes, though, as e.g. Squid will not be able to handle that.
947 my ($r, $res, @elements) = @_;
948 return if (scalar @elements == 0);
951 for my $elem (@elements) {
952 log_info($r, "Purging $elem");
953 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
958 if (scalar @pe == 1) {
961 $regex .= "(" . join('|', @pe) . ")";
963 $regex .= "(\\?.*)?\$";
964 $res->header('X-Pr0n-Purge' => $regex);
967 # Find a list of all cache URLs for a given image, given what we have on disk.
968 sub get_all_cache_urls {
969 my ($r, $dbh, $id) = @_;
970 my $dir = POSIX::floor($id / 256);
973 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
974 or die "Couldn't prepare: " . $dbh->errstr;
976 or die "Couldn't find event and filename: " . $dbh->errstr;
977 my $ref = $q->fetchrow_hashref;
978 my $event = $ref->{'event'};
979 my $filename = $ref->{'filename'};
982 my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
983 for my $file (<$base/$id-*>) {
984 my $fname = File::Basename::basename($file);
985 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
986 # Mipmaps don't have an URL, ignore
987 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
988 push @ret, "/$event/$filename";
989 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
990 push @ret, "/$event/$1x$2/$filename";
991 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
992 push @ret, "/$event/$1x$2/nobox/$filename";
993 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
994 push @ret, "/$event/box/$filename";
995 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
996 push @ret, "/$event/$1x$2/box/$filename";
998 log_warn($r, "Couldn't find a purging URL for $fname");
1005 sub set_last_modified {
1006 my ($res, $mtime) = @_;
1008 my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
1009 $res->headers({ 'Last-Modified' => $str });
1012 sub get_server_name {
1014 my $host = $r->env->{'HTTP_HOST'};
1021 if (defined($r->logger)) {
1022 $r->logger->({ level => 'info', message => $msg });
1024 print STDERR "[INFO] $msg\n";
1030 if (defined($r->logger)) {
1031 $r->logger->({ level => 'warn', message => $msg });
1033 print STDERR "[WARN] $msg\n";
1039 if (defined($r->logger)) {
1040 $r->logger->({ level => 'error', message => $msg });
1042 print STDERR "[ERROR] $msg\n";