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';
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
30 use Sesse::pr0n::Config;
32 require Sesse::pr0n::Config_local;
37 @EXPORT = qw(&error &dberror);
39 @EXPORT_OK = qw(&error &dberror);
41 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
42 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
43 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
44 our $mimetypes = new MIME::Types;
46 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
53 our ($dbh, $mimetypes);
56 my ($r,$err,$status,$title) = @_;
58 if (!defined($status) || !defined($title)) {
60 $title = "Internal server error";
63 $r->content_type('text/html; charset=utf-8');
67 $r->print(" <p>Error: $err</p>\n");
71 $r->log->error("Stack trace follows: " . Carp::longmess());
73 ModPerl::Util::exit();
78 error($r, "$err (DB error: " . $dbh->errstr . ")");
84 $r->content_type("text/html; charset=utf-8");
86 # Fetch quote if we're itk-bilder.samfundet.no
88 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
89 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
90 $quote = "Error: Could not fetch quotes." if (!defined($quote));
92 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
97 Sesse::pr0n::Templates::print_template($r, "footer",
98 { version => $Sesse::pr0n::Common::VERSION });
102 my ($width, $height, $thumbxres, $thumbyres) = @_;
104 unless ($thumbxres >= $width &&
105 $thumbyres >= $height) {
106 my $sfh = $width / $thumbxres;
107 my $sfv = $height / $thumbyres;
115 $width = POSIX::floor($width);
116 $height = POSIX::floor($height);
119 return ($width, $height);
122 sub get_query_string {
123 my ($param, $defparam) = @_;
127 while (my ($key, $value) = each %$param) {
128 next unless defined($value);
129 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
131 $str .= ($first) ? "?" : '&';
132 $str .= "$key=$value";
139 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
140 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
141 if (defined($accesskey) && length($accesskey) == 1) {
142 $str .= " accesskey=\"$accesskey\"";
144 $str .= ">$title</a>";
149 # Check that we are alive
150 if (!(defined($dbh) && $dbh->ping)) {
152 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
153 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
154 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
156 die "Couldn't connect to PostgreSQL database";
165 return $r->dir_config('ImageBase');
168 sub get_disk_location {
170 my $dir = POSIX::floor($id / 256);
171 return get_base($r) . "images/$dir/$id.jpg";
174 sub get_cache_location {
175 my ($r, $id, $width, $height, $infobox) = @_;
176 my $dir = POSIX::floor($id / 256);
179 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
181 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
185 sub update_width_height {
186 my ($r, $id, $width, $height) = @_;
188 # Also find the date taken if appropriate (from the EXIF tag etc.)
189 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
190 my $datetime = undef;
192 if (defined($info->{'DateTimeOriginal'})) {
193 # Parse the date and time over to ISO format
194 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
195 $datetime = "$1-$2-$3 $4:$5:$6";
199 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
200 undef, $width, $height, $datetime, $id)
201 or die "Couldn't update width/height in SQL: $!";
203 # update the last_picture cache as well (this should of course be done
204 # via a trigger, but this is less complicated :-) )
205 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
206 undef, $datetime, $id)
207 or die "Couldn't update last_picture in SQL: $!";
213 my $auth = $r->headers_in->{'authorization'};
214 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
215 $r->content_type('text/plain; charset=utf-8');
217 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
218 $r->print("Need authorization\n");
222 #return qw(sesse Sesse);
224 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
225 # WinXP is stupid :-)
226 if ($user =~ /^.*\\(.*)$/) {
231 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
235 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
239 $pass = Digest::SHA1::sha1_base64($pass);
240 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
241 undef, $user, $pass, $r->get_server_name);
242 if ($ref->{'auth'} != 1) {
243 $r->content_type('text/plain; charset=utf-8');
244 warn "No user exists, only $auth";
246 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
247 $r->print("Authorization failed");
248 $r->log->warn("Authentication failed for $user/$takenby");
252 $r->log->info("Authentication succeeded for $user/$takenby");
254 return ($user, $takenby);
258 my ($r, $event, $filename) = (@_);
259 my $ref = $dbh->selectrow_hashref(
260 'SELECT id FROM images WHERE event=? AND filename=?',
261 undef, $event, $filename);
262 if (!defined($ref)) {
263 return (undef, undef, undef);
265 return stat_image_from_id($r, $ref->{'id'});
268 sub stat_image_from_id {
271 my $fname = get_disk_location($r, $id);
272 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
273 or return (undef, undef, undef);
275 return ($fname, $size, $mtime);
279 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
281 my $fname = get_disk_location($r, $id);
282 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
286 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
287 if (! -r $cachename or (-M $cachename > -M $fname)) {
288 # If we are in overload mode (aka Slashdot mode), refuse to generate
290 if (Sesse::pr0n::Overload::is_in_overload($r)) {
291 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
292 error($r, 'System is in overload mode, not doing any scaling');
295 # Need to generate the cache; read in the image
296 my $magick = new Image::Magick;
297 my $info = Image::ExifTool::ImageInfo($fname);
299 # NEF files aren't autodetected
300 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
302 my $err = $magick->Read($fname);
304 $r->log->warn("$fname: $err");
308 error($r, "$fname: $err");
312 # If we use ->[0] unconditionally, text rendering (!) seems to crash
313 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
315 my $width = $img->Get('columns');
316 my $height = $img->Get('rows');
318 # Update the SQL database if it doesn't contain the required info
319 if ($dbwidth == -1 || $dbheight == -1) {
320 $r->log->info("Updating width/height for $id: $width x $height");
321 update_width_height($r, $id, $width, $height);
324 # We always want RGB JPEGs
325 if ($img->Get('Colorspace') eq "CMYK") {
326 $img->Set(colorspace=>'RGB');
329 while (defined($xres) && defined($yres)) {
330 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
331 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
334 if (defined($nxres) && defined($nyres)) {
335 # we have more resolutions to scale, so don't throw
337 $cimg = $img->Clone();
342 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
344 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
345 my $filter = 'Mitchell';
348 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
354 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
357 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
358 make_infobox($cimg, $info, $r);
361 # Strip EXIF tags etc.
364 $err = $cimg->write(filename=>$cachename, quality=>$quality);
368 ($xres, $yres) = ($nxres, $nyres);
370 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
376 $r->log->warn("$fname: $err");
380 error($r, "$fname: $err");
384 return ($cachename, 1);
387 sub get_mimetype_from_filename {
388 my $filename = shift;
389 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
390 $type = "image/jpeg" if (!defined($type));
395 my ($img, $info, $r) = @_;
398 my @classic_fields = ();
400 if (defined($info->{'DateTimeOriginal'}) &&
401 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
403 push @lines, "$1-$2-$3 $4:$5";
406 if (defined($info->{'Model'})) {
407 my $model = $info->{'Model'};
414 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
415 push @classic_fields, ($1 . "mm");
416 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
417 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
419 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
420 my ($a, $b) = ($1, $2);
421 my $gcd = gcd($a, $b);
422 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
424 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
427 push @classic_fields, (sprintf "f/%.0f", $f);
429 push @classic_fields, (sprintf "f/%.1f", $f);
431 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
432 my $f = $info->{'FNumber'};
434 push @classic_fields, (sprintf "f/%.0f", $f);
436 push @classic_fields, (sprintf "f/%.1f", $f);
440 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
442 if (defined($info->{'NikonD1-ISOSetting'})) {
443 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
444 } elsif (defined($info->{'ISOSetting'})) {
445 push @classic_fields, $info->{'ISOSetting'} . " ISO";
448 push @classic_fields, $info->{'ExposureBiasValue'} . " EV" if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0);
450 if (scalar @classic_fields > 0) {
451 push @lines, join(', ', @classic_fields);
454 if (defined($info->{'Flash'})) {
455 if ($info->{'Flash'} =~ /did not fire/i ||
456 $info->{'Flash'} =~ /no flash/i ||
457 $info->{'Flash'} =~ /not fired/i ||
458 $info->{'Flash'} =~ /Off/) {
459 push @lines, "No flash";
460 } elsif ($info->{'Flash'} =~ /fired/i ||
461 $info->{'Flash'} =~ /On/) {
462 push @lines, "Flash";
464 push @lines, $info->{'Flash'};
468 return if (scalar @lines == 0);
470 # OK, this sucks. Let's make something better :-)
471 @lines = ( join(" - ", @lines) );
473 # Find the required width
474 my $th = 14 * (scalar @lines) + 6;
477 for my $line (@lines) {
478 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
479 $tw = $this_w if ($this_w >= $tw);
484 # Round up so we hit exact DCT blocks
485 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
486 $th += 8 - ($th % 8) unless ($th % 8 == 0);
488 return if ($tw > $img->Get('columns'));
490 # my $x = $img->Get('columns') - 8 - $tw;
491 # my $y = $img->Get('rows') - 8 - $th;
493 my $y = $img->Get('rows') - $th;
494 $tw = $img->Get('columns');
499 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
500 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
501 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
502 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
503 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
505 my $i = -(scalar @lines - 1)/2.0;
506 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
507 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
508 #my $yc = ($y + $img->Get('rows'))/4;
509 my $yi = $th / (scalar @lines);
511 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
513 for my $line (@lines) {
514 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
515 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
516 x=>int($xc), y=>int($yc + $i * $yi));
524 return $a if ($b == 0);
525 return gcd($b, $a % $b);