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