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