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 = URI::Escape::uri_escape($value);
136 # Unescape a few for prettiness (we'll need something for a real _, though)
138 $value =~ s/%2F/\//g;
140 $str .= ($first) ? "?" : ';';
141 $str .= "$key=$value";
148 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
149 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
150 if (defined($accesskey) && length($accesskey) == 1) {
151 $str .= " accesskey=\"$accesskey\"";
153 $str .= ">$title</a>";
158 # Check that we are alive
159 if (!(defined($dbh) && $dbh->ping)) {
161 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
162 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
163 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
165 die "Couldn't connect to PostgreSQL database";
174 return $r->dir_config('ImageBase');
177 sub get_disk_location {
179 my $dir = POSIX::floor($id / 256);
180 return get_base($r) . "images/$dir/$id.jpg";
183 sub get_cache_location {
184 my ($r, $id, $width, $height, $infobox) = @_;
185 my $dir = POSIX::floor($id / 256);
188 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
190 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
194 sub update_image_info {
195 my ($r, $id, $width, $height) = @_;
197 # Also find the date taken if appropriate (from the EXIF tag etc.)
198 my $exiftool = Image::ExifTool->new;
199 $exiftool->ExtractInfo(get_disk_location($r, $id));
200 my $info = $exiftool->GetInfo();
201 my $datetime = undef;
203 if (defined($info->{'DateTimeOriginal'})) {
204 # Parse the date and time over to ISO format
205 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
206 $datetime = "$1-$2-$3 $4:$5:$6";
211 local $dbh->{AutoCommit} = 0;
213 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
214 undef, $width, $height, $datetime, $id)
215 or die "Couldn't update width/height in SQL: $!";
218 $dbh->do('DELETE FROM exif_info WHERE image=?',
220 or die "Couldn't delete old EXIF information in SQL: $!";
222 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
223 or die "Couldn't prepare inserting EXIF information: $!";
225 for my $key (keys %$info) {
226 next if ref $info->{$key};
227 $q->execute($id, $key, guess_charset($info->{$key}))
228 or die "Couldn't insert EXIF information in database: $!";
232 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
233 $dbh->do('DELETE FROM tags WHERE image=?',
235 or die "Couldn't delete old tag information in SQL: $!";
237 my $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
238 or die "Couldn't prepare inserting tag information: $!";
240 for my $tag (@tags) {
241 $q->execute($id, guess_charset($tag))
242 or die "Couldn't insert tag information in database: $!";
245 # update the last_picture cache as well (this should of course be done
246 # via a trigger, but this is less complicated :-) )
247 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
248 undef, $datetime, $id)
249 or die "Couldn't update last_picture in SQL: $!";
256 my $auth = $r->headers_in->{'authorization'};
257 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
258 $r->content_type('text/plain; charset=utf-8');
260 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
261 $r->print("Need authorization\n");
265 #return qw(sesse Sesse);
267 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
268 # WinXP is stupid :-)
269 if ($user =~ /^.*\\(.*)$/) {
274 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
278 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
282 $pass = Digest::SHA1::sha1_base64($pass);
283 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
284 undef, $user, $pass, $r->get_server_name);
285 if ($ref->{'auth'} != 1) {
286 $r->content_type('text/plain; charset=utf-8');
287 warn "No user exists, only $auth";
289 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
290 $r->print("Authorization failed");
291 $r->log->warn("Authentication failed for $user/$takenby");
295 $r->log->info("Authentication succeeded for $user/$takenby");
297 return ($user, $takenby);
301 my ($r, $event, $filename) = (@_);
302 my $ref = $dbh->selectrow_hashref(
303 'SELECT id FROM images WHERE event=? AND filename=?',
304 undef, $event, $filename);
305 if (!defined($ref)) {
306 return (undef, undef, undef);
308 return stat_image_from_id($r, $ref->{'id'});
311 sub stat_image_from_id {
314 my $fname = get_disk_location($r, $id);
315 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
316 or return (undef, undef, undef);
318 return ($fname, $size, $mtime);
322 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
324 my $fname = get_disk_location($r, $id);
325 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
329 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
330 if (! -r $cachename or (-M $cachename > -M $fname)) {
331 # If we are in overload mode (aka Slashdot mode), refuse to generate
333 if (Sesse::pr0n::Overload::is_in_overload($r)) {
334 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
335 error($r, 'System is in overload mode, not doing any scaling');
338 # Need to generate the cache; read in the image
339 my $magick = new Image::Magick;
340 my $info = Image::ExifTool::ImageInfo($fname);
343 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
344 # The delegate support is rather broken and causes very odd stuff to happen when
345 # more than one thread does this at the same time. Thus, we simply do it ourselves.
346 if ($filename =~ /\.nef$/) {
347 # this would suffice if ImageMagick gets to fix their handling
348 # $fname = "NEF:$fname";
350 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
351 or error("dcraw: $!");
352 $err = $magick->Read(file => \*DCRAW);
355 $err = $magick->Read($fname);
359 $r->log->warn("$fname: $err");
363 error($r, "$fname: $err");
367 # If we use ->[0] unconditionally, text rendering (!) seems to crash
368 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
370 my $width = $img->Get('columns');
371 my $height = $img->Get('rows');
373 # Update the SQL database if it doesn't contain the required info
374 if ($dbwidth == -1 || $dbheight == -1) {
375 $r->log->info("Updating width/height for $id: $width x $height");
376 update_image_info($r, $id, $width, $height);
379 # We always want RGB JPEGs
380 if ($img->Get('Colorspace') eq "CMYK") {
381 $img->Set(colorspace=>'RGB');
384 while (defined($xres) && defined($yres)) {
385 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
386 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
389 if (defined($nxres) && defined($nyres)) {
390 # we have more resolutions to scale, so don't throw
392 $cimg = $img->Clone();
397 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
399 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
400 my $filter = 'Mitchell';
404 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
411 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
414 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
415 make_infobox($cimg, $info, $r);
418 # Strip EXIF tags etc.
423 filename => $cachename,
426 if (($nwidth >= 640 && $nheight >= 480) ||
427 ($nwidth >= 480 && $nheight >= 640)) {
428 $parms{'interlace'} = 'Plane';
431 $parms{'sampling-factor'} = $sf;
433 $err = $cimg->write(%parms);
438 ($xres, $yres) = ($nxres, $nyres);
440 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
446 $r->log->warn("$fname: $err");
450 error($r, "$fname: $err");
454 return ($cachename, 1);
457 sub get_mimetype_from_filename {
458 my $filename = shift;
459 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
460 $type = "image/jpeg" if (!defined($type));
465 my ($img, $info, $r) = @_;
468 my @classic_fields = ();
470 if (defined($info->{'DateTimeOriginal'}) &&
471 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
473 push @lines, "$1-$2-$3 $4:$5";
476 if (defined($info->{'Model'})) {
477 my $model = $info->{'Model'};
484 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
485 push @classic_fields, ($1 . "mm");
486 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
487 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
489 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
490 my ($a, $b) = ($1, $2);
491 my $gcd = gcd($a, $b);
492 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
493 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
494 push @classic_fields, ($1 . "s");
496 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
499 push @classic_fields, (sprintf "f/%.0f", $f);
501 push @classic_fields, (sprintf "f/%.1f", $f);
503 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
504 my $f = $info->{'FNumber'};
506 push @classic_fields, (sprintf "f/%.0f", $f);
508 push @classic_fields, (sprintf "f/%.1f", $f);
512 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
514 if (defined($info->{'NikonD1-ISOSetting'})) {
515 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
516 } elsif (defined($info->{'ISOSetting'})) {
517 push @classic_fields, $info->{'ISOSetting'} . " ISO";
520 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
521 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
522 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
523 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
526 if (scalar @classic_fields > 0) {
527 push @lines, join(', ', @classic_fields);
530 if (defined($info->{'Flash'})) {
531 if ($info->{'Flash'} =~ /did not fire/i ||
532 $info->{'Flash'} =~ /no flash/i ||
533 $info->{'Flash'} =~ /not fired/i ||
534 $info->{'Flash'} =~ /Off/) {
535 push @lines, "No flash";
536 } elsif ($info->{'Flash'} =~ /fired/i ||
537 $info->{'Flash'} =~ /On/) {
538 push @lines, "Flash";
540 push @lines, $info->{'Flash'};
544 return if (scalar @lines == 0);
546 # OK, this sucks. Let's make something better :-)
547 @lines = ( join(" - ", @lines) );
549 # Find the required width
550 my $th = 14 * (scalar @lines) + 6;
553 for my $line (@lines) {
554 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
555 $tw = $this_w if ($this_w >= $tw);
560 # Round up so we hit exact DCT blocks
561 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
562 $th += 8 - ($th % 8) unless ($th % 8 == 0);
564 return if ($tw > $img->Get('columns'));
566 # my $x = $img->Get('columns') - 8 - $tw;
567 # my $y = $img->Get('rows') - 8 - $th;
569 my $y = $img->Get('rows') - $th;
570 $tw = $img->Get('columns');
575 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
576 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
577 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
578 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
579 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
581 my $i = -(scalar @lines - 1)/2.0;
582 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
583 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
584 #my $yc = ($y + $img->Get('rows'))/4;
585 my $yi = $th / (scalar @lines);
587 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
589 for my $line (@lines) {
590 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
591 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
592 x=>int($xc), y=>int($yc + $i * $yi));
600 return $a if ($b == 0);
601 return gcd($b, $a % $b);
605 my ($dbh, $id, $date, $desc, $vhost) = @_;
608 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
609 push @errors, "Manglende eller ugyldig ID.";
611 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
612 push @errors, "Manglende eller ugyldig dato.";
614 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
615 push @errors, "Manglende eller ugyldig beskrivelse.";
618 if (scalar @errors > 0) {
622 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
623 undef, $id, $date, $desc, $vhost)
624 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
625 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
627 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
637 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
640 $decoded = Encode::decode("iso8859-1", $text);