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