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