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