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