Bug 8258: Use patron's library's notice for DUEDGST and PREDUEDGST
[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 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
27 use Getopt::Long qw(:config auto_help auto_version);
28 use Pod::Usage;
29 use Mail::Sendmail;
30 use Text::CSV_XS;
31 use CGI;
32 use Carp;
33 use Encode;
34
35 use vars qw($VERSION);
36
37 BEGIN {
38     # find Koha's Perl modules
39     # test carefully before changing this
40     use FindBin;
41     eval { require "$FindBin::Bin/../kohalib.pl" };
42     $VERSION = 0.22;
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    --username      username to pass to the SMTP server for authentication
62    --password      password to pass to the SMTP server for authentication
63    --method        method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
64    --to=s          e-mail address to send report to
65    --from=s        e-mail address to send report from
66    --subject=s     subject for the e-mail
67
68
69  Arguments:
70    reportID        report ID Number from saved_sql.id, multiple ID's may be specified
71
72 =head1 OPTIONS
73
74 =over
75
76 =item B<--help>
77
78 Print a brief help message and exits.
79
80 =item B<--man>
81
82 Prints the manual page and exits.
83
84 =item B<-v>
85
86 Verbose. Without this flag set, only fatal errors are reported.
87
88 =item B<--format>
89
90 Current options are text, html, csv, and tsv. At the moment, text and tsv both produce tab-separated tab-separated output.
91
92 =item B<--email>
93
94 Whether to use e-mail (implied by --to or --from).
95
96 =item B<--username>
97
98 Username to pass to the SMTP server for authentication
99
100 =item B<--password>
101
102 Password to pass to the SMTP server for authentication
103
104 =item B<--method>
105
106 Method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
107
108 =item B<--to>
109
110 E-mail address to send report to. Defaults to KohaAdminEmailAddress.
111
112 =item B<--from>
113
114 E-mail address to send report from. Defaults to KohaAdminEmailAddress.
115
116 =item B<--subject>
117
118 Subject for the e-mail message. Defaults to "Koha Saved Report"
119
120 =back
121
122 =head1 DESCRIPTION
123
124 This script is designed to run existing Saved Reports.
125
126 =head1 USAGE EXAMPLES
127
128 B<runreport.pl 16>
129
130 In the most basic form, runs the report specified by ID number from 
131 saved_sql.id, in this case #16, outputting the results to STDOUT.  
132
133 B<runreport.pl 16 17>
134
135 Same as above, but also runs report #17. 
136
137 =head1 TO DO
138
139 =over
140
141
142 =item *
143
144 Allow Saved Results option.
145
146
147 =back
148
149 =head1 SEE ALSO
150
151 Reports - Guided Reports
152
153 =cut
154
155 # These variables can be set by command line options,
156 # initially set to default values.
157
158 my $help    = 0;
159 my $man     = 0;
160 my $verbose = 0;
161 my $email   = 0;
162 my $format  = "text";
163 my $to      = "";
164 my $from    = "";
165 my $subject = 'Koha Saved Report';
166 my $separator = ',';
167 my $quote = '"';
168
169 my $username = undef;
170 my $password = undef;
171 my $method = 'LOGIN';
172
173 GetOptions(
174     'help|?'            => \$help,
175     'man'               => \$man,
176     'verbose'           => \$verbose,
177     'format=s'          => \$format,
178     'to=s'              => \$to,
179     'from=s'            => \$from,
180     'subject=s'         => \$subject,
181     'email'             => \$email,
182     'username:s'        => \$username,
183     'password:s'        => \$password,
184     'method:s'          => \$method,
185
186 ) or pod2usage(2);
187 pod2usage( -verbose => 2 ) if ($man);
188 pod2usage( -verbose => 2 ) if ($help and $verbose);
189 pod2usage(1) if $help;
190
191 unless ($format) {
192     $verbose and print STDERR "No format specified, assuming 'text'\n";
193     $format = 'text';
194 }
195
196 if ($format eq 'tsv' || $format eq 'text') {
197     $format = 'csv';
198     $separator = "\t";
199 }
200
201 if ($to or $from or $email) {
202     $email = 1;
203     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
204     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
205 }
206
207 unless (scalar(@ARGV)) {
208     print STDERR "ERROR: No reportID(s) specified\n";
209     pod2usage(1);
210 }
211 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
212
213
214 foreach my $report_id (@ARGV) {
215     my $report = get_saved_report($report_id);
216     unless ($report) {
217         warn "ERROR: No saved report $report_id found";
218         next;
219     }
220     my $sql         = $report->{savedsql};
221     my $report_name = $report->{report_name};
222     my $type        = $report->{type};
223
224     $verbose and print "SQL: $sql\n\n";
225     if (defined($report_name) and $report_name ne "")
226     {
227         $subject = $report_name ;
228     }
229     else
230     {
231         $subject = 'Koha Saved Report';
232     }
233     # my $results = execute_query($sql, undef, 0, 99999, $format, $report_id);
234     my ($sth) = execute_query($sql);
235     # execute_query(sql, , 0, 20, , )
236     my $count = scalar($sth->rows);
237     unless ($count) {
238         print "NO OUTPUT: 0 results from execute_query\n";
239         next;
240     }
241     $verbose and print "$count results from execute_query\n";
242
243     my $message;
244     if ($format eq 'html') {
245         my $cgi = CGI->new();
246         my @rows = ();
247         while (my $line = $sth->fetchrow_arrayref) {
248             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
249             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
250         }
251         $message = $cgi->table(join "", @rows);
252     } elsif ($format eq 'csv') {
253         my $csv = Text::CSV_XS->new({
254             quote_char  => $quote,
255             sep_char    => $separator,
256             });
257         while (my $line = $sth->fetchrow_arrayref) {
258             $csv->combine(@$line);
259 #            foreach (@$line) {
260 #                defined($_) or $_ = '';
261 #                $_ =~ s/$quote/\\$quote/g;
262 #                $_ = "$quote$_$quote";
263 #            }    # catch undef values, replace w/ ''
264 #            $message .= join ($separator, @$line) . "\n";
265             $message .= $csv->string() . "\n";
266         }
267     }
268     if ($email){
269         my %mail;
270         if ($format eq 'html') {
271                 $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
272            %mail = (
273               To      => $to,
274               From    => $from,
275               'Content-Type' => 'text/html',
276               Subject => encode('utf8', $subject ),
277               Message => encode('utf8', $message )
278           );
279         } else {
280           %mail = (
281               To      => $to,
282               From    => $from,
283               Subject => encode('utf8', $subject ),
284               Message => encode('utf8', $message )
285           );
286         }
287         $mail{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
288         sendmail(%mail) or carp 'mail not sent:' . $Mail::Sendmail::error;
289     } else {
290         print $message;
291     }
292     # my @xmlarray = ... ;
293     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
294     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
295     # store_results($id,$xml);
296 }