]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Escape titles and dates on their way out of the HTML. It _shouldn't_ be
[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.21";
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 => $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_width_height {
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         $dbh->do('UPDATE images SET width=?, height=?, date=? WHERE id=?',
202                  undef, $width, $height, $datetime, $id)
203                 or die "Couldn't update width/height in SQL: $!";
204
205         # update the last_picture cache as well (this should of course be done
206         # via a trigger, but this is less complicated :-) )
207         $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE event=(SELECT event FROM images WHERE id=?)',
208                 undef, $datetime, $id)
209                 or die "Couldn't update last_picture in SQL: $!";
210 }
211
212 sub check_access {
213         my $r = shift;
214
215         my $auth = $r->headers_in->{'authorization'};
216         if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
217                 $r->content_type('text/plain; charset=utf-8');
218                 $r->status(401);
219                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
220                 $r->print("Need authorization\n");
221                 return undef;
222         }
223         
224         #return qw(sesse Sesse);
225
226         my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
227         # WinXP is stupid :-)
228         if ($user =~ /^.*\\(.*)$/) {
229                 $user = $1;
230         }
231
232         my $takenby;
233         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
234                 $user = $1;
235                 $takenby = $2;
236         } else {
237                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
238         }
239         
240         my $oldpass = $pass;
241         $pass = Digest::SHA1::sha1_base64($pass);
242         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
243                 undef, $user, $pass, $r->get_server_name);
244         if ($ref->{'auth'} != 1) {
245                 $r->content_type('text/plain; charset=utf-8');
246                 warn "No user exists, only $auth";
247                 $r->status(401);
248                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
249                 $r->print("Authorization failed");
250                 $r->log->warn("Authentication failed for $user/$takenby");
251                 return undef;
252         }
253
254         $r->log->info("Authentication succeeded for $user/$takenby");
255
256         return ($user, $takenby);
257 }
258         
259 sub stat_image {
260         my ($r, $event, $filename) = (@_);
261         my $ref = $dbh->selectrow_hashref(
262                 'SELECT id FROM images WHERE event=? AND filename=?',
263                 undef, $event, $filename);
264         if (!defined($ref)) {
265                 return (undef, undef, undef);
266         }
267         return stat_image_from_id($r, $ref->{'id'});
268 }
269
270 sub stat_image_from_id {
271         my ($r, $id) = @_;
272
273         my $fname = get_disk_location($r, $id);
274         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
275                 or return (undef, undef, undef);
276
277         return ($fname, $size, $mtime);
278 }
279
280 sub ensure_cached {
281         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
282
283         my $fname = get_disk_location($r, $id);
284         unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || $dbwidth == -1 || $dbheight == -1 || $xres == -1)) {
285                 return ($fname, 0);
286         }
287
288         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
289         if (! -r $cachename or (-M $cachename > -M $fname)) {
290                 # If we are in overload mode (aka Slashdot mode), refuse to generate
291                 # new thumbnails.
292                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
293                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
294                         error($r, 'System is in overload mode, not doing any scaling');
295                 }
296         
297                 # Need to generate the cache; read in the image
298                 my $magick = new Image::Magick;
299                 my $info = Image::ExifTool::ImageInfo($fname);
300
301                 # NEF files aren't autodetected
302                 $fname = "NEF:$fname" if ($filename =~ /\.nef$/i);
303                 
304                 my $err = $magick->Read($fname);
305                 if ($err) {
306                         $r->log->warn("$fname: $err");
307                         $err =~ /(\d+)/;
308                         if ($1 >= 400) {
309                                 undef $magick;
310                                 error($r, "$fname: $err");
311                         }
312                 }
313
314                 # If we use ->[0] unconditionally, text rendering (!) seems to crash
315                 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
316
317                 my $width = $img->Get('columns');
318                 my $height = $img->Get('rows');
319
320                 # Update the SQL database if it doesn't contain the required info
321                 if ($dbwidth == -1 || $dbheight == -1) {
322                         $r->log->info("Updating width/height for $id: $width x $height");
323                         update_width_height($r, $id, $width, $height);
324                 }
325                         
326                 # We always want RGB JPEGs
327                 if ($img->Get('Colorspace') eq "CMYK") {
328                         $img->Set(colorspace=>'RGB');
329                 }
330
331                 while (defined($xres) && defined($yres)) {
332                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
333                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
334                         
335                         my $cimg;
336                         if (defined($nxres) && defined($nyres)) {
337                                 # we have more resolutions to scale, so don't throw
338                                 # the image away
339                                 $cimg = $img->Clone();
340                         } else {
341                                 $cimg = $img;
342                         }
343                 
344                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
345
346                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
347                         my $filter = 'Mitchell';
348                         my $quality = 90;
349
350                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
351                                 $filter = 'Lanczos';
352                                 $quality = 80;
353                         }
354
355                         if ($xres != -1) {
356                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
357                         }
358
359                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
360                                 make_infobox($cimg, $info, $r);
361                         }
362
363                         # Strip EXIF tags etc.
364                         $cimg->Strip();
365
366                         if (($nwidth >= 640 && $nheight >= 480) ||
367                             ($nwidth >= 480 && $nheight >= 640)) {
368                                 $err = $cimg->write(filename=>$cachename, quality=>$quality, interlace=>'Plane');
369                         } else {
370                                 $err = $cimg->write(filename=>$cachename, quality=>$quality);
371                         }
372
373                         undef $cimg;
374
375                         ($xres, $yres) = ($nxres, $nyres);
376
377                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
378                 }
379                 
380                 undef $magick;
381                 undef $img;
382                 if ($err) {
383                         $r->log->warn("$fname: $err");
384                         $err =~ /(\d+)/;
385                         if ($1 >= 400) {
386                                 @$magick = ();
387                                 error($r, "$fname: $err");
388                         }
389                 }
390         }
391         return ($cachename, 1);
392 }
393
394 sub get_mimetype_from_filename {
395         my $filename = shift;
396         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
397         $type = "image/jpeg" if (!defined($type));
398         return $type;
399 }
400
401 sub make_infobox {
402         my ($img, $info, $r) = @_;
403         
404         my @lines = ();
405         my @classic_fields = ();
406         
407         if (defined($info->{'DateTimeOriginal'}) &&
408             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
409             && $1 >= 1990) {
410                 push @lines, "$1-$2-$3 $4:$5";
411         }
412
413         if (defined($info->{'Model'})) {
414                 my $model = $info->{'Model'}; 
415                 $model =~ s/^\s+//;
416                 $model =~ s/\s+$//;
417                 push @lines, $model;
418         }
419         
420         # classic fields
421         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
422                 push @classic_fields, ($1 . "mm");
423         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
424                 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
425         }
426         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
427                 my ($a, $b) = ($1, $2);
428                 my $gcd = gcd($a, $b);
429                 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
430         }
431         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
432                 my $f = $1/$2;
433                 if ($f >= 10) {
434                         push @classic_fields, (sprintf "f/%.0f", $f);
435                 } else {
436                         push @classic_fields, (sprintf "f/%.1f", $f);
437                 }
438         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
439                 my $f = $info->{'FNumber'};
440                 if ($f >= 10) {
441                         push @classic_fields, (sprintf "f/%.0f", $f);
442                 } else {
443                         push @classic_fields, (sprintf "f/%.1f", $f);
444                 }
445         }
446
447 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
448
449         if (defined($info->{'NikonD1-ISOSetting'})) {
450                 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
451         } elsif (defined($info->{'ISOSetting'})) {
452                 push @classic_fields, $info->{'ISOSetting'} . " ISO";
453         }
454
455         push @classic_fields, $info->{'ExposureBiasValue'} . " EV" if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} != 0);
456         
457         if (scalar @classic_fields > 0) {
458                 push @lines, join(', ', @classic_fields);
459         }
460
461         if (defined($info->{'Flash'})) {
462                 if ($info->{'Flash'} =~ /did not fire/i ||
463                     $info->{'Flash'} =~ /no flash/i ||
464                     $info->{'Flash'} =~ /not fired/i ||
465                     $info->{'Flash'} =~ /Off/)  {
466                         push @lines, "No flash";
467                 } elsif ($info->{'Flash'} =~ /fired/i ||
468                          $info->{'Flash'} =~ /On/) {
469                         push @lines, "Flash";
470                 } else {
471                         push @lines, $info->{'Flash'};
472                 }
473         }
474
475         return if (scalar @lines == 0);
476
477         # OK, this sucks. Let's make something better :-)
478         @lines = ( join(" - ", @lines) );
479
480         # Find the required width
481         my $th = 14 * (scalar @lines) + 6;
482         my $tw = 1;
483
484         for my $line (@lines) {
485                 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
486                 $tw = $this_w if ($this_w >= $tw);
487         }
488
489         $tw += 6;
490
491         # Round up so we hit exact DCT blocks
492         $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
493         $th += 8 - ($th % 8) unless ($th % 8 == 0);
494         
495         return if ($tw > $img->Get('columns'));
496
497 #       my $x = $img->Get('columns') - 8 - $tw;
498 #       my $y = $img->Get('rows') - 8 - $th;
499         my $x = 0;
500         my $y = $img->Get('rows') - $th;
501         $tw = $img->Get('columns');
502
503         $x -= $x % 8;
504         $y -= $y % 8;
505
506         my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
507         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
508 #       $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
509         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
510         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
511
512         my $i = -(scalar @lines - 1)/2.0;
513         my $xc = $x + $tw / 2 - $img->Get('columns')/2;
514         my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
515         #my $yc = ($y + $img->Get('rows'))/4;
516         my $yi = $th / (scalar @lines);
517         
518         $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
519
520         for my $line (@lines) {
521                 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
522                 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
523                         x=>int($xc), y=>int($yc + $i * $yi));
524         
525                 $i = $i + 1;
526         }
527 }
528
529 sub gcd {
530         my ($a, $b) = @_;
531         return $a if ($b == 0);
532         return gcd($b, $a % $b);
533 }
534
535 sub add_new_event {
536         my ($dbh, $id, $date, $desc, $vhost) = @_;
537         my @errors = ();
538
539         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
540                 push @errors, "Manglende eller ugyldig ID.";
541         }
542         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
543                 push @errors, "Manglende eller ugyldig dato.";
544         }
545         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
546                 push @errors, "Manglende eller ugyldig beskrivelse.";
547         }
548         
549         if (scalar @errors > 0) {
550                 return @errors;
551         }
552                 
553         $dbh->do("INSERT INTO events (id,date,name,vhost) VALUES (?,?,?,?)",
554                 undef, $id, $date, $desc, $vhost)
555                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
556         $dbh->do("INSERT INTO last_picture_cache (event,last_picture) VALUES (?,NULL)",
557                 undef, $id)
558                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
559
560         return ();
561 }
562
563 sub guess_charset {
564         my $text = shift;
565         my $decoded;
566
567         eval {
568                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
569         };
570         if ($@) {
571                 $decoded = Encode::decode("iso8859-1", $text);
572         }
573
574         return $decoded;
575 }
576
577 1;
578
579