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';
30 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
32 use Sesse::pr0n::Config;
34 require Sesse::pr0n::Config_local;
39 @EXPORT = qw(&error &dberror);
41 @EXPORT_OK = qw(&error &dberror);
43 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
44 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
45 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
46 our $mimetypes = new MIME::Types;
48 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
55 our ($dbh, $mimetypes);
58 my ($r,$err,$status,$title) = @_;
60 if (!defined($status) || !defined($title)) {
62 $title = "Internal server error";
65 $r->content_type('text/html; charset=utf-8');
69 $r->print(" <p>Error: $err</p>\n");
73 $r->log->error("Stack trace follows: " . Carp::longmess());
75 ModPerl::Util::exit();
80 error($r, "$err (DB error: " . $dbh->errstr . ")");
86 $r->content_type("text/html; charset=utf-8");
88 # Fetch quote if we're itk-bilder.samfundet.no
90 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
91 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
92 $quote = "Error: Could not fetch quotes." if (!defined($quote));
94 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
99 Sesse::pr0n::Templates::print_template($r, "footer",
100 { version => $Sesse::pr0n::Common::VERSION });
104 my ($width, $height, $thumbxres, $thumbyres) = @_;
106 unless ($thumbxres >= $width &&
107 $thumbyres >= $height) {
108 my $sfh = $width / $thumbxres;
109 my $sfv = $height / $thumbyres;
117 $width = POSIX::floor($width);
118 $height = POSIX::floor($height);
121 return ($width, $height);
124 sub get_query_string {
125 my ($param, $defparam) = @_;
129 while (my ($key, $value) = each %$param) {
130 next unless defined($value);
131 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
133 $str .= ($first) ? "?" : ';';
134 $str .= "$key=$value";
141 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
142 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
143 if (defined($accesskey) && length($accesskey) == 1) {
144 $str .= " accesskey=\"$accesskey\"";
146 $str .= ">$title</a>";
151 # Check that we are alive
152 if (!(defined($dbh) && $dbh->ping)) {
154 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
155 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
156 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
158 die "Couldn't connect to PostgreSQL database";
167 return $r->dir_config('ImageBase');
170 sub get_disk_location {
172 my $dir = POSIX::floor($id / 256);
173 return get_base($r) . "images/$dir/$id.jpg";
176 sub get_cache_location {
177 my ($r, $id, $width, $height, $infobox) = @_;
178 my $dir = POSIX::floor($id / 256);
181 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
183 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
187 sub update_image_info {
188 my ($r, $id, $width, $height) = @_;
190 # Also find the date taken if appropriate (from the EXIF tag etc.)
191 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
192 my $datetime = undef;
194 if (defined($info->{'DateTimeOriginal'})) {
195 # Parse the date and time over to ISO format
196 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
197 $datetime = "$1-$2-$3 $4:$5:$6";
202 local $dbh->{AutoCommit} = 0;
204 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
205 undef, $width, $height, $datetime, $id)
206 or die "Couldn't update width/height in SQL: $!";
208 $dbh->do('DELETE FROM exif_info WHERE image=?',
210 or die "Couldn't delete old EXIF information in SQL: $!";
212 my $q = $dbh->prepare('INSERT INTO exif_info (image,tag,value) VALUES (?,?,?)')
213 or die "Couldn't prepare inserting EXIF information: $!";
215 for my $key (keys %$info) {
216 next if ref $info->{$key};
217 $q->execute($id, $key, guess_charset($info->{$key}))
218 or die "Couldn't insert EXIF information in database: $!";
221 # update the last_picture cache as well (this should of course be done
222 # via a trigger, but this is less complicated :-) )
223 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
224 undef, $datetime, $id)
225 or die "Couldn't update last_picture in SQL: $!";
232 my $auth = $r->headers_in->{'authorization'};
233 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
234 $r->content_type('text/plain; charset=utf-8');
236 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
237 $r->print("Need authorization\n");
241 #return qw(sesse Sesse);
243 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
244 # WinXP is stupid :-)
245 if ($user =~ /^.*\\(.*)$/) {
250 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
254 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
258 $pass = Digest::SHA1::sha1_base64($pass);
259 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
260 undef, $user, $pass, $r->get_server_name);
261 if ($ref->{'auth'} != 1) {
262 $r->content_type('text/plain; charset=utf-8');
263 warn "No user exists, only $auth";
265 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
266 $r->print("Authorization failed");
267 $r->log->warn("Authentication failed for $user/$takenby");
271 $r->log->info("Authentication succeeded for $user/$takenby");
273 return ($user, $takenby);
277 my ($r, $event, $filename) = (@_);
278 my $ref = $dbh->selectrow_hashref(
279 'SELECT id FROM images WHERE event=? AND filename=?',
280 undef, $event, $filename);
281 if (!defined($ref)) {
282 return (undef, undef, undef);
284 return stat_image_from_id($r, $ref->{'id'});
287 sub stat_image_from_id {
290 my $fname = get_disk_location($r, $id);
291 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
292 or return (undef, undef, undef);
294 return ($fname, $size, $mtime);
298 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
300 my $fname = get_disk_location($r, $id);
301 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
305 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
306 if (! -r $cachename or (-M $cachename > -M $fname)) {
307 # If we are in overload mode (aka Slashdot mode), refuse to generate
309 if (Sesse::pr0n::Overload::is_in_overload($r)) {
310 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
311 error($r, 'System is in overload mode, not doing any scaling');
314 # Need to generate the cache; read in the image
315 my $magick = new Image::Magick;
316 my $info = Image::ExifTool::ImageInfo($fname);
318 # NEF files aren't autodetected
319 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
321 my $err = $magick->Read($fname);
323 $r->log->warn("$fname: $err");
327 error($r, "$fname: $err");
331 # If we use ->[0] unconditionally, text rendering (!) seems to crash
332 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
334 my $width = $img->Get('columns');
335 my $height = $img->Get('rows');
337 # Update the SQL database if it doesn't contain the required info
338 if ($dbwidth == -1 || $dbheight == -1) {
339 $r->log->info("Updating width/height for $id: $width x $height");
340 update_image_info($r, $id, $width, $height);
343 # We always want RGB JPEGs
344 if ($img->Get('Colorspace') eq "CMYK") {
345 $img->Set(colorspace=>'RGB');
348 while (defined($xres) && defined($yres)) {
349 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
350 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
353 if (defined($nxres) && defined($nyres)) {
354 # we have more resolutions to scale, so don't throw
356 $cimg = $img->Clone();
361 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
363 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
364 my $filter = 'Mitchell';
367 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
373 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
376 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
377 make_infobox($cimg, $info, $r);
380 # Strip EXIF tags etc.
383 if (($nwidth >= 640 && $nheight >= 480) ||
384 ($nwidth >= 480 && $nheight >= 640)) {
385 $err = $cimg->write(filename=>$cachename, quality=>$quality, interlace=>'Plane');
387 $err = $cimg->write(filename=>$cachename, quality=>$quality);
392 ($xres, $yres) = ($nxres, $nyres);
394 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
400 $r->log->warn("$fname: $err");
404 error($r, "$fname: $err");
408 return ($cachename, 1);
411 sub get_mimetype_from_filename {
412 my $filename = shift;
413 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
414 $type = "image/jpeg" if (!defined($type));
419 my ($img, $info, $r) = @_;
422 my @classic_fields = ();
424 if (defined($info->{'DateTimeOriginal'}) &&
425 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
427 push @lines, "$1-$2-$3 $4:$5";
430 if (defined($info->{'Model'})) {
431 my $model = $info->{'Model'};
438 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
439 push @classic_fields, ($1 . "mm");
440 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
441 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
443 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
444 my ($a, $b) = ($1, $2);
445 my $gcd = gcd($a, $b);
446 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
447 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
448 push @classic_fields, ($1 . "s");
450 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
453 push @classic_fields, (sprintf "f/%.0f", $f);
455 push @classic_fields, (sprintf "f/%.1f", $f);
457 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
458 my $f = $info->{'FNumber'};
460 push @classic_fields, (sprintf "f/%.0f", $f);
462 push @classic_fields, (sprintf "f/%.1f", $f);
466 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
468 if (defined($info->{'NikonD1-ISOSetting'})) {
469 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
470 } elsif (defined($info->{'ISOSetting'})) {
471 push @classic_fields, $info->{'ISOSetting'} . " ISO";
474 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
475 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
476 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
477 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
480 if (scalar @classic_fields > 0) {
481 push @lines, join(', ', @classic_fields);
484 if (defined($info->{'Flash'})) {
485 if ($info->{'Flash'} =~ /did not fire/i ||
486 $info->{'Flash'} =~ /no flash/i ||
487 $info->{'Flash'} =~ /not fired/i ||
488 $info->{'Flash'} =~ /Off/) {
489 push @lines, "No flash";
490 } elsif ($info->{'Flash'} =~ /fired/i ||
491 $info->{'Flash'} =~ /On/) {
492 push @lines, "Flash";
494 push @lines, $info->{'Flash'};
498 return if (scalar @lines == 0);
500 # OK, this sucks. Let's make something better :-)
501 @lines = ( join(" - ", @lines) );
503 # Find the required width
504 my $th = 14 * (scalar @lines) + 6;
507 for my $line (@lines) {
508 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
509 $tw = $this_w if ($this_w >= $tw);
514 # Round up so we hit exact DCT blocks
515 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
516 $th += 8 - ($th % 8) unless ($th % 8 == 0);
518 return if ($tw > $img->Get('columns'));
520 # my $x = $img->Get('columns') - 8 - $tw;
521 # my $y = $img->Get('rows') - 8 - $th;
523 my $y = $img->Get('rows') - $th;
524 $tw = $img->Get('columns');
529 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
530 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
531 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
532 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
533 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
535 my $i = -(scalar @lines - 1)/2.0;
536 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
537 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
538 #my $yc = ($y + $img->Get('rows'))/4;
539 my $yi = $th / (scalar @lines);
541 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
543 for my $line (@lines) {
544 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
545 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
546 x=>int($xc), y=>int($yc + $i * $yi));
554 return $a if ($b == 0);
555 return gcd($b, $a % $b);
559 my ($dbh, $id, $date, $desc, $vhost) = @_;
562 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
563 push @errors, "Manglende eller ugyldig ID.";
565 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
566 push @errors, "Manglende eller ugyldig dato.";
568 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
569 push @errors, "Manglende eller ugyldig beskrivelse.";
572 if (scalar @errors > 0) {
576 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
577 undef, $id, $date, $desc, $vhost)
578 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
579 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
581 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
591 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
594 $decoded = Encode::decode("iso8859-1", $text);