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 # FIXME: We'll need to escape _ here somehow
136 $str .= ($first) ? "?" : ';';
137 $str .= "$key=$value";
144 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
145 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
146 if (defined($accesskey) && length($accesskey) == 1) {
147 $str .= " accesskey=\"$accesskey\"";
149 $str .= ">$title</a>";
154 # Check that we are alive
155 if (!(defined($dbh) && $dbh->ping)) {
157 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
158 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
159 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
161 die "Couldn't connect to PostgreSQL database";
170 return $r->dir_config('ImageBase');
173 sub get_disk_location {
175 my $dir = POSIX::floor($id / 256);
176 return get_base($r) . "images/$dir/$id.jpg";
179 sub get_cache_location {
180 my ($r, $id, $width, $height, $infobox) = @_;
181 my $dir = POSIX::floor($id / 256);
184 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
186 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
190 sub update_image_info {
191 my ($r, $id, $width, $height) = @_;
193 # Also find the date taken if appropriate (from the EXIF tag etc.)
194 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
195 my $datetime = undef;
197 if (defined($info->{'DateTimeOriginal'})) {
198 # Parse the date and time over to ISO format
199 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
200 $datetime = "$1-$2-$3 $4:$5:$6";
205 local $dbh->{AutoCommit} = 0;
207 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
208 undef, $width, $height, $datetime, $id)
209 or die "Couldn't update width/height in SQL: $!";
211 $dbh->do('DELETE FROM exif_info WHERE image=?',
213 or die "Couldn't delete old EXIF information in SQL: $!";
215 my $q = $dbh->prepare('INSERT INTO exif_info (image,tag,value) VALUES (?,?,?)')
216 or die "Couldn't prepare inserting EXIF information: $!";
218 for my $key (keys %$info) {
219 next if ref $info->{$key};
220 $q->execute($id, $key, guess_charset($info->{$key}))
221 or die "Couldn't insert EXIF information in database: $!";
224 # update the last_picture cache as well (this should of course be done
225 # via a trigger, but this is less complicated :-) )
226 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
227 undef, $datetime, $id)
228 or die "Couldn't update last_picture in SQL: $!";
235 my $auth = $r->headers_in->{'authorization'};
236 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
237 $r->content_type('text/plain; charset=utf-8');
239 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
240 $r->print("Need authorization\n");
244 #return qw(sesse Sesse);
246 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
247 # WinXP is stupid :-)
248 if ($user =~ /^.*\\(.*)$/) {
253 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
257 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
261 $pass = Digest::SHA1::sha1_base64($pass);
262 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
263 undef, $user, $pass, $r->get_server_name);
264 if ($ref->{'auth'} != 1) {
265 $r->content_type('text/plain; charset=utf-8');
266 warn "No user exists, only $auth";
268 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
269 $r->print("Authorization failed");
270 $r->log->warn("Authentication failed for $user/$takenby");
274 $r->log->info("Authentication succeeded for $user/$takenby");
276 return ($user, $takenby);
280 my ($r, $event, $filename) = (@_);
281 my $ref = $dbh->selectrow_hashref(
282 'SELECT id FROM images WHERE event=? AND filename=?',
283 undef, $event, $filename);
284 if (!defined($ref)) {
285 return (undef, undef, undef);
287 return stat_image_from_id($r, $ref->{'id'});
290 sub stat_image_from_id {
293 my $fname = get_disk_location($r, $id);
294 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
295 or return (undef, undef, undef);
297 return ($fname, $size, $mtime);
301 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
303 my $fname = get_disk_location($r, $id);
304 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
308 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
309 if (! -r $cachename or (-M $cachename > -M $fname)) {
310 # If we are in overload mode (aka Slashdot mode), refuse to generate
312 if (Sesse::pr0n::Overload::is_in_overload($r)) {
313 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
314 error($r, 'System is in overload mode, not doing any scaling');
317 # Need to generate the cache; read in the image
318 my $magick = new Image::Magick;
319 my $info = Image::ExifTool::ImageInfo($fname);
322 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
323 # The delegate support is rather broken and causes very odd stuff to happen when
324 # more than one thread does this at the same time. Thus, we simply do it ourselves.
325 if ($filename =~ /\.nef$/) {
326 # this would suffice if ImageMagick gets to fix their handling
327 # $fname = "NEF:$fname";
329 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
330 or error("dcraw: $!");
331 $err = $magick->Read(file => \*DCRAW);
334 $err = $magick->Read($fname);
338 $r->log->warn("$fname: $err");
342 error($r, "$fname: $err");
346 # If we use ->[0] unconditionally, text rendering (!) seems to crash
347 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
349 my $width = $img->Get('columns');
350 my $height = $img->Get('rows');
352 # Update the SQL database if it doesn't contain the required info
353 if ($dbwidth == -1 || $dbheight == -1) {
354 $r->log->info("Updating width/height for $id: $width x $height");
355 update_image_info($r, $id, $width, $height);
358 # We always want RGB JPEGs
359 if ($img->Get('Colorspace') eq "CMYK") {
360 $img->Set(colorspace=>'RGB');
363 while (defined($xres) && defined($yres)) {
364 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
365 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
368 if (defined($nxres) && defined($nyres)) {
369 # we have more resolutions to scale, so don't throw
371 $cimg = $img->Clone();
376 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
378 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
379 my $filter = 'Mitchell';
383 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
390 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
393 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
394 make_infobox($cimg, $info, $r);
397 # Strip EXIF tags etc.
402 filename => $cachename,
405 if (($nwidth >= 640 && $nheight >= 480) ||
406 ($nwidth >= 480 && $nheight >= 640)) {
407 $parms{'interlace'} = 'Plane';
410 $parms{'sampling-factor'} = $sf;
412 $err = $cimg->write(%parms);
417 ($xres, $yres) = ($nxres, $nyres);
419 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
425 $r->log->warn("$fname: $err");
429 error($r, "$fname: $err");
433 return ($cachename, 1);
436 sub get_mimetype_from_filename {
437 my $filename = shift;
438 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
439 $type = "image/jpeg" if (!defined($type));
444 my ($img, $info, $r) = @_;
447 my @classic_fields = ();
449 if (defined($info->{'DateTimeOriginal'}) &&
450 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
452 push @lines, "$1-$2-$3 $4:$5";
455 if (defined($info->{'Model'})) {
456 my $model = $info->{'Model'};
463 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
464 push @classic_fields, ($1 . "mm");
465 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
466 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
468 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
469 my ($a, $b) = ($1, $2);
470 my $gcd = gcd($a, $b);
471 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
472 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
473 push @classic_fields, ($1 . "s");
475 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
478 push @classic_fields, (sprintf "f/%.0f", $f);
480 push @classic_fields, (sprintf "f/%.1f", $f);
482 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
483 my $f = $info->{'FNumber'};
485 push @classic_fields, (sprintf "f/%.0f", $f);
487 push @classic_fields, (sprintf "f/%.1f", $f);
491 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
493 if (defined($info->{'NikonD1-ISOSetting'})) {
494 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
495 } elsif (defined($info->{'ISOSetting'})) {
496 push @classic_fields, $info->{'ISOSetting'} . " ISO";
499 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
500 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
501 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
502 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
505 if (scalar @classic_fields > 0) {
506 push @lines, join(', ', @classic_fields);
509 if (defined($info->{'Flash'})) {
510 if ($info->{'Flash'} =~ /did not fire/i ||
511 $info->{'Flash'} =~ /no flash/i ||
512 $info->{'Flash'} =~ /not fired/i ||
513 $info->{'Flash'} =~ /Off/) {
514 push @lines, "No flash";
515 } elsif ($info->{'Flash'} =~ /fired/i ||
516 $info->{'Flash'} =~ /On/) {
517 push @lines, "Flash";
519 push @lines, $info->{'Flash'};
523 return if (scalar @lines == 0);
525 # OK, this sucks. Let's make something better :-)
526 @lines = ( join(" - ", @lines) );
528 # Find the required width
529 my $th = 14 * (scalar @lines) + 6;
532 for my $line (@lines) {
533 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
534 $tw = $this_w if ($this_w >= $tw);
539 # Round up so we hit exact DCT blocks
540 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
541 $th += 8 - ($th % 8) unless ($th % 8 == 0);
543 return if ($tw > $img->Get('columns'));
545 # my $x = $img->Get('columns') - 8 - $tw;
546 # my $y = $img->Get('rows') - 8 - $th;
548 my $y = $img->Get('rows') - $th;
549 $tw = $img->Get('columns');
554 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
555 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
556 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
557 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
558 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
560 my $i = -(scalar @lines - 1)/2.0;
561 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
562 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
563 #my $yc = ($y + $img->Get('rows'))/4;
564 my $yi = $th / (scalar @lines);
566 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
568 for my $line (@lines) {
569 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
570 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
571 x=>int($xc), y=>int($yc + $i * $yi));
579 return $a if ($b == 0);
580 return gcd($b, $a % $b);
584 my ($dbh, $id, $date, $desc, $vhost) = @_;
587 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
588 push @errors, "Manglende eller ugyldig ID.";
590 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
591 push @errors, "Manglende eller ugyldig dato.";
593 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
594 push @errors, "Manglende eller ugyldig beskrivelse.";
597 if (scalar @errors > 0) {
601 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
602 undef, $id, $date, $desc, $vhost)
603 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
604 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
606 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
616 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
619 $decoded = Encode::decode("iso8859-1", $text);