]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Add model/lens fields to the images table, and make upgrade code to populate
[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.49";
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', 'ValueConv');
263                 my $lens = $exiftool->GetValue('Lens', 'ValueConv');
264                 $lens = $exiftool->GetValue('LensSpec', 'ValueConv') if (!defined($lens));
265
266                 $model =~ s/^\s*//;
267                 $model =~ s/\s*$//;
268
269                 $lens =~ s/^\s*//;
270                 $lens =~ s/\s*$//;
271                 
272                 # Now update the main table with the information we've got
273                 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
274                          undef, $width, $height, $datetime, $model, $lens, $id)
275                         or die "Couldn't update width/height in SQL: $!";
276                 
277                 # Tags
278                 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
279                 $dbh->do('DELETE FROM tags WHERE image=?',
280                         undef, $id)
281                         or die "Couldn't delete old tag information in SQL: $!";
282
283                 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
284                         or die "Couldn't prepare inserting tag information: $!";
285
286
287                 for my $tag (@tags) {
288                         $q->execute($id, guess_charset($tag))
289                                 or die "Couldn't insert tag information in database: $!";
290                 }
291
292                 # update the last_picture cache as well (this should of course be done
293                 # via a trigger, but this is less complicated :-) )
294                 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
295                         undef, $datetime, $id)
296                         or die "Couldn't update last_picture in SQL: $!";
297         }
298 }
299
300 sub check_access {
301         my $r = shift;
302
303         my $auth = $r->headers_in->{'authorization'};
304         if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
305                 $r->content_type('text/plain; charset=utf-8');
306                 $r->status(401);
307                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
308                 $r->print("Need authorization\n");
309                 return undef;
310         }
311         
312         #return qw(sesse Sesse);
313
314         my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
315         # WinXP is stupid :-)
316         if ($user =~ /^.*\\(.*)$/) {
317                 $user = $1;
318         }
319
320         my $takenby;
321         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
322                 $user = $1;
323                 $takenby = $2;
324         } else {
325                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
326         }
327         
328         my $oldpass = $pass;
329         $pass = Digest::SHA1::sha1_base64($pass);
330         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
331                 undef, $user, $pass, $r->get_server_name);
332         if ($ref->{'auth'} != 1) {
333                 $r->content_type('text/plain; charset=utf-8');
334                 warn "No user exists, only $auth";
335                 $r->status(401);
336                 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
337                 $r->print("Authorization failed");
338                 $r->log->warn("Authentication failed for $user/$takenby");
339                 return undef;
340         }
341
342         $r->log->info("Authentication succeeded for $user/$takenby");
343
344         return ($user, $takenby);
345 }
346         
347 sub stat_image {
348         my ($r, $event, $filename) = (@_);
349         my $ref = $dbh->selectrow_hashref(
350                 'SELECT id FROM images WHERE event=? AND filename=?',
351                 undef, $event, $filename);
352         if (!defined($ref)) {
353                 return (undef, undef, undef);
354         }
355         return stat_image_from_id($r, $ref->{'id'});
356 }
357
358 sub stat_image_from_id {
359         my ($r, $id) = @_;
360
361         my $fname = get_disk_location($r, $id);
362         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
363                 or return (undef, undef, undef);
364
365         return ($fname, $size, $mtime);
366 }
367
368 sub ensure_cached {
369         my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
370
371         my $fname = get_disk_location($r, $id);
372         unless (defined($xres) && ($xres < $dbheight || $yres < $dbwidth || !defined($dbwidth) || !defined($dbheight) || $xres == -1)) {
373                 return ($fname, 0);
374         }
375
376         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
377         if (! -r $cachename or (-M $cachename > -M $fname)) {
378                 # If we are in overload mode (aka Slashdot mode), refuse to generate
379                 # new thumbnails.
380                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
381                         $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
382                         error($r, 'System is in overload mode, not doing any scaling');
383                 }
384         
385                 # Need to generate the cache; read in the image
386                 my $magick = new Image::Magick;
387                 my $info = Image::ExifTool::ImageInfo($fname);
388                 my $err;
389
390                 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
391                 # The delegate support is rather broken and causes very odd stuff to happen when
392                 # more than one thread does this at the same time. Thus, we simply do it ourselves.
393                 if ($filename =~ /\.nef$/) {
394                         # this would suffice if ImageMagick gets to fix their handling
395                         # $fname = "NEF:$fname";
396                         
397                         open DCRAW, "-|", "dcraw", "-w", "-c", $fname
398                                 or error("dcraw: $!");
399                         $err = $magick->Read(file => \*DCRAW);
400                         close(DCRAW);
401                 } else {
402                         $err = $magick->Read($fname);
403                 }
404                 
405                 if ($err) {
406                         $r->log->warn("$fname: $err");
407                         $err =~ /(\d+)/;
408                         if ($1 >= 400) {
409                                 undef $magick;
410                                 error($r, "$fname: $err");
411                         }
412                 }
413
414                 # If we use ->[0] unconditionally, text rendering (!) seems to crash
415                 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
416
417                 my $width = $img->Get('columns');
418                 my $height = $img->Get('rows');
419
420                 # Update the SQL database if it doesn't contain the required info
421                 if (!defined($dbwidth) || !defined($dbheight)) {
422                         $r->log->info("Updating width/height for $id: $width x $height");
423                         update_image_info($r, $id, $width, $height);
424                 }
425                         
426                 # We always want RGB JPEGs
427                 if ($img->Get('Colorspace') eq "CMYK") {
428                         $img->Set(colorspace=>'RGB');
429                 }
430
431                 while (defined($xres) && defined($yres)) {
432                         my ($nxres, $nyres) = (shift @otherres, shift @otherres);
433                         my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
434                         
435                         my $cimg;
436                         if (defined($nxres) && defined($nyres)) {
437                                 # we have more resolutions to scale, so don't throw
438                                 # the image away
439                                 $cimg = $img->Clone();
440                         } else {
441                                 $cimg = $img;
442                         }
443                 
444                         my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
445
446                         # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
447                         my $filter = 'Mitchell';
448                         my $quality = 90;
449                         my $sf = undef;
450
451                         if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
452                                 $filter = 'Lanczos';
453                                 $quality = 85;
454                                 $sf = "1x1";
455                         }
456
457                         if ($xres != -1) {
458                                 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
459                         }
460
461                         if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox == 1) {
462                                 make_infobox($cimg, $info, $r);
463                         }
464
465                         # Strip EXIF tags etc.
466                         $cimg->Strip();
467
468                         {
469                                 my %parms = (
470                                         filename => $cachename,
471                                         quality => $quality
472                                 );
473                                 if (($nwidth >= 640 && $nheight >= 480) ||
474                                     ($nwidth >= 480 && $nheight >= 640)) {
475                                         $parms{'interlace'} = 'Plane';
476                                 }
477                                 if (defined($sf)) {
478                                         $parms{'sampling-factor'} = $sf;
479                                 }
480                                 $err = $cimg->write(%parms);
481                         }
482
483                         undef $cimg;
484
485                         ($xres, $yres) = ($nxres, $nyres);
486
487                         $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
488                 }
489                 
490                 undef $magick;
491                 undef $img;
492                 if ($err) {
493                         $r->log->warn("$fname: $err");
494                         $err =~ /(\d+)/;
495                         if ($1 >= 400) {
496                                 @$magick = ();
497                                 error($r, "$fname: $err");
498                         }
499                 }
500         }
501         return ($cachename, 1);
502 }
503
504 sub get_mimetype_from_filename {
505         my $filename = shift;
506         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
507         $type = "image/jpeg" if (!defined($type));
508         return $type;
509 }
510
511 sub make_infobox {
512         my ($img, $info, $r) = @_;
513         
514         my @lines = ();
515         my @classic_fields = ();
516         
517         if (defined($info->{'DateTimeOriginal'}) &&
518             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
519             && $1 >= 1990) {
520                 push @lines, "$1-$2-$3 $4:$5";
521         }
522
523         if (defined($info->{'Model'})) {
524                 my $model = $info->{'Model'}; 
525                 $model =~ s/^\s+//;
526                 $model =~ s/\s+$//;
527                 push @lines, $model;
528         }
529         
530         # classic fields
531         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?(?:mm)?$/) {
532                 push @classic_fields, ($1 . "mm");
533         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
534                 push @classic_fields, (sprintf "%.1fmm", ($1/$2));
535         }
536         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
537                 my ($a, $b) = ($1, $2);
538                 my $gcd = gcd($a, $b);
539                 push @classic_fields, ($a/$gcd . "/" . $b/$gcd . "s");
540         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
541                 push @classic_fields, ($1 . "s");
542         }
543         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
544                 my $f = $1/$2;
545                 if ($f >= 10) {
546                         push @classic_fields, (sprintf "f/%.0f", $f);
547                 } else {
548                         push @classic_fields, (sprintf "f/%.1f", $f);
549                 }
550         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
551                 my $f = $info->{'FNumber'};
552                 if ($f >= 10) {
553                         push @classic_fields, (sprintf "f/%.0f", $f);
554                 } else {
555                         push @classic_fields, (sprintf "f/%.1f", $f);
556                 }
557         }
558
559 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
560
561         if (defined($info->{'NikonD1-ISOSetting'})) {
562                 push @classic_fields, $info->{'NikonD1-ISOSetting'}->[1] . " ISO";
563         } elsif (defined($info->{'ISOSetting'})) {
564                 push @classic_fields, $info->{'ISOSetting'} . " ISO";
565         }
566
567         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
568                 push @classic_fields, $info->{'ExposureBiasValue'} . " EV";
569         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
570                 push @classic_fields, $info->{'ExposureCompensation'} . " EV";
571         }
572         
573         if (scalar @classic_fields > 0) {
574                 push @lines, join(', ', @classic_fields);
575         }
576
577         if (defined($info->{'Flash'})) {
578                 if ($info->{'Flash'} =~ /did not fire/i ||
579                     $info->{'Flash'} =~ /no flash/i ||
580                     $info->{'Flash'} =~ /not fired/i ||
581                     $info->{'Flash'} =~ /Off/)  {
582                         push @lines, "No flash";
583                 } elsif ($info->{'Flash'} =~ /fired/i ||
584                          $info->{'Flash'} =~ /On/) {
585                         push @lines, "Flash";
586                 } else {
587                         push @lines, $info->{'Flash'};
588                 }
589         }
590
591         return if (scalar @lines == 0);
592
593         # OK, this sucks. Let's make something better :-)
594         @lines = ( join(" - ", @lines) );
595
596         # Find the required width
597         my $th = 14 * (scalar @lines) + 6;
598         my $tw = 1;
599
600         for my $line (@lines) {
601                 my $this_w = ($img->QueryFontMetrics(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12))[4];
602                 $tw = $this_w if ($this_w >= $tw);
603         }
604
605         $tw += 6;
606
607         # Round up so we hit exact DCT blocks
608         $tw += 8 - ($tw % 8) unless ($tw % 8 == 0);
609         $th += 8 - ($th % 8) unless ($th % 8 == 0);
610         
611         return if ($tw > $img->Get('columns'));
612
613 #       my $x = $img->Get('columns') - 8 - $tw;
614 #       my $y = $img->Get('rows') - 8 - $th;
615         my $x = 0;
616         my $y = $img->Get('rows') - $th;
617         $tw = $img->Get('columns');
618
619         $x -= $x % 8;
620         $y -= $y % 8;
621
622         my $points = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), ($img->Get('rows') - 1);
623         my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($x+$tw-1), $y;
624 #       $img->Draw(primitive=>'rectangle', stroke=>'black', fill=>'white', points=>$points);
625         $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
626         $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
627
628         my $i = -(scalar @lines - 1)/2.0;
629         my $xc = $x + $tw / 2 - $img->Get('columns')/2;
630         my $yc = ($y + $img->Get('rows'))/2 - $img->Get('rows')/2;
631         #my $yc = ($y + $img->Get('rows'))/4;
632         my $yi = $th / (scalar @lines);
633         
634         $lpoints = sprintf "%u,%u %u,%u", $x, $yc + $img->Get('rows')/2, ($x+$tw-1), $yc+$img->Get('rows')/2;
635
636         for my $line (@lines) {
637                 $img->Annotate(text=>$line, font=>'/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', pointsize=>12, gravity=>'Center',
638                 # $img->Annotate(text=>$line, font=>'Helvetica', pointsize=>12, gravity=>'Center',
639                         x=>int($xc), y=>int($yc + $i * $yi));
640         
641                 $i = $i + 1;
642         }
643 }
644
645 sub gcd {
646         my ($a, $b) = @_;
647         return $a if ($b == 0);
648         return gcd($b, $a % $b);
649 }
650
651 sub add_new_event {
652         my ($dbh, $id, $date, $desc, $vhost) = @_;
653         my @errors = ();
654
655         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
656                 push @errors, "Manglende eller ugyldig ID.";
657         }
658         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
659                 push @errors, "Manglende eller ugyldig dato.";
660         }
661         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
662                 push @errors, "Manglende eller ugyldig beskrivelse.";
663         }
664         
665         if (scalar @errors > 0) {
666                 return @errors;
667         }
668                 
669         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
670                 undef, $id, $date, $desc, $vhost)
671                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
672         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
673                 undef, $vhost, $id)
674                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
675
676         return ();
677 }
678
679 sub guess_charset {
680         my $text = shift;
681         my $decoded;
682
683         eval {
684                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
685         };
686         if ($@) {
687                 $decoded = Encode::decode("iso8859-1", $text);
688         }
689
690         return $decoded;
691 }
692
693 1;
694
695