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';
27 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
29 use Sesse::pr0n::Config;
31 require Sesse::pr0n::Config_local;
36 @EXPORT = qw(&error &dberror);
38 @EXPORT_OK = qw(&error &dberror);
40 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
41 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
42 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
43 our $mimetypes = new MIME::Types;
45 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
52 our ($dbh, $mimetypes);
55 my ($r,$err,$status,$title) = @_;
57 if (!defined($status) || !defined($title)) {
59 $title = "Internal server error";
62 $r->content_type('text/html; charset=utf-8');
66 $r->print(" <p>Error: $err</p>\n");
71 ModPerl::Util::exit();
76 error($r, "$err (DB error: " . $dbh->errstr . ")");
82 $r->content_type("text/html; charset=utf-8");
84 # Fetch quote if we're itk-bilder.samfundet.no
86 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
87 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
88 $quote = "Error: Could not fetch quotes." if (!defined($quote));
90 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
95 Sesse::pr0n::Templates::print_template($r, "footer",
96 { version => $Sesse::pr0n::Common::VERSION });
100 my ($width, $height, $thumbxres, $thumbyres) = @_;
102 unless ($thumbxres >= $width &&
103 $thumbyres >= $height) {
104 my $sfh = $width / $thumbxres;
105 my $sfv = $height / $thumbyres;
113 $width = POSIX::floor($width);
114 $height = POSIX::floor($height);
117 return ($width, $height);
120 sub get_query_string {
121 my ($param, $defparam) = @_;
125 while (my ($key, $value) = each %$param) {
126 next unless defined($value);
127 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
129 $str .= ($first) ? "?" : '&';
130 $str .= "$key=$value";
137 my ($r, $title, $baseurl, $param, $defparam) = @_;
138 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\">$title</a>";
143 # Check that we are alive
144 if (!(defined($dbh) && $dbh->ping)) {
146 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
147 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
148 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
150 die "Couldn't connect to PostgreSQL database";
159 return $r->dir_config('ImageBase');
162 sub get_disk_location {
164 my $dir = POSIX::floor($id / 256);
165 return get_base($r) . "images/$dir/$id.jpg";
168 sub get_cache_location {
169 my ($r, $id, $width, $height, $infobox) = @_;
170 my $dir = POSIX::floor($id / 256);
173 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
175 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
179 sub update_width_height {
180 my ($r, $id, $width, $height) = @_;
182 # Also find the date taken if appropriate (from the EXIF tag etc.)
183 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
184 my $datetime = undef;
186 if (defined($info->{'DateTimeOriginal'})) {
187 # Parse the date and time over to ISO format
188 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/ && $1 > 1990) {
189 $datetime = "$1-$2-$3 $4:$5:$6";
193 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
194 undef, $width, $height, $datetime, $id)
195 or die "Couldn't update width/height in SQL: $!";
197 # update the last_picture cache as well (this should of course be done
198 # via a trigger, but this is less complicated :-) )
199 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
200 undef, $datetime, $id)
201 or die "Couldn't update last_picture in SQL: $!";
207 my $auth = $r->headers_in->{'authorization'};
208 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
209 $r->content_type('text/plain; charset=utf-8');
211 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
212 $r->print("Need authorization\n");
216 #return qw(sesse Sesse);
218 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
219 # WinXP is stupid :-)
220 if ($user =~ /^.*\\(.*)$/) {
225 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
229 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
233 $pass = Digest::SHA1::sha1_base64($pass);
234 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
235 undef, $user, $pass, $r->get_server_name);
236 if ($ref->{'auth'} != 1) {
237 $r->content_type('text/plain; charset=utf-8');
238 warn "No user exists, only $auth";
240 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
241 $r->print("Authorization failed");
242 $r->log->warn("Authentication failed for $user/$takenby");
246 $r->log->info("Authentication succeeded for $user/$takenby");
248 return ($user, $takenby);
252 my ($r, $event, $filename) = (@_);
253 my $ref = $dbh->selectrow_hashref(
254 'SELECT id FROM images WHERE event=? AND filename=?',
255 undef, $event, $filename);
256 if (!defined($ref)) {
257 return (undef, undef, undef);
259 return stat_image_from_id($r, $ref->{'id'});
262 sub stat_image_from_id {
265 my $fname = get_disk_location($r, $id);
266 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
267 or return (undef, undef, undef);
269 return ($fname, $size, $mtime);
273 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
275 my $fname = get_disk_location($r, $id);
276 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
280 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
281 if (! -r $cachename or (-M $cachename > -M $fname)) {
282 # If we are in overload mode (aka Slashdot mode), refuse to generate
284 if (Sesse::pr0n::Overload::is_in_overload($r)) {
285 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
286 error($r, 'System is in overload mode, not doing any scaling');
289 # Need to generate the cache; read in the image
290 my $magick = new Image::Magick;
291 my $info = Image::ExifTool::ImageInfo($fname);
293 # NEF files aren't autodetected
294 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
296 my $err = $magick->Read($fname);
298 $r->log->warn("$fname: $err");
302 error($r, "$fname: $err");
306 # If we use ->[0] unconditionally, text rendering (!) seems to crash
307 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
309 my $width = $img->Get('columns');
310 my $height = $img->Get('rows');
312 # Update the SQL database if it doesn't contain the required info
313 if ($dbwidth == -1 || $dbheight == -1) {
314 $r->log->info("Updating width/height for $id: $width x $height");
315 update_width_height($r, $id, $width, $height);
318 # We always want RGB JPEGs
319 if ($img->Get('Colorspace') eq "CMYK") {
320 $img->Set(colorspace=>'RGB');
323 while (defined($xres) && defined($yres)) {
324 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
325 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
328 if (defined($nxres) && defined($nyres)) {
329 # we have more resolutions to scale, so don't throw
331 $cimg = $img->Clone();
336 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
338 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
339 my $filter = 'Mitchell';
342 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
348 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
351 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
352 make_infobox($cimg, $info, $r);
355 # Strip EXIF tags etc.
358 $err = $cimg->write(filename=>$cachename, quality=>$quality);
362 ($xres, $yres) = ($nxres, $nyres);
364 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
370 $r->log->warn("$fname: $err");
374 error($r, "$fname: $err");
378 return ($cachename, 1);
381 sub get_mimetype_from_filename {
382 my $filename = shift;
383 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
384 $type = "image/jpeg" if (!defined($type));
389 my ($img, $info, $r) = @_;
392 my @classic_fields = ();
394 if (defined($info->{'DateTimeOriginal'}) &&
395 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
397 push @lines, "$1-$2-$3 $4:$5";
400 if (defined($info->{'Model'})) {
401 my $model = $info->{'Model'};
408 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
409 push @classic_fields, ($1 . "mm");
410 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
411 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
413 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
414 my ($a, $b) = ($1, $2);
415 my $gcd = gcd($a, $b);
416 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
418 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
421 push @classic_fields, (sprintf "f/%.0f", $f);
423 push @classic_fields, (sprintf "f/%.1f", $f);
425 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
426 my $f = $info->{'FNumber'};
428 push @classic_fields, (sprintf "f/%.0f", $f);
430 push @classic_fields, (sprintf "f/%.1f", $f);
434 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
436 if (defined($info->{'NikonD1-ISOSetting'})) {
437 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
438 } elsif (defined($info->{'ISOSetting'})) {
439 push @classic_fields, $info->{'ISOSetting'} . " ISO";
442 push @classic_fields, $info->{'ExposureBiasValue'} . " EV" if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0);
444 if (scalar @classic_fields > 0) {
445 push @lines, join(', ', @classic_fields);
448 if (defined($info->{'Flash'})) {
449 if ($info->{'Flash'} =~ /did not fire/i ||
450 $info->{'Flash'} =~ /no flash/i ||
451 $info->{'Flash'} =~ /not fired/i ||
452 $info->{'Flash'} =~ /Off/) {
453 push @lines, "No flash";
454 } elsif ($info->{'Flash'} =~ /fired/i ||
455 $info->{'Flash'} =~ /On/) {
456 push @lines, "Flash";
458 push @lines, $info->{'Flash'};
462 return if (scalar @lines == 0);
464 # OK, this sucks. Let's make something better :-)
465 @lines = ( join(" - ", @lines) );
467 # Find the required width
468 my $th = 14 * (scalar @lines) + 6;
471 for my $line (@lines) {
472 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
473 $tw = $this_w if ($this_w >= $tw);
478 # Round up so we hit exact DCT blocks
479 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
480 $th += 8 - ($th % 8) unless ($th % 8 == 0);
482 return if ($tw > $img->Get('columns'));
484 # my $x = $img->Get('columns') - 8 - $tw;
485 # my $y = $img->Get('rows') - 8 - $th;
487 my $y = $img->Get('rows') - $th;
488 $tw = $img->Get('columns');
493 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
494 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
495 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
496 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
497 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
499 my $i = -(scalar @lines - 1)/2.0;
500 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
501 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
502 #my $yc = ($y + $img->Get('rows'))/4;
503 my $yi = $th / (scalar @lines);
505 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
507 for my $line (@lines) {
508 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
509 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
510 x=>int($xc), y=>int($yc + $i * $yi));
518 return $a if ($b == 0);
519 return gcd($b, $a % $b);