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';
23 use Digest::HMAC_SHA1;
35 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
37 use Sesse::pr0n::Config;
39 require Sesse::pr0n::Config_local;
44 @EXPORT = qw(&error &dberror);
46 @EXPORT_OK = qw(&error &dberror);
48 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
49 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
50 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
51 our $mimetypes = new MIME::Types;
53 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
60 our ($dbh, $mimetypes);
63 my ($r,$err,$status,$title) = @_;
65 if (!defined($status) || !defined($title)) {
67 $title = "Internal server error";
70 $r->content_type('text/html; charset=utf-8');
74 $r->print(" <p>Error: $err</p>\n");
78 $r->log->error("Stack trace follows: " . Carp::longmess());
80 ModPerl::Util::exit();
85 error($r, "$err (DB error: " . $dbh->errstr . ")");
91 $r->content_type("text/html; charset=utf-8");
93 # Fetch quote if we're itk-bilder.samfundet.no
95 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
96 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
97 $quote = "Error: Could not fetch quotes." if (!defined($quote));
99 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
104 Sesse::pr0n::Templates::print_template($r, "footer",
105 { version => $Sesse::pr0n::Common::VERSION });
109 my ($width, $height, $thumbxres, $thumbyres) = @_;
111 unless ($thumbxres >= $width &&
112 $thumbyres >= $height) {
113 my $sfh = $width / $thumbxres;
114 my $sfv = $height / $thumbyres;
122 $width = POSIX::floor($width);
123 $height = POSIX::floor($height);
126 return ($width, $height);
129 sub get_query_string {
130 my ($param, $defparam) = @_;
134 while (my ($key, $value) = each %$param) {
135 next unless defined($value);
136 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
138 $value = pretty_escape($value);
140 $str .= ($first) ? "?" : ';';
141 $str .= "$key=$value";
147 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
148 sub weird_space_encode {
151 return "_" x (length($val) * 2);
153 return "_" x (length($val) * 2 - 1);
157 sub weird_space_unencode {
159 if (length($val) % 2 == 0) {
160 return "_" x (length($val) / 2);
162 return " " x ((length($val) + 1) / 2);
169 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
170 $value = URI::Escape::uri_escape($value);
171 $value =~ s/%2F/\//g;
176 sub pretty_unescape {
179 # URI unescaping is already done for us
180 $value =~ s/(_+)/weird_space_unencode($1)/ge;
186 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
187 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
188 if (defined($accesskey) && length($accesskey) == 1) {
189 $str .= " accesskey=\"$accesskey\"";
191 $str .= ">$title</a>";
196 # Check that we are alive
197 if (!(defined($dbh) && $dbh->ping)) {
199 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
200 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
201 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
203 die "Couldn't connect to PostgreSQL database";
212 return $r->dir_config('ImageBase');
215 sub get_disk_location {
217 my $dir = POSIX::floor($id / 256);
218 return get_base($r) . "images/$dir/$id.jpg";
221 sub get_cache_location {
222 my ($r, $id, $width, $height, $infobox) = @_;
223 my $dir = POSIX::floor($id / 256);
225 if ($infobox eq 'both') {
226 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
227 } elsif ($infobox eq 'nobox') {
228 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
230 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
234 sub ensure_disk_location_exists {
236 my $dir = POSIX::floor($id / 256);
238 my $img_dir = get_base($r) . "/images/$dir/";
240 $r->log->info("Need to create new image directory $img_dir");
241 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
244 my $cache_dir = get_base($r) . "/cache/$dir/";
245 if (! -d $cache_dir) {
246 $r->log->info("Need to create new cache directory $cache_dir");
247 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
251 sub get_mipmap_location {
252 my ($r, $id, $width, $height) = @_;
253 my $dir = POSIX::floor($id / 256);
255 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
258 sub update_image_info {
259 my ($r, $id, $width, $height) = @_;
261 # Also find the date taken if appropriate (from the EXIF tag etc.)
262 my $exiftool = Image::ExifTool->new;
263 $exiftool->ExtractInfo(get_disk_location($r, $id));
264 my $info = $exiftool->GetInfo();
265 my $datetime = undef;
267 if (defined($info->{'DateTimeOriginal'})) {
268 # Parse the date and time over to ISO format
269 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
270 $datetime = "$1-$2-$3 $4:$5:$6";
275 local $dbh->{AutoCommit} = 0;
278 $dbh->do('DELETE FROM exif_info WHERE image=?',
280 or die "Couldn't delete old EXIF information in SQL: $!";
282 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
283 or die "Couldn't prepare inserting EXIF information: $!";
285 for my $key (keys %$info) {
286 next if ref $info->{$key};
287 $q->execute($id, $key, guess_charset($info->{$key}))
288 or die "Couldn't insert EXIF information in database: $!";
292 my $model = $exiftool->GetValue('Model', 'PrintConv');
293 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
294 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
298 $model = undef if (length($model) == 0);
302 $lens = undef if (length($lens) == 0);
304 # Now update the main table with the information we've got
305 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
306 undef, $width, $height, $datetime, $model, $lens, $id)
307 or die "Couldn't update width/height in SQL: $!";
310 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
311 if (scalar @tags == 0) {
312 # This is XMP-dc:Subject, an RDF bag of tags.
313 @tags = $exiftool->GetValue('Subject', 'ValueConv');
315 $dbh->do('DELETE FROM tags WHERE image=?',
317 or die "Couldn't delete old tag information in SQL: $!";
319 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
320 or die "Couldn't prepare inserting tag information: $!";
323 for my $tag (@tags) {
324 $q->execute($id, guess_charset($tag))
325 or die "Couldn't insert tag information in database: $!";
328 # update the last_picture cache as well (this should of course be done
329 # via a trigger, but this is less complicated :-) )
330 $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=?)',
331 undef, $datetime, $id)
332 or die "Couldn't update last_picture in SQL: $!";
339 #return qw(sesse Sesse);
341 my $auth = $r->headers_in->{'authorization'};
342 if (!defined($auth)) {
346 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
347 return check_basic_auth($r, $1);
349 if ($auth =~ /^Digest (.*)$/) {
350 return check_digest_auth($r, $1);
357 my ($r, %options) = @_;
358 $r->content_type('text/plain; charset=utf-8');
360 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
362 # Digest auth is disabled for now, due to various client problems.
363 if (0 && ($options{'DigestAuth'} // 1)) {
364 # We make our nonce similar to the scheme of RFC2069 section 2.1.1,
365 # with some changes: We don't care about client IP (these have a nasty
366 # tendency to change from request to request when load-balancing
367 # proxies etc. are being used), and we use HMAC instead of simple
368 # hashing simply because that's a better signing method.
370 # NOTE: For some weird reason, Digest::HMAC_SHA doesn't like taking
371 # the output from time directly (it gives a different response), so we
372 # forcefully stringify the argument.
374 my $nonce = Digest::HMAC_SHA->hmac_sha1_hex($ts . "", $Sesse::pr0n::Config::db_password);
375 my $stale_nonce_text = "";
376 $stale_nonce_text = ", stale=\"true\"" if ($options{'StaleNonce'} // 0);
378 $r->headers_out->{'www-authenticate'} =
379 "Digest realm=\"pr0n.sesse.net\", " .
380 "nonce=\"$nonce\", " .
382 "qop=\"auth\"" . $stale_nonce_text; # FIXME: support auth-int
385 $r->print("Need authorization\n");
388 sub check_basic_auth {
391 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
392 my ($user, $takenby) = extract_takenby($raw_user);
394 my $ref = $dbh->selectrow_hashref('SELECT sha1password,digest_ha1_hex FROM users WHERE username=? AND vhost=?',
395 undef, $user, $r->get_server_name);
396 if (!defined($ref) || $ref->{'sha1password'} ne Digest::SHA::sha1_base64($pass)) {
397 $r->content_type('text/plain; charset=utf-8');
398 $r->log->warn("Authentication failed for $user/$takenby");
402 $r->log->info("Authentication succeeded for $user/$takenby");
404 # Make sure we can use Digest authentication in the future with this password.
405 my $ha1 = Digest::MD5::md5_hex($user . ':pr0n.sesse.net:' . $pass);
406 if (!defined($ref->{'digest_ha1_hex'}) || $ref->{'digest_ha1_hex'} ne $ha1) {
407 $dbh->do('UPDATE users SET digest_ha1_hex=? WHERE username=? AND vhost=?',
408 undef, $ha1, $user, $r->get_server_name)
409 or die "Couldn't update: " . $dbh->errstr;
410 $r->log->info("Updated Digest auth hash for for $user");
413 return ($user, $takenby);
416 sub check_digest_auth {
419 # We're a bit more liberal than RFC2069 in the parsing here, allowing
420 # quoted strings everywhere.
422 while ($auth =~ s/^ ([a-zA-Z]+) # key
425 [^",]* # either something that doesn't contain comma or quotes
427 " ( [^"\\] | \\ . ) * " # or a full quoted string
429 (?: (?: , \s* ) + | $ ) # delimiter(s), or end of string
431 my ($key, $value) = ($1, $2);
432 if ($value =~ /^"(.*)"$/) {
434 $value =~ s/\\(.)/$1/g;
436 $auth{$key} = $value;
438 unless (exists($auth{'username'}) &&
439 exists($auth{'uri'}) &&
440 exists($auth{'nonce'}) &&
441 exists($auth{'opaque'}) &&
442 exists($auth{'response'})) {
446 if ($r->uri ne $auth{'uri'}) {
451 # Verify that the opaque data does indeed look like a timestamp, and that the nonce
452 # is indeed a signed version of it.
453 if ($auth{'opaque'} !~ /^\d+$/) {
457 my $compare_nonce = Digest::HMAC_SHA1->hmac_sha1_hex($auth{'opaque'}, $Sesse::pr0n::Config::db_password);
458 if ($auth{'nonce'} ne $compare_nonce) {
463 # Now look up the user's HA1 from the database, and calculate HA2.
464 my ($user, $takenby) = extract_takenby($auth{'username'});
465 my $ref = $dbh->selectrow_hashref('SELECT digest_ha1_hex FROM users WHERE username=? AND vhost=?',
466 undef, $user, $r->get_server_name);
467 if (!defined($ref)) {
471 if (!defined($ref->{'digest_ha1_hex'}) || $ref->{'digest_ha1_hex'} !~ /^[0-9a-f]{32}$/) {
472 # A user that exists but has empty HA1 is a user that's not
473 # ready for digest auth, so we hack it and resend 401,
474 # only this time without digest auth.
475 output_401($r, DigestAuth => 0);
478 my $ha1 = $ref->{'digest_ha1_hex'};
479 my $ha2 = Digest::MD5::md5_hex($r->method . ':' . $auth{'uri'});
481 if (exists($auth{'qop'}) && $auth{'qop'} eq 'auth') {
482 unless (exists($auth{'nc'}) && exists($auth{'cnonce'})) {
488 $response .= ':' . $auth{'nonce'};
489 $response .= ':' . $auth{'nc'};
490 $response .= ':' . $auth{'cnonce'};
491 $response .= ':' . $auth{'qop'};
492 $response .= ':' . $ha2;
495 $response .= ':' . $auth{'nonce'};
496 $response .= ':' . $ha2;
498 if ($auth{'response'} ne Digest::MD5::md5_hex($response)) {
503 # OK, everything is good, and there's only one thing we need to check: That the nonce
504 # isn't too old. If it is, but everything else is ok, we tell the browser that and it
505 # will re-encrypt with the new nonce.
506 my $timediff = time - $auth{'opaque'};
507 if ($timediff < 0 || $timediff > 300) {
508 output_401($r, StaleNonce => 1);
512 return ($user, $takenby);
515 sub extract_takenby {
518 # WinXP is stupid :-)
519 if ($user =~ /^.*\\(.*)$/) {
524 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
528 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
531 return ($user, $takenby);
535 my ($r, $event, $filename) = (@_);
536 my $ref = $dbh->selectrow_hashref(
537 'SELECT id FROM images WHERE event=? AND filename=?',
538 undef, $event, $filename);
539 if (!defined($ref)) {
540 return (undef, undef, undef);
542 return stat_image_from_id($r, $ref->{'id'});
545 sub stat_image_from_id {
548 my $fname = get_disk_location($r, $id);
549 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
550 or return (undef, undef, undef);
552 return ($fname, $size, $mtime);
555 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
556 # the smallest mipmap larger than the largest of them, as well as the original image
559 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
560 my ($img, $mmimg, $width, $height);
562 my $physical_fname = get_disk_location($r, $id);
564 # If we don't know the size, we'll need to read it in anyway
565 if (!defined($dbwidth) || !defined($dbheight)) {
566 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
567 $width = $img->Get('columns');
568 $height = $img->Get('rows');
574 # Generate the list of mipmaps
577 my $mmwidth = $width;
578 my $mmheight = $height;
580 while ($mmwidth > 1 || $mmheight > 1) {
581 my $new_mmwidth = POSIX::floor($mmwidth / 2);
582 my $new_mmheight = POSIX::floor($mmheight / 2);
584 $new_mmwidth = 1 if ($new_mmwidth < 1);
585 $new_mmheight = 1 if ($new_mmheight < 1);
587 my $large_enough = 1;
588 for my $i (0..($#res/2)) {
589 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
590 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
596 last if (!$large_enough);
598 $mmwidth = $new_mmwidth;
599 $mmheight = $new_mmheight;
601 push @mmlist, [ $mmwidth, $mmheight ];
604 # Ensure that all of them are OK
605 my $last_good_mmlocation;
606 for my $i (0..$#mmlist) {
607 my $last = ($i == $#mmlist);
608 my $mmres = $mmlist[$i];
610 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
611 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
612 if (!defined($img)) {
613 if (defined($last_good_mmlocation)) {
614 if ($can_use_qscale) {
615 $img = Sesse::pr0n::QscaleProxy->new;
617 $img = Image::Magick->new;
619 $img->Read($last_good_mmlocation);
621 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
628 $cimg = $img->Clone();
630 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
631 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
633 my $err = $cimg->write(
634 filename => $mmlocation,
636 'sampling-factor' => '1x1'
640 $last_good_mmlocation = $mmlocation;
642 if ($last && !defined($img)) {
643 # OK, read in the smallest one
644 if ($can_use_qscale) {
645 $img = Sesse::pr0n::QscaleProxy->new;
647 $img = Image::Magick->new;
649 my $err = $img->Read($mmlocation);
653 if (!defined($img)) {
654 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
655 $width = $img->Get('columns');
656 $height = $img->Get('rows');
658 return ($img, $width, $height);
661 sub read_original_image {
662 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
664 my $physical_fname = get_disk_location($r, $id);
666 # Read in the original image
668 if ($can_use_qscale && ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i)) {
669 $magick = Sesse::pr0n::QscaleProxy->new;
671 $magick = Image::Magick->new;
675 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
676 # The delegate support is rather broken and causes very odd stuff to happen when
677 # more than one thread does this at the same time. Thus, we simply do it ourselves.
678 if ($filename =~ /\.(nef|cr2)$/i) {
679 # this would suffice if ImageMagick gets to fix their handling
680 # $physical_fname = "NEF:$physical_fname";
682 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
683 or error("dcraw: $!");
684 $err = $magick->Read(file => \*DCRAW);
687 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
688 # RGB is slightly faster (no colorspace conversion needed) and works equally
689 # well for our uses, as long as we don't need to draw an information box,
690 # which trickles several ImageMagick bugs related to colorspace handling.
691 # (Ideally we'd be able to keep the image subsampled and
692 # planar, but that would probably be difficult for ImageMagick to expose.)
694 # $magick->Set(colorspace=>'YCbCr');
696 $err = $magick->Read($physical_fname);
700 $r->log->warn("$physical_fname: $err");
704 error($r, "$physical_fname: $err");
708 # If we use ->[0] unconditionally, text rendering (!) seems to crash
710 if (ref($magick) !~ /Image::Magick/) {
713 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
720 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
722 my ($new_dbwidth, $new_dbheight);
724 my $fname = get_disk_location($r, $id);
725 if ($infobox ne 'box') {
726 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
727 return ($fname, undef);
731 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
733 if (! -r $cachename or (-M $cachename > -M $fname)) {
734 # If we are in overload mode (aka Slashdot mode), refuse to generate
736 if (Sesse::pr0n::Overload::is_in_overload($r)) {
737 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
738 error($r, 'System is in overload mode, not doing any scaling');
741 # If we're being asked for just the box, make a new image with just the box.
742 # We don't care about @otherres since each of these images are
743 # already pretty cheap to generate, but we need the exact width so we can make
744 # one in the right size.
745 if ($infobox eq 'box') {
746 my ($img, $width, $height);
748 # This is slow, but should fortunately almost never happen, so don't bother
750 if (!defined($dbwidth) || !defined($dbheight)) {
751 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
752 $new_dbwidth = $width = $img->Get('columns');
753 $new_dbheight = $height = $img->Get('rows');
756 $img = Image::Magick->new;
761 if (defined($xres) && defined($yres)) {
762 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
765 $img->Set(size=>($width . "x" . $height));
766 $img->Read('xc:white');
768 my $info = Image::ExifTool::ImageInfo($fname);
769 if (make_infobox($img, $info, $r)) {
770 $img->Quantize(colors=>16, dither=>'False');
772 # Since the image is grayscale, ImageMagick overrides us and writes this
773 # as grayscale anyway, but at least we get rid of the alpha channel this
775 $img->Set(type=>'Palette');
777 # Not enough room for the text, make a tiny dummy transparent infobox
779 $img->Set(size=>"1x1");
786 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
787 $r->log->info("New infobox cache: $width x $height for $id.jpg");
789 return ($cachename, 'image/png');
792 my $can_use_qscale = 0;
793 if ($infobox eq 'nobox') {
798 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
800 while (defined($xres) && defined($yres)) {
801 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
802 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
805 if (defined($nxres) && defined($nyres)) {
806 # we have more resolutions to scale, so don't throw
808 $cimg = $img->Clone();
813 my $width = $img->Get('columns');
814 my $height = $img->Get('rows');
815 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
817 my $filter = 'Lanczos';
822 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
825 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
826 my $info = Image::ExifTool::ImageInfo($fname);
827 make_infobox($cimg, $info, $r);
830 # Strip EXIF tags etc.
835 filename => $cachename,
838 if (($nwidth >= 640 && $nheight >= 480) ||
839 ($nwidth >= 480 && $nheight >= 640)) {
840 $parms{'interlace'} = 'Plane';
843 $parms{'sampling-factor'} = $sf;
845 $err = $cimg->write(%parms);
850 ($xres, $yres) = ($nxres, $nyres);
852 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
857 $r->log->warn("$fname: $err");
861 error($r, "$fname: $err");
866 # Update the SQL database if it doesn't contain the required info
867 if (!defined($dbwidth) && defined($new_dbwidth)) {
868 $r->log->info("Updating width/height for $id: $new_dbwidth x $new_dbheight");
869 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
872 return ($cachename, 'image/jpeg');
875 sub get_mimetype_from_filename {
876 my $filename = shift;
877 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
878 $type = "image/jpeg" if (!defined($type));
883 my ($img, $info, $r) = @_;
885 # The infobox is of the form
886 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
887 # possibly with some parts omitted -- the middle part is known as the "classic
888 # fields"; note the comma separation. Every field has an associated "bold flag"
889 # in the second part.
891 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
892 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
893 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
894 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
895 if ($info->{'ExposureProgram'} =~ /manual/i) {
897 $manual_aperture = 1;
900 my @classic_fields = ();
901 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
902 push @classic_fields, [ $1 . "mm", 0 ];
903 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
904 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
907 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
908 my ($a, $b) = ($1, $2);
909 my $gcd = gcd($a, $b);
910 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
911 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
912 push @classic_fields, [ $1 . "s", $manual_shutter ];
915 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
918 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
920 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
922 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
923 my $f = $info->{'FNumber'};
925 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
927 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
931 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
934 if (defined($info->{'NikonD1-ISOSetting'})) {
935 $iso = $info->{'NikonD1-ISOSetting'};
936 } elsif (defined($info->{'ISO'})) {
937 $iso = $info->{'ISO'};
938 } elsif (defined($info->{'ISOSetting'})) {
939 $iso = $info->{'ISOSetting'};
941 if (defined($iso) && $iso =~ /(\d+)/) {
942 push @classic_fields, [ $1 . " ISO", 0 ];
945 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
946 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
947 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
948 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
951 # Now piece together the rest
954 if (defined($info->{'DateTimeOriginal'}) &&
955 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
957 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
960 if (defined($info->{'Model'})) {
961 my $model = $info->{'Model'};
965 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
966 push @parts, [ $model, 0 ];
970 if (scalar @classic_fields > 0) {
971 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
974 for my $field (@classic_fields) {
975 push @parts, [ ', ', 0 ] if (!$first_elem);
981 if (defined($info->{'Flash'})) {
982 if ($info->{'Flash'} =~ /did not fire/i ||
983 $info->{'Flash'} =~ /no flash/i ||
984 $info->{'Flash'} =~ /not fired/i ||
985 $info->{'Flash'} =~ /Off/) {
986 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
987 push @parts, [ "No flash", 0 ];
988 } elsif ($info->{'Flash'} =~ /fired/i ||
989 $info->{'Flash'} =~ /On/) {
990 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
991 push @parts, [ "Flash", 0 ];
993 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
994 push @parts, [ $info->{'Flash'}, 0 ];
998 return 0 if (scalar @parts == 0);
1000 # Find the required width
1004 for my $part (@parts) {
1007 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
1009 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
1012 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
1015 $th = $h if ($h > $th);
1018 return 0 if ($tw > $img->Get('columns'));
1021 my $y = $img->Get('rows') - 24;
1023 # Hit exact DCT blocks
1026 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
1027 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
1028 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
1029 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
1031 # Start writing out the text
1032 $x = ($img->Get('columns') - $tw) / 2;
1034 my $room = ($img->Get('rows') - 1 - $y - $th);
1035 $y = ($img->Get('rows') - 1) - $room/2;
1037 for my $part (@parts) {
1040 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
1042 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
1044 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
1045 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
1053 return $a if ($b == 0);
1054 return gcd($b, $a % $b);
1058 my ($r, $dbh, $id, $date, $desc) = @_;
1061 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
1062 push @errors, "Manglende eller ugyldig ID.";
1064 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
1065 push @errors, "Manglende eller ugyldig dato.";
1067 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
1068 push @errors, "Manglende eller ugyldig beskrivelse.";
1071 if (scalar @errors > 0) {
1075 my $vhost = $r->get_server_name;
1076 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
1077 undef, $id, $date, $desc, $vhost)
1078 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
1079 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
1081 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
1082 purge_cache($r, "/");
1092 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
1095 $decoded = Encode::decode("iso8859-1", $text);
1101 # Depending on your front-end cache, you might want to get creative somehow here.
1102 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
1103 # regex tacked onto a request into something useful. The elements given in
1104 # should not be regexes, though, as e.g. Squid will not be able to handle that.
1106 my ($r, @elements) = @_;
1107 return if (scalar @elements == 0);
1110 for my $elem (@elements) {
1111 $r->log->info("Purging $elem");
1112 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
1117 if (scalar @pe == 1) {
1120 $regex .= "(" . join('|', @pe) . ")";
1122 $regex .= "(\\?.*)?\$";
1123 $r->headers_out->{'X-Pr0n-Purge'} = $regex;
1126 # Find a list of all cache URLs for a given image, given what we have on disk.
1127 sub get_all_cache_urls {
1128 my ($r, $dbh, $id) = @_;
1129 my $dir = POSIX::floor($id / 256);
1132 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
1133 or die "Couldn't prepare: " . $dbh->errstr;
1135 or die "Couldn't find event and filename: " . $dbh->errstr;
1136 my $ref = $q->fetchrow_hashref;
1137 my $event = $ref->{'event'};
1138 my $filename = $ref->{'filename'};
1141 my $base = get_base($r) . "cache/$dir";
1142 for my $file (<$base/$id-*>) {
1143 my $fname = File::Basename::basename($file);
1144 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1145 # Mipmaps don't have an URL, ignore
1146 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1147 push @ret, "/$event/$filename";
1148 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1149 push @ret, "/$event/$1x$2/$filename";
1150 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1151 push @ret, "/$event/$1x$2/nobox/$filename";
1152 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1153 push @ret, "/$event/box/$filename";
1154 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1155 push @ret, "/$event/$1x$2/box/$filename";
1157 $r->log->warn("Couldn't find a purging URL for $fname");