1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Templates;
6 use Sesse::pr0n::Overload;
8 use Apache2::RequestRec (); # for $r->content_type
9 use Apache2::RequestIO (); # for $r->print
10 use Apache2::Const -compile => ':common';
31 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 use Sesse::pr0n::Config;
35 require Sesse::pr0n::Config_local;
40 @EXPORT = qw(&error &dberror);
42 @EXPORT_OK = qw(&error &dberror);
44 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
45 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
46 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
47 our $mimetypes = new MIME::Types;
49 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
56 our ($dbh, $mimetypes);
59 my ($r,$err,$status,$title) = @_;
61 if (!defined($status) || !defined($title)) {
63 $title = "Internal server error";
66 $r->content_type('text/html; charset=utf-8');
70 $r->print(" <p>Error: $err</p>\n");
74 $r->log->error("Stack trace follows: " . Carp::longmess());
76 ModPerl::Util::exit();
81 error($r, "$err (DB error: " . $dbh->errstr . ")");
87 $r->content_type("text/html; charset=utf-8");
89 # Fetch quote if we're itk-bilder.samfundet.no
91 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
92 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
93 $quote = "Error: Could not fetch quotes." if (!defined($quote));
95 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
100 Sesse::pr0n::Templates::print_template($r, "footer",
101 { version => $Sesse::pr0n::Common::VERSION });
105 my ($width, $height, $thumbxres, $thumbyres) = @_;
107 unless ($thumbxres >= $width &&
108 $thumbyres >= $height) {
109 my $sfh = $width / $thumbxres;
110 my $sfv = $height / $thumbyres;
118 $width = POSIX::floor($width);
119 $height = POSIX::floor($height);
122 return ($width, $height);
125 sub get_query_string {
126 my ($param, $defparam) = @_;
130 while (my ($key, $value) = each %$param) {
131 next unless defined($value);
132 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
134 $value = pretty_escape($value);
136 $str .= ($first) ? "?" : ';';
137 $str .= "$key=$value";
143 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
144 sub weird_space_encode {
147 return "_" x (length($val) * 2);
149 return "_" x (length($val) * 2 - 1);
153 sub weird_space_unencode {
155 if (length($val) % 2 == 0) {
156 return "_" x (length($val) / 2);
158 return " " x ((length($val) + 1) / 2);
165 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
166 $value = URI::Escape::uri_escape($value);
167 $value =~ s/%2F/\//g;
172 sub pretty_unescape {
175 # URI unescaping is already done for us
176 $value =~ s/(_+)/weird_space_unencode($1)/ge;
182 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
183 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
184 if (defined($accesskey) && length($accesskey) == 1) {
185 $str .= " accesskey=\"$accesskey\"";
187 $str .= ">$title</a>";
192 # Check that we are alive
193 if (!(defined($dbh) && $dbh->ping)) {
195 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
196 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
197 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
199 die "Couldn't connect to PostgreSQL database";
208 return $r->dir_config('ImageBase');
211 sub get_disk_location {
213 my $dir = POSIX::floor($id / 256);
214 return get_base($r) . "images/$dir/$id.jpg";
217 sub get_cache_location {
218 my ($r, $id, $width, $height, $infobox) = @_;
219 my $dir = POSIX::floor($id / 256);
222 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
224 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
228 sub update_image_info {
229 my ($r, $id, $width, $height) = @_;
231 # Also find the date taken if appropriate (from the EXIF tag etc.)
232 my $exiftool = Image::ExifTool->new;
233 $exiftool->ExtractInfo(get_disk_location($r, $id));
234 my $info = $exiftool->GetInfo();
235 my $datetime = undef;
237 if (defined($info->{'DateTimeOriginal'})) {
238 # Parse the date and time over to ISO format
239 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
240 $datetime = "$1-$2-$3 $4:$5:$6";
245 local $dbh->{AutoCommit} = 0;
248 $dbh->do('DELETE FROM exif_info WHERE image=?',
250 or die "Couldn't delete old EXIF information in SQL: $!";
252 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
253 or die "Couldn't prepare inserting EXIF information: $!";
255 for my $key (keys %$info) {
256 next if ref $info->{$key};
257 $q->execute($id, $key, guess_charset($info->{$key}))
258 or die "Couldn't insert EXIF information in database: $!";
262 my $model = $exiftool->GetValue('Model', 'PrintConv');
263 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
264 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
268 $model = undef if (length($model) == 0);
272 $lens = undef if (length($lens) == 0);
274 # Now update the main table with the information we've got
275 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
276 undef, $width, $height, $datetime, $model, $lens, $id)
277 or die "Couldn't update width/height in SQL: $!";
280 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
281 $dbh->do('DELETE FROM tags WHERE image=?',
283 or die "Couldn't delete old tag information in SQL: $!";
285 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
286 or die "Couldn't prepare inserting tag information: $!";
289 for my $tag (@tags) {
290 $q->execute($id, guess_charset($tag))
291 or die "Couldn't insert tag information in database: $!";
294 # update the last_picture cache as well (this should of course be done
295 # via a trigger, but this is less complicated :-) )
296 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
297 undef, $datetime, $id)
298 or die "Couldn't update last_picture in SQL: $!";
305 my $auth = $r->headers_in->{'authorization'};
306 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
307 $r->content_type('text/plain; charset=utf-8');
309 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
310 $r->print("Need authorization\n");
314 #return qw(sesse Sesse);
316 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
317 # WinXP is stupid :-)
318 if ($user =~ /^.*\\(.*)$/) {
323 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
327 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
331 $pass = Digest::SHA1::sha1_base64($pass);
332 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
333 undef, $user, $pass, $r->get_server_name);
334 if ($ref->{'auth'} != 1) {
335 $r->content_type('text/plain; charset=utf-8');
336 warn "No user exists, only $auth";
338 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
339 $r->print("Authorization failed");
340 $r->log->warn("Authentication failed for $user/$takenby");
344 $r->log->info("Authentication succeeded for $user/$takenby");
346 return ($user, $takenby);
350 my ($r, $event, $filename) = (@_);
351 my $ref = $dbh->selectrow_hashref(
352 'SELECT id FROM images WHERE event=? AND filename=?',
353 undef, $event, $filename);
354 if (!defined($ref)) {
355 return (undef, undef, undef);
357 return stat_image_from_id($r, $ref->{'id'});
360 sub stat_image_from_id {
363 my $fname = get_disk_location($r, $id);
364 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
365 or return (undef, undef, undef);
367 return ($fname, $size, $mtime);
371 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
373 my $fname = get_disk_location($r, $id);
374 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
378 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
379 if (! -r $cachename or (-M $cachename > -M $fname)) {
380 # If we are in overload mode (aka Slashdot mode), refuse to generate
382 if (Sesse::pr0n::Overload::is_in_overload($r)) {
383 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
384 error($r, 'System is in overload mode, not doing any scaling');
387 # Need to generate the cache; read in the image
388 my $magick = new Image::Magick;
389 my $info = Image::ExifTool::ImageInfo($fname);
392 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
393 # The delegate support is rather broken and causes very odd stuff to happen when
394 # more than one thread does this at the same time. Thus, we simply do it ourselves.
395 if ($filename =~ /\.nef$/i) {
396 # this would suffice if ImageMagick gets to fix their handling
397 # $fname = "NEF:$fname";
399 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
400 or error("dcraw: $!");
401 $err = $magick->Read(file => \*DCRAW);
404 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
405 # RGB is slightly faster (no colorspace conversion needed) and works equally
406 # well for our uses, as long as we don't need to draw an information box,
407 # which trickles several ImageMagick bugs related to colorspace handling.
408 # (Ideally we'd be able to keep the image subsampled and
409 # planar, but that would probably be difficult for ImageMagick to expose.)
411 $magick->Set(colorspace=>'YCbCr');
413 $err = $magick->Read($fname);
417 $r->log->warn("$fname: $err");
421 error($r, "$fname: $err");
425 # If we use ->[0] unconditionally, text rendering (!) seems to crash
426 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
428 my $width = $img->Get('columns');
429 my $height = $img->Get('rows');
431 # Update the SQL database if it doesn't contain the required info
432 if (!defined($dbwidth) || !defined($dbheight)) {
433 $r->log->info("Updating width/height for $id: $width x $height");
434 update_image_info($r, $id, $width, $height);
437 while (defined($xres) && defined($yres)) {
438 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
439 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
442 if (defined($nxres) && defined($nyres)) {
443 # we have more resolutions to scale, so don't throw
445 $cimg = $img->Clone();
450 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
452 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
453 my $filter = 'Mitchell';
457 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
464 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
467 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
468 make_infobox($cimg, $info, $r);
471 # Strip EXIF tags etc.
476 filename => $cachename,
479 if (($nwidth >= 640 && $nheight >= 480) ||
480 ($nwidth >= 480 && $nheight >= 640)) {
481 $parms{'interlace'} = 'Plane';
484 $parms{'sampling-factor'} = $sf;
486 $err = $cimg->write(%parms);
491 ($xres, $yres) = ($nxres, $nyres);
493 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
499 $r->log->warn("$fname: $err");
503 error($r, "$fname: $err");
507 return ($cachename, 1);
510 sub get_mimetype_from_filename {
511 my $filename = shift;
512 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
513 $type = "image/jpeg" if (!defined($type));
518 my ($img, $info, $r) = @_;
520 # The infobox is of the form
521 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
522 # possibly with some parts omitted -- the middle part is known as the "classic
523 # fields"; note the comma separation. Every field has an associated "bold flag"
524 # in the second part.
526 my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
527 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
528 my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
529 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
531 my @classic_fields = ();
532 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
533 push @classic_fields, [ $1 . "mm", 0 ];
534 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
535 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
538 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
539 my ($a, $b) = ($1, $2);
540 my $gcd = gcd($a, $b);
541 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
542 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
543 push @classic_fields, [ $1 . "s", $shutter_priority ];
546 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
549 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
551 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
553 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
554 my $f = $info->{'FNumber'};
556 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
558 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
562 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
565 if (defined($info->{'NikonD1-ISOSetting'})) {
566 $iso = $info->{'NikonD1-ISOSetting'};
567 } elsif (defined($info->{'ISO'})) {
568 $iso = $info->{'ISO'};
569 } elsif (defined($info->{'ISOSetting'})) {
570 $iso = $info->{'ISOSetting'};
572 if (defined($iso) && $iso =~ /(\d+)/) {
573 push @classic_fields, [ $1 . " ISO", 0 ];
576 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
577 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
578 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
579 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
582 # Now piece together the rest
585 if (defined($info->{'DateTimeOriginal'}) &&
586 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
588 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
591 if (defined($info->{'Model'})) {
592 my $model = $info->{'Model'};
596 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
597 push @parts, [ $model, 0 ];
601 if (scalar @classic_fields > 0) {
602 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
605 for my $field (@classic_fields) {
606 push @parts, [ ', ', 0 ] if (!$first_elem);
612 if (defined($info->{'Flash'})) {
613 if ($info->{'Flash'} =~ /did not fire/i ||
614 $info->{'Flash'} =~ /no flash/i ||
615 $info->{'Flash'} =~ /not fired/i ||
616 $info->{'Flash'} =~ /Off/) {
617 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
618 push @parts, [ "No flash", 0 ];
619 } elsif ($info->{'Flash'} =~ /fired/i ||
620 $info->{'Flash'} =~ /On/) {
621 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
622 push @parts, [ "Flash", 0 ];
624 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
625 push @parts, [ $info->{'Flash'}, 0 ];
629 return if (scalar @parts == 0);
631 # Find the required width
635 for my $part (@parts) {
638 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
640 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
643 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
646 $th = $h if ($h > $th);
649 return if ($tw > $img->Get('columns'));
652 my $y = $img->Get('rows') - 24;
654 # Hit exact DCT blocks
657 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
658 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
659 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
660 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
662 # Start writing out the text
663 $x = ($img->Get('columns') - $tw) / 2;
665 my $room = ($img->Get('rows') - 1 - $y - $th);
666 $y = ($img->Get('rows') - 1) - $room/2;
668 for my $part (@parts) {
671 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
673 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
675 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
676 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
682 return $a if ($b == 0);
683 return gcd($b, $a % $b);
687 my ($dbh, $id, $date, $desc, $vhost) = @_;
690 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
691 push @errors, "Manglende eller ugyldig ID.";
693 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
694 push @errors, "Manglende eller ugyldig dato.";
696 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
697 push @errors, "Manglende eller ugyldig beskrivelse.";
700 if (scalar @errors > 0) {
704 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
705 undef, $id, $date, $desc, $vhost)
706 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
707 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
709 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
719 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
722 $decoded = Encode::decode("iso8859-1", $text);