cb101259388ccaf40adcafa279cb9659872d7368
[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    --csv-header    add column names as first line of csv output
70
71
72  Arguments:
73    reportID        report ID Number from saved_sql.id, multiple ID's may be specified
74
75 =head1 OPTIONS
76
77 =over
78
79 =item B<--help>
80
81 Print a brief help message and exits.
82
83 =item B<--man>
84
85 Prints the manual page and exits.
86
87 =item B<-v>
88
89 Verbose. Without this flag set, only fatal errors are reported.
90
91 =item B<--format>
92
93 Current options are text, html, csv, and tsv. At the moment, text and tsv both produce tab-separated tab-separated output.
94
95 =item B<--email>
96
97 Whether to use e-mail (implied by --to or --from).
98
99 =item B<--username>
100
101 Username to pass to the SMTP server for authentication
102
103 =item B<--password>
104
105 Password to pass to the SMTP server for authentication
106
107 =item B<--method>
108
109 Method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
110
111 =item B<--to>
112
113 E-mail address to send report to. Defaults to KohaAdminEmailAddress.
114
115 =item B<--from>
116
117 E-mail address to send report from. Defaults to KohaAdminEmailAddress.
118
119 =item B<--subject>
120
121 Subject for the e-mail message. Defaults to "Koha Saved Report"
122
123 =item B<--store-results>
124
125 Store the result of the report into the saved_reports DB table.
126
127 To access the results, go on Reports > Guided reports > Saved report.
128
129 =back
130
131 =head1 DESCRIPTION
132
133 This script is designed to run existing Saved Reports.
134
135 =head1 USAGE EXAMPLES
136
137 B<runreport.pl 16>
138
139 In the most basic form, runs the report specified by ID number from 
140 saved_sql.id, in this case #16, outputting the results to STDOUT.  
141
142 B<runreport.pl 16 17>
143
144 Same as above, but also runs report #17. 
145
146 =head1 TO DO
147
148 =over
149
150
151 =item *
152
153 Allow Saved Results option.
154
155
156 =back
157
158 =head1 SEE ALSO
159
160 Reports - Guided Reports
161
162 =cut
163
164 # These variables can be set by command line options,
165 # initially set to default values.
166
167 my $help    = 0;
168 my $man     = 0;
169 my $verbose = 0;
170 my $email   = 0;
171 my $attachment = 0;
172 my $format  = "text";
173 my $to      = "";
174 my $from    = "";
175 my $subject = "";
176 my $separator = ',';
177 my $quote = '"';
178 my $store_results = 0;
179 my $csv_header = 0;
180
181 my $username = undef;
182 my $password = undef;
183 my $method = 'LOGIN';
184
185 GetOptions(
186     'help|?'            => \$help,
187     'man'               => \$man,
188     'verbose'           => \$verbose,
189     'format=s'          => \$format,
190     'to=s'              => \$to,
191     'from=s'            => \$from,
192     'subject=s'         => \$subject,
193     'email'             => \$email,
194     'a|attachment'      => \$attachment,
195     'username:s'        => \$username,
196     'password:s'        => \$password,
197     'method:s'          => \$method,
198     'store-results'     => \$store_results,
199     'csv-header'        => \$csv_header,
200
201 ) or pod2usage(2);
202 pod2usage( -verbose => 2 ) if ($man);
203 pod2usage( -verbose => 2 ) if ($help and $verbose);
204 pod2usage(1) if $help;
205
206 cronlogaction();
207
208 unless ($format) {
209     $verbose and print STDERR "No format specified, assuming 'text'\n";
210     $format = 'text';
211 }
212
213 if ($format eq 'tsv' || $format eq 'text') {
214     $format = 'csv';
215     $separator = "\t";
216 }
217
218 if ($to or $from or $email) {
219     $email = 1;
220     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
221     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
222 }
223
224 unless (scalar(@ARGV)) {
225     print STDERR "ERROR: No reportID(s) specified\n";
226     pod2usage(1);
227 }
228 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
229
230 my $today = dt_from_string();
231 my $date = $today->ymd();
232
233 foreach my $report_id (@ARGV) {
234     my $report = get_saved_report($report_id);
235     unless ($report) {
236         warn "ERROR: No saved report $report_id found";
237         next;
238     }
239     my $sql         = $report->{savedsql};
240     my $report_name = $report->{report_name};
241     my $type        = $report->{type};
242
243     $verbose and print "SQL: $sql\n\n";
244     if ( $subject eq "" )
245     {
246         if ( defined($report_name) and $report_name ne "")
247         {
248             $subject = $report_name ;
249         }
250         else
251         {
252             $subject = 'Koha Saved Report';
253         }
254     }
255     my ($sth) = execute_query( $sql, undef, undef, undef, $report_id );
256     my $count = scalar($sth->rows);
257     unless ($count) {
258         print "NO OUTPUT: 0 results from execute_query\n";
259         next;
260     }
261     $verbose and print "$count results from execute_query\n";
262
263     my $message;
264     my @rows_to_store;
265     if ($format eq 'html') {
266         my $cgi = CGI->new();
267         my @rows;
268         while (my $line = $sth->fetchrow_arrayref) {
269             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
270             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
271             push @rows_to_store, [@$line] if $store_results;
272         }
273         $message = $cgi->table(join "", @rows);
274     } elsif ($format eq 'csv') {
275         my $csv = Text::CSV_XS->new({
276             quote_char  => $quote,
277             sep_char    => $separator,
278             });
279
280         if ( $csv_header ) {
281             my $fields = $sth->{NAME};
282             $csv->combine( @$fields );
283             $message .= $csv->string() . "\n";
284             push @rows_to_store, [@$fields] if $store_results;
285         }
286
287         while (my $line = $sth->fetchrow_arrayref) {
288             $csv->combine(@$line);
289             $message .= $csv->string() . "\n";
290             push @rows_to_store, [@$line] if $store_results;
291         }
292     }
293     if ( $store_results ) {
294         my $json = to_json( \@rows_to_store );
295         C4::Reports::Guided::store_results( $report_id, $json );
296     }
297     if ($email) {
298         my $args = { to => $to, from => $from, subject => $subject };
299         if ( $format eq 'html' ) {
300             $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
301             $args->{contenttype} = 'text/html';
302         }
303         my $email = Koha::Email->new();
304         my %mail  = $email->create_message_headers($args);
305         $mail{Data} = $message;
306         $mail{Auth} = { user => $username, pass => $password, method => $method } if $username;
307
308         my $msg = MIME::Lite->new(%mail);
309
310         $msg->attach(
311             Type        => "text/$format",
312             Data        => encode( 'utf8', $message ),
313             Filename    => "report$report_id-$date.$format",
314             Disposition => 'attachment',
315         ) if $attachment;
316
317         $msg->send();
318         carp "Mail not sent" unless $msg->last_send_successful();
319     }
320     else {
321         print $message;
322     }
323 }