1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Templates;
6 use Sesse::pr0n::Overload;
8 use Apache2::RequestRec (); # for $r->content_type
9 use Apache2::RequestIO (); # for $r->print
10 use Apache2::Const -compile => ':common';
31 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 use Sesse::pr0n::Config;
35 require Sesse::pr0n::Config_local;
40 @EXPORT = qw(&error &dberror);
42 @EXPORT_OK = qw(&error &dberror);
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;
49 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
56 our ($dbh, $mimetypes);
59 my ($r,$err,$status,$title) = @_;
61 if (!defined($status) || !defined($title)) {
63 $title = "Internal server error";
66 $r->content_type('text/html; charset=utf-8');
70 $r->print(" <p>Error: $err</p>\n");
74 $r->log->error("Stack trace follows: " . Carp::longmess());
76 ModPerl::Util::exit();
81 error($r, "$err (DB error: " . $dbh->errstr . ")");
87 $r->content_type("text/html; charset=utf-8");
89 # Fetch quote if we're itk-bilder.samfundet.no
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));
95 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
100 Sesse::pr0n::Templates::print_template($r, "footer",
101 { version => $Sesse::pr0n::Common::VERSION });
105 my ($width, $height, $thumbxres, $thumbyres) = @_;
107 unless ($thumbxres >= $width &&
108 $thumbyres >= $height) {
109 my $sfh = $width / $thumbxres;
110 my $sfv = $height / $thumbyres;
118 $width = POSIX::floor($width);
119 $height = POSIX::floor($height);
122 return ($width, $height);
125 sub get_query_string {
126 my ($param, $defparam) = @_;
130 while (my ($key, $value) = each %$param) {
131 next unless defined($value);
132 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
134 $value = pretty_escape($value);
136 $str .= ($first) ? "?" : ';';
137 $str .= "$key=$value";
143 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
144 sub weird_space_encode {
147 return "_" x (length($val) * 2);
149 return "_" x (length($val) * 2 - 1);
153 sub weird_space_unencode {
155 if (length($val) % 2 == 0) {
156 return "_" x (length($val) / 2);
158 return " " x ((length($val) + 1) / 2);
165 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
166 $value = URI::Escape::uri_escape($value);
167 $value =~ s/%2F/\//g;
172 sub pretty_unescape {
175 # URI unescaping is already done for us
176 $value =~ s/(_+)/weird_space_unencode($1)/ge;
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\"";
187 $str .= ">$title</a>";
192 # Check that we are alive
193 if (!(defined($dbh) && $dbh->ping)) {
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)) {
199 die "Couldn't connect to PostgreSQL database";
208 return $r->dir_config('ImageBase');
211 sub get_disk_location {
213 my $dir = POSIX::floor($id / 256);
214 return get_base($r) . "images/$dir/$id.jpg";
217 sub get_cache_location {
218 my ($r, $id, $width, $height, $infobox) = @_;
219 my $dir = POSIX::floor($id / 256);
221 if ($infobox eq 'both') {
222 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
223 } elsif ($infobox eq 'nobox') {
224 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
226 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
230 sub get_mipmap_location {
231 my ($r, $id, $width, $height) = @_;
232 my $dir = POSIX::floor($id / 256);
234 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
237 sub update_image_info {
238 my ($r, $id, $width, $height) = @_;
240 # Also find the date taken if appropriate (from the EXIF tag etc.)
241 my $exiftool = Image::ExifTool->new;
242 $exiftool->ExtractInfo(get_disk_location($r, $id));
243 my $info = $exiftool->GetInfo();
244 my $datetime = undef;
246 if (defined($info->{'DateTimeOriginal'})) {
247 # Parse the date and time over to ISO format
248 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
249 $datetime = "$1-$2-$3 $4:$5:$6";
254 local $dbh->{AutoCommit} = 0;
257 $dbh->do('DELETE FROM exif_info WHERE image=?',
259 or die "Couldn't delete old EXIF information in SQL: $!";
261 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
262 or die "Couldn't prepare inserting EXIF information: $!";
264 for my $key (keys %$info) {
265 next if ref $info->{$key};
266 $q->execute($id, $key, guess_charset($info->{$key}))
267 or die "Couldn't insert EXIF information in database: $!";
271 my $model = $exiftool->GetValue('Model', 'PrintConv');
272 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
273 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
277 $model = undef if (length($model) == 0);
281 $lens = undef if (length($lens) == 0);
283 # Now update the main table with the information we've got
284 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
285 undef, $width, $height, $datetime, $model, $lens, $id)
286 or die "Couldn't update width/height in SQL: $!";
289 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
290 $dbh->do('DELETE FROM tags WHERE image=?',
292 or die "Couldn't delete old tag information in SQL: $!";
294 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
295 or die "Couldn't prepare inserting tag information: $!";
298 for my $tag (@tags) {
299 $q->execute($id, guess_charset($tag))
300 or die "Couldn't insert tag information in database: $!";
303 # update the last_picture cache as well (this should of course be done
304 # via a trigger, but this is less complicated :-) )
305 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
306 undef, $datetime, $id)
307 or die "Couldn't update last_picture in SQL: $!";
314 my $auth = $r->headers_in->{'authorization'};
315 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
316 $r->content_type('text/plain; charset=utf-8');
318 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
319 $r->print("Need authorization\n");
323 #return qw(sesse Sesse);
325 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
326 # WinXP is stupid :-)
327 if ($user =~ /^.*\\(.*)$/) {
332 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
336 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
340 $pass = Digest::SHA1::sha1_base64($pass);
341 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
342 undef, $user, $pass, $r->get_server_name);
343 if ($ref->{'auth'} != 1) {
344 $r->content_type('text/plain; charset=utf-8');
345 warn "No user exists, only $auth";
347 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
348 $r->print("Authorization failed");
349 $r->log->warn("Authentication failed for $user/$takenby");
353 $r->log->info("Authentication succeeded for $user/$takenby");
355 return ($user, $takenby);
359 my ($r, $event, $filename) = (@_);
360 my $ref = $dbh->selectrow_hashref(
361 'SELECT id FROM images WHERE event=? AND filename=?',
362 undef, $event, $filename);
363 if (!defined($ref)) {
364 return (undef, undef, undef);
366 return stat_image_from_id($r, $ref->{'id'});
369 sub stat_image_from_id {
372 my $fname = get_disk_location($r, $id);
373 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
374 or return (undef, undef, undef);
376 return ($fname, $size, $mtime);
379 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
380 # the smallest mipmap larger than the largest of them.
382 my ($r, $filename, $id, $dbwidth, $dbheight, @res) = @_;
383 my ($img, $mmimg, $width, $height);
385 # If we don't know the size, we'll need to read it in anyway
386 if (!defined($dbwidth) || !defined($dbheight)) {
387 $img = read_original_image($r, $id, $dbwidth, $dbheight);
388 $width = $img->Get('columns');
389 $height = $img->Get('rows');
395 # Generate the list of mipmaps
398 my $mmwidth = $width;
399 my $mmheight = $height;
401 while ($mmwidth > 1 || $mmheight > 1) {
402 my $new_mmwidth = POSIX::floor($mmwidth / 2);
403 my $new_mmheight = POSIX::floor($mmheight / 2);
405 $new_mmwidth = 1 if ($new_mmwidth < 1);
406 $new_mmheight = 1 if ($new_mmheight < 1);
408 my $large_enough = 1;
409 for my $i (0..($#res/2)) {
410 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
411 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
417 last if (!$large_enough);
419 $mmwidth = $new_mmwidth;
420 $mmheight = $new_mmheight;
422 push @mmlist, [ $mmwidth, $mmheight ];
425 # Ensure that all of them are OK
426 my $last_good_mmlocation;
427 for my $i (0..$#mmlist) {
428 my $last = ($i == $#mmlist);
429 my $mmres = $mmlist[$i];
431 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
432 if (! -r $mmlocation or (-M $mmlocation > -M $filename)) {
433 if (!defined($img)) {
434 if (defined($last_good_mmlocation)) {
435 $img = Image::Magick->new;
436 $img->Read($last_good_mmlocation);
438 $img = read_original_image($r, $id, $dbwidth, $dbheight);
445 $cimg = $img->Clone();
447 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
448 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos');
450 my $err = $cimg->write(
451 filename => $mmlocation,
453 'sampling-factor' => '1x1'
457 $last_good_mmlocation = $mmlocation;
459 if ($last && !defined($img)) {
460 # OK, read in the smallest one
461 $img = Image::Magick->new;
462 my $err = $img->Read($mmlocation);
466 if (!defined($img)) {
467 $img = read_original_image($r, $id, $dbwidth, $dbheight);
472 sub read_original_image {
473 my ($r, $id, $dbwidth, $dbheight) = @_;
475 my $fname = get_disk_location($r, $id);
477 # Read in the original image
478 my $magick = new Image::Magick;
481 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
482 # The delegate support is rather broken and causes very odd stuff to happen when
483 # more than one thread does this at the same time. Thus, we simply do it ourselves.
484 if ($fname =~ /\.nef$/i) {
485 # this would suffice if ImageMagick gets to fix their handling
486 # $fname = "NEF:$fname";
488 open DCRAW, "-|", "dcraw", "-w", "-c", $fname
489 or error("dcraw: $!");
490 $err = $magick->Read(file => \*DCRAW);
493 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
494 # RGB is slightly faster (no colorspace conversion needed) and works equally
495 # well for our uses, as long as we don't need to draw an information box,
496 # which trickles several ImageMagick bugs related to colorspace handling.
497 # (Ideally we'd be able to keep the image subsampled and
498 # planar, but that would probably be difficult for ImageMagick to expose.)
500 # $magick->Set(colorspace=>'YCbCr');
502 $err = $magick->Read($fname);
506 $r->log->warn("$fname: $err");
510 error($r, "$fname: $err");
514 # If we use ->[0] unconditionally, text rendering (!) seems to crash
515 my $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
517 my $width = $img->Get('columns');
518 my $height = $img->Get('rows');
520 # Update the SQL database if it doesn't contain the required info
521 if (!defined($dbwidth) || !defined($dbheight)) {
522 $r->log->info("Updating width/height for $id: $width x $height");
523 update_image_info($r, $id, $width, $height);
530 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
532 my $fname = get_disk_location($r, $id);
533 if ($infobox ne 'box') {
534 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
535 return ($fname, undef);
539 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
541 if (! -r $cachename or (-M $cachename > -M $fname)) {
542 # If we are in overload mode (aka Slashdot mode), refuse to generate
544 if (Sesse::pr0n::Overload::is_in_overload($r)) {
545 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
546 error($r, 'System is in overload mode, not doing any scaling');
549 # If we're being asked for just the box, make a new image with just the box.
550 # We don't care about @otherres since each of these images are
551 # already pretty cheap to generate, but we need the exact width so we can make
552 # one in the right size.
553 if ($infobox eq 'box') {
554 my ($img, $width, $height);
556 # This is slow, but should fortunately almost never happen, so don't bother
558 if (!defined($dbwidth) || !defined($dbheight)) {
559 $img = read_original_image($r, $id, $dbwidth, $dbheight);
560 $width = $img->Get('columns');
561 $height = $img->Get('rows');
564 $img = Image::Magick->new;
569 if (defined($xres) && defined($yres)) {
570 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
573 $img->Set(size=>($width . "x" . $height));
574 $img->Read('xc:white');
576 my $info = Image::ExifTool::ImageInfo($fname);
577 if (make_infobox($img, $info, $r)) {
578 $img->Quantize(colors=>16, dither=>'False');
580 # Since the image is grayscale, ImageMagick overrides us and writes this
581 # as grayscale anyway, but at least we get rid of the alpha channel this
583 $img->Set(type=>'Palette');
585 # Not enough room for the text, make a tiny dummy transparent infobox
587 $img->Set(size=>"1x1");
594 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
595 $r->log->info("New infobox cache: $width x $height for $id.jpg");
597 return ($cachename, 'image/png');
600 my $img = make_mipmap($r, $fname, $id, $dbwidth, $dbheight, $xres, $yres, @otherres);
602 while (defined($xres) && defined($yres)) {
603 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
604 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
607 if (defined($nxres) && defined($nyres)) {
608 # we have more resolutions to scale, so don't throw
610 $cimg = $img->Clone();
615 my $width = $img->Get('columns');
616 my $height = $img->Get('rows');
617 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
619 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
620 my $filter = 'Mitchell';
624 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
631 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
634 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
635 my $info = Image::ExifTool::ImageInfo($fname);
636 make_infobox($cimg, $info, $r);
639 # Strip EXIF tags etc.
644 filename => $cachename,
647 if (($nwidth >= 640 && $nheight >= 480) ||
648 ($nwidth >= 480 && $nheight >= 640)) {
649 $parms{'interlace'} = 'Plane';
652 $parms{'sampling-factor'} = $sf;
654 $err = $cimg->write(%parms);
659 ($xres, $yres) = ($nxres, $nyres);
661 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
666 $r->log->warn("$fname: $err");
670 error($r, "$fname: $err");
674 return ($cachename, 'image/jpeg');
677 sub get_mimetype_from_filename {
678 my $filename = shift;
679 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
680 $type = "image/jpeg" if (!defined($type));
685 my ($img, $info, $r) = @_;
687 # The infobox is of the form
688 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
689 # possibly with some parts omitted -- the middle part is known as the "classic
690 # fields"; note the comma separation. Every field has an associated "bold flag"
691 # in the second part.
693 my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
694 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
695 my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
696 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
698 my @classic_fields = ();
699 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
700 push @classic_fields, [ $1 . "mm", 0 ];
701 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
702 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
705 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
706 my ($a, $b) = ($1, $2);
707 my $gcd = gcd($a, $b);
708 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
709 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
710 push @classic_fields, [ $1 . "s", $shutter_priority ];
713 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
716 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
718 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
720 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
721 my $f = $info->{'FNumber'};
723 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
725 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
729 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
732 if (defined($info->{'NikonD1-ISOSetting'})) {
733 $iso = $info->{'NikonD1-ISOSetting'};
734 } elsif (defined($info->{'ISO'})) {
735 $iso = $info->{'ISO'};
736 } elsif (defined($info->{'ISOSetting'})) {
737 $iso = $info->{'ISOSetting'};
739 if (defined($iso) && $iso =~ /(\d+)/) {
740 push @classic_fields, [ $1 . " ISO", 0 ];
743 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
744 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
745 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
746 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
749 # Now piece together the rest
752 if (defined($info->{'DateTimeOriginal'}) &&
753 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
755 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
758 if (defined($info->{'Model'})) {
759 my $model = $info->{'Model'};
763 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
764 push @parts, [ $model, 0 ];
768 if (scalar @classic_fields > 0) {
769 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
772 for my $field (@classic_fields) {
773 push @parts, [ ', ', 0 ] if (!$first_elem);
779 if (defined($info->{'Flash'})) {
780 if ($info->{'Flash'} =~ /did not fire/i ||
781 $info->{'Flash'} =~ /no flash/i ||
782 $info->{'Flash'} =~ /not fired/i ||
783 $info->{'Flash'} =~ /Off/) {
784 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
785 push @parts, [ "No flash", 0 ];
786 } elsif ($info->{'Flash'} =~ /fired/i ||
787 $info->{'Flash'} =~ /On/) {
788 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
789 push @parts, [ "Flash", 0 ];
791 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
792 push @parts, [ $info->{'Flash'}, 0 ];
796 return 0 if (scalar @parts == 0);
798 # Find the required width
802 for my $part (@parts) {
805 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
807 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
810 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
813 $th = $h if ($h > $th);
816 return 0 if ($tw > $img->Get('columns'));
819 my $y = $img->Get('rows') - 24;
821 # Hit exact DCT blocks
824 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
825 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
826 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
827 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
829 # Start writing out the text
830 $x = ($img->Get('columns') - $tw) / 2;
832 my $room = ($img->Get('rows') - 1 - $y - $th);
833 $y = ($img->Get('rows') - 1) - $room/2;
835 for my $part (@parts) {
838 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
840 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
842 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
843 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
851 return $a if ($b == 0);
852 return gcd($b, $a % $b);
856 my ($dbh, $id, $date, $desc, $vhost) = @_;
859 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
860 push @errors, "Manglende eller ugyldig ID.";
862 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
863 push @errors, "Manglende eller ugyldig dato.";
865 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
866 push @errors, "Manglende eller ugyldig beskrivelse.";
869 if (scalar @errors > 0) {
873 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
874 undef, $id, $date, $desc, $vhost)
875 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
876 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
878 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
888 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
891 $decoded = Encode::decode("iso8859-1", $text);