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