Change subject for freeside-fetch emailed reports from "subject" to "Freeside report...
[freeside.git] / FS / bin / freeside-fetch
1 #!/usr/bin/perl -Tw
2
3 use strict;
4 use LWP::UserAgent;
5 use FS::UID qw(adminsuidsetup);
6 use FS::Record qw(qsearchs);
7 use FS::Misc qw(send_email);
8
9 my $user = shift or die &usage;
10 my $employeelist = shift or die &usage;
11 my $url = shift or die &usage;
12 adminsuidsetup $user;
13
14 my @employees = split ',', $employeelist;
15
16 foreach my $employee (@employees) {
17
18   $employee =~ /^(\w+)$/;
19
20   my $access_user = qsearchs( 'access_user', { 'username' => $1 } );
21   unless ($access_user) {
22     warn "Can't find employee $employee... skipping";
23     next;
24   }
25
26   my $email_address = $access_user->option('email_address');
27   unless ($email_address) {
28     warn "No email address for $employee... skipping";
29     next;
30   }
31
32   no warnings 'redefine';
33   local *LWP::UserAgent::get_basic_credentials = sub {
34     return ($access_user->username, $access_user->_password);
35   };
36
37   my $ua = new LWP::UserAgent;
38   $ua->agent("FreesideFetcher/0.1 " . $ua->agent);
39
40   my $req = new HTTP::Request GET => $url;
41   my $res = $ua->request($req);
42
43   my $conf = new FS::Conf;
44   my $subject = $conf->config('email_report-subject') || 'Freeside report';
45
46   my %options = ( 'from'             => $email_address,
47                   'to'               => $email_address,
48                   'subject'          => $subject,
49                   'body'             => $res->content,
50                 );
51
52   $options{'content-type'} = $res->content_type
53     if $res->content_type;
54   $options{'content-encoding'} = $res->content_encoding
55     if $res->content_encoding;
56
57   if ($res->is_success) {
58     send_email %options;
59   }else{
60     warn "fetching $url failed for $employee: " . $res->status_line;
61   }
62 }
63
64 sub usage {
65   die "Usage:\n\n  freeside-fetch user employee[,employee ...] url\n\n";
66 }
67
68 =head1 NAME
69
70 freeside-fetch - Send a freeside page to a list of employees.
71
72 =head1 SYNOPSIS
73
74   freeside-fetch user employee[,employee ...] url
75
76 =head1 DESCRIPTION
77
78   Fetches a web page specified by url as if employee and emails it to
79   employee.  Useful when run out of cron to send freeside web pages.
80
81   user: From the mapsecrets file - a user with access to the freeside database
82
83   employee: the username of an employee to receive the emailed page.  May be a comma separated list
84
85   url: the web page to be received
86
87 =head1 BUGS
88
89   Can leak employee usernames and passwords if requested to access inappropriate urls.
90
91 =cut
92