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';
29 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
31 use Sesse::pr0n::Config;
33 require Sesse::pr0n::Config_local;
38 @EXPORT = qw(&error &dberror);
40 @EXPORT_OK = qw(&error &dberror);
42 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
43 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
44 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
45 our $mimetypes = new MIME::Types;
47 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
54 our ($dbh, $mimetypes);
57 my ($r,$err,$status,$title) = @_;
59 if (!defined($status) || !defined($title)) {
61 $title = "Internal server error";
64 $r->content_type('text/html; charset=utf-8');
68 $r->print(" <p>Error: $err</p>\n");
72 $r->log->error("Stack trace follows: " . Carp::longmess());
74 ModPerl::Util::exit();
79 error($r, "$err (DB error: " . $dbh->errstr . ")");
85 $r->content_type("text/html; charset=utf-8");
87 # Fetch quote if we're itk-bilder.samfundet.no
89 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
90 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
91 $quote = "Error: Could not fetch quotes." if (!defined($quote));
93 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
98 Sesse::pr0n::Templates::print_template($r, "footer",
99 { version => $Sesse::pr0n::Common::VERSION });
103 my ($width, $height, $thumbxres, $thumbyres) = @_;
105 unless ($thumbxres >= $width &&
106 $thumbyres >= $height) {
107 my $sfh = $width / $thumbxres;
108 my $sfv = $height / $thumbyres;
116 $width = POSIX::floor($width);
117 $height = POSIX::floor($height);
120 return ($width, $height);
123 sub get_query_string {
124 my ($param, $defparam) = @_;
128 while (my ($key, $value) = each %$param) {
129 next unless defined($value);
130 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
132 $str .= ($first) ? "?" : ';';
133 $str .= "$key=$value";
140 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
141 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
142 if (defined($accesskey) && length($accesskey) == 1) {
143 $str .= " accesskey=\"$accesskey\"";
145 $str .= ">$title</a>";
150 # Check that we are alive
151 if (!(defined($dbh) && $dbh->ping)) {
153 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
154 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
155 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
157 die "Couldn't connect to PostgreSQL database";
166 return $r->dir_config('ImageBase');
169 sub get_disk_location {
171 my $dir = POSIX::floor($id / 256);
172 return get_base($r) . "images/$dir/$id.jpg";
175 sub get_cache_location {
176 my ($r, $id, $width, $height, $infobox) = @_;
177 my $dir = POSIX::floor($id / 256);
180 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
182 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
186 sub update_width_height {
187 my ($r, $id, $width, $height) = @_;
189 # Also find the date taken if appropriate (from the EXIF tag etc.)
190 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
191 my $datetime = undef;
193 if (defined($info->{'DateTimeOriginal'})) {
194 # Parse the date and time over to ISO format
195 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
196 $datetime = "$1-$2-$3 $4:$5:$6";
200 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
201 undef, $width, $height, $datetime, $id)
202 or die "Couldn't update width/height in SQL: $!";
204 # update the last_picture cache as well (this should of course be done
205 # via a trigger, but this is less complicated :-) )
206 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
207 undef, $datetime, $id)
208 or die "Couldn't update last_picture in SQL: $!";
214 my $auth = $r->headers_in->{'authorization'};
215 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
216 $r->content_type('text/plain; charset=utf-8');
218 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
219 $r->print("Need authorization\n");
223 #return qw(sesse Sesse);
225 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
226 # WinXP is stupid :-)
227 if ($user =~ /^.*\\(.*)$/) {
232 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
236 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
240 $pass = Digest::SHA1::sha1_base64($pass);
241 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
242 undef, $user, $pass, $r->get_server_name);
243 if ($ref->{'auth'} != 1) {
244 $r->content_type('text/plain; charset=utf-8');
245 warn "No user exists, only $auth";
247 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
248 $r->print("Authorization failed");
249 $r->log->warn("Authentication failed for $user/$takenby");
253 $r->log->info("Authentication succeeded for $user/$takenby");
255 return ($user, $takenby);
259 my ($r, $event, $filename) = (@_);
260 my $ref = $dbh->selectrow_hashref(
261 'SELECT id FROM images WHERE event=? AND filename=?',
262 undef, $event, $filename);
263 if (!defined($ref)) {
264 return (undef, undef, undef);
266 return stat_image_from_id($r, $ref->{'id'});
269 sub stat_image_from_id {
272 my $fname = get_disk_location($r, $id);
273 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
274 or return (undef, undef, undef);
276 return ($fname, $size, $mtime);
280 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
282 my $fname = get_disk_location($r, $id);
283 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
287 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
288 if (! -r $cachename or (-M $cachename > -M $fname)) {
289 # If we are in overload mode (aka Slashdot mode), refuse to generate
291 if (Sesse::pr0n::Overload::is_in_overload($r)) {
292 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
293 error($r, 'System is in overload mode, not doing any scaling');
296 # Need to generate the cache; read in the image
297 my $magick = new Image::Magick;
298 my $info = Image::ExifTool::ImageInfo($fname);
300 # NEF files aren't autodetected
301 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
303 my $err = $magick->Read($fname);
305 $r->log->warn("$fname: $err");
309 error($r, "$fname: $err");
313 # If we use ->[0] unconditionally, text rendering (!) seems to crash
314 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
316 my $width = $img->Get('columns');
317 my $height = $img->Get('rows');
319 # Update the SQL database if it doesn't contain the required info
320 if ($dbwidth == -1 || $dbheight == -1) {
321 $r->log->info("Updating width/height for $id: $width x $height");
322 update_width_height($r, $id, $width, $height);
325 # We always want RGB JPEGs
326 if ($img->Get('Colorspace') eq "CMYK") {
327 $img->Set(colorspace=>'RGB');
330 while (defined($xres) && defined($yres)) {
331 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
332 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
335 if (defined($nxres) && defined($nyres)) {
336 # we have more resolutions to scale, so don't throw
338 $cimg = $img->Clone();
343 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
345 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
346 my $filter = 'Mitchell';
349 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
355 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
358 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
359 make_infobox($cimg, $info, $r);
362 # Strip EXIF tags etc.
365 $err = $cimg->write(filename=>$cachename, quality=>$quality);
369 ($xres, $yres) = ($nxres, $nyres);
371 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
377 $r->log->warn("$fname: $err");
381 error($r, "$fname: $err");
385 return ($cachename, 1);
388 sub get_mimetype_from_filename {
389 my $filename = shift;
390 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
391 $type = "image/jpeg" if (!defined($type));
396 my ($img, $info, $r) = @_;
399 my @classic_fields = ();
401 if (defined($info->{'DateTimeOriginal'}) &&
402 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
404 push @lines, "$1-$2-$3 $4:$5";
407 if (defined($info->{'Model'})) {
408 my $model = $info->{'Model'};
415 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
416 push @classic_fields, ($1 . "mm");
417 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
418 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
420 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
421 my ($a, $b) = ($1, $2);
422 my $gcd = gcd($a, $b);
423 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
425 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
428 push @classic_fields, (sprintf "f/%.0f", $f);
430 push @classic_fields, (sprintf "f/%.1f", $f);
432 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
433 my $f = $info->{'FNumber'};
435 push @classic_fields, (sprintf "f/%.0f", $f);
437 push @classic_fields, (sprintf "f/%.1f", $f);
441 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
443 if (defined($info->{'NikonD1-ISOSetting'})) {
444 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
445 } elsif (defined($info->{'ISOSetting'})) {
446 push @classic_fields, $info->{'ISOSetting'} . " ISO";
449 push @classic_fields, $info->{'ExposureBiasValue'} . " EV" if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0);
451 if (scalar @classic_fields > 0) {
452 push @lines, join(', ', @classic_fields);
455 if (defined($info->{'Flash'})) {
456 if ($info->{'Flash'} =~ /did not fire/i ||
457 $info->{'Flash'} =~ /no flash/i ||
458 $info->{'Flash'} =~ /not fired/i ||
459 $info->{'Flash'} =~ /Off/) {
460 push @lines, "No flash";
461 } elsif ($info->{'Flash'} =~ /fired/i ||
462 $info->{'Flash'} =~ /On/) {
463 push @lines, "Flash";
465 push @lines, $info->{'Flash'};
469 return if (scalar @lines == 0);
471 # OK, this sucks. Let's make something better :-)
472 @lines = ( join(" - ", @lines) );
474 # Find the required width
475 my $th = 14 * (scalar @lines) + 6;
478 for my $line (@lines) {
479 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
480 $tw = $this_w if ($this_w >= $tw);
485 # Round up so we hit exact DCT blocks
486 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
487 $th += 8 - ($th % 8) unless ($th % 8 == 0);
489 return if ($tw > $img->Get('columns'));
491 # my $x = $img->Get('columns') - 8 - $tw;
492 # my $y = $img->Get('rows') - 8 - $th;
494 my $y = $img->Get('rows') - $th;
495 $tw = $img->Get('columns');
500 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
501 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
502 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
503 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
504 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
506 my $i = -(scalar @lines - 1)/2.0;
507 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
508 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
509 #my $yc = ($y + $img->Get('rows'))/4;
510 my $yi = $th / (scalar @lines);
512 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
514 for my $line (@lines) {
515 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
516 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
517 x=>int($xc), y=>int($yc + $i * $yi));
525 return $a if ($b == 0);
526 return gcd($b, $a % $b);
530 my ($dbh, $id, $date, $desc, $vhost) = @_;
533 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
534 push @errors, "Manglende eller ugyldig ID.";
536 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
537 push @errors, "Manglende eller ugyldig dato.";
539 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
540 push @errors, "Manglende eller ugyldig beskrivelse.";
543 if (scalar @errors > 0) {
547 $dbh->do("INSERT INTO events (id,date,name,vhost) VALUES (?,?,?,?)",
548 undef, $id, $date, $desc, $vhost)
549 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
550 $dbh->do("INSERT INTO last_picture_cache (event,last_picture) VALUES (?,NULL)",
552 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);