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