6b25908ca566bf01cfa08c3bc47df7b8a635a1a4
[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
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 strict;
22 use warnings;
23
24 use C4::Reports::Guided; # 0.12
25 use C4::Context;
26 use Koha::Email;
27 use C4::Log;
28
29 use Getopt::Long qw(:config auto_help auto_version);
30 use Pod::Usage;
31 use Mail::Sendmail;
32 use Text::CSV_XS;
33 use CGI qw ( -utf8 );
34 use Carp;
35 use Encode;
36
37 use vars qw($VERSION);
38
39 BEGIN {
40     # find Koha's Perl modules
41     # test carefully before changing this
42     use FindBin;
43     eval { require "$FindBin::Bin/../kohalib.pl" };
44     $VERSION = 0.22;
45 }
46
47 =head1 NAME
48
49 runreport.pl - Run pre-existing saved reports
50
51 =head1 SYNOPSIS
52
53 runreport.pl [ -h | -m ] [ -v ] reportID [ reportID ... ]
54
55  Options:
56    -h --help       brief help message
57    -m --man        full documentation, same as --help --verbose
58    -v --verbose    verbose output
59
60    --format=s      selects format. Choice of text, html, csv, or tsv
61
62    -e --email      whether to use e-mail (implied by --to or --from)
63    --username      username to pass to the SMTP server for authentication
64    --password      password to pass to the SMTP server for authentication
65    --method        method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
66    --to=s          e-mail address to send report to
67    --from=s        e-mail address to send report from
68    --subject=s     subject for the e-mail
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 =back
123
124 =head1 DESCRIPTION
125
126 This script is designed to run existing Saved Reports.
127
128 =head1 USAGE EXAMPLES
129
130 B<runreport.pl 16>
131
132 In the most basic form, runs the report specified by ID number from 
133 saved_sql.id, in this case #16, outputting the results to STDOUT.  
134
135 B<runreport.pl 16 17>
136
137 Same as above, but also runs report #17. 
138
139 =head1 TO DO
140
141 =over
142
143
144 =item *
145
146 Allow Saved Results option.
147
148
149 =back
150
151 =head1 SEE ALSO
152
153 Reports - Guided Reports
154
155 =cut
156
157 # These variables can be set by command line options,
158 # initially set to default values.
159
160 my $help    = 0;
161 my $man     = 0;
162 my $verbose = 0;
163 my $email   = 0;
164 my $format  = "text";
165 my $to      = "";
166 my $from    = "";
167 my $subject = "";
168 my $separator = ',';
169 my $quote = '"';
170
171 my $username = undef;
172 my $password = undef;
173 my $method = 'LOGIN';
174
175 GetOptions(
176     'help|?'            => \$help,
177     'man'               => \$man,
178     'verbose'           => \$verbose,
179     'format=s'          => \$format,
180     'to=s'              => \$to,
181     'from=s'            => \$from,
182     'subject=s'         => \$subject,
183     'email'             => \$email,
184     'username:s'        => \$username,
185     'password:s'        => \$password,
186     'method:s'          => \$method,
187
188 ) or pod2usage(2);
189 pod2usage( -verbose => 2 ) if ($man);
190 pod2usage( -verbose => 2 ) if ($help and $verbose);
191 pod2usage(1) if $help;
192
193 cronlogaction();
194
195 unless ($format) {
196     $verbose and print STDERR "No format specified, assuming 'text'\n";
197     $format = 'text';
198 }
199
200 if ($format eq 'tsv' || $format eq 'text') {
201     $format = 'csv';
202     $separator = "\t";
203 }
204
205 if ($to or $from or $email) {
206     $email = 1;
207     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
208     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
209 }
210
211 unless (scalar(@ARGV)) {
212     print STDERR "ERROR: No reportID(s) specified\n";
213     pod2usage(1);
214 }
215 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
216
217
218 foreach my $report_id (@ARGV) {
219     my $report = get_saved_report($report_id);
220     unless ($report) {
221         warn "ERROR: No saved report $report_id found";
222         next;
223     }
224     my $sql         = $report->{savedsql};
225     my $report_name = $report->{report_name};
226     my $type        = $report->{type};
227
228     $verbose and print "SQL: $sql\n\n";
229     if ( $subject eq "" )
230     {
231         if ( defined($report_name) and $report_name ne "")
232         {
233             $subject = $report_name ;
234         }
235         else
236         {
237             $subject = 'Koha Saved Report';
238         }
239     }
240     # my $results = execute_query($sql, undef, 0, 99999, $format, $report_id);
241     my ($sth) = execute_query($sql);
242     # execute_query(sql, , 0, 20, , )
243     my $count = scalar($sth->rows);
244     unless ($count) {
245         print "NO OUTPUT: 0 results from execute_query\n";
246         next;
247     }
248     $verbose and print "$count results from execute_query\n";
249
250     my $message;
251     if ($format eq 'html') {
252         my $cgi = CGI->new();
253         my @rows = ();
254         while (my $line = $sth->fetchrow_arrayref) {
255             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
256             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
257         }
258         $message = $cgi->table(join "", @rows);
259     } elsif ($format eq 'csv') {
260         my $csv = Text::CSV_XS->new({
261             quote_char  => $quote,
262             sep_char    => $separator,
263             });
264         while (my $line = $sth->fetchrow_arrayref) {
265             $csv->combine(@$line);
266 #            foreach (@$line) {
267 #                defined($_) or $_ = '';
268 #                $_ =~ s/$quote/\\$quote/g;
269 #                $_ = "$quote$_$quote";
270 #            }    # catch undef values, replace w/ ''
271 #            $message .= join ($separator, @$line) . "\n";
272             $message .= $csv->string() . "\n";
273         }
274     }
275     if ($email){
276         my $email = Koha::Email->new();
277         my %mail;
278         if ($format eq 'html') {
279                 $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
280            %mail = $email->create_message_headers({
281               to      => $to,
282               from    => $from,
283               contenttype => 'text/html',
284               subject => encode('utf8', $subject ),
285               message => encode('utf8', $message )
286            }
287           );
288         } else {
289           %mail = $email->create_message_headers ({
290               to      => $to,
291               from    => $from,
292               subject => encode('utf8', $subject ),
293               message => encode('utf8', $message )
294           }
295           );
296         }
297         $mail{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
298         sendmail(%mail) or carp 'mail not sent:' . $Mail::Sendmail::error;
299     } else {
300         print $message;
301     }
302     # my @xmlarray = ... ;
303     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
304     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
305     # store_results($id,$xml);
306 }