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