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