Bug 9988: Refactor the cron script
[koha.git] / misc / cronjobs / runreport.pl
1 #!/usr/bin/perl
2 #
3 # Copyright 2008 Liblime
4 # Copyright 2014 Foundations Bible College, Inc.
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use C4::Reports::Guided; # 0.12
24 use C4::Context;
25 use C4::Log;
26 use Koha::Email;
27 use Koha::DateUtils;
28
29 use Getopt::Long qw(:config auto_help auto_version);
30 use Pod::Usage;
31 use MIME::Lite;
32 use Text::CSV_XS;
33 use CGI qw ( -utf8 );
34 use Carp;
35 use Encode;
36 use JSON qw( to_json );
37
38 BEGIN {
39     # find Koha's Perl modules
40     # test carefully before changing this
41     use FindBin;
42     eval { require "$FindBin::Bin/../kohalib.pl" };
43 }
44
45 =head1 NAME
46
47 runreport.pl - Run pre-existing saved reports
48
49 =head1 SYNOPSIS
50
51 runreport.pl [ -h | -m ] [ -v ] reportID [ reportID ... ]
52
53  Options:
54    -h --help       brief help message
55    -m --man        full documentation, same as --help --verbose
56    -v --verbose    verbose output
57
58    --format=s      selects format. Choice of text, html, csv or tsv
59
60    -e --email      whether to use e-mail (implied by --to or --from)
61    -a --attachment additionally attach the report as a file. cannot be used with html format
62    --username      username to pass to the SMTP server for authentication
63    --password      password to pass to the SMTP server for authentication
64    --method        method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
65    --to=s          e-mail address to send report to
66    --from=s        e-mail address to send report from
67    --subject=s     subject for the e-mail
68    --store-results store the result of the report
69
70
71  Arguments:
72    reportID        report ID Number from saved_sql.id, multiple ID's may be specified
73
74 =head1 OPTIONS
75
76 =over
77
78 =item B<--help>
79
80 Print a brief help message and exits.
81
82 =item B<--man>
83
84 Prints the manual page and exits.
85
86 =item B<-v>
87
88 Verbose. Without this flag set, only fatal errors are reported.
89
90 =item B<--format>
91
92 Current options are text, html, csv, and tsv. At the moment, text and tsv both produce tab-separated tab-separated output.
93
94 =item B<--email>
95
96 Whether to use e-mail (implied by --to or --from).
97
98 =item B<--username>
99
100 Username to pass to the SMTP server for authentication
101
102 =item B<--password>
103
104 Password to pass to the SMTP server for authentication
105
106 =item B<--method>
107
108 Method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
109
110 =item B<--to>
111
112 E-mail address to send report to. Defaults to KohaAdminEmailAddress.
113
114 =item B<--from>
115
116 E-mail address to send report from. Defaults to KohaAdminEmailAddress.
117
118 =item B<--subject>
119
120 Subject for the e-mail message. Defaults to "Koha Saved Report"
121
122 =item B<--store-results>
123
124 Store the result of the report into the saved_reports DB table.
125
126 To access the results, go on Reports > Guided reports > Saved report.
127
128 =back
129
130 =head1 DESCRIPTION
131
132 This script is designed to run existing Saved Reports.
133
134 =head1 USAGE EXAMPLES
135
136 B<runreport.pl 16>
137
138 In the most basic form, runs the report specified by ID number from 
139 saved_sql.id, in this case #16, outputting the results to STDOUT.  
140
141 B<runreport.pl 16 17>
142
143 Same as above, but also runs report #17. 
144
145 =head1 TO DO
146
147 =over
148
149
150 =item *
151
152 Allow Saved Results option.
153
154
155 =back
156
157 =head1 SEE ALSO
158
159 Reports - Guided Reports
160
161 =cut
162
163 # These variables can be set by command line options,
164 # initially set to default values.
165
166 my $help    = 0;
167 my $man     = 0;
168 my $verbose = 0;
169 my $email   = 0;
170 my $attachment = 0;
171 my $format  = "text";
172 my $to      = "";
173 my $from    = "";
174 my $subject = "";
175 my $separator = ',';
176 my $quote = '"';
177 my $store_results = 0;
178
179 my $username = undef;
180 my $password = undef;
181 my $method = 'LOGIN';
182
183 GetOptions(
184     'help|?'            => \$help,
185     'man'               => \$man,
186     'verbose'           => \$verbose,
187     'format=s'          => \$format,
188     'to=s'              => \$to,
189     'from=s'            => \$from,
190     'subject=s'         => \$subject,
191     'email'             => \$email,
192     'a|attachment'      => \$attachment,
193     'username:s'        => \$username,
194     'password:s'        => \$password,
195     'method:s'          => \$method,
196     'store-results'     => \$store_results,
197
198 ) or pod2usage(2);
199 pod2usage( -verbose => 2 ) if ($man);
200 pod2usage( -verbose => 2 ) if ($help and $verbose);
201 pod2usage(1) if $help;
202
203 cronlogaction();
204
205 unless ($format) {
206     $verbose and print STDERR "No format specified, assuming 'text'\n";
207     $format = 'text';
208 }
209
210 if ($format eq 'tsv' || $format eq 'text') {
211     $format = 'csv';
212     $separator = "\t";
213 }
214
215 if ($to or $from or $email) {
216     $email = 1;
217     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
218     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
219 }
220
221 unless (scalar(@ARGV)) {
222     print STDERR "ERROR: No reportID(s) specified\n";
223     pod2usage(1);
224 }
225 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
226
227 my $today = dt_from_string();
228 my $date = $today->ymd();
229
230 foreach my $report_id (@ARGV) {
231     my $report = get_saved_report($report_id);
232     unless ($report) {
233         warn "ERROR: No saved report $report_id found";
234         next;
235     }
236     my $sql         = $report->{savedsql};
237     my $report_name = $report->{report_name};
238     my $type        = $report->{type};
239
240     $verbose and print "SQL: $sql\n\n";
241     if ( $subject eq "" )
242     {
243         if ( defined($report_name) and $report_name ne "")
244         {
245             $subject = $report_name ;
246         }
247         else
248         {
249             $subject = 'Koha Saved Report';
250         }
251     }
252     my ($sth) = execute_query( $sql, undef, undef, undef, $report_id );
253     my $count = scalar($sth->rows);
254     unless ($count) {
255         print "NO OUTPUT: 0 results from execute_query\n";
256         next;
257     }
258     $verbose and print "$count results from execute_query\n";
259
260     my $message;
261     my @rows_to_store;
262     if ($format eq 'html') {
263         my $cgi = CGI->new();
264         my @rows;
265         while (my $line = $sth->fetchrow_arrayref) {
266             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
267             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
268             push @rows_to_store, [@$line] if $store_results;
269         }
270         $message = $cgi->table(join "", @rows);
271     } elsif ($format eq 'csv') {
272         my $csv = Text::CSV_XS->new({
273             quote_char  => $quote,
274             sep_char    => $separator,
275             });
276         while (my $line = $sth->fetchrow_arrayref) {
277             $csv->combine(@$line);
278             $message .= $csv->string() . "\n";
279             push @rows_to_store, [@$line] if $store_results;
280         }
281     }
282     if ( $store_results ) {
283         my $json = to_json( \@rows_to_store );
284         C4::Reports::Guided::store_results( $report_id, $json );
285     }
286     if ($email) {
287         my $args = { to => $to, from => $from, subject => $subject };
288         if ( $format eq 'html' ) {
289             $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
290             $args->{contenttype} = 'text/html';
291         }
292         my $email = Koha::Email->new();
293         my %mail  = $email->create_message_headers($args);
294         $mail{Data} = $message;
295         $mail{Auth} = { user => $username, pass => $password, method => $method } if $username;
296
297         my $msg = MIME::Lite->new(%mail);
298
299         $msg->attach(
300             Type        => "text/$format",
301             Data        => encode( 'utf8', $message ),
302             Filename    => "report$report_id-$date.$format",
303             Disposition => 'attachment',
304         ) if $attachment;
305
306         $msg->send();
307         carp "Mail not sent" unless $msg->last_send_successful();
308     }
309     else {
310         print $message;
311     }
312 }