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