]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
e446ca831969567ae788fc4289912df6fd4289d7
[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.40";
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 => Encode::decode_utf8($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 (vhost,event)=(SELECT vhost,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                 my $err;
318
319                 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
320                 # The delegate support is rather broken and causes very odd stuff to happen when
321                 # more than one thread does this at the same time. Thus, we simply do it ourselves.
322                 if ($filename =~ /\.nef$/) {
323                         # this would suffice if ImageMagick gets to fix their handling
324                         # $fname = "NEF:$fname";
325                         
326                         open DCRAW, "-|", "dcraw", "-w", "-c", $fname
327                                 or error("dcraw: $!");
328                         $err = $magick->Read(file => \*DCRAW);
329                         close(DCRAW);
330                 } else {
331                         $err = $magick->Read($fname);
332                 }
333                 
334                 if ($err) {
335                         $r->log->warn("$fname: $err");
336                         $err =~ /(\d+)/;
337                         if ($1 >= 400) {
338                                 undef $magick;
339                                 error($r, "$fname: $err");
340                         }
341                 }
342
343                 # If we use ->[0] unconditionally, text rendering (!) seems to crash
344                 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
345
346                 my $width = $img->Get('columns');
347                 my $height = $img->Get('rows');
348
349                 # Update the SQL database if it doesn't contain the required info
350                 if ($dbwidth == -1 || $dbheight == -1) {
351                         $r->log->info("Updating width/height for $id: $width x $height");
352                         update_image_info($r, $id, $width, $height);
353                 }
354                         
355                 # We always want RGB JPEGs
356                 if ($img->Get('Colorspace') eq "CMYK") {
357                         $img->Set(colorspace=>'RGB');
358                 }
359
360                 while (defined($xres) && defined($yres)) {
361                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
362                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
363                         
364                         my $cimg;
365                         if (defined($nxres) && defined($nyres)) {
366                                 # we have more resolutions to scale, so don't throw
367                                 # the image away
368                                 $cimg = $img->Clone();
369                         } else {
370                                 $cimg = $img;
371                         }
372                 
373                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
374
375                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
376                         my $filter = 'Mitchell';
377                         my $quality = 90;
378                         my $sf = undef;
379
380                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
381                                 $filter = 'Lanczos';
382                                 $quality = 85;
383                                 $sf = "1x1";
384                         }
385
386                         if ($xres != -1) {
387                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
388                         }
389
390                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
391                                 make_infobox($cimg, $info, $r);
392                         }
393
394                         # Strip EXIF tags etc.
395                         $cimg->Strip();
396
397                         {
398                                 my %parms = (
399                                         filename => $cachename,
400                                         quality => $quality
401                                 );
402                                 if (($nwidth >= 640 && $nheight >= 480) ||
403                                     ($nwidth >= 480 && $nheight >= 640)) {
404                                         $parms{'interlace'} = 'Plane';
405                                 }
406                                 if (defined($sf)) {
407                                         $parms{'scaling-factor'} = $sf;
408                                 }
409                                 $err = $cimg->write(%parms);
410                         }
411
412                         undef $cimg;
413
414                         ($xres, $yres) = ($nxres, $nyres);
415
416                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
417                 }
418                 
419                 undef $magick;
420                 undef $img;
421                 if ($err) {
422                         $r->log->warn("$fname: $err");
423                         $err =~ /(\d+)/;
424                         if ($1 >= 400) {
425                                 @$magick = ();
426                                 error($r, "$fname: $err");
427                         }
428                 }
429         }
430         return ($cachename, 1);
431 }
432
433 sub get_mimetype_from_filename {
434         my $filename = shift;
435         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
436         $type = "image/jpeg" if (!defined($type));
437         return $type;
438 }
439
440 sub make_infobox {
441         my ($img, $info, $r) = @_;
442         
443         my @lines = ();
444         my @classic_fields = ();
445         
446         if (defined($info->{'DateTimeOriginal'}) &&
447             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
448             && $1 >= 1990) {
449                 push @lines, "$1-$2-$3 $4:$5";
450         }
451
452         if (defined($info->{'Model'})) {
453                 my $model = $info->{'Model'}; 
454                 $model =~ s/^\s+//;
455                 $model =~ s/\s+$//;
456                 push @lines, $model;
457         }
458         
459         # classic fields
460         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
461                 push @classic_fields, ($1 . "mm");
462         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
463                 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
464         }
465         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
466                 my ($a, $b) = ($1, $2);
467                 my $gcd = gcd($a, $b);
468                 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
469         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
470                 push @classic_fields, ($1 . "s");
471         }
472         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
473                 my $f = $1/$2;
474                 if ($f >= 10) {
475                         push @classic_fields, (sprintf "f/%.0f", $f);
476                 } else {
477                         push @classic_fields, (sprintf "f/%.1f", $f);
478                 }
479         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
480                 my $f = $info->{'FNumber'};
481                 if ($f >= 10) {
482                         push @classic_fields, (sprintf "f/%.0f", $f);
483                 } else {
484                         push @classic_fields, (sprintf "f/%.1f", $f);
485                 }
486         }
487
488 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
489
490         if (defined($info->{'NikonD1-ISOSetting'})) {
491                 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
492         } elsif (defined($info->{'ISOSetting'})) {
493                 push @classic_fields, $info->{'ISOSetting'} . " ISO";
494         }
495
496         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0) {
497                 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
498         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
499                 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
500         }
501         
502         if (scalar @classic_fields > 0) {
503                 push @lines, join(', ', @classic_fields);
504         }
505
506         if (defined($info->{'Flash'})) {
507                 if ($info->{'Flash'} =~ /did not fire/i ||
508                     $info->{'Flash'} =~ /no flash/i ||
509                     $info->{'Flash'} =~ /not fired/i ||
510                     $info->{'Flash'} =~ /Off/)  {
511                         push @lines, "No flash";
512                 } elsif ($info->{'Flash'} =~ /fired/i ||
513                          $info->{'Flash'} =~ /On/) {
514                         push @lines, "Flash";
515                 } else {
516                         push @lines, $info->{'Flash'};
517                 }
518         }
519
520         return if (scalar @lines == 0);
521
522         # OK, this sucks. Let's make something better :-)
523         @lines = ( join(" - ", @lines) );
524
525         # Find the required width
526         my $th = 14 * (scalar @lines) + 6;
527         my $tw = 1;
528
529         for my $line (@lines) {
530                 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
531                 $tw = $this_w if ($this_w >= $tw);
532         }
533
534         $tw += 6;
535
536         # Round up so we hit exact DCT blocks
537         $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
538         $th += 8 - ($th % 8) unless ($th % 8 == 0);
539         
540         return if ($tw > $img->Get('columns'));
541
542 #       my $x = $img->Get('columns') - 8 - $tw;
543 #       my $y = $img->Get('rows') - 8 - $th;
544         my $x = 0;
545         my $y = $img->Get('rows') - $th;
546         $tw = $img->Get('columns');
547
548         $x -= $x % 8;
549         $y -= $y % 8;
550
551         my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
552         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
553 #       $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
554         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
555         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
556
557         my $i = -(scalar @lines - 1)/2.0;
558         my $xc = $x + $tw / 2 - $img->Get('columns')/2;
559         my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
560         #my $yc = ($y + $img->Get('rows'))/4;
561         my $yi = $th / (scalar @lines);
562         
563         $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
564
565         for my $line (@lines) {
566                 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
567                 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
568                         x=>int($xc), y=>int($yc + $i * $yi));
569         
570                 $i = $i + 1;
571         }
572 }
573
574 sub gcd {
575         my ($a, $b) = @_;
576         return $a if ($b == 0);
577         return gcd($b, $a % $b);
578 }
579
580 sub add_new_event {
581         my ($dbh, $id, $date, $desc, $vhost) = @_;
582         my @errors = ();
583
584         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
585                 push @errors, "Manglende eller ugyldig ID.";
586         }
587         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
588                 push @errors, "Manglende eller ugyldig dato.";
589         }
590         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
591                 push @errors, "Manglende eller ugyldig beskrivelse.";
592         }
593         
594         if (scalar @errors > 0) {
595                 return @errors;
596         }
597                 
598         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
599                 undef, $id, $date, $desc, $vhost)
600                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
601         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
602                 undef, $vhost, $id)
603                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
604
605         return ();
606 }
607
608 sub guess_charset {
609         my $text = shift;
610         my $decoded;
611
612         eval {
613                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
614         };
615         if ($@) {
616                 $decoded = Encode::decode("iso8859-1", $text);
617         }
618
619         return $decoded;
620 }
621
622 1;
623
624