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';
31 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 use Sesse::pr0n::Config;
35 require Sesse::pr0n::Config_local;
40 @EXPORT = qw(&error &dberror);
42 @EXPORT_OK = qw(&error &dberror);
44 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
45 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
46 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
47 our $mimetypes = new MIME::Types;
49 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
56 our ($dbh, $mimetypes);
59 my ($r,$err,$status,$title) = @_;
61 if (!defined($status) || !defined($title)) {
63 $title = "Internal server error";
66 $r->content_type('text/html; charset=utf-8');
70 $r->print(" <p>Error: $err</p>\n");
74 $r->log->error("Stack trace follows: " . Carp::longmess());
76 ModPerl::Util::exit();
81 error($r, "$err (DB error: " . $dbh->errstr . ")");
87 $r->content_type("text/html; charset=utf-8");
89 # Fetch quote if we're itk-bilder.samfundet.no
91 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
92 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
93 $quote = "Error: Could not fetch quotes." if (!defined($quote));
95 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
100 Sesse::pr0n::Templates::print_template($r, "footer",
101 { version => $Sesse::pr0n::Common::VERSION });
105 my ($width, $height, $thumbxres, $thumbyres) = @_;
107 unless ($thumbxres >= $width &&
108 $thumbyres >= $height) {
109 my $sfh = $width / $thumbxres;
110 my $sfv = $height / $thumbyres;
118 $width = POSIX::floor($width);
119 $height = POSIX::floor($height);
122 return ($width, $height);
125 sub get_query_string {
126 my ($param, $defparam) = @_;
130 while (my ($key, $value) = each %$param) {
131 next unless defined($value);
132 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
134 $value = URI::Escape::uri_escape($value);
136 # Unescape a few for prettiness (we'll need something for a real _, though)
138 $value =~ s/%2F/\//g;
140 $str .= ($first) ? "?" : ';';
141 $str .= "$key=$value";
148 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
149 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
150 if (defined($accesskey) && length($accesskey) == 1) {
151 $str .= " accesskey=\"$accesskey\"";
153 $str .= ">$title</a>";
158 # Check that we are alive
159 if (!(defined($dbh) && $dbh->ping)) {
161 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
162 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
163 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
165 die "Couldn't connect to PostgreSQL database";
174 return $r->dir_config('ImageBase');
177 sub get_disk_location {
179 my $dir = POSIX::floor($id / 256);
180 return get_base($r) . "images/$dir/$id.jpg";
183 sub get_cache_location {
184 my ($r, $id, $width, $height, $infobox) = @_;
185 my $dir = POSIX::floor($id / 256);
188 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
190 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
194 sub update_image_info {
195 my ($r, $id, $width, $height) = @_;
197 # Also find the date taken if appropriate (from the EXIF tag etc.)
198 my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
199 my $datetime = undef;
201 if (defined($info->{'DateTimeOriginal'})) {
202 # Parse the date and time over to ISO format
203 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
204 $datetime = "$1-$2-$3 $4:$5:$6";
209 local $dbh->{AutoCommit} = 0;
211 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
212 undef, $width, $height, $datetime, $id)
213 or die "Couldn't update width/height in SQL: $!";
215 $dbh->do('DELETE FROM exif_info WHERE image=?',
217 or die "Couldn't delete old EXIF information in SQL: $!";
219 my $q = $dbh->prepare('INSERT INTO exif_info (image,tag,value) VALUES (?,?,?)')
220 or die "Couldn't prepare inserting EXIF information: $!";
222 for my $key (keys %$info) {
223 next if ref $info->{$key};
224 $q->execute($id, $key, guess_charset($info->{$key}))
225 or die "Couldn't insert EXIF information in database: $!";
228 # update the last_picture cache as well (this should of course be done
229 # via a trigger, but this is less complicated :-) )
230 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
231 undef, $datetime, $id)
232 or die "Couldn't update last_picture in SQL: $!";
239 my $auth = $r->headers_in->{'authorization'};
240 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
241 $r->content_type('text/plain; charset=utf-8');
243 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
244 $r->print("Need authorization\n");
248 #return qw(sesse Sesse);
250 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
251 # WinXP is stupid :-)
252 if ($user =~ /^.*\\(.*)$/) {
257 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
261 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
265 $pass = Digest::SHA1::sha1_base64($pass);
266 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
267 undef, $user, $pass, $r->get_server_name);
268 if ($ref->{'auth'} != 1) {
269 $r->content_type('text/plain; charset=utf-8');
270 warn "No user exists, only $auth";
272 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
273 $r->print("Authorization failed");
274 $r->log->warn("Authentication failed for $user/$takenby");
278 $r->log->info("Authentication succeeded for $user/$takenby");
280 return ($user, $takenby);
284 my ($r, $event, $filename) = (@_);
285 my $ref = $dbh->selectrow_hashref(
286 'SELECT id FROM images WHERE event=? AND filename=?',
287 undef, $event, $filename);
288 if (!defined($ref)) {
289 return (undef, undef, undef);
291 return stat_image_from_id($r, $ref->{'id'});
294 sub stat_image_from_id {
297 my $fname = get_disk_location($r, $id);
298 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
299 or return (undef, undef, undef);
301 return ($fname, $size, $mtime);
305 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
307 my $fname = get_disk_location($r, $id);
308 unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
312 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
313 if (! -r $cachename or (-M $cachename > -M $fname)) {
314 # If we are in overload mode (aka Slashdot mode), refuse to generate
316 if (Sesse::pr0n::Overload::is_in_overload($r)) {
317 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
318 error($r, 'System is in overload mode, not doing any scaling');
321 # Need to generate the cache; read in the image
322 my $magick = new Image::Magick;
323 my $info = Image::ExifTool::ImageInfo($fname);
326 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
327 # The delegate support is rather broken and causes very odd stuff to happen when
328 # more than one thread does this at the same time. Thus, we simply do it ourselves.
329 if ($filename =~ /\.nef$/) {
330 # this would suffice if ImageMagick gets to fix their handling
331 # $fname = "NEF:$fname";
333 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
334 or error("dcraw: $!");
335 $err = $magick->Read(file => \*DCRAW);
338 $err = $magick->Read($fname);
342 $r->log->warn("$fname: $err");
346 error($r, "$fname: $err");
350 # If we use ->[0] unconditionally, text rendering (!) seems to crash
351 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
353 my $width = $img->Get('columns');
354 my $height = $img->Get('rows');
356 # Update the SQL database if it doesn't contain the required info
357 if ($dbwidth == -1 || $dbheight == -1) {
358 $r->log->info("Updating width/height for $id: $width x $height");
359 update_image_info($r, $id, $width, $height);
362 # We always want RGB JPEGs
363 if ($img->Get('Colorspace') eq "CMYK") {
364 $img->Set(colorspace=>'RGB');
367 while (defined($xres) && defined($yres)) {
368 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
369 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
372 if (defined($nxres) && defined($nyres)) {
373 # we have more resolutions to scale, so don't throw
375 $cimg = $img->Clone();
380 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
382 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
383 my $filter = 'Mitchell';
387 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
394 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
397 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
398 make_infobox($cimg, $info, $r);
401 # Strip EXIF tags etc.
406 filename => $cachename,
409 if (($nwidth >= 640 && $nheight >= 480) ||
410 ($nwidth >= 480 && $nheight >= 640)) {
411 $parms{'interlace'} = 'Plane';
414 $parms{'sampling-factor'} = $sf;
416 $err = $cimg->write(%parms);
421 ($xres, $yres) = ($nxres, $nyres);
423 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
429 $r->log->warn("$fname: $err");
433 error($r, "$fname: $err");
437 return ($cachename, 1);
440 sub get_mimetype_from_filename {
441 my $filename = shift;
442 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
443 $type = "image/jpeg" if (!defined($type));
448 my ($img, $info, $r) = @_;
451 my @classic_fields = ();
453 if (defined($info->{'DateTimeOriginal'}) &&
454 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
456 push @lines, "$1-$2-$3 $4:$5";
459 if (defined($info->{'Model'})) {
460 my $model = $info->{'Model'};
467 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
468 push @classic_fields, ($1 . "mm");
469 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
470 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
472 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
473 my ($a, $b) = ($1, $2);
474 my $gcd = gcd($a, $b);
475 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
476 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
477 push @classic_fields, ($1 . "s");
479 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
482 push @classic_fields, (sprintf "f/%.0f", $f);
484 push @classic_fields, (sprintf "f/%.1f", $f);
486 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
487 my $f = $info->{'FNumber'};
489 push @classic_fields, (sprintf "f/%.0f", $f);
491 push @classic_fields, (sprintf "f/%.1f", $f);
495 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
497 if (defined($info->{'NikonD1-ISOSetting'})) {
498 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
499 } elsif (defined($info->{'ISOSetting'})) {
500 push @classic_fields, $info->{'ISOSetting'} . " ISO";
503 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
504 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
505 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
506 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
509 if (scalar @classic_fields > 0) {
510 push @lines, join(', ', @classic_fields);
513 if (defined($info->{'Flash'})) {
514 if ($info->{'Flash'} =~ /did not fire/i ||
515 $info->{'Flash'} =~ /no flash/i ||
516 $info->{'Flash'} =~ /not fired/i ||
517 $info->{'Flash'} =~ /Off/) {
518 push @lines, "No flash";
519 } elsif ($info->{'Flash'} =~ /fired/i ||
520 $info->{'Flash'} =~ /On/) {
521 push @lines, "Flash";
523 push @lines, $info->{'Flash'};
527 return if (scalar @lines == 0);
529 # OK, this sucks. Let's make something better :-)
530 @lines = ( join(" - ", @lines) );
532 # Find the required width
533 my $th = 14 * (scalar @lines) + 6;
536 for my $line (@lines) {
537 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
538 $tw = $this_w if ($this_w >= $tw);
543 # Round up so we hit exact DCT blocks
544 $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
545 $th += 8 - ($th % 8) unless ($th % 8 == 0);
547 return if ($tw > $img->Get('columns'));
549 # my $x = $img->Get('columns') - 8 - $tw;
550 # my $y = $img->Get('rows') - 8 - $th;
552 my $y = $img->Get('rows') - $th;
553 $tw = $img->Get('columns');
558 my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
559 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
560 # $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
561 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
562 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
564 my $i = -(scalar @lines - 1)/2.0;
565 my $xc = $x + $tw / 2 - $img->Get('columns')/2;
566 my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
567 #my $yc = ($y + $img->Get('rows'))/4;
568 my $yi = $th / (scalar @lines);
570 $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
572 for my $line (@lines) {
573 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
574 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
575 x=>int($xc), y=>int($yc + $i * $yi));
583 return $a if ($b == 0);
584 return gcd($b, $a % $b);
588 my ($dbh, $id, $date, $desc, $vhost) = @_;
591 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
592 push @errors, "Manglende eller ugyldig ID.";
594 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
595 push @errors, "Manglende eller ugyldig dato.";
597 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
598 push @errors, "Manglende eller ugyldig beskrivelse.";
601 if (scalar @errors > 0) {
605 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
606 undef, $id, $date, $desc, $vhost)
607 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
608 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
610 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
620 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
623 $decoded = Encode::decode("iso8859-1", $text);