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