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