]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Version number bump.
[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.30";
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         {
202                 local $dbh->{AutoCommit} = 0;
203
204                 $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
205                          undef, $width, $height, $datetime, $id)
206                         or die "Couldn't update width/height in SQL: $!";
207
208                 $dbh->do('DELETE FROM exif_info WHERE image=?',
209                         undef, $id)
210                         or die "Couldn't delete old EXIF information in SQL: $!";
211
212                 my $q = $dbh->prepare('INSERT INTO exif_info (image,tag,value) VALUES (?,?,?)')
213                         or die "Couldn't prepare inserting EXIF information: $!";
214
215                 for my $key (keys %$info) {
216                         next if ref $info->{$key};
217                         $q->execute($id, $key, guess_charset($info->{$key}))
218                                 or die "Couldn't insert EXIF information in database: $!";
219                 }
220
221                 # update the last_picture cache as well (this should of course be done
222                 # via a trigger, but this is less complicated :-) )
223                 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
224                         undef, $datetime, $id)
225                         or die "Couldn't update last_picture in SQL: $!";
226         }
227 }
228
229 sub check_access {
230         my $r = shift;
231
232         my $auth = $r->headers_in->{'authorization'};
233         if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
234                 $r->content_type('text/plain; charset=utf-8');
235                 $r->status(401);
236                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
237                 $r->print("Need authorization\n");
238                 return undef;
239         }
240         
241         #return qw(sesse Sesse);
242
243         my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
244         # WinXP is stupid :-)
245         if ($user =~ /^.*\\(.*)$/) {
246                 $user = $1;
247         }
248
249         my $takenby;
250         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
251                 $user = $1;
252                 $takenby = $2;
253         } else {
254                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
255         }
256         
257         my $oldpass = $pass;
258         $pass = Digest::SHA1::sha1_base64($pass);
259         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
260                 undef, $user, $pass, $r->get_server_name);
261         if ($ref->{'auth'} != 1) {
262                 $r->content_type('text/plain; charset=utf-8');
263                 warn "No user exists, only $auth";
264                 $r->status(401);
265                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
266                 $r->print("Authorization failed");
267                 $r->log->warn("Authentication failed for $user/$takenby");
268                 return undef;
269         }
270
271         $r->log->info("Authentication succeeded for $user/$takenby");
272
273         return ($user, $takenby);
274 }
275         
276 sub stat_image {
277         my ($r, $event, $filename) = (@_);
278         my $ref = $dbh->selectrow_hashref(
279                 'SELECT id FROM images WHERE event=? AND filename=?',
280                 undef, $event, $filename);
281         if (!defined($ref)) {
282                 return (undef, undef, undef);
283         }
284         return stat_image_from_id($r, $ref->{'id'});
285 }
286
287 sub stat_image_from_id {
288         my ($r, $id) = @_;
289
290         my $fname = get_disk_location($r, $id);
291         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
292                 or return (undef, undef, undef);
293
294         return ($fname, $size, $mtime);
295 }
296
297 sub ensure_cached {
298         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
299
300         my $fname = get_disk_location($r, $id);
301         unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
302                 return ($fname, 0);
303         }
304
305         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
306         if (! -r $cachename or (-M $cachename > -M $fname)) {
307                 # If we are in overload mode (aka Slashdot mode), refuse to generate
308                 # new thumbnails.
309                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
310                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
311                         error($r, 'System is in overload mode, not doing any scaling');
312                 }
313         
314                 # Need to generate the cache; read in the image
315                 my $magick = new Image::Magick;
316                 my $info = Image::ExifTool::ImageInfo($fname);
317
318                 # NEF files aren't autodetected
319                 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
320                 
321                 my $err = $magick->Read($fname);
322                 if ($err) {
323                         $r->log->warn("$fname: $err");
324                         $err =~ /(\d+)/;
325                         if ($1 >= 400) {
326                                 undef $magick;
327                                 error($r, "$fname: $err");
328                         }
329                 }
330
331                 # If we use ->[0] unconditionally, text rendering (!) seems to crash
332                 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
333
334                 my $width = $img->Get('columns');
335                 my $height = $img->Get('rows');
336
337                 # Update the SQL database if it doesn't contain the required info
338                 if ($dbwidth == -1 || $dbheight == -1) {
339                         $r->log->info("Updating width/height for $id: $width x $height");
340                         update_image_info($r, $id, $width, $height);
341                 }
342                         
343                 # We always want RGB JPEGs
344                 if ($img->Get('Colorspace') eq "CMYK") {
345                         $img->Set(colorspace=>'RGB');
346                 }
347
348                 while (defined($xres) && defined($yres)) {
349                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
350                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
351                         
352                         my $cimg;
353                         if (defined($nxres) && defined($nyres)) {
354                                 # we have more resolutions to scale, so don't throw
355                                 # the image away
356                                 $cimg = $img->Clone();
357                         } else {
358                                 $cimg = $img;
359                         }
360                 
361                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
362
363                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
364                         my $filter = 'Mitchell';
365                         my $quality = 90;
366
367                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
368                                 $filter = 'Lanczos';
369                                 $quality = 80;
370                         }
371
372                         if ($xres != -1) {
373                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
374                         }
375
376                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
377                                 make_infobox($cimg, $info, $r);
378                         }
379
380                         # Strip EXIF tags etc.
381                         $cimg->Strip();
382
383                         if (($nwidth >= 640 && $nheight >= 480) ||
384                             ($nwidth >= 480 && $nheight >= 640)) {
385                                 $err = $cimg->write(filename=>$cachename, quality=>$quality, interlace=>'Plane');
386                         } else {
387                                 $err = $cimg->write(filename=>$cachename, quality=>$quality);
388                         }
389
390                         undef $cimg;
391
392                         ($xres, $yres) = ($nxres, $nyres);
393
394                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
395                 }
396                 
397                 undef $magick;
398                 undef $img;
399                 if ($err) {
400                         $r->log->warn("$fname: $err");
401                         $err =~ /(\d+)/;
402                         if ($1 >= 400) {
403                                 @$magick = ();
404                                 error($r, "$fname: $err");
405                         }
406                 }
407         }
408         return ($cachename, 1);
409 }
410
411 sub get_mimetype_from_filename {
412         my $filename = shift;
413         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
414         $type = "image/jpeg" if (!defined($type));
415         return $type;
416 }
417
418 sub make_infobox {
419         my ($img, $info, $r) = @_;
420         
421         my @lines = ();
422         my @classic_fields = ();
423         
424         if (defined($info->{'DateTimeOriginal'}) &&
425             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
426             && $1 >= 1990) {
427                 push @lines, "$1-$2-$3 $4:$5";
428         }
429
430         if (defined($info->{'Model'})) {
431                 my $model = $info->{'Model'}; 
432                 $model =~ s/^\s+//;
433                 $model =~ s/\s+$//;
434                 push @lines, $model;
435         }
436         
437         # classic fields
438         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
439                 push @classic_fields, ($1 . "mm");
440         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
441                 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
442         }
443         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
444                 my ($a, $b) = ($1, $2);
445                 my $gcd = gcd($a, $b);
446                 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
447         }
448         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
449                 my $f = $1/$2;
450                 if ($f >= 10) {
451                         push @classic_fields, (sprintf "f/%.0f", $f);
452                 } else {
453                         push @classic_fields, (sprintf "f/%.1f", $f);
454                 }
455         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
456                 my $f = $info->{'FNumber'};
457                 if ($f >= 10) {
458                         push @classic_fields, (sprintf "f/%.0f", $f);
459                 } else {
460                         push @classic_fields, (sprintf "f/%.1f", $f);
461                 }
462         }
463
464 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
465
466         if (defined($info->{'NikonD1-ISOSetting'})) {
467                 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
468         } elsif (defined($info->{'ISOSetting'})) {
469                 push @classic_fields, $info->{'ISOSetting'} . " ISO";
470         }
471
472         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
473                 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
474         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
475                 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
476         }
477         
478         if (scalar @classic_fields > 0) {
479                 push @lines, join(', ', @classic_fields);
480         }
481
482         if (defined($info->{'Flash'})) {
483                 if ($info->{'Flash'} =~ /did not fire/i ||
484                     $info->{'Flash'} =~ /no flash/i ||
485                     $info->{'Flash'} =~ /not fired/i ||
486                     $info->{'Flash'} =~ /Off/)  {
487                         push @lines, "No flash";
488                 } elsif ($info->{'Flash'} =~ /fired/i ||
489                          $info->{'Flash'} =~ /On/) {
490                         push @lines, "Flash";
491                 } else {
492                         push @lines, $info->{'Flash'};
493                 }
494         }
495
496         return if (scalar @lines == 0);
497
498         # OK, this sucks. Let's make something better :-)
499         @lines = ( join(" - ", @lines) );
500
501         # Find the required width
502         my $th = 14 * (scalar @lines) + 6;
503         my $tw = 1;
504
505         for my $line (@lines) {
506                 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
507                 $tw = $this_w if ($this_w >= $tw);
508         }
509
510         $tw += 6;
511
512         # Round up so we hit exact DCT blocks
513         $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
514         $th += 8 - ($th % 8) unless ($th % 8 == 0);
515         
516         return if ($tw > $img->Get('columns'));
517
518 #       my $x = $img->Get('columns') - 8 - $tw;
519 #       my $y = $img->Get('rows') - 8 - $th;
520         my $x = 0;
521         my $y = $img->Get('rows') - $th;
522         $tw = $img->Get('columns');
523
524         $x -= $x % 8;
525         $y -= $y % 8;
526
527         my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
528         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
529 #       $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
530         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
531         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
532
533         my $i = -(scalar @lines - 1)/2.0;
534         my $xc = $x + $tw / 2 - $img->Get('columns')/2;
535         my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
536         #my $yc = ($y + $img->Get('rows'))/4;
537         my $yi = $th / (scalar @lines);
538         
539         $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
540
541         for my $line (@lines) {
542                 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
543                 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
544                         x=>int($xc), y=>int($yc + $i * $yi));
545         
546                 $i = $i + 1;
547         }
548 }
549
550 sub gcd {
551         my ($a, $b) = @_;
552         return $a if ($b == 0);
553         return gcd($b, $a % $b);
554 }
555
556 sub add_new_event {
557         my ($dbh, $id, $date, $desc, $vhost) = @_;
558         my @errors = ();
559
560         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
561                 push @errors, "Manglende eller ugyldig ID.";
562         }
563         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
564                 push @errors, "Manglende eller ugyldig dato.";
565         }
566         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
567                 push @errors, "Manglende eller ugyldig beskrivelse.";
568         }
569         
570         if (scalar @errors > 0) {
571                 return @errors;
572         }
573                 
574         $dbh->do("INSERT INTO events (id,date,name,vhost) VALUES (?,?,?,?)",
575                 undef, $id, $date, $desc, $vhost)
576                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
577         $dbh->do("INSERT INTO last_picture_cache (event,last_picture) VALUES (?,NULL)",
578                 undef, $id)
579                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
580
581         return ();
582 }
583
584 sub guess_charset {
585         my $text = shift;
586         my $decoded;
587
588         eval {
589                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
590         };
591         if ($@) {
592                 $decoded = Encode::decode("iso8859-1", $text);
593         }
594
595         return $decoded;
596 }
597
598 1;
599
600