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";
146 $value = URI::Escape::uri_escape($value);
148 # Unescape a few for prettiness (we'll need something for a real _, though)
150 $value =~ s/%2F/\//g;
155 sub pretty_unescape {
158 # URI unescaping is already done for us
165 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
166 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
167 if (defined($accesskey) && length($accesskey) == 1) {
168 $str .= " accesskey=\"$accesskey\"";
170 $str .= ">$title</a>";
175 # Check that we are alive
176 if (!(defined($dbh) && $dbh->ping)) {
178 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
179 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
180 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
182 die "Couldn't connect to PostgreSQL database";
191 return $r->dir_config('ImageBase');
194 sub get_disk_location {
196 my $dir = POSIX::floor($id / 256);
197 return get_base($r) . "images/$dir/$id.jpg";
200 sub get_cache_location {
201 my ($r, $id, $width, $height, $infobox) = @_;
202 my $dir = POSIX::floor($id / 256);
205 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
207 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
211 sub update_image_info {
212 my ($r, $id, $width, $height) = @_;
214 # Also find the date taken if appropriate (from the EXIF tag etc.)
215 my $exiftool = Image::ExifTool->new;
216 $exiftool->ExtractInfo(get_disk_location($r, $id));
217 my $info = $exiftool->GetInfo();
218 my $datetime = undef;
220 if (defined($info->{'DateTimeOriginal'})) {
221 # Parse the date and time over to ISO format
222 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
223 $datetime = "$1-$2-$3 $4:$5:$6";
228 local $dbh->{AutoCommit} = 0;
230 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
231 undef, $width, $height, $datetime, $id)
232 or die "Couldn't update width/height in SQL: $!";
235 $dbh->do('DELETE FROM exif_info WHERE image=?',
237 or die "Couldn't delete old EXIF information in SQL: $!";
239 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
240 or die "Couldn't prepare inserting EXIF information: $!";
242 for my $key (keys %$info) {
243 next if ref $info->{$key};
244 $q->execute($id, $key, guess_charset($info->{$key}))
245 or die "Couldn't insert EXIF information in database: $!";
249 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
250 $dbh->do('DELETE FROM tags WHERE image=?',
252 or die "Couldn't delete old tag information in SQL: $!";
254 my $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
255 or die "Couldn't prepare inserting tag information: $!";
257 for my $tag (@tags) {
258 $q->execute($id, guess_charset($tag))
259 or die "Couldn't insert tag information in database: $!";
262 # update the last_picture cache as well (this should of course be done
263 # via a trigger, but this is less complicated :-) )
264 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
265 undef, $datetime, $id)
266 or die "Couldn't update last_picture in SQL: $!";
273 my $auth = $r->headers_in->{'authorization'};
274 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
275 $r->content_type('text/plain; charset=utf-8');
277 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
278 $r->print("Need authorization\n");
282 #return qw(sesse Sesse);
284 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
285 # WinXP is stupid :-)
286 if ($user =~ /^.*\\(.*)$/) {
291 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
295 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
299 $pass = Digest::SHA1::sha1_base64($pass);
300 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
301 undef, $user, $pass, $r->get_server_name);
302 if ($ref->{'auth'} != 1) {
303 $r->content_type('text/plain; charset=utf-8');
304 warn "No user exists, only $auth";
306 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
307 $r->print("Authorization failed");
308 $r->log->warn("Authentication failed for $user/$takenby");
312 $r->log->info("Authentication succeeded for $user/$takenby");
314 return ($user, $takenby);
318 my ($r, $event, $filename) = (@_);
319 my $ref = $dbh->selectrow_hashref(
320 'SELECT id FROM images WHERE event=? AND filename=?',
321 undef, $event, $filename);
322 if (!defined($ref)) {
323 return (undef, undef, undef);
325 return stat_image_from_id($r, $ref->{'id'});
328 sub stat_image_from_id {
331 my $fname = get_disk_location($r, $id);
332 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
333 or return (undef, undef, undef);
335 return ($fname, $size, $mtime);
339 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
341 my $fname = get_disk_location($r, $id);
342 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
346 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
347 if (! -r $cachename or (-M $cachename > -M $fname)) {
348 # If we are in overload mode (aka Slashdot mode), refuse to generate
350 if (Sesse::pr0n::Overload::is_in_overload($r)) {
351 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
352 error($r, 'System is in overload mode, not doing any scaling');
355 # Need to generate the cache; read in the image
356 my $magick = new Image::Magick;
357 my $info = Image::ExifTool::ImageInfo($fname);
360 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
361 # The delegate support is rather broken and causes very odd stuff to happen when
362 # more than one thread does this at the same time. Thus, we simply do it ourselves.
363 if ($filename =~ /\.nef$/) {
364 # this would suffice if ImageMagick gets to fix their handling
365 # $fname = "NEF:$fname";
367 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
368 or error("dcraw: $!");
369 $err = $magick->Read(file => \*DCRAW);
372 $err = $magick->Read($fname);
376 $r->log->warn("$fname: $err");
380 error($r, "$fname: $err");
384 # If we use ->[0] unconditionally, text rendering (!) seems to crash
385 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
387 my $width = $img->Get('columns');
388 my $height = $img->Get('rows');
390 # Update the SQL database if it doesn't contain the required info
391 if ($dbwidth == -1 || $dbheight == -1) {
392 $r->log->info("Updating width/height for $id: $width x $height");
393 update_image_info($r, $id, $width, $height);
396 # We always want RGB JPEGs
397 if ($img->Get('Colorspace') eq "CMYK") {
398 $img->Set(colorspace=>'RGB');
401 while (defined($xres) && defined($yres)) {
402 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
403 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
406 if (defined($nxres) && defined($nyres)) {
407 # we have more resolutions to scale, so don't throw
409 $cimg = $img->Clone();
414 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
416 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
417 my $filter = 'Mitchell';
421 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
428 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
431 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
432 make_infobox($cimg, $info, $r);
435 # Strip EXIF tags etc.
440 filename => $cachename,
443 if (($nwidth >= 640 && $nheight >= 480) ||
444 ($nwidth >= 480 && $nheight >= 640)) {
445 $parms{'interlace'} = 'Plane';
448 $parms{'sampling-factor'} = $sf;
450 $err = $cimg->write(%parms);
455 ($xres, $yres) = ($nxres, $nyres);
457 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
463 $r->log->warn("$fname: $err");
467 error($r, "$fname: $err");
471 return ($cachename, 1);
474 sub get_mimetype_from_filename {
475 my $filename = shift;
476 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
477 $type = "image/jpeg" if (!defined($type));
482 my ($img, $info, $r) = @_;
485 my @classic_fields = ();
487 if (defined($info->{'DateTimeOriginal'}) &&
488 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
490 push @lines, "$1-$2-$3 $4:$5";
493 if (defined($info->{'Model'})) {
494 my $model = $info->{'Model'};
501 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
502 push @classic_fields, ($1 . "mm");
503 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
504 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
506 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
507 my ($a, $b) = ($1, $2);
508 my $gcd = gcd($a, $b);
509 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
510 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
511 push @classic_fields, ($1 . "s");
513 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
516 push @classic_fields, (sprintf "f/%.0f", $f);
518 push @classic_fields, (sprintf "f/%.1f", $f);
520 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
521 my $f = $info->{'FNumber'};
523 push @classic_fields, (sprintf "f/%.0f", $f);
525 push @classic_fields, (sprintf "f/%.1f", $f);
529 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
531 if (defined($info->{'NikonD1-ISOSetting'})) {
532 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
533 } elsif (defined($info->{'ISOSetting'})) {
534 push @classic_fields, $info->{'ISOSetting'} . " ISO";
537 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
538 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
539 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
540 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
543 if (scalar @classic_fields > 0) {
544 push @lines, join(', ', @classic_fields);
547 if (defined($info->{'Flash'})) {
548 if ($info->{'Flash'} =~ /did not fire/i ||
549 $info->{'Flash'} =~ /no flash/i ||
550 $info->{'Flash'} =~ /not fired/i ||
551 $info->{'Flash'} =~ /Off/) {
552 push @lines, "No flash";
553 } elsif ($info->{'Flash'} =~ /fired/i ||
554 $info->{'Flash'} =~ /On/) {
555 push @lines, "Flash";
557 push @lines, $info->{'Flash'};
561 return if (scalar @lines == 0);
563 # OK, this sucks. Let's make something better :-)
564 @lines = ( join(" - ", @lines) );
566 # Find the required width
567 my $th = 14 * (scalar @lines) + 6;
570 for my $line (@lines) {
571 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
572 $tw = $this_w if ($this_w >= $tw);
577 # Round up so we hit exact DCT blocks
578 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
579 $th += 8 - ($th % 8) unless ($th % 8 == 0);
581 return if ($tw > $img->Get('columns'));
583 # my $x = $img->Get('columns') - 8 - $tw;
584 # my $y = $img->Get('rows') - 8 - $th;
586 my $y = $img->Get('rows') - $th;
587 $tw = $img->Get('columns');
592 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
593 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
594 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
595 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
596 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
598 my $i = -(scalar @lines - 1)/2.0;
599 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
600 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
601 #my $yc = ($y + $img->Get('rows'))/4;
602 my $yi = $th / (scalar @lines);
604 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
606 for my $line (@lines) {
607 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
608 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
609 x=>int($xc), y=>int($yc + $i * $yi));
617 return $a if ($b == 0);
618 return gcd($b, $a % $b);
622 my ($dbh, $id, $date, $desc, $vhost) = @_;
625 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
626 push @errors, "Manglende eller ugyldig ID.";
628 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
629 push @errors, "Manglende eller ugyldig dato.";
631 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
632 push @errors, "Manglende eller ugyldig beskrivelse.";
635 if (scalar @errors > 0) {
639 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
640 undef, $id, $date, $desc, $vhost)
641 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
642 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
644 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
654 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
657 $decoded = Encode::decode("iso8859-1", $text);