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