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