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