]> git.donarmstrong.com Git - debbugs.git/blob - cgi/libravatar.cgi
219d65ee0c268c69bca1f5d63b8467422072fa90
[debbugs.git] / cgi / libravatar.cgi
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use Debbugs::Config qw(:config);
7 use Debbugs::CGI qw(cgi_parameters);
8 use Debbugs::Common;
9 use Digest::MD5 qw(md5_hex);
10 use File::LibMagic;
11 use Debbugs::Libravatar qw(:libravatar);
12
13 use Libravatar::URL;
14
15 use CGI::Simple;
16 use Cwd qw(abs_path);
17
18 my $q = CGI::Simple->new();
19
20 my %param =
21     cgi_parameters(query => $q,
22                    single => [qw(email avatar default)],
23                    default => {avatar => 'yes',
24                                default => $config{libravatar_uri_options},
25                               },
26                   );
27 # if avatar is no, serve the empty png
28 if ($param{avatar} ne 'yes' or not defined $param{email} or not length $param{email}) {
29     serve_cache('',$q);
30     exit 0;
31 }
32
33 # figure out what the md5sum of the e-mail is.
34 my $email_md5sum = md5_hex(lc($param{email}));
35 my ($cache_location, $is_valid) = cache_location(email => lc($param{email}));
36 # if we've got it, and it's less than one hour old, return it.
37 if ($is_valid) {
38     serve_cache($cache_location,$q);
39     exit 0;
40 }
41 # if we don't have it, get it, and store it in the cache
42 $cache_location = retrieve_libravatar(location => $cache_location,
43                                       email => lc($param{email}),
44                                      );
45 if (not defined $cache_location) {
46     # failure, serve the default image
47     serve_cache('',$q);
48     exit 0;
49 } else {
50     serve_cache($cache_location,$q);
51     exit 0;
52 }
53
54
55 sub serve_cache {
56     my ($cache_location,$q) = @_;
57     if (not defined $cache_location or not length $cache_location) {
58         # serve the default image
59         $cache_location = $config{libravatar_default_image};
60     }
61     my $fh = IO::File->new($cache_location,'r') or
62         error($q,404, "Failed to open cached image $cache_location");
63     my $m = File::LibMagic->new() or
64         error($q,500,'Unable to create File::LibMagic object');
65     my $mime_string = $m->checktype_filename(abs_path($cache_location)) or
66         error($q,500,'Bad file; no mime known');
67     print $q->header(-type => $mime_string,
68                      -expires => '+1d',
69                     );
70     print <$fh>;
71     close($fh);
72 }
73
74
75 sub error {
76     my ($q,$error,$text) = @_;
77     $text //= '';
78     print $q->header(-status => $error);
79     print "<h2>$error: $text</h2>";
80     exit 0;
81 }