]> git.sesse.net Git - pr0n/blobdiff - perl/Sesse/pr0n/Common.pm
Micro-modularization.
[pr0n] / perl / Sesse / pr0n / Common.pm
index 8fe17d738f7b9300dda864abe45e6de6bd17a0ea..098c9d36d22ea766ce6f828dc6f0633f15fa00a6 100644 (file)
@@ -11,6 +11,8 @@ use Apache2::Const -compile => ':common';
 use Apache2::Log;
 use ModPerl::Util;
 
+use Carp;
+use Encode;
 use DBI;
 use DBD::Pg;
 use Image::Magick;
@@ -21,6 +23,8 @@ use MIME::Types;
 use LWP::Simple;
 # use Image::Info;
 use Image::ExifTool;
+use HTML::Entities;
+use URI::Escape;
 
 BEGIN {
        use Exporter ();
@@ -31,7 +35,7 @@ BEGIN {
                require Sesse::pr0n::Config_local;
        };
 
-       $VERSION     = "v2.05";
+       $VERSION     = "v2.41";
        @ISA         = qw(Exporter);
        @EXPORT      = qw(&error &dberror);
        %EXPORT_TAGS = qw();
@@ -67,6 +71,7 @@ sub error {
         footer($r);
 
        $r->log->error($err);
+       $r->log->error("Stack trace follows: " . Carp::longmess());
 
        ModPerl::Util::exit();
 }
@@ -87,7 +92,7 @@ sub header {
                $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
                $quote = "Error: Could not fetch quotes." if (!defined($quote));
        }
-       Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
+       Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
 }
 
 sub footer {
@@ -117,21 +122,52 @@ sub scale_aspect {
        return ($width, $height);
 }
 
-sub print_link {
-       my ($r, $title, $baseurl, $param, $defparam) = @_;
-       my $str = "<a href=\"$baseurl";
+sub get_query_string {
+       my ($param, $defparam) = @_;
        my $first = 1;
+       my $str = "";
 
        while (my ($key, $value) = each %$param) {
                next unless defined($value);
                next if (defined($defparam->{$key}) && $value == $defparam->{$key});
+
+               $value = pretty_escape($value);
        
-               $str .= ($first) ? "?" : '&amp;';
+               $str .= ($first) ? "?" : ';';
                $str .= "$key=$value";
                $first = 0;
        }
-       
-       $str .= "\">$title</a>";
+       return $str;
+}
+               
+sub pretty_escape {
+       my $value = shift;
+
+       $value = URI::Escape::uri_escape($value);
+
+       # Unescape a few for prettiness (we'll need something for a real _, though)
+       $value =~ s/%20/_/g;
+       $value =~ s/%2F/\//g;
+
+       return $value;
+}
+
+sub pretty_unescape {
+       my $value = shift;
+
+       # URI unescaping is already done for us
+       $value =~ s/_/ /g;
+
+       return $value;
+}
+
+sub print_link {
+       my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
+       my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
+       if (defined($accesskey) && length($accesskey) == 1) {
+               $str .= " accesskey=\"$accesskey\"";
+       }
+       $str .= ">$title</a>";
        $r->print($str);
 }
 
@@ -141,7 +177,7 @@ sub get_dbh {
                # Try to reconnect
                Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
                unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
-                       $Sesse::pr0n::Config::db_user, $Sesse::pr0n::Config::db_password)) {
+                       $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
                        $dbh = undef;
                        die "Couldn't connect to PostgreSQL database";
                }
@@ -172,29 +208,63 @@ sub get_cache_location {
        }
 }
 
-sub update_width_height {
+sub update_image_info {
        my ($r, $id, $width, $height) = @_;
 
        # Also find the date taken if appropriate (from the EXIF tag etc.)
-       my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
+       my $exiftool = Image::ExifTool->new;
+       $exiftool->ExtractInfo(get_disk_location($r, $id));
+       my $info = $exiftool->GetInfo();
        my $datetime = undef;
-
+                       
        if (defined($info->{'DateTimeOriginal'})) {
                # Parse the date and time over to ISO format
-               if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/ && $1 > 1990) {
+               if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
                        $datetime = "$1-$2-$3 $4:$5:$6";
                }
        }
 
-       $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
-                undef, $width, $height, $datetime, $id)
-               or die "Couldn't update width/height in SQL: $!";
+       {
+               local $dbh->{AutoCommit} = 0;
+
+               $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
+                        undef, $width, $height, $datetime, $id)
+                       or die "Couldn't update width/height in SQL: $!";
+
+               # EXIF information
+               $dbh->do('DELETE FROM exif_info WHERE image=?',
+                       undef, $id)
+                       or die "Couldn't delete old EXIF information in SQL: $!";
 
-       # update the last_picture cache as well (this should of course be done
-       # via a trigger, but this is less complicated :-) )
-       $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
-               undef, $datetime, $id)
-               or die "Couldn't update last_picture in SQL: $!";
+               my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
+                       or die "Couldn't prepare inserting EXIF information: $!";
+
+               for my $key (keys %$info) {
+                       next if ref $info->{$key};
+                       $q->execute($id, $key, guess_charset($info->{$key}))
+                               or die "Couldn't insert EXIF information in database: $!";
+               }
+
+               # Tags
+               my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
+               $dbh->do('DELETE FROM tags WHERE image=?',
+                       undef, $id)
+                       or die "Couldn't delete old tag information in SQL: $!";
+
+               my $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
+                       or die "Couldn't prepare inserting tag information: $!";
+
+               for my $tag (@tags) {
+                       $q->execute($id, guess_charset($tag))
+                               or die "Couldn't insert tag information in database: $!";
+               }
+
+               # update the last_picture cache as well (this should of course be done
+               # via a trigger, but this is less complicated :-) )
+               $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
+                       undef, $datetime, $id)
+                       or die "Couldn't update last_picture in SQL: $!";
+       }
 }
 
 sub check_access {
@@ -285,11 +355,23 @@ sub ensure_cached {
                # Need to generate the cache; read in the image
                my $magick = new Image::Magick;
                my $info = Image::ExifTool::ImageInfo($fname);
-
-               # NEF files aren't autodetected
-               $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
+               my $err;
+
+               # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
+               # The delegate support is rather broken and causes very odd stuff to happen when
+               # more than one thread does this at the same time. Thus, we simply do it ourselves.
+               if ($filename =~ /\.nef$/) {
+                       # this would suffice if ImageMagick gets to fix their handling
+                       # $fname = "NEF:$fname";
+                       
+                       open DCRAW, "-|", "dcraw", "-w", "-c", $fname
+                               or error("dcraw: $!");
+                       $err = $magick->Read(file => \*DCRAW);
+                       close(DCRAW);
+               } else {
+                       $err = $magick->Read($fname);
+               }
                
-               my $err = $magick->Read($fname);
                if ($err) {
                        $r->log->warn("$fname: $err");
                        $err =~ /(\d+)/;
@@ -308,7 +390,7 @@ sub ensure_cached {
                # Update the SQL database if it doesn't contain the required info
                if ($dbwidth == -1 || $dbheight == -1) {
                        $r->log->info("Updating width/height for $id: $width x $height");
-                       update_width_height($r, $id, $width, $height);
+                       update_image_info($r, $id, $width, $height);
                }
                        
                # We always want RGB JPEGs
@@ -334,10 +416,12 @@ sub ensure_cached {
                        # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
                        my $filter = 'Mitchell';
                        my $quality = 90;
+                       my $sf = undef;
 
                        if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
                                $filter = 'Lanczos';
-                               $quality = 80;
+                               $quality = 85;
+                               $sf = "1x1";
                        }
 
                        if ($xres != -1) {
@@ -351,7 +435,20 @@ sub ensure_cached {
                        # Strip EXIF tags etc.
                        $cimg->Strip();
 
-                       $err = $cimg->write(filename=>$cachename, quality=>$quality);
+                       {
+                               my %parms = (
+                                       filename => $cachename,
+                                       quality => $quality
+                               );
+                               if (($nwidth >= 640 && $nheight >= 480) ||
+                                   ($nwidth >= 480 && $nheight >= 640)) {
+                                       $parms{'interlace'} = 'Plane';
+                               }
+                               if (defined($sf)) {
+                                       $parms{'sampling-factor'} = $sf;
+                               }
+                               $err = $cimg->write(%parms);
+                       }
 
                        undef $cimg;
 
@@ -393,7 +490,12 @@ sub make_infobox {
                push @lines, "$1-$2-$3 $4:$5";
        }
 
-       push @lines, $info->{'Model'} if (defined($info->{'Model'}));
+       if (defined($info->{'Model'})) {
+               my $model = $info->{'Model'}; 
+               $model =~ s/^\s+//;
+               $model =~ s/\s+$//;
+               push @lines, $model;
+       }
        
        # classic fields
        if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
@@ -405,6 +507,8 @@ sub make_infobox {
                my ($a, $b) = ($1, $2);
                my $gcd = gcd($a, $b);
                push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
+       } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
+               push @classic_fields, ($1 . "s");
        }
        if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
                my $f = $1/$2;
@@ -430,7 +534,11 @@ sub make_infobox {
                push @classic_fields, $info->{'ISOSetting'} . " ISO";
        }
 
-       push @classic_fields, $info->{'ExposureBiasValue'} . " EV" if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0);
+       if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
+               push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
+       } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
+               push @classic_fields, $info->{'ExposureCompensation'} . " EV";
+       }
        
        if (scalar @classic_fields > 0) {
                push @lines, join(', ', @classic_fields);
@@ -510,6 +618,48 @@ sub gcd {
        return gcd($b, $a % $b);
 }
 
+sub add_new_event {
+       my ($dbh, $id, $date, $desc, $vhost) = @_;
+       my @errors = ();
+
+       if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
+               push @errors, "Manglende eller ugyldig ID.";
+       }
+       if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
+               push @errors, "Manglende eller ugyldig dato.";
+       }
+       if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
+               push @errors, "Manglende eller ugyldig beskrivelse.";
+       }
+       
+       if (scalar @errors > 0) {
+               return @errors;
+       }
+               
+       $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
+               undef, $id, $date, $desc, $vhost)
+               or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
+       $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
+               undef, $vhost, $id)
+               or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
+
+       return ();
+}
+
+sub guess_charset {
+       my $text = shift;
+       my $decoded;
+
+       eval {
+               $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
+       };
+       if ($@) {
+               $decoded = Encode::decode("iso8859-1", $text);
+       }
+
+       return $decoded;
+}
+
 1;