]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Allow latin1 in EXIF info.
[pr0n] / perl / Sesse / pr0n / Common.pm
1 package Sesse::pr0n::Common;
2 use strict;
3 use warnings;
4
5 use Sesse::pr0n::Templates;
6 use Sesse::pr0n::Overload;
7
8 use Apache2::RequestRec (); # for $r->content_type
9 use Apache2::RequestIO ();  # for $r->print
10 use Apache2::Const -compile => ':common';
11 use Apache2::Log;
12 use ModPerl::Util;
13
14 use Carp;
15 use Encode;
16 use DBI;
17 use DBD::Pg;
18 use Image::Magick;
19 use POSIX;
20 use Digest::SHA1;
21 use MIME::Base64;
22 use MIME::Types;
23 use LWP::Simple;
24 # use Image::Info;
25 use Image::ExifTool;
26 use HTML::Entities;
27
28 BEGIN {
29         use Exporter ();
30         our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
31
32         use Sesse::pr0n::Config;
33         eval {
34                 require Sesse::pr0n::Config_local;
35         };
36
37         $VERSION     = "v2.21";
38         @ISA         = qw(Exporter);
39         @EXPORT      = qw(&error &dberror);
40         %EXPORT_TAGS = qw();
41         @EXPORT_OK   = qw(&error &dberror);
42
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;
47         
48         Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
49 }
50 END {
51         our $dbh;
52         $dbh->disconnect;
53 }
54
55 our ($dbh, $mimetypes);
56
57 sub error {
58         my ($r,$err,$status,$title) = @_;
59
60         if (!defined($status) || !defined($title)) {
61                 $status = 500;
62                 $title = "Internal server error";
63         }
64         
65         $r->content_type('text/html; charset=utf-8');
66         $r->status($status);
67
68         header($r, $title);
69         $r->print("    <p>Error: $err</p>\n");
70         footer($r);
71
72         $r->log->error($err);
73         $r->log->error("Stack trace follows: " . Carp::longmess());
74
75         ModPerl::Util::exit();
76 }
77
78 sub dberror {
79         my ($r,$err) = @_;
80         error($r, "$err (DB error: " . $dbh->errstr . ")");
81 }
82
83 sub header {
84         my ($r,$title) = @_;
85
86         $r->content_type("text/html; charset=utf-8");
87
88         # Fetch quote if we're itk-bilder.samfundet.no
89         my $quote = "";
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));
93         }
94         Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => $quote });
95 }
96
97 sub footer {
98         my ($r) = @_;
99         Sesse::pr0n::Templates::print_template($r, "footer",
100                 { version => $Sesse::pr0n::Common::VERSION });
101 }
102
103 sub scale_aspect {
104         my ($width, $height, $thumbxres, $thumbyres) = @_;
105
106         unless ($thumbxres >= $width &&
107                 $thumbyres >= $height) {
108                 my $sfh = $width / $thumbxres;
109                 my $sfv = $height / $thumbyres;
110                 if ($sfh > $sfv) {
111                         $width  /= $sfh;
112                         $height /= $sfh;
113                 } else {
114                         $width  /= $sfv;
115                         $height /= $sfv;
116                 }
117                 $width = POSIX::floor($width);
118                 $height = POSIX::floor($height);
119         }
120
121         return ($width, $height);
122 }
123
124 sub get_query_string {
125         my ($param, $defparam) = @_;
126         my $first = 1;
127         my $str = "";
128
129         while (my ($key, $value) = each %$param) {
130                 next unless defined($value);
131                 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
132         
133                 $str .= ($first) ? "?" : ';';
134                 $str .= "$key=$value";
135                 $first = 0;
136         }
137         return $str;
138 }
139
140 sub print_link {
141         my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
142         my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
143         if (defined($accesskey) && length($accesskey) == 1) {
144                 $str .= " accesskey=\"$accesskey\"";
145         }
146         $str .= ">$title</a>";
147         $r->print($str);
148 }
149
150 sub get_dbh {
151         # Check that we are alive
152         if (!(defined($dbh) && $dbh->ping)) {
153                 # Try to reconnect
154                 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
155                 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
156                         $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
157                         $dbh = undef;
158                         die "Couldn't connect to PostgreSQL database";
159                 }
160         }
161
162         return $dbh;
163 }
164
165 sub get_base {
166         my $r = shift;
167         return $r->dir_config('ImageBase');
168 }
169
170 sub get_disk_location {
171         my ($r, $id) = @_;
172         my $dir = POSIX::floor($id / 256);
173         return get_base($r) . "images/$dir/$id.jpg";
174 }
175
176 sub get_cache_location {
177         my ($r, $id, $width, $height, $infobox) = @_;
178         my $dir = POSIX::floor($id / 256);
179
180         if ($infobox) {
181                 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
182         } else {
183                 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
184         }
185 }
186
187 sub update_image_info {
188         my ($r, $id, $width, $height) = @_;
189
190         # Also find the date taken if appropriate (from the EXIF tag etc.)
191         my $info = Image::ExifTool::ImageInfo(get_disk_location($r, $id));
192         my $datetime = undef;
193                         
194         if (defined($info->{'DateTimeOriginal'})) {
195                 # Parse the date and time over to ISO format
196                 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
197                         $datetime = "$1-$2-$3 $4:$5:$6";
198                 }
199         }
200
201         $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
202                  undef, $width, $height, $datetime, $id)
203                 or die "Couldn't update width/height in SQL: $!";
204
205         $dbh->do('DELETE FROM exif_info WHERE image=?',
206                 undef, $id)
207                 or die "Couldn't delete old EXIF information in SQL: $!";
208
209         my $q = $dbh->prepare('INSERT INTO exif_info (image,tag,value) VALUES (?,?,?)')
210                 or die "Couldn't prepare inserting EXIF information: $!";
211
212         for my $key (keys %$info) {
213                 next if ref $info->{$key};
214                 $q->execute($id, $key, guess_charset($info->{$key}))
215                         or die "Couldn't insert EXIF information in database: $!";
216         }
217
218         # update the last_picture cache as well (this should of course be done
219         # via a trigger, but this is less complicated :-) )
220         $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
221                 undef, $datetime, $id)
222                 or die "Couldn't update last_picture in SQL: $!";
223 }
224
225 sub check_access {
226         my $r = shift;
227
228         my $auth = $r->headers_in->{'authorization'};
229         if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
230                 $r->content_type('text/plain; charset=utf-8');
231                 $r->status(401);
232                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
233                 $r->print("Need authorization\n");
234                 return undef;
235         }
236         
237         #return qw(sesse Sesse);
238
239         my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
240         # WinXP is stupid :-)
241         if ($user =~ /^.*\\(.*)$/) {
242                 $user = $1;
243         }
244
245         my $takenby;
246         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
247                 $user = $1;
248                 $takenby = $2;
249         } else {
250                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
251         }
252         
253         my $oldpass = $pass;
254         $pass = Digest::SHA1::sha1_base64($pass);
255         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
256                 undef, $user, $pass, $r->get_server_name);
257         if ($ref->{'auth'} != 1) {
258                 $r->content_type('text/plain; charset=utf-8');
259                 warn "No user exists, only $auth";
260                 $r->status(401);
261                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
262                 $r->print("Authorization failed");
263                 $r->log->warn("Authentication failed for $user/$takenby");
264                 return undef;
265         }
266
267         $r->log->info("Authentication succeeded for $user/$takenby");
268
269         return ($user, $takenby);
270 }
271         
272 sub stat_image {
273         my ($r, $event, $filename) = (@_);
274         my $ref = $dbh->selectrow_hashref(
275                 'SELECT id FROM images WHERE event=? AND filename=?',
276                 undef, $event, $filename);
277         if (!defined($ref)) {
278                 return (undef, undef, undef);
279         }
280         return stat_image_from_id($r, $ref->{'id'});
281 }
282
283 sub stat_image_from_id {
284         my ($r, $id) = @_;
285
286         my $fname = get_disk_location($r, $id);
287         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
288                 or return (undef, undef, undef);
289
290         return ($fname, $size, $mtime);
291 }
292
293 sub ensure_cached {
294         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
295
296         my $fname = get_disk_location($r, $id);
297         unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
298                 return ($fname, 0);
299         }
300
301         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
302         if (! -r $cachename or (-M $cachename > -M $fname)) {
303                 # If we are in overload mode (aka Slashdot mode), refuse to generate
304                 # new thumbnails.
305                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
306                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
307                         error($r, 'System is in overload mode, not doing any scaling');
308                 }
309         
310                 # Need to generate the cache; read in the image
311                 my $magick = new Image::Magick;
312                 my $info = Image::ExifTool::ImageInfo($fname);
313
314                 # NEF files aren't autodetected
315                 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
316                 
317                 my $err = $magick->Read($fname);
318                 if ($err) {
319                         $r->log->warn("$fname: $err");
320                         $err =~ /(\d+)/;
321                         if ($1 >= 400) {
322                                 undef $magick;
323                                 error($r, "$fname: $err");
324                         }
325                 }
326
327                 # If we use ->[0] unconditionally, text rendering (!) seems to crash
328                 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
329
330                 my $width = $img->Get('columns');
331                 my $height = $img->Get('rows');
332
333                 # Update the SQL database if it doesn't contain the required info
334                 if ($dbwidth == -1 || $dbheight == -1) {
335                         $r->log->info("Updating width/height for $id: $width x $height");
336                         update_image_info($r, $id, $width, $height);
337                 }
338                         
339                 # We always want RGB JPEGs
340                 if ($img->Get('Colorspace') eq "CMYK") {
341                         $img->Set(colorspace=>'RGB');
342                 }
343
344                 while (defined($xres) && defined($yres)) {
345                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
346                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
347                         
348                         my $cimg;
349                         if (defined($nxres) && defined($nyres)) {
350                                 # we have more resolutions to scale, so don't throw
351                                 # the image away
352                                 $cimg = $img->Clone();
353                         } else {
354                                 $cimg = $img;
355                         }
356                 
357                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
358
359                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
360                         my $filter = 'Mitchell';
361                         my $quality = 90;
362
363                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
364                                 $filter = 'Lanczos';
365                                 $quality = 80;
366                         }
367
368                         if ($xres != -1) {
369                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
370                         }
371
372                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
373                                 make_infobox($cimg, $info, $r);
374                         }
375
376                         # Strip EXIF tags etc.
377                         $cimg->Strip();
378
379                         if (($nwidth >= 640 && $nheight >= 480) ||
380                             ($nwidth >= 480 && $nheight >= 640)) {
381                                 $err = $cimg->write(filename=>$cachename, quality=>$quality, interlace=>'Plane');
382                         } else {
383                                 $err = $cimg->write(filename=>$cachename, quality=>$quality);
384                         }
385
386                         undef $cimg;
387
388                         ($xres, $yres) = ($nxres, $nyres);
389
390                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
391                 }
392                 
393                 undef $magick;
394                 undef $img;
395                 if ($err) {
396                         $r->log->warn("$fname: $err");
397                         $err =~ /(\d+)/;
398                         if ($1 >= 400) {
399                                 @$magick = ();
400                                 error($r, "$fname: $err");
401                         }
402                 }
403         }
404         return ($cachename, 1);
405 }
406
407 sub get_mimetype_from_filename {
408         my $filename = shift;
409         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
410         $type = "image/jpeg" if (!defined($type));
411         return $type;
412 }
413
414 sub make_infobox {
415         my ($img, $info, $r) = @_;
416         
417         my @lines = ();
418         my @classic_fields = ();
419         
420         if (defined($info->{'DateTimeOriginal'}) &&
421             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
422             && $1 >= 1990) {
423                 push @lines, "$1-$2-$3 $4:$5";
424         }
425
426         if (defined($info->{'Model'})) {
427                 my $model = $info->{'Model'}; 
428                 $model =~ s/^\s+//;
429                 $model =~ s/\s+$//;
430                 push @lines, $model;
431         }
432         
433         # classic fields
434         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
435                 push @classic_fields, ($1 . "mm");
436         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
437                 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
438         }
439         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
440                 my ($a, $b) = ($1, $2);
441                 my $gcd = gcd($a, $b);
442                 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
443         }
444         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
445                 my $f = $1/$2;
446                 if ($f >= 10) {
447                         push @classic_fields, (sprintf "f/%.0f", $f);
448                 } else {
449                         push @classic_fields, (sprintf "f/%.1f", $f);
450                 }
451         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
452                 my $f = $info->{'FNumber'};
453                 if ($f >= 10) {
454                         push @classic_fields, (sprintf "f/%.0f", $f);
455                 } else {
456                         push @classic_fields, (sprintf "f/%.1f", $f);
457                 }
458         }
459
460 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
461
462         if (defined($info->{'NikonD1-ISOSetting'})) {
463                 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
464         } elsif (defined($info->{'ISOSetting'})) {
465                 push @classic_fields, $info->{'ISOSetting'} . " ISO";
466         }
467
468         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
469                 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
470         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
471                 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
472         }
473         
474         if (scalar @classic_fields > 0) {
475                 push @lines, join(', ', @classic_fields);
476         }
477
478         if (defined($info->{'Flash'})) {
479                 if ($info->{'Flash'} =~ /did not fire/i ||
480                     $info->{'Flash'} =~ /no flash/i ||
481                     $info->{'Flash'} =~ /not fired/i ||
482                     $info->{'Flash'} =~ /Off/)  {
483                         push @lines, "No flash";
484                 } elsif ($info->{'Flash'} =~ /fired/i ||
485                          $info->{'Flash'} =~ /On/) {
486                         push @lines, "Flash";
487                 } else {
488                         push @lines, $info->{'Flash'};
489                 }
490         }
491
492         return if (scalar @lines == 0);
493
494         # OK, this sucks. Let's make something better :-)
495         @lines = ( join(" - ", @lines) );
496
497         # Find the required width
498         my $th = 14 * (scalar @lines) + 6;
499         my $tw = 1;
500
501         for my $line (@lines) {
502                 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
503                 $tw = $this_w if ($this_w >= $tw);
504         }
505
506         $tw += 6;
507
508         # Round up so we hit exact DCT blocks
509         $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
510         $th += 8 - ($th % 8) unless ($th % 8 == 0);
511         
512         return if ($tw > $img->Get('columns'));
513
514 #       my $x = $img->Get('columns') - 8 - $tw;
515 #       my $y = $img->Get('rows') - 8 - $th;
516         my $x = 0;
517         my $y = $img->Get('rows') - $th;
518         $tw = $img->Get('columns');
519
520         $x -= $x % 8;
521         $y -= $y % 8;
522
523         my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
524         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
525 #       $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
526         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
527         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
528
529         my $i = -(scalar @lines - 1)/2.0;
530         my $xc = $x + $tw / 2 - $img->Get('columns')/2;
531         my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
532         #my $yc = ($y + $img->Get('rows'))/4;
533         my $yi = $th / (scalar @lines);
534         
535         $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
536
537         for my $line (@lines) {
538                 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
539                 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
540                         x=>int($xc), y=>int($yc + $i * $yi));
541         
542                 $i = $i + 1;
543         }
544 }
545
546 sub gcd {
547         my ($a, $b) = @_;
548         return $a if ($b == 0);
549         return gcd($b, $a % $b);
550 }
551
552 sub add_new_event {
553         my ($dbh, $id, $date, $desc, $vhost) = @_;
554         my @errors = ();
555
556         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
557                 push @errors, "Manglende eller ugyldig ID.";
558         }
559         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
560                 push @errors, "Manglende eller ugyldig dato.";
561         }
562         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
563                 push @errors, "Manglende eller ugyldig beskrivelse.";
564         }
565         
566         if (scalar @errors > 0) {
567                 return @errors;
568         }
569                 
570         $dbh->do("INSERT INTO events (id,date,name,vhost) VALUES (?,?,?,?)",
571                 undef, $id, $date, $desc, $vhost)
572                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
573         $dbh->do("INSERT INTO last_picture_cache (event,last_picture) VALUES (?,NULL)",
574                 undef, $id)
575                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
576
577         return ();
578 }
579
580 sub guess_charset {
581         my $text = shift;
582         my $decoded;
583
584         eval {
585                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
586         };
587         if ($@) {
588                 $decoded = Encode::decode("iso8859-1", $text);
589         }
590
591         return $decoded;
592 }
593
594 1;
595
596