1 package Sesse::pr0n::Common;
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
24 use Crypt::Eksblowfish::Bcrypt;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
30 use Sesse::pr0n::Config;
32 require Sesse::pr0n::Config_local;
37 @EXPORT = qw(&error &dberror);
39 @EXPORT_OK = qw(&error &dberror);
41 our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
42 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
43 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
44 our $mimetypes = new MIME::Types;
46 print STDERR "Initializing pr0n $VERSION\n";
53 our ($dbh, $mimetypes);
56 my ($r,$err,$status,$title) = @_;
58 if (!defined($status) || !defined($title)) {
60 $title = "Internal server error";
63 my $res = Plack::Response->new($status);
64 my $io = IO::String->new;
66 $r->content_type('text/html; charset=utf-8');
68 header($r, $io, $title);
69 $io->print(" <p>Error: $err</p>\n");
73 log_error($r, "Stack trace follows: " . Carp::longmess());
82 return error($r, "$err (DB error: " . $dbh->errstr . ")");
86 my ($r, $io, $title) = @_;
88 $r->content_type("text/html; charset=utf-8");
90 # Fetch quote if we're itk-bilder.samfundet.no
92 if (Sesse::pr0n::Common::get_server_name($r) 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, $io, "header", { title => $title, quotes => $quote });
101 Sesse::pr0n::Templates::print_template($r, $io, "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 for my $key (sort keys %$param) {
132 my $value = $param->{$key};
133 next unless defined($value);
134 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
136 $value = pretty_escape($value);
138 $str .= ($first) ? "?" : ';';
139 $str .= "$key=$value";
145 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
146 sub weird_space_encode {
149 return "_" x (length($val) * 2);
151 return "_" x (length($val) * 2 - 1);
155 sub weird_space_unencode {
157 if (length($val) % 2 == 0) {
158 return "_" x (length($val) / 2);
160 return " " x ((length($val) + 1) / 2);
167 $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
168 $value = URI::Escape::uri_escape($value);
169 $value =~ s/%2F/\//g;
174 sub pretty_unescape {
177 # URI unescaping is already done for us
178 $value =~ s/(_+)/weird_space_unencode($1)/ge;
184 my ($io, $title, $baseurl, $param, $defparam, $accesskey) = @_;
185 my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
186 if (defined($accesskey) && length($accesskey) == 1) {
187 $str .= " accesskey=\"$accesskey\"";
189 $str .= ">$title</a>";
194 # Check that we are alive
195 if (!(defined($dbh) && $dbh->ping)) {
197 print STDERR "Lost contact with PostgreSQL server, trying to reconnect...\n";
198 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
199 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
201 die "Couldn't connect to PostgreSQL database";
208 sub get_disk_location {
210 my $dir = POSIX::floor($id / 256);
211 return $Sesse::pr0n::Config::image_base . "images/$dir/$id.jpg";
214 sub get_cache_location {
215 my ($id, $width, $height) = @_;
216 my $dir = POSIX::floor($id / 256);
218 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-nobox.jpg";
221 sub get_infobox_cache_location {
222 my ($id, $width, $height, $dpr) = @_;
223 my $dir = POSIX::floor($id / 256);
226 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box.png";
228 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-box\@$dpr.png";
232 sub ensure_disk_location_exists {
234 my $dir = POSIX::floor($id / 256);
236 my $img_dir = $Sesse::pr0n::Config::image_base . "/images/$dir/";
238 log_info($r, "Need to create new image directory $img_dir");
239 mkdir($img_dir) or die "Couldn't create new image directory $img_dir";
242 my $cache_dir = $Sesse::pr0n::Config::image_base . "/cache/$dir/";
243 if (! -d $cache_dir) {
244 log_info($r, "Need to create new cache directory $cache_dir");
245 mkdir($cache_dir) or die "Couldn't create new image directory $cache_dir";
249 sub get_mipmap_location {
250 my ($r, $id, $width, $height) = @_;
251 my $dir = POSIX::floor($id / 256);
253 return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-mipmap-$width-$height.jpg";
256 sub update_image_info {
257 my ($r, $id, $width, $height) = @_;
259 # Also find the date taken if appropriate (from the EXIF tag etc.)
260 my $exiftool = Image::ExifTool->new;
261 $exiftool->ExtractInfo(get_disk_location($r, $id));
262 my $info = $exiftool->GetInfo();
263 my $datetime = undef;
265 if (defined($info->{'DateTimeOriginal'})) {
266 # Parse the date and time over to ISO format
267 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
268 $datetime = "$1-$2-$3 $4:$5:$6";
273 local $dbh->{AutoCommit} = 0;
276 $dbh->do('DELETE FROM exif_info WHERE image=?',
278 or die "Couldn't delete old EXIF information in SQL: $!";
280 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
281 or die "Couldn't prepare inserting EXIF information: $!";
283 for my $key (keys %$info) {
284 next if ref $info->{$key};
285 $q->execute($id, $key, guess_charset($info->{$key}))
286 or die "Couldn't insert EXIF information in database: $!";
290 my $model = $exiftool->GetValue('Model', 'PrintConv');
291 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
292 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
296 $model = undef if (length($model) == 0);
300 $lens = undef if (length($lens) == 0);
302 # Now update the main table with the information we've got
303 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
304 undef, $width, $height, $datetime, $model, $lens, $id)
305 or die "Couldn't update width/height in SQL: $!";
307 # update the last_picture cache as well (this should of course be done
308 # via a trigger, but this is less complicated :-) )
309 $dbh->do('UPDATE last_picture_cache SET last_picture=GREATEST(last_picture, ?),last_update=CURRENT_TIMESTAMP WHERE (vhost,event)=(SELECT vhost,event FROM images WHERE id=?)',
310 undef, $datetime, $id)
311 or die "Couldn't update last_picture in SQL: $!";
318 #return qw(sesse Sesse);
320 my $auth = $r->header('authorization');
321 if (!defined($auth)) {
324 if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
325 return check_basic_auth($r, $1);
332 my $res = Plack::Response->new(401);
333 $res->content_type('text/plain; charset=utf-8');
335 $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
337 $res->body("Need authorization\n");
341 sub check_basic_auth {
344 my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
345 my ($user, $takenby) = extract_takenby($raw_user);
347 my $ref = $dbh->selectrow_hashref('SELECT cryptpassword FROM users WHERE username=? AND vhost=?',
348 undef, $user, Sesse::pr0n::Common::get_server_name($r));
349 my $bcrypt_matches = 0;
350 if (!defined($ref) || Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) ne $ref->{'cryptpassword'}) {
351 $r->content_type('text/plain; charset=utf-8');
352 log_warn($r, "Authentication failed for $user/$takenby");
355 log_info($r, "Authentication succeeded for $user/$takenby");
357 return ($user, $takenby);
360 sub get_pseudorandom_bytes {
361 my $num_left = shift;
363 open my $randfh, "<", "/dev/urandom"
364 or die "/dev/urandom: $!";
366 while ($num_left > 0) {
368 if (sysread($randfh, $tmp, $num_left) == -1) {
369 die "sysread(/dev/urandom): $!";
372 $num_left -= length($bytes);
378 sub extract_takenby {
381 # WinXP is stupid :-)
382 if ($user =~ /^.*\\(.*)$/) {
387 if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
391 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
394 return ($user, $takenby);
398 my ($r, $event, $filename) = (@_);
399 my $ref = $dbh->selectrow_hashref(
400 'SELECT id FROM images WHERE event=? AND filename=?',
401 undef, $event, $filename);
402 if (!defined($ref)) {
403 return (undef, undef, undef);
405 return stat_image_from_id($r, $ref->{'id'});
408 sub stat_image_from_id {
411 my $fname = get_disk_location($r, $id);
412 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
413 or return (undef, undef, undef);
415 return ($fname, $size, $mtime);
418 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
419 # the smallest mipmap larger than the largest of them, as well as the original image
422 my ($r, $filename, $id, $dbwidth, $dbheight, @res) = @_;
423 my ($img, $mmimg, $width, $height);
425 my $physical_fname = get_disk_location($r, $id);
427 # If we don't know the size, we'll need to read it in anyway
428 if (!defined($dbwidth) || !defined($dbheight)) {
429 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
430 $width = $img->Get('columns');
431 $height = $img->Get('rows');
437 # Generate the list of mipmaps
440 my $mmwidth = $width;
441 my $mmheight = $height;
443 while ($mmwidth > 1 || $mmheight > 1) {
444 my $new_mmwidth = POSIX::floor($mmwidth / 2);
445 my $new_mmheight = POSIX::floor($mmheight / 2);
447 $new_mmwidth = 1 if ($new_mmwidth < 1);
448 $new_mmheight = 1 if ($new_mmheight < 1);
450 my $large_enough = 1;
451 for my $i (0..($#res/2)) {
452 my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
453 if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
459 last if (!$large_enough);
461 $mmwidth = $new_mmwidth;
462 $mmheight = $new_mmheight;
464 push @mmlist, [ $mmwidth, $mmheight ];
467 # Ensure that all of them are OK
468 my $last_good_mmlocation;
469 for my $i (0..$#mmlist) {
470 my $last = ($i == $#mmlist);
471 my $mmres = $mmlist[$i];
473 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
474 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
475 if (!defined($img)) {
476 if (defined($last_good_mmlocation)) {
477 $img = Sesse::pr0n::QscaleProxy->new;
478 $img->Read($last_good_mmlocation);
480 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
487 $cimg = $img->Clone();
489 log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
490 $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
492 my $err = $cimg->write(
493 filename => $mmlocation,
495 'sampling-factor' => '1x1'
499 $last_good_mmlocation = $mmlocation;
501 if ($last && !defined($img)) {
502 # OK, read in the smallest one
503 $img = Sesse::pr0n::QscaleProxy->new;
504 my $err = $img->Read($mmlocation);
508 if (!defined($img)) {
509 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
510 $width = $img->Get('columns');
511 $height = $img->Get('rows');
513 return ($img, $width, $height);
516 sub read_original_image {
517 my ($r, $filename, $id, $dbwidth, $dbheight) = @_;
519 my $physical_fname = get_disk_location($r, $id);
521 # Read in the original image
523 if ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
524 $magick = Sesse::pr0n::QscaleProxy->new;
526 $magick = Image::Magick->new;
530 # ImageMagick can handle NEF files, but it does it by calling dcraw as a delegate.
531 # The delegate support is rather broken and causes very odd stuff to happen when
532 # more than one thread does this at the same time. Thus, we simply do it ourselves.
533 if ($filename =~ /\.(nef|cr2)$/i) {
534 # this would suffice if ImageMagick gets to fix their handling
535 # $physical_fname = "NEF:$physical_fname";
537 open DCRAW, "-|", "dcraw", "-w", "-c", $physical_fname
538 or error("dcraw: $!");
539 $err = $magick->Read(file => \*DCRAW);
542 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
543 # RGB is slightly faster (no colorspace conversion needed) and works equally
544 # well for our uses, as long as we don't need to draw an information box,
545 # which trickles several ImageMagick bugs related to colorspace handling.
546 # (Ideally we'd be able to keep the image subsampled and
547 # planar, but that would probably be difficult for ImageMagick to expose.)
549 # $magick->Set(colorspace=>'YCbCr');
551 $err = $magick->Read($physical_fname);
555 log_warn($r, "$physical_fname: $err");
559 error($r, "$physical_fname: $err");
563 # If we use ->[0] unconditionally, text rendering (!) seems to crash
565 if (ref($magick) !~ /Image::Magick/) {
568 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
575 my ($r, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres) = @_;
577 my ($new_dbwidth, $new_dbheight);
579 my $fname = get_disk_location($r, $id);
580 unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
581 return ($fname, undef);
584 my $cachename = get_cache_location($id, $xres, $yres);
586 if (! -r $cachename or (-M $cachename > -M $fname)) {
587 # If we are in overload mode (aka Slashdot mode), refuse to generate
589 if (Sesse::pr0n::Overload::is_in_overload($r)) {
590 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
591 error($r, 'System is in overload mode, not doing any scaling');
595 ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres);
597 while (defined($xres) && defined($yres)) {
598 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
599 my $cachename = get_cache_location($id, $xres, $yres);
602 if (defined($nxres) && defined($nyres)) {
603 # we have more resolutions to scale, so don't throw
605 $cimg = $img->Clone();
610 my $width = $img->Get('columns');
611 my $height = $img->Get('rows');
612 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
614 my $filter = 'Lanczos';
619 $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter, 'sampling-factor'=>$sf);
622 # Strip EXIF tags etc.
627 filename => $cachename,
630 if (($nwidth >= 640 && $nheight >= 480) ||
631 ($nwidth >= 480 && $nheight >= 640)) {
632 $parms{'interlace'} = 'Plane';
635 $parms{'sampling-factor'} = $sf;
637 $err = $cimg->write(%parms);
642 ($xres, $yres) = ($nxres, $nyres);
644 log_info($r, "New cache: $nwidth x $nheight for $id.jpg");
649 log_warn($r, "$fname: $err");
653 error($r, "$fname: $err");
658 # Update the SQL database if it doesn't contain the required info
659 if (!defined($dbwidth) && defined($new_dbwidth)) {
660 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
661 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
664 return ($cachename, 'image/jpeg');
667 sub ensure_infobox_cached {
668 my ($r, $filename, $id, $dbwidth, $dbheight, $dpr, $xres, $yres) = @_;
670 my ($new_dbwidth, $new_dbheight);
672 my $fname = get_disk_location($r, $id);
673 my $cachename = get_infobox_cache_location($id, $xres, $yres, $dpr);
675 if (! -r $cachename or (-M $cachename > -M $fname)) {
676 # If we are in overload mode (aka Slashdot mode), refuse to generate
678 if (Sesse::pr0n::Overload::is_in_overload($r)) {
679 log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
680 error($r, 'System is in overload mode, not doing any scaling');
683 # We need the exact width so we can make one in the right size.
684 my ($width, $height);
686 # This is slow, but should fortunately almost never happen, so don't bother
688 if (!defined($dbwidth) || !defined($dbheight)) {
689 my $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight, 0);
690 $new_dbwidth = $width = $img->Get('columns');
691 $new_dbheight = $height = $img->Get('rows');
696 my $img = Image::Magick->new;
698 if (defined($xres) && defined($yres)) {
699 ($width, $height) = scale_aspect($width, $height, $xres, $yres);
702 $img->Set(size=>($width . "x" . $height));
703 $img->Read('xc:white');
705 my $info = Image::ExifTool::ImageInfo($fname);
706 if (make_infobox($img, $info, $r, $dpr)) {
707 $img->Quantize(colors=>16, dither=>'False');
709 # Since the image is grayscale, ImageMagick overrides us and writes this
710 # as grayscale anyway, but at least we get rid of the alpha channel this
712 $img->Set(type=>'Palette');
714 # Not enough room for the text, make a tiny dummy transparent infobox
716 $img->Set(size=>"1x1");
723 $err = $img->write(filename => $cachename, quality => 90, depth => 8);
724 log_info($r, "New infobox cache: $width x $height for $id.jpg");
727 return ($cachename, 'image/png');
730 sub get_mimetype_from_filename {
731 my $filename = shift;
732 my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
733 $type = "image/jpeg" if (!defined($type));
738 my ($img, $info, $r, $dpr) = @_;
740 # The infobox is of the form
741 # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
742 # possibly with some parts omitted -- the middle part is known as the "classic
743 # fields"; note the comma separation. Every field has an associated "bold flag"
744 # in the second part.
746 my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
747 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
748 my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
749 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
750 if (defined($info->{'ExposureProgram'}) && $info->{'ExposureProgram'} =~ /manual/i) {
752 $manual_aperture = 1;
755 my @classic_fields = ();
756 if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
757 push @classic_fields, [ $1 . "mm", 0 ];
758 } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
759 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
762 if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
763 my ($a, $b) = ($1, $2);
764 my $gcd = gcd($a, $b);
765 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
766 } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
767 push @classic_fields, [ $1 . "s", $manual_shutter ];
770 if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
773 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
775 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
777 } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
778 my $f = $info->{'FNumber'};
780 push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
782 push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
786 # Apache2::ServerUtil->server->log_error(join(':', keys %$info));
789 if (defined($info->{'NikonD1-ISOSetting'})) {
790 $iso = $info->{'NikonD1-ISOSetting'};
791 } elsif (defined($info->{'ISO'})) {
792 $iso = $info->{'ISO'};
793 } elsif (defined($info->{'ISOSetting'})) {
794 $iso = $info->{'ISOSetting'};
796 if (defined($iso) && $iso =~ /(\d+)/) {
797 push @classic_fields, [ $1 . " ISO", 0 ];
800 if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
801 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
802 } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
803 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
806 # Now piece together the rest
809 if (defined($info->{'DateTimeOriginal'}) &&
810 $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
812 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
815 if (defined($info->{'Model'})) {
816 my $model = $info->{'Model'};
820 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
821 push @parts, [ $model, 0 ];
825 if (scalar @classic_fields > 0) {
826 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
829 for my $field (@classic_fields) {
830 push @parts, [ ', ', 0 ] if (!$first_elem);
836 if (defined($info->{'Flash'})) {
837 if ($info->{'Flash'} =~ /did not fire/i ||
838 $info->{'Flash'} =~ /no flash/i ||
839 $info->{'Flash'} =~ /not fired/i ||
840 $info->{'Flash'} =~ /Off/) {
841 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
842 push @parts, [ "No flash", 0 ];
843 } elsif ($info->{'Flash'} =~ /fired/i ||
844 $info->{'Flash'} =~ /On/) {
845 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
846 push @parts, [ "Flash", 0 ];
848 push @parts, [ ' - ', 0 ] if (scalar @parts > 0);
849 push @parts, [ $info->{'Flash'}, 0 ];
853 return 0 if (scalar @parts == 0);
855 # Find the required width
859 for my $part (@parts) {
862 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
864 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
867 my (undef, undef, $h, undef, $w) = ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr));
870 $th = $h if ($h > $th);
873 return 0 if ($tw > $img->Get('columns'));
876 my $y = $img->Get('rows') - 24*$dpr;
878 # Hit exact DCT blocks
881 my $points = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), ($img->Get('rows') - 1);
882 my $lpoints = sprintf "%u,%u %u,%u", $x, $y, ($img->Get('columns') - 1), $y;
883 $img->Draw(primitive=>'rectangle', stroke=>'white', fill=>'white', points=>$points);
884 $img->Draw(primitive=>'line', stroke=>'black', strokewidth=>$dpr, points=>$lpoints);
886 # Start writing out the text
887 $x = ($img->Get('columns') - $tw) / 2;
889 my $room = ($img->Get('rows') - $dpr - $y - $th);
890 $y = ($img->Get('rows') - $dpr) - $room/2;
892 for my $part (@parts) {
895 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf';
897 $font = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf';
899 $img->Annotate(text=>$part->[0], font=>$font, pointsize=>12*$dpr, x=>int($x), y=>int($y));
900 $x += ($img->QueryFontMetrics(text=>$part->[0], font=>$font, pointsize=>12*$dpr))[4];
908 return $a if ($b == 0);
909 return gcd($b, $a % $b);
913 my ($r, $res, $dbh, $id, $date, $desc) = @_;
916 if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
917 push @errors, "Manglende eller ugyldig ID.";
919 if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
920 push @errors, "Manglende eller ugyldig dato.";
922 if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
923 push @errors, "Manglende eller ugyldig beskrivelse.";
926 if (scalar @errors > 0) {
930 my $vhost = Sesse::pr0n::Common::get_server_name($r);
931 $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
932 undef, $id, $date, $desc, $vhost)
933 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
934 $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
936 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
937 purge_cache($r, $res, "/");
947 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
950 $decoded = Encode::decode("iso8859-1", $text);
956 # Depending on your front-end cache, you might want to get creative somehow here.
957 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
958 # regex tacked onto a request into something useful. The elements given in
959 # should not be regexes, though, as e.g. Squid will not be able to handle that.
961 my ($r, $res, @elements) = @_;
962 return if (scalar @elements == 0);
965 for my $elem (@elements) {
966 log_info($r, "Purging $elem");
967 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
972 if (scalar @pe == 1) {
975 $regex .= "(" . join('|', @pe) . ")";
977 $regex .= "(\\?.*)?\$";
978 $res->header('X-Pr0n-Purge' => $regex);
981 # Find a list of all cache URLs for a given image, given what we have on disk.
982 sub get_all_cache_urls {
983 my ($r, $dbh, $id) = @_;
984 my $dir = POSIX::floor($id / 256);
987 my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
988 or die "Couldn't prepare: " . $dbh->errstr;
990 or die "Couldn't find event and filename: " . $dbh->errstr;
991 my $ref = $q->fetchrow_hashref;
992 my $event = $ref->{'event'};
993 my $filename = $ref->{'filename'};
996 my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
997 for my $file (<$base/$id-*>) {
998 my $fname = File::Basename::basename($file);
999 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
1000 # Mipmaps don't have an URL, ignore
1001 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
1002 push @ret, "/$event/$filename";
1003 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
1004 push @ret, "/$event/$1x$2/$filename";
1005 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
1006 push @ret, "/$event/$1x$2/nobox/$filename";
1007 } elsif ($fname =~ /^$id--1--1-box\.png$/) {
1008 push @ret, "/$event/box/$filename";
1009 } elsif ($fname =~ /^$id-(\d+)-(\d+)-box\.png$/) {
1010 push @ret, "/$event/$1x$2/box/$filename";
1012 log_warn($r, "Couldn't find a purging URL for $fname");
1019 sub set_last_modified {
1020 my ($res, $mtime) = @_;
1022 my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
1023 $res->header('Last-Modified' => $str);
1026 sub get_server_name {
1028 my $host = $r->env->{'HTTP_HOST'};
1035 if (defined($r->logger)) {
1036 $r->logger->({ level => 'info', message => $msg });
1038 print STDERR "[INFO] $msg\n";
1044 if (defined($r->logger)) {
1045 $r->logger->({ level => 'warn', message => $msg });
1047 print STDERR "[WARN] $msg\n";
1053 if (defined($r->logger)) {
1054 $r->logger->({ level => 'error', message => $msg });
1056 print STDERR "[ERROR] $msg\n";