1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
9 use Apache2::RequestRec (); # for $r->content_type
10 use Apache2::RequestIO (); # for $r->print
11 use Apache2::Const -compile => ':common';
32 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
34 use Sesse::pr0n::Config;
36 require Sesse::pr0n::Config_local;
41 @EXPORT = qw(&error &dberror);
43 @EXPORT_OK = qw(&error &dberror);
45 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
46 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
47 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
48 our $mimetypes = new MIME::Types;
50 Apache2::ServerUtil->server->log_error("Initializing pr0n $VERSION");
57 our ($dbh, $mimetypes);
60 my ($r,$err,$status,$title) = @_;
62 if (!defined($status) || !defined($title)) {
64 $title = "Internal server error";
67 $r->content_type('text/html; charset=utf-8');
71 $r->print(" <p>Error: $err</p>\n");
75 $r->log->error("Stack trace follows: " . Carp::longmess());
77 ModPerl::Util::exit();
82 error($r, "$err (DB error: " . $dbh->errstr . ")");
88 $r->content_type("text/html; charset=utf-8");
90 # Fetch quote if we're itk-bilder.samfundet.no
92 if ($r->get_server_name eq 'itk-bilder.samfundet.no') {
93 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
94 $quote = "Error: Could not fetch quotes." if (!defined($quote));
96 Sesse::pr0n::Templates::print_template($r, "header", { title => $title, quotes => Encode::decode_utf8($quote) });
101 Sesse::pr0n::Templates::print_template($r, "footer",
102 { version => $Sesse::pr0n::Common::VERSION });
106 my ($width, $height, $thumbxres, $thumbyres) = @_;
108 unless ($thumbxres >= $width &&
109 $thumbyres >= $height) {
110 my $sfh = $width / $thumbxres;
111 my $sfv = $height / $thumbyres;
119 $width = POSIX::floor($width);
120 $height = POSIX::floor($height);
123 return ($width, $height);
126 sub get_query_string {
127 my ($param, $defparam) = @_;
131 while (my ($key, $value) = each %$param) {
132 next unless defined($value);
133 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
135 $value = pretty_escape($value);
137 $str .= ($first) ? "?" : ';';
138 $str .= "$key=$value";
144 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
145 sub weird_space_encode {
148 return "_" x (length($val) * 2);
150 return "_" x (length($val) * 2 - 1);
154 sub weird_space_unencode {
156 if (length($val) % 2 == 0) {
157 return "_" x (length($val) / 2);
159 return " " x ((length($val) + 1) / 2);
166 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
167 $value = URI::Escape::uri_escape($value);
168 $value =~ s/%2F/\//g;
173 sub pretty_unescape {
176 # URI unescaping is already done for us
177 $value =~ s/(_+)/weird_space_unencode($1)/ge;
183 my ($r, $title, $baseurl, $param, $defparam, $accesskey) = @_;
184 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
185 if (defined($accesskey) && length($accesskey) == 1) {
186 $str .= " accesskey=\"$accesskey\"";
188 $str .= ">$title</a>";
193 # Check that we are alive
194 if (!(defined($dbh) && $dbh->ping)) {
196 Apache2::ServerUtil->server->log_error("Lost contact with PostgreSQL server, trying to reconnect...");
197 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
198 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
200 die "Couldn't connect to PostgreSQL database";
209 return $r->dir_config('ImageBase');
212 sub get_disk_location {
214 my $dir = POSIX::floor($id / 256);
215 return get_base($r) . "images/$dir/$id.jpg";
218 sub get_cache_location {
219 my ($r, $id, $width, $height, $infobox) = @_;
220 my $dir = POSIX::floor($id / 256);
222 if ($infobox eq 'both') {
223 return get_base($r) . "cache/$dir/$id-$width-$height.jpg";
224 } elsif ($infobox eq 'nobox') {
225 return get_base($r) . "cache/$dir/$id-$width-$height-nobox.jpg";
227 return get_base($r) . "cache/$dir/$id-$width-$height-box.png";
231 sub get_mipmap_location {
232 my ($r, $id, $width, $height) = @_;
233 my $dir = POSIX::floor($id / 256);
235 return get_base($r) . "cache/$dir/$id-mipmap-$width-$height.jpg";
238 sub update_image_info {
239 my ($r, $id, $width, $height) = @_;
241 # Also find the date taken if appropriate (from the EXIF tag etc.)
242 my $exiftool = Image::ExifTool->new;
243 $exiftool->ExtractInfo(get_disk_location($r, $id));
244 my $info = $exiftool->GetInfo();
245 my $datetime = undef;
247 if (defined($info->{'DateTimeOriginal'})) {
248 # Parse the date and time over to ISO format
249 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
250 $datetime = "$1-$2-$3 $4:$5:$6";
255 local $dbh->{AutoCommit} = 0;
258 $dbh->do('DELETE FROM exif_info WHERE image=?',
260 or die "Couldn't delete old EXIF information in SQL: $!";
262 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
263 or die "Couldn't prepare inserting EXIF information: $!";
265 for my $key (keys %$info) {
266 next if ref $info->{$key};
267 $q->execute($id, $key, guess_charset($info->{$key}))
268 or die "Couldn't insert EXIF information in database: $!";
272 my $model = $exiftool->GetValue('Model', 'PrintConv');
273 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
274 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
278 $model = undef if (length($model) == 0);
282 $lens = undef if (length($lens) == 0);
284 # Now update the main table with the information we've got
285 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
286 undef, $width, $height, $datetime, $model, $lens, $id)
287 or die "Couldn't update width/height in SQL: $!";
290 my @tags = $exiftool->GetValue('Keywords', 'ValueConv');
291 $dbh->do('DELETE FROM tags WHERE image=?',
293 or die "Couldn't delete old tag information in SQL: $!";
295 $q = $dbh->prepare('INSERT INTO tags (image,tag) VALUES (?,?)')
296 or die "Couldn't prepare inserting tag information: $!";
299 for my $tag (@tags) {
300 $q->execute($id, guess_charset($tag))
301 or die "Couldn't insert tag information in database: $!";
304 # update the last_picture cache as well (this should of course be done
305 # via a trigger, but this is less complicated :-) )
306 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?) WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
307 undef, $datetime, $id)
308 or die "Couldn't update last_picture in SQL: $!";
315 my $auth = $r->headers_in->{'authorization'};
316 if (!defined($auth) || $auth !~ m#^Basic ([a-zA-Z0-9+/]+=*)$#) {
317 $r->content_type('text/plain; charset=utf-8');
319 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
320 $r->print("Need authorization\n");
324 #return qw(sesse Sesse);
326 my ($user, $pass) = split /:/, MIME::Base64::decode_base64($1);
327 # WinXP is stupid :-)
328 if ($user =~ /^.*\\(.*)$/) {
333 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
337 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
341 $pass = Digest::SHA1::sha1_base64($pass);
342 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS auth FROM users WHERE username=? AND sha1password=? AND vhost=?',
343 undef, $user, $pass, $r->get_server_name);
344 if ($ref->{'auth'} != 1) {
345 $r->content_type('text/plain; charset=utf-8');
346 warn "No user exists, only $auth";
348 $r->headers_out->{'www-authenticate'} = 'Basic realm="pr0n.sesse.net"';
349 $r->print("Authorization failed");
350 $r->log->warn("Authentication failed for $user/$takenby");
354 $r->log->info("Authentication succeeded for $user/$takenby");
356 return ($user, $takenby);
360 my ($r, $event, $filename) = (@_);
361 my $ref = $dbh->selectrow_hashref(
362 'SELECT id FROM images WHERE event=? AND filename=?',
363 undef, $event, $filename);
364 if (!defined($ref)) {
365 return (undef, undef, undef);
367 return stat_image_from_id($r, $ref->{'id'});
370 sub stat_image_from_id {
373 my $fname = get_disk_location($r, $id);
374 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
375 or return (undef, undef, undef);
377 return ($fname, $size, $mtime);
380 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
381 # the smallest mipmap larger than the largest of them.
383 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, @res) = @_;
384 my ($img, $mmimg, $width, $height);
386 my $physical_fname = get_disk_location($r, $id);
388 # If we don't know the size, we'll need to read it in anyway
389 if (!defined($dbwidth) || !defined($dbheight)) {
390 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
391 $width = $img->Get('columns');
392 $height = $img->Get('rows');
398 # Generate the list of mipmaps
401 my $mmwidth = $width;
402 my $mmheight = $height;
404 while ($mmwidth > 1 || $mmheight > 1) {
405 my $new_mmwidth = POSIX::floor($mmwidth / 2);
406 my $new_mmheight = POSIX::floor($mmheight / 2);
408 $new_mmwidth = 1 if ($new_mmwidth < 1);
409 $new_mmheight = 1 if ($new_mmheight < 1);
411 my $large_enough = 1;
412 for my $i (0..($#res/2)) {
413 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
414 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
420 last if (!$large_enough);
422 $mmwidth = $new_mmwidth;
423 $mmheight = $new_mmheight;
425 push @mmlist, [ $mmwidth, $mmheight ];
428 # Ensure that all of them are OK
429 my $last_good_mmlocation;
430 for my $i (0..$#mmlist) {
431 my $last = ($i == $#mmlist);
432 my $mmres = $mmlist[$i];
434 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
435 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
436 if (!defined($img)) {
437 if (defined($last_good_mmlocation)) {
438 $img = Sesse::pr0n::QscaleProxy->new;
439 $img->Read($last_good_mmlocation);
441 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
448 $cimg = $img->Clone();
450 $r->log->info("Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
451 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
453 my $err = $cimg->write(
454 filename => $mmlocation,
456 'sampling-factor' => '1x1'
460 $last_good_mmlocation = $mmlocation;
462 if ($last && !defined($img)) {
463 # OK, read in the smallest one
464 $img = Sesse::pr0n::QscaleProxy->new;
465 my $err = $img->Read($mmlocation);
469 if (!defined($img)) {
470 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale);
475 sub read_original_image {
476 my ($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale) = @_;
478 my $physical_fname = get_disk_location($r, $id);
480 # Read in the original image
482 if ($can_use_qscale && $filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
483 $magick = Sesse::pr0n::QscaleProxy->new;
485 $magick = Image::Magick->new;
489 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
490 # The delegate support is rather broken and causes very odd stuff to happen when
491 # more than one thread does this at the same time. Thus, we simply do it ourselves.
492 if ($filename =~ /\.nef$/i) {
493 # this would suffice if ImageMagick gets to fix their handling
494 # $physical_fname = "NEF:$physical_fname";
496 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
497 or error("dcraw: $!");
498 $err = $magick->Read(file => \*DCRAW);
501 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
502 # RGB is slightly faster (no colorspace conversion needed) and works equally
503 # well for our uses, as long as we don't need to draw an information box,
504 # which trickles several ImageMagick bugs related to colorspace handling.
505 # (Ideally we'd be able to keep the image subsampled and
506 # planar, but that would probably be difficult for ImageMagick to expose.)
508 # $magick->Set(colorspace=>'YCbCr');
510 $err = $magick->Read($physical_fname);
514 $r->log->warn("$physical_fname: $err");
518 error($r, "$physical_fname: $err");
522 # If we use ->[0] unconditionally, text rendering (!) seems to crash
527 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
530 my $width = $img->Get('columns');
531 my $height = $img->Get('rows');
533 # Update the SQL database if it doesn't contain the required info
534 if (!defined($dbwidth) || !defined($dbheight)) {
535 $r->log->info("Updating width/height for $id: $width x $height");
536 update_image_info($r, $id, $width, $height);
543 my ($r, $filename, $id, $dbwidth, $dbheight, $infobox, $xres, $yres, @otherres) = @_;
545 my $fname = get_disk_location($r, $id);
546 if ($infobox ne 'box') {
547 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbheight || $yres < $dbwidth || $xres == -1)) {
548 return ($fname, undef);
552 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
554 if (! -r $cachename or (-M $cachename > -M $fname)) {
555 # If we are in overload mode (aka Slashdot mode), refuse to generate
557 if (Sesse::pr0n::Overload::is_in_overload($r)) {
558 $r->log->warn("In overload mode, not scaling $id to $xres x $yres");
559 error($r, 'System is in overload mode, not doing any scaling');
562 # If we're being asked for just the box, make a new image with just the box.
563 # We don't care about @otherres since each of these images are
564 # already pretty cheap to generate, but we need the exact width so we can make
565 # one in the right size.
566 if ($infobox eq 'box') {
567 my ($img, $width, $height);
569 # This is slow, but should fortunately almost never happen, so don't bother
571 if (!defined($dbwidth) || !defined($dbheight)) {
572 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
573 $width = $img->Get('columns');
574 $height = $img->Get('rows');
577 $img = Image::Magick->new;
582 if (defined($xres) && defined($yres)) {
583 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
586 $img->Set(size=>($width . "x" . $height));
587 $img->Read('xc:white');
589 my $info = Image::ExifTool::ImageInfo($fname);
590 if (make_infobox($img, $info, $r)) {
591 $img->Quantize(colors=>16, dither=>'False');
593 # Since the image is grayscale, ImageMagick overrides us and writes this
594 # as grayscale anyway, but at least we get rid of the alpha channel this
596 $img->Set(type=>'Palette');
598 # Not enough room for the text, make a tiny dummy transparent infobox
600 $img->Set(size=>"1x1");
607 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
608 $r->log->info("New infobox cache: $width x $height for $id.jpg");
610 return ($cachename, 'image/png');
613 my $can_use_qscale = 0;
614 if ($infobox eq 'nobox') {
618 my $img = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $can_use_qscale, $xres, $yres, @otherres);
620 while (defined($xres) && defined($yres)) {
621 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
622 my $cachename = get_cache_location($r, $id, $xres, $yres, $infobox);
625 if (defined($nxres) && defined($nyres)) {
626 # we have more resolutions to scale, so don't throw
628 $cimg = $img->Clone();
633 my $width = $img->Get('columns');
634 my $height = $img->Get('rows');
635 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
637 # Use lanczos (sharper) for heavy scaling, mitchell (faster) otherwise
638 my $filter = 'Mitchell';
642 if ($width / $nwidth > 8.0 || $height / $nheight > 8.0) {
649 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
652 if (($nwidth >= 800 || $nheight >= 600 || $xres == -1) && $infobox ne 'nobox') {
653 my $info = Image::ExifTool::ImageInfo($fname);
654 make_infobox($cimg, $info, $r);
657 # Strip EXIF tags etc.
662 filename => $cachename,
665 if (($nwidth >= 640 && $nheight >= 480) ||
666 ($nwidth >= 480 && $nheight >= 640)) {
667 $parms{'interlace'} = 'Plane';
670 $parms{'sampling-factor'} = $sf;
672 $err = $cimg->write(%parms);
677 ($xres, $yres) = ($nxres, $nyres);
679 $r->log->info("New cache: $nwidth x $nheight for $id.jpg");
684 $r->log->warn("$fname: $err");
688 error($r, "$fname: $err");
692 return ($cachename, 'image/jpeg');
695 sub get_mimetype_from_filename {
696 my $filename = shift;
697 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
698 $type = "image/jpeg" if (!defined($type));
703 my ($img, $info, $r) = @_;
705 # The infobox is of the form
706 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
707 # possibly with some parts omitted -- the middle part is known as the "classic
708 # fields"; note the comma separation. Every field has an associated "bold flag"
709 # in the second part.
711 my $shutter_priority = (defined($info->{'ExposureProgram'}) &&
712 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
713 my $aperture_priority = (defined($info->{'ExposureProgram'}) &&
714 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
716 my @classic_fields = ();
717 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
718 push @classic_fields, [ $1 . "mm", 0 ];
719 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
720 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
723 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
724 my ($a, $b) = ($1, $2);
725 my $gcd = gcd($a, $b);
726 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $shutter_priority ];
727 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)$/) {
728 push @classic_fields, [ $1 . "s", $shutter_priority ];
731 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
734 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
736 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
738 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
739 my $f = $info->{'FNumber'};
741 push @classic_fields, [ (sprintf "f/%.0f", $f), $aperture_priority ];
743 push @classic_fields, [ (sprintf "f/%.1f", $f), $aperture_priority ];
747 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
750 if (defined($info->{'NikonD1-ISOSetting'})) {
751 $iso = $info->{'NikonD1-ISOSetting'};
752 } elsif (defined($info->{'ISO'})) {
753 $iso = $info->{'ISO'};
754 } elsif (defined($info->{'ISOSetting'})) {
755 $iso = $info->{'ISOSetting'};
757 if (defined($iso) && $iso =~ /(\d+)/) {
758 push @classic_fields, [ $1 . " ISO", 0 ];
761 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
762 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
763 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} != 0) {
764 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
767 # Now piece together the rest
770 if (defined($info->{'DateTimeOriginal'}) &&
771 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
773 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
776 if (defined($info->{'Model'})) {
777 my $model = $info->{'Model'};
781 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
782 push @parts, [ $model, 0 ];
786 if (scalar @classic_fields > 0) {
787 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
790 for my $field (@classic_fields) {
791 push @parts, [ ', ', 0 ] if (!$first_elem);
797 if (defined($info->{'Flash'})) {
798 if ($info->{'Flash'} =~ /did not fire/i ||
799 $info->{'Flash'} =~ /no flash/i ||
800 $info->{'Flash'} =~ /not fired/i ||
801 $info->{'Flash'} =~ /Off/) {
802 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
803 push @parts, [ "No flash", 0 ];
804 } elsif ($info->{'Flash'} =~ /fired/i ||
805 $info->{'Flash'} =~ /On/) {
806 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
807 push @parts, [ "Flash", 0 ];
809 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
810 push @parts, [ $info->{'Flash'}, 0 ];
814 return 0 if (scalar @parts == 0);
816 # Find the required width
820 for my $part (@parts) {
823 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
825 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
828 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12));
831 $th = $h if ($h > $th);
834 return 0 if ($tw > $img->Get('columns'));
837 my $y = $img->Get('rows') - 24;
839 # Hit exact DCT blocks
842 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
843 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
844 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
845 $img->Draw(primitive=>'line', stroke=>'black', points=>$lpoints);
847 # Start writing out the text
848 $x = ($img->Get('columns') - $tw) / 2;
850 my $room = ($img->Get('rows') - 1 - $y - $th);
851 $y = ($img->Get('rows') - 1) - $room/2;
853 for my $part (@parts) {
856 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
858 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
860 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12, x=>int($x), y=>int($y));
861 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12))[4];
869 return $a if ($b == 0);
870 return gcd($b, $a % $b);
874 my ($dbh, $id, $date, $desc, $vhost) = @_;
877 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
878 push @errors, "Manglende eller ugyldig ID.";
880 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
881 push @errors, "Manglende eller ugyldig dato.";
883 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
884 push @errors, "Manglende eller ugyldig beskrivelse.";
887 if (scalar @errors > 0) {
891 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
892 undef, $id, $date, $desc, $vhost)
893 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
894 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
896 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
906 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
909 $decoded = Encode::decode("iso8859-1", $text);