]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/Common.pm
Fix an (irrelevant) confusion about addEventListener.
[pr0n] / perl / Sesse / pr0n / Common.pm
1 package Sesse::pr0n::Common;
2 use strict;
3 use warnings;
4
5 use Sesse::pr0n::Overload;
6 use Sesse::pr0n::QscaleProxy;
7 use Sesse::pr0n::Templates;
8
9 use Carp;
10 use Encode;
11 use DBI;
12 use DBD::Pg;
13 use Image::Magick;
14 use IO::String;
15 use POSIX;
16 use MIME::Base64;
17 use MIME::Types;
18 use LWP::Simple;
19 # use Image::Info;
20 use Image::ExifTool;
21 use HTML::Entities;
22 use URI::Escape;
23 use File::Basename;
24 use Crypt::Eksblowfish::Bcrypt;
25 use File::Temp;
26
27 BEGIN {
28         use Exporter ();
29         our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
30
31         use Sesse::pr0n::Config;
32         eval {
33                 require Sesse::pr0n::Config_local;
34         };
35
36         $VERSION     = "v3.20";
37         @ISA         = qw(Exporter);
38         @EXPORT      = qw(&error &dberror);
39         %EXPORT_TAGS = qw();
40         @EXPORT_OK   = qw(&error &dberror);
41
42         our $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
43                 $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
44                 or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
45         our $mimetypes = new MIME::Types;
46         
47         print STDERR "Initializing pr0n $VERSION\n";
48 }
49 END {
50         our $dbh;
51         $dbh->disconnect;
52 }
53
54 our ($dbh, $mimetypes);
55
56 sub error {
57         my ($r,$err,$status,$title) = @_;
58
59         if (!defined($status) || !defined($title)) {
60                 $status = 500;
61                 $title = "Internal server error";
62         }
63
64         my $res = Plack::Response->new($status);
65         my $io = IO::String->new;
66         
67         $r->content_type('text/html; charset=utf-8');
68
69         header($r, $io, $title);
70         $io->print("    <p>Error: $err</p>\n");
71         footer($r, $io);
72
73         log_error($r, $err);
74         log_error($r, "Stack trace follows: " . Carp::longmess());
75
76         $io->setpos(0);
77         $res->body($io);
78         return $res;
79 }
80
81 sub dberror {
82         my ($r,$err) = @_;
83         return error($r, "$err (DB error: " . $dbh->errstr . ")");
84 }
85
86 sub header {
87         my ($r, $io, $title) = @_;
88
89         $r->content_type("text/html; charset=utf-8");
90
91         # Fetch quote if we're itk-bilder.samfundet.no
92         my $quote = "";
93         if (Sesse::pr0n::Common::get_server_name($r) eq 'itk-bilder.samfundet.no') {
94                 $quote = LWP::Simple::get("http://itk.samfundet.no/include/quotes.cli.php");
95                 $quote = "Error: Could not fetch quotes." if (!defined($quote));
96         }
97         Sesse::pr0n::Templates::print_template($r, $io, "header", { title => $title, quotes => $quote });
98 }
99
100 sub footer {
101         my ($r, $io) = @_;
102         Sesse::pr0n::Templates::print_template($r, $io, "footer",
103                 { version => $Sesse::pr0n::Common::VERSION });
104 }
105
106 sub scale_aspect {
107         my ($width, $height, $thumbxres, $thumbyres) = @_;
108
109         unless ($thumbxres >= $width &&
110                 $thumbyres >= $height) {
111                 my $sfh = $width / $thumbxres;
112                 my $sfv = $height / $thumbyres;
113                 if ($sfh > $sfv) {
114                         $width  /= $sfh;
115                         $height /= $sfh;
116                 } else {
117                         $width  /= $sfv;
118                         $height /= $sfv;
119                 }
120                 $width = POSIX::floor($width);
121                 $height = POSIX::floor($height);
122         }
123
124         return ($width, $height);
125 }
126
127 sub get_query_string {
128         my ($param, $defparam) = @_;
129         my $first = 1;
130         my $str = "";
131
132         for my $key (sort keys %$param) {
133                 my $value = $param->{$key};
134                 next unless defined($value);
135                 next if (defined($defparam->{$key}) && $value == $defparam->{$key});
136
137                 $value = pretty_escape($value);
138         
139                 $str .= ($first) ? "?" : ';';
140                 $str .= "$key=$value";
141                 $first = 0;
142         }
143         return $str;
144 }
145
146 # This is not perfect (it can't handle "_ " right, for one), but it will do for now
147 sub weird_space_encode {
148         my $val = shift;
149         if ($val =~ /_/) {
150                 return "_" x (length($val) * 2);
151         } else {
152                 return "_" x (length($val) * 2 - 1);
153         }
154 }
155
156 sub weird_space_unencode {
157         my $val = shift;
158         if (length($val) % 2 == 0) {
159                 return "_" x (length($val) / 2);
160         } else {
161                 return " " x ((length($val) + 1) / 2);
162         }
163 }
164                 
165 sub pretty_escape {
166         my $value = shift;
167
168         $value =~ s/(([_ ])\2*)/weird_space_encode($1)/ge;
169         $value = URI::Escape::uri_escape($value);
170         $value =~ s/%2F/\//g;
171
172         return $value;
173 }
174
175 sub pretty_unescape {
176         my $value = shift;
177
178         # URI unescaping is already done for us
179         $value =~ s/(_+)/weird_space_unencode($1)/ge;
180
181         return $value;
182 }
183
184 sub print_link {
185         my ($io, $title, $baseurl, $param, $defparam, $accesskey) = @_;
186         my $str = "<a href=\"$baseurl" . get_query_string($param, $defparam) . "\"";
187         if (defined($accesskey) && length($accesskey) == 1) {
188                 $str .= " accesskey=\"$accesskey\"";
189         }
190         $str .= ">$title</a>";
191         $io->print($str);
192 }
193
194 sub get_dbh {
195         # Check that we are alive
196         if (!(defined($dbh) && $dbh->ping)) {
197                 # Try to reconnect
198                 print STDERR "Lost contact with PostgreSQL server, trying to reconnect...\n";
199                 unless ($dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
200                         $Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)) {
201                         $dbh = undef;
202                         die "Couldn't connect to PostgreSQL database";
203                 }
204         }
205
206         return $dbh;
207 }
208
209 sub get_disk_location {
210         my ($r, $id) = @_;
211         my $dir = POSIX::floor($id / 256);
212         return $Sesse::pr0n::Config::image_base . "images/$dir/$id.jpg";
213 }
214
215 sub get_cache_location {
216         my ($id, $width, $height, $format) = @_;
217         my $dir = POSIX::floor($id / 256);
218
219         return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-$width-$height-nobox.$format";
220 }
221
222 sub ensure_disk_location_exists {
223         my ($r, $id) = @_;
224         my $dir = POSIX::floor($id / 256);
225
226         my $img_dir = $Sesse::pr0n::Config::image_base . "/images/$dir/";
227         if (! -d $img_dir) {
228                 log_info($r, "Need to create new image directory $img_dir");
229                 mkdir($img_dir);  # Ignore errors, there could be a race.
230                 -d $img_dir or die "Couldn't create new image directory $img_dir";
231         }
232
233         my $cache_dir = $Sesse::pr0n::Config::image_base . "/cache/$dir/";
234         if (! -d $cache_dir) {
235                 log_info($r, "Need to create new cache directory $cache_dir");
236                 mkdir($cache_dir);  # Ignore errors, there could be a race.
237                 -d $cache_dir or die "Couldn't create new cache directory $cache_dir";
238         }
239 }
240
241 sub get_mipmap_location {
242         my ($r, $id, $width, $height) = @_;
243         my $dir = POSIX::floor($id / 256);
244
245         return $Sesse::pr0n::Config::image_base . "cache/$dir/$id-mipmap-$width-$height.jpg";
246 }
247
248 sub update_image_info {
249         my ($r, $id, $width, $height) = @_;
250
251         # Also find the date taken if appropriate (from the EXIF tag etc.)
252         my $exiftool = Image::ExifTool->new;
253         $exiftool->ExtractInfo(get_disk_location($r, $id));
254         my $info = $exiftool->GetInfo();
255         my $datetime = undef;
256                         
257         if (defined($info->{'DateTimeOriginal'})) {
258                 # Parse the date and time over to ISO format
259                 if ($info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)(?:\+\d\d:\d\d)?$/ && $1 > 1990) {
260                         $datetime = "$1-$2-$3 $4:$5:$6";
261                 }
262         }
263
264         {
265                 local $dbh->{AutoCommit} = 0;
266
267                 # EXIF information
268                 $dbh->do('DELETE FROM exif_info WHERE image=?',
269                         undef, $id)
270                         or die "Couldn't delete old EXIF information in SQL: $!";
271
272                 my $q = $dbh->prepare('INSERT INTO exif_info (image,key,value) VALUES (?,?,?)')
273                         or die "Couldn't prepare inserting EXIF information: $!";
274
275                 for my $key (keys %$info) {
276                         next if ref $info->{$key};
277                         $q->execute($id, $key, guess_charset($info->{$key}))
278                                 or die "Couldn't insert EXIF information in database: $!";
279                 }
280
281                 # Model/Lens
282                 my $model = $exiftool->GetValue('Model', 'PrintConv');
283                 my $lens = $exiftool->GetValue('Lens', 'PrintConv');
284                 $lens = $exiftool->GetValue('LensSpec', 'PrintConv') if (!defined($lens));
285
286                 $model =~ s/^\s*//;
287                 $model =~ s/\s*$//;
288                 $model = undef if (length($model) == 0);
289
290                 $lens =~ s/^\s*//;
291                 $lens =~ s/\s*$//;
292                 $lens = undef if (length($lens) == 0);
293                 
294                 # Now update the main table with the information we've got
295                 $dbh->do('UPDATE images SET width=?, height=?, date=?, model=?, lens=? WHERE id=?',
296                          undef, $width, $height, $datetime, $model, $lens, $id)
297                         or die "Couldn't update width/height in SQL: $!";
298                 
299                 # update the last_picture cache as well (this should of course be done
300                 # via a trigger, but this is less complicated :-) )
301                 $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=?)',
302                         undef, $datetime, $id)
303                         or die "Couldn't update last_picture in SQL: $!";
304         }
305 }
306
307 sub check_access {
308         my $r = shift;
309         
310         #return qw(sesse Sesse);
311
312         my $auth = $r->header('authorization');
313         if (!defined($auth)) {
314                 return undef;
315         } 
316         if ($auth =~ /^Basic ([a-zA-Z0-9+\/]+=*)$/) {
317                 return check_basic_auth($r, $1);
318         }       
319         return undef;
320 }
321
322 sub generate_401 {
323         my ($r) = @_;
324         my $res = Plack::Response->new(401);
325         $res->content_type('text/plain; charset=utf-8');
326         $res->status(401);
327         $res->header('WWW-Authenticate' => 'Basic realm="pr0n.sesse.net"');
328
329         $res->body("Need authorization\n");
330         return $res;
331 }
332
333 sub check_basic_auth {
334         my ($r, $auth) = @_;    
335
336         my ($raw_user, $pass) = split /:/, MIME::Base64::decode_base64($auth);
337         my ($user, $takenby) = extract_takenby($raw_user);
338
339         my $ref = $dbh->selectrow_hashref('SELECT cryptpassword FROM users WHERE username=? AND vhost=?',
340                 undef, $user, Sesse::pr0n::Common::get_server_name($r));
341         my $bcrypt_matches = 0;
342         if (!defined($ref) || Crypt::Eksblowfish::Bcrypt::bcrypt($pass, $ref->{'cryptpassword'}) ne $ref->{'cryptpassword'}) {
343                 $r->content_type('text/plain; charset=utf-8');
344                 log_warn($r, "Authentication failed for $user/$takenby");
345                 return undef;
346         }
347         log_info($r, "Authentication succeeded for $user/$takenby");
348
349         return ($user, $takenby);
350 }
351
352 sub get_pseudorandom_bytes {
353         my $num_left = shift;
354         my $bytes = "";
355         open my $randfh, "<", "/dev/urandom"
356                 or die "/dev/urandom: $!";
357         binmode $randfh;
358         while ($num_left > 0) {
359                 my $tmp;
360                 if (sysread($randfh, $tmp, $num_left) == -1) {
361                         die "sysread(/dev/urandom): $!";
362                 }
363                 $bytes .= $tmp;
364                 $num_left -= length($bytes);
365         }
366         close $randfh;
367         return $bytes;
368 }
369
370 sub extract_takenby {
371         my ($user) = shift;
372
373         # WinXP is stupid :-)
374         if ($user =~ /^.*\\(.*)$/) {
375                 $user = $1;
376         }
377
378         my $takenby;
379         if ($user =~ /^([a-zA-Z0-9^_-]+)\@([a-zA-Z0-9^_-]+)$/) {
380                 $user = $1;
381                 $takenby = $2;
382         } else {
383                 ($takenby = $user) =~ s/^([a-zA-Z])/uc($1)/e;
384         }
385
386         return ($user, $takenby);
387 }
388         
389 sub stat_image {
390         my ($r, $event, $filename) = (@_);
391         my $ref = $dbh->selectrow_hashref(
392                 'SELECT id FROM images WHERE event=? AND filename=?',
393                 undef, $event, $filename);
394         if (!defined($ref)) {
395                 return (undef, undef, undef);
396         }
397         return stat_image_from_id($r, $ref->{'id'});
398 }
399
400 sub stat_image_from_id {
401         my ($r, $id) = @_;
402
403         my $fname = get_disk_location($r, $id);
404         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
405                 or return (undef, undef, undef);
406
407         return ($fname, $size, $mtime);
408 }
409
410 # Takes in an image ID and a set of resolutions, and returns (generates if needed)
411 # the smallest mipmap larger than the largest of them, as well as the original image
412 # dimensions.
413 sub make_mipmap {
414         my ($r, $filename, $id, $dbwidth, $dbheight, @res) = @_;
415         my ($img, $mmimg, $width, $height);
416         
417         my $physical_fname = get_disk_location($r, $id);
418
419         # If we don't know the size, we'll need to read it in anyway
420         if (!defined($dbwidth) || !defined($dbheight)) {
421                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
422                 $width = $img->Get('columns');
423                 $height = $img->Get('rows');
424         } else {
425                 $width = $dbwidth;
426                 $height = $dbheight;
427         }
428
429         # Generate the list of mipmaps
430         my @mmlist = ();
431         
432         my $mmwidth = $width;
433         my $mmheight = $height;
434
435         while ($mmwidth > 1 || $mmheight > 1) {
436                 my $new_mmwidth = POSIX::floor($mmwidth / 2);           
437                 my $new_mmheight = POSIX::floor($mmheight / 2);         
438
439                 $new_mmwidth = 1 if ($new_mmwidth < 1);
440                 $new_mmheight = 1 if ($new_mmheight < 1);
441
442                 my $large_enough = 1;
443                 for my $i (0..($#res/2)) {
444                         my ($xres, $yres) = ($res[$i*2], $res[$i*2+1]);
445                         if ($xres == -1 || $xres > $new_mmwidth || $yres > $new_mmheight) {
446                                 $large_enough = 0;
447                                 last;
448                         }
449                 }
450                                 
451                 last if (!$large_enough);
452
453                 $mmwidth = $new_mmwidth;
454                 $mmheight = $new_mmheight;
455
456                 push @mmlist, [ $mmwidth, $mmheight ];
457         }
458                 
459         # Ensure that all of them are OK
460         my $last_good_mmlocation;
461         for my $i (0..$#mmlist) {
462                 my $last = ($i == $#mmlist);
463                 my $mmres = $mmlist[$i];
464
465                 my $mmlocation = get_mipmap_location($r, $id, $mmres->[0], $mmres->[1]);
466                 if (! -r $mmlocation or (-M $mmlocation > -M $physical_fname)) {
467                         if (!defined($img)) {
468                                 if (defined($last_good_mmlocation)) {
469                                         $img = Sesse::pr0n::QscaleProxy->new;
470                                         $img->Read($last_good_mmlocation);
471                                 } else {
472                                         $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
473                                 }
474                         }
475                         my $cimg;
476                         if ($last) {
477                                 $cimg = $img;
478                         } else {
479                                 $cimg = $img->Clone();
480                         }
481                         log_info($r, "Making mipmap for $id: " . $mmres->[0] . " x " . $mmres->[1]);
482                         $cimg->Resize(width=>$mmres->[0], height=>$mmres->[1], filter=>'Lanczos', 'sampling-factor'=>'1x1');
483                         $cimg->Strip();
484                         my $err = $cimg->write(
485                                 filename => $mmlocation,
486                                 quality => 95,
487                                 'sampling-factor' => '1x1'
488                         );
489                         $img = $cimg;
490                 } else {
491                         $last_good_mmlocation = $mmlocation;
492                 }
493                 if ($last && !defined($img)) {
494                         # OK, read in the smallest one
495                         $img = Sesse::pr0n::QscaleProxy->new;
496                         my $err = $img->Read($mmlocation);
497                 }
498         }
499
500         if (!defined($img)) {
501                 $img = read_original_image($r, $filename, $id, $dbwidth, $dbheight);
502                 $width = $img->Get('columns');
503                 $height = $img->Get('rows');
504         }
505         return ($img, $width, $height);
506 }
507
508 sub read_original_image {
509         my ($r, $filename, $id, $dbwidth, $dbheight) = @_;
510
511         my $physical_fname = get_disk_location($r, $id);
512
513         # Read in the original image
514         my $magick;
515         if ($filename =~ /\.jpeg$/i || $filename =~ /\.jpg$/i) {
516                 $magick = Sesse::pr0n::QscaleProxy->new;
517         } else {
518                 $magick = Image::Magick->new;
519         }
520         my $err;
521
522         if ($filename =~ /\.(nef|cr2)$/i) {
523                 $physical_fname = "NEF:$physical_fname";
524                 $err = $magick->Read($physical_fname);
525         } else {
526                 # We always want YCbCr JPEGs. Setting this explicitly here instead of using
527                 # RGB is slightly faster (no colorspace conversion needed) and works equally
528                 # well for our uses, as long as we don't need to draw an information box,
529                 # which trickles several ImageMagick bugs related to colorspace handling.
530                 # (Ideally we'd be able to keep the image subsampled and
531                 # planar, but that would probably be difficult for ImageMagick to expose.)
532                 #if (!$infobox) {
533                 #       $magick->Set(colorspace=>'YCbCr');
534                 #}
535                 $err = $magick->Read($physical_fname);
536         }
537         
538         if ($err) {
539                 log_warn($r, "$physical_fname: $err");
540                 $err =~ /(\d+)/;
541                 if ($1 >= 400) {
542                         undef $magick;
543                         error($r, "$physical_fname: $err");
544                 }
545         }
546
547         # If we use ->[0] unconditionally, text rendering (!) seems to crash
548         my $img;
549         if (ref($magick) !~ /Image::Magick/) {
550                 $img = $magick;
551         } else {
552                 $img = (scalar @$magick > 1) ? $magick->[0] : $magick;
553         }
554
555         return $img;
556 }
557
558 sub ensure_cached {
559         my ($r, $avif_ok, $jxl_ok, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres) = @_;
560
561         my $fname = get_disk_location($r, $id);
562         unless (defined($xres) && (!defined($dbwidth) || !defined($dbheight) || $xres < $dbwidth || $yres < $dbheight || $xres == -1)) {
563                 return ($fname, undef);
564         }
565
566         # See if we have an up-to-date JPEG-XL or AVIF to serve.
567         # (We never generate them on-the-fly, since they're so slow.)
568         my $cachename = get_cache_location($id, $xres, $yres, 'jxl');
569         if ($jxl_ok && -r $cachename and (-M $cachename <= -M $fname)) {
570                 return ($cachename, 'image/jxl');
571         }
572
573         $cachename = get_cache_location($id, $xres, $yres, 'avif');
574         if ($avif_ok && -r $cachename and (-M $cachename <= -M $fname)) {
575                 return ($cachename, 'image/avif');
576         }
577
578         $cachename = get_cache_location($id, $xres, $yres, 'jpg');
579         if (! -r $cachename or (-M $cachename > -M $fname)) {
580                 # If we are in overload mode (aka Slashdot mode), refuse to generate
581                 # new thumbnails.
582                 if (Sesse::pr0n::Overload::is_in_overload($r)) {
583                         log_warn($r, "In overload mode, not scaling $id to $xres x $yres");
584                         error($r, 'System is in overload mode, not doing any scaling');
585                 }
586
587                 make_cache($r, $filename, $id, $dbwidth, $dbheight, 'jpg', $xres, $yres, @otherres);
588         }
589
590         return ($cachename, 'image/jpeg');
591 }
592
593 sub make_cache {
594         my ($r, $filename, $id, $dbwidth, $dbheight, $format, $xres, $yres, @otherres) = @_;
595
596         my ($img, $new_dbwidth, $new_dbheight) = make_mipmap($r, $filename, $id, $dbwidth, $dbheight, $xres, $yres, @otherres);
597
598         # Update the SQL database if it doesn't contain the required info
599         if (!defined($dbwidth) && defined($new_dbwidth)) {
600                 log_info($r, "Updating width/height for $id: $new_dbwidth x $new_dbheight");
601                 update_image_info($r, $id, $new_dbwidth, $new_dbheight);
602         }
603
604         my $err;
605         while (defined($xres) && defined($yres)) {
606                 my ($nxres, $nyres) = (shift @otherres, shift @otherres);
607                 my $cachename = get_cache_location($id, $xres, $yres, $format);
608                 
609                 my $cimg;
610                 if (defined($nxres) && defined($nyres)) {
611                         # we have more resolutions to scale, so don't throw
612                         # the image away
613                         $cimg = $img->Clone();
614                 } else {
615                         $cimg = $img;
616                 }
617         
618                 my $width = $img->Get('columns');
619                 my $height = $img->Get('rows');
620                 my ($nwidth, $nheight) = scale_aspect($width, $height, $xres, $yres);
621
622                 my $filter = 'Lanczos';
623                 my $quality = 87;
624                 my $sf = "1x1";
625
626                 if ($xres != -1) {
627                         $cimg->Resize(width=>$nwidth, height=>$nheight, filter=>$filter);
628                 }
629
630                 # Strip EXIF tags etc.
631                 $cimg->Strip();
632
633                 if ($format eq 'jpg') {
634                         my %parms = (
635                                 filename => $cachename,
636                                 quality => $quality
637                         );
638                         if (($nwidth >= 640 && $nheight >= 480) ||
639                             ($nwidth >= 480 && $nheight >= 640)) {
640                                 $parms{'interlace'} = 'Plane';
641                         }
642                         if (defined($sf)) {
643                                 $parms{'sampling-factor'} = $sf;
644                         }
645                         $err = $cimg->write(%parms);
646                 } elsif ($format eq 'avif') {
647                         # ImageMagick doesn't have AVIF support until version 7,
648                         # and Debian hasn't packaged that even in unstable as of 2021.
649                         # So we'll need to do it the manual way. (We don't use /tmp, for security reasons.)
650                         (my $dirname = $cachename) =~ s,/[^/]*$,,;
651                         my ($fh, $raw_filename) = File::Temp::tempfile('tmp.XXXXXXXX', DIR => $dirname, SUFFIX => '.ycbcr');
652                         # Write a Y4M header, so that we get the chroma range correct.
653                         printf $fh "YUV4MPEG2 W%d H%d F25:1 Ip A1:1 C444 XYSCSS=444 XCOLORRANGE=FULL\nFRAME\n", $nwidth, $nheight;
654                         my %parms = (
655                                 file => $fh,
656                                 filename => $raw_filename,
657                                 interlace => 'Plane'
658                         );
659                         $cimg->write(%parms);
660                         close($fh);
661                         my $ivf_filename;
662                         ($fh, $ivf_filename) = File::Temp::tempfile('tmp.XXXXXXXX', DIR => $dirname, SUFFIX => '.ivf');
663                         close($fh);
664                         system('aomenc', '--quiet', '--cpu-used=0', '--bit-depth=10', '--end-usage=q', '--cq-level=13', '--target-bitrate=0', '--good', '--aq-mode=1', '--matrix-coefficients=bt601', '-o', $ivf_filename, $raw_filename);
665                         unlink($raw_filename);
666                         system('MP4Box', '-quiet', '-add-image', "$ivf_filename:primary", '-ab', 'avif', '-ab', 'miaf', '-new', $cachename);
667                         unlink($ivf_filename);
668                 } elsif ($format eq 'jxl') {
669                         # Similar, for JPEG-XL.
670                         (my $dirname = $cachename) =~ s,/[^/]*$,,;
671                         my ($fh, $raw_filename) = File::Temp::tempfile('tmp.XXXXXXXX', DIR => $dirname, SUFFIX => '.ppm');
672                         my %parms = (
673                                 file => $fh,
674                                 filename => $raw_filename
675                         );
676                         $cimg->write(%parms);
677                         close($fh);
678                         system('cjxl', '-p', $raw_filename, $cachename);
679                         unlink($raw_filename);
680                 } else {
681                         die "Unknown format $format";
682                 }
683
684                 undef $cimg;
685
686                 ($xres, $yres) = ($nxres, $nyres);
687
688                 log_info($r, "New cache: $nwidth x $nheight ($format) for $id");
689         }
690         
691         undef $img;
692         if ($err) {
693                 log_warn($r, "$filename: $err");
694                 $err =~ /(\d+)/;
695                 if ($1 >= 400) {
696                         #@$magick = ();
697                         error($r, "$filename: $err");
698                 }
699         }
700 }
701
702 sub get_mimetype_from_filename {
703         my $filename = shift;
704         my MIME::Type $type = $mimetypes->mimeTypeOf($filename);
705         $type = "image/jpeg" if (!defined($type));
706         return $type;
707 }
708
709 sub make_infobox_parts {
710         my ($info) = @_;
711
712         # The infobox is of the form
713         # "Time - date - focal length, shutter time, aperture, sensitivity, exposure bias - flash",
714         # possibly with some parts omitted -- the middle part is known as the "classic
715         # fields"; note the comma separation. Every field has an associated "bold flag"
716         # in the second part.
717         
718         my $manual_shutter = (defined($info->{'ExposureProgram'}) &&
719                 $info->{'ExposureProgram'} =~ /shutter\b.*\bpriority/i);
720         my $manual_aperture = (defined($info->{'ExposureProgram'}) &&
721                 $info->{'ExposureProgram'} =~ /aperture\b.*\bpriority/i);
722         if (defined($info->{'ExposureProgram'}) && $info->{'ExposureProgram'} =~ /manual/i) {
723                 $manual_shutter = 1;
724                 $manual_aperture = 1;
725         }
726
727         my @classic_fields = ();
728         if (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)(?:\.\d+)?\s*(?:mm)?$/) {
729                 push @classic_fields, [ $1 . "mm", 0 ];
730         } elsif (defined($info->{'FocalLength'}) && $info->{'FocalLength'} =~ /^(\d+)\/(\d+)$/) {
731                 push @classic_fields, [ (sprintf "%.1fmm", ($1/$2)), 0 ];
732         }
733
734         if (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+)\/(\d+)$/) {
735                 my ($a, $b) = ($1, $2);
736                 my $gcd = gcd($a, $b);
737                 push @classic_fields, [ $a/$gcd . "/" . $b/$gcd . "s", $manual_shutter ];
738         } elsif (defined($info->{'ExposureTime'}) && $info->{'ExposureTime'} =~ /^(\d+(?:\.\d+)?)$/) {
739                 push @classic_fields, [ $1 . "s", $manual_shutter ];
740         }
741
742         if (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\/(\d+)$/) {
743                 my $f = $1/$2;
744                 if ($f >= 10) {
745                         push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
746                 } else {
747                         push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
748                 }
749         } elsif (defined($info->{'FNumber'}) && $info->{'FNumber'} =~ /^(\d+)\.(\d+)$/) {
750                 my $f = $info->{'FNumber'};
751                 if ($f >= 10) {
752                         push @classic_fields, [ (sprintf "f/%.0f", $f), $manual_aperture ];
753                 } else {
754                         push @classic_fields, [ (sprintf "f/%.1f", $f), $manual_aperture ];
755                 }
756         }
757
758 #       Apache2::ServerUtil->server->log_error(join(':', keys %$info));
759
760         my $iso = undef;
761         if (defined($info->{'NikonD1-ISOSetting'})) {
762                 $iso = $info->{'NikonD1-ISOSetting'};
763         } elsif (defined($info->{'ISO'})) {
764                 $iso = $info->{'ISO'};
765         } elsif (defined($info->{'ISOSetting'})) {
766                 $iso = $info->{'ISOSetting'};
767         }
768         if (defined($iso) && $iso =~ /(\d+)/) {
769                 push @classic_fields, [ $1 . " ISO", 0 ];
770         }
771
772         if (defined($info->{'ExposureBiasValue'}) && $info->{'ExposureBiasValue'} ne "0") {
773                 push @classic_fields, [ $info->{'ExposureBiasValue'} . " EV", 0 ];
774         } elsif (defined($info->{'ExposureCompensation'}) && $info->{'ExposureCompensation'} ne "0") {
775                 push @classic_fields, [ $info->{'ExposureCompensation'} . " EV", 0 ];
776         }
777
778         # Now piece together the rest
779         my @parts = ();
780         
781         if (defined($info->{'DateTimeOriginal'}) &&
782             $info->{'DateTimeOriginal'} =~ /^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/
783             && $1 >= 1990) {
784                 push @parts, [ "$1-$2-$3 $4:$5", 0 ];
785         }
786
787         if (defined($info->{'Model'})) {
788                 my $model = $info->{'Model'}; 
789                 $model =~ s/^\s+//;
790                 $model =~ s/\s+$//;
791
792                 push @parts, [ "\x{00A0}\x{2013}\x{00A0}", 0 ] if (scalar @parts > 0);
793                 push @parts, [ $model, 0 ];
794         }
795         
796         # classic fields
797         if (scalar @classic_fields > 0) {
798                 push @parts, [ "\x{00A0}\x{2013}\x{00A0}", 0 ] if (scalar @parts > 0);
799
800                 my $first_elem = 1;
801                 for my $field (@classic_fields) {
802                         push @parts, [ ', ', 0 ] if (!$first_elem);
803                         $first_elem = 0;
804                         push @parts, $field;
805                 }
806         }
807
808         if (defined($info->{'Flash'})) {
809                 if ($info->{'Flash'} =~ /did not fire/i ||
810                     $info->{'Flash'} =~ /no flash/i ||
811                     $info->{'Flash'} =~ /not fired/i ||
812                     $info->{'Flash'} =~ /Off/)  {
813                         push @parts, [ "\x{00A0}\x{2013}\x{00A0}", 0 ] if (scalar @parts > 0);
814                         push @parts, [ "No flash", 0 ];
815                 } elsif ($info->{'Flash'} =~ /fired/i ||
816                          $info->{'Flash'} =~ /On/) {
817                         push @parts, [ "\x{00A0}\x{2013}\x{00A0}", 0 ] if (scalar @parts > 0);
818                         push @parts, [ "Flash", 0 ];
819                 } else {
820                         push @parts, [ "\x{00A0}\x{2013}\x{00A0}", 0 ] if (scalar @parts > 0);
821                         push @parts, [ $info->{'Flash'}, 0 ];
822                 }
823         }
824
825         return @parts;
826 }
827
828 sub gcd {
829         my ($a, $b) = @_;
830         return $a if ($b == 0);
831         return gcd($b, $a % $b);
832 }
833
834 sub add_new_event {
835         my ($r, $res, $dbh, $id, $date, $desc) = @_;
836         my @errors = ();
837
838         if (!defined($id) || $id =~ /^\s*$/ || $id !~ /^([a-zA-Z0-9-]+)$/) {
839                 push @errors, "Manglende eller ugyldig ID.";
840         }
841         if (!defined($date) || $date =~ /^\s*$/ || $date =~ /[<>&]/ || length($date) > 100) {
842                 push @errors, "Manglende eller ugyldig dato.";
843         }
844         if (!defined($desc) || $desc =~ /^\s*$/ || $desc =~ /[<>&]/ || length($desc) > 100) {
845                 push @errors, "Manglende eller ugyldig beskrivelse.";
846         }
847         
848         if (scalar @errors > 0) {
849                 return @errors;
850         }
851                 
852         my $vhost = Sesse::pr0n::Common::get_server_name($r);
853         $dbh->do("INSERT INTO events (event,date,name,vhost) VALUES (?,?,?,?)",
854                 undef, $id, $date, $desc, $vhost)
855                 or return ("Kunne ikke sette inn ny hendelse" . $dbh->errstr);
856         $dbh->do("INSERT INTO last_picture_cache (vhost,event,last_picture) VALUES (?,?,NULL)",
857                 undef, $vhost, $id)
858                 or return ("Kunne ikke sette inn ny cache-rad" . $dbh->errstr);
859         purge_cache($r, $res, "/");
860
861         return ();
862 }
863
864 sub guess_charset {
865         my $text = shift;
866         my $decoded;
867
868         eval {
869                 $decoded = Encode::decode("utf-8", $text, Encode::FB_CROAK);
870         };
871         if ($@) {
872                 $decoded = Encode::decode("iso8859-1", $text);
873         }
874
875         return $decoded;
876 }
877
878 # Depending on your front-end cache, you might want to get creative somehow here.
879 # This example assumes you have a front-end cache and it can translate an X-Pr0n-Purge
880 # regex tacked onto a request into something useful. The elements given in
881 # should not be regexes, though, as e.g. Squid will not be able to handle that.
882 sub purge_cache {
883         my ($r, $res, @elements) = @_;
884         return if (scalar @elements == 0);
885
886         my @pe = ();
887         for my $elem (@elements) {
888                 log_info($r, "Purging $elem");
889                 (my $e = $elem) =~ s/[.+*|()]/\\$&/g;
890                 push @pe, $e;
891         }
892
893         my $regex = "^";
894         if (scalar @pe == 1) {
895                 $regex .= $pe[0];
896         } else {
897                 $regex .= "(" . join('|', @pe) . ")";
898         }
899         $regex .= "(\\?.*)?\$";
900         $res->header('X-Pr0n-Purge' => $regex);
901 }
902                                 
903 # Find a list of all cache URLs for a given image, given what we have on disk.
904 sub get_all_cache_urls {
905         my ($r, $dbh, $id) = @_;
906         my $dir = POSIX::floor($id / 256);
907         my @ret = ();
908
909         my $q = $dbh->prepare('SELECT event, filename FROM images WHERE id=?')
910                 or die "Couldn't prepare: " . $dbh->errstr;
911         $q->execute($id)
912                 or die "Couldn't find event and filename: " . $dbh->errstr;
913         my $ref = $q->fetchrow_hashref; 
914         my $event = $ref->{'event'};
915         my $filename = $ref->{'filename'};
916         $q->finish;
917
918         my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
919         for my $file (<$base/$id-*>) {
920                 my $fname = File::Basename::basename($file);
921                 if ($fname =~ /^$id-mipmap-.*\.jpg$/) {
922                         # Mipmaps don't have an URL, ignore
923                 } elsif ($fname =~ /^$id--1--1\.jpg$/) {
924                         push @ret, "/$event/$filename";
925                 } elsif ($fname =~ /^$id-(\d+)-(\d+)\.jpg$/) {
926                         push @ret, "/$event/$1x$2/$filename";
927                 } elsif ($fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/) {
928                         push @ret, "/$event/$1x$2/nobox/$filename";
929                 } else {
930                         log_warn($r, "Couldn't find a purging URL for $fname");
931                 }
932         }
933
934         return @ret;
935 }
936
937 sub set_last_modified {
938         my ($res, $mtime) = @_;
939
940         my $str = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
941         $res->header('Last-Modified' => $str);
942 }
943
944 sub get_server_name {
945         my $r = shift;
946         my $host = $r->env->{'HTTP_HOST'};
947         $host =~ s/:.*//;
948         return $host;
949 }
950
951 sub log_info {
952         my ($r, $msg) = @_;
953         if (defined($r->{'logger'})) {
954                 $r->logger->({ level => 'info', message => $msg });
955         } else {
956                 print STDERR "[INFO] $msg\n";
957         }
958 }
959
960 sub log_warn {
961         my ($r, $msg) = @_;
962         if (defined($r->{'logger'})) {
963                 $r->logger->({ level => 'warn', message => $msg });
964         } else {
965                 print STDERR "[WARN] $msg\n";
966         }
967 }
968
969 sub log_error {
970         my ($r, $msg) = @_;
971         if (defined($r->{'logger'})) {
972                 $r->logger->({ level => 'error', message => $msg });
973         } else {
974                 print STDERR "[ERROR] $msg\n";
975         }
976 }
977
978 1;
979
980