Bug 17200 - Badly formatted "hold for" patron name on catalog detail page
[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
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 C4::Log;
27 use Koha::Email;
28 use Koha::DateUtils;
29
30 use Getopt::Long qw(:config auto_help auto_version);
31 use Pod::Usage;
32 use MIME::Lite;
33 use Text::CSV_XS;
34 use CGI qw ( -utf8 );
35 use Carp;
36 use Encode;
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 }
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    -a --attachment additionally attach the report as a file. cannot be used with html format
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 $attachment = 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     'a|attachment'      => \$attachment,
185     'username:s'        => \$username,
186     'password:s'        => \$password,
187     'method:s'          => \$method,
188
189 ) or pod2usage(2);
190 pod2usage( -verbose => 2 ) if ($man);
191 pod2usage( -verbose => 2 ) if ($help and $verbose);
192 pod2usage(1) if $help;
193
194 cronlogaction();
195
196 unless ($format) {
197     $verbose and print STDERR "No format specified, assuming 'text'\n";
198     $format = 'text';
199 }
200
201 if ($format eq 'tsv' || $format eq 'text') {
202     $format = 'csv';
203     $separator = "\t";
204 }
205
206 if ($to or $from or $email) {
207     $email = 1;
208     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
209     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
210 }
211
212 unless (scalar(@ARGV)) {
213     print STDERR "ERROR: No reportID(s) specified\n";
214     pod2usage(1);
215 }
216 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
217
218 my $today = dt_from_string();
219 my $date = $today->ymd();
220
221 foreach my $report_id (@ARGV) {
222     my $report = get_saved_report($report_id);
223     unless ($report) {
224         warn "ERROR: No saved report $report_id found";
225         next;
226     }
227     my $sql         = $report->{savedsql};
228     my $report_name = $report->{report_name};
229     my $type        = $report->{type};
230
231     $verbose and print "SQL: $sql\n\n";
232     if ( $subject eq "" )
233     {
234         if ( defined($report_name) and $report_name ne "")
235         {
236             $subject = $report_name ;
237         }
238         else
239         {
240             $subject = 'Koha Saved Report';
241         }
242     }
243     # my $results = execute_query($sql, undef, 0, 99999, $format, $report_id);
244     my ($sth) = execute_query($sql);
245     # execute_query(sql, , 0, 20, , )
246     my $count = scalar($sth->rows);
247     unless ($count) {
248         print "NO OUTPUT: 0 results from execute_query\n";
249         next;
250     }
251     $verbose and print "$count results from execute_query\n";
252
253     my $message;
254     if ($format eq 'html') {
255         my $cgi = CGI->new();
256         my @rows = ();
257         while (my $line = $sth->fetchrow_arrayref) {
258             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
259             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
260         }
261         $message = $cgi->table(join "", @rows);
262     } elsif ($format eq 'csv') {
263         my $csv = Text::CSV_XS->new({
264             quote_char  => $quote,
265             sep_char    => $separator,
266             });
267         while (my $line = $sth->fetchrow_arrayref) {
268             $csv->combine(@$line);
269 #            foreach (@$line) {
270 #                defined($_) or $_ = '';
271 #                $_ =~ s/$quote/\\$quote/g;
272 #                $_ = "$quote$_$quote";
273 #            }    # catch undef values, replace w/ ''
274 #            $message .= join ($separator, @$line) . "\n";
275             $message .= $csv->string() . "\n";
276         }
277     }
278
279     if ($email) {
280         my $args = { to => $to, from => $from, subject => $subject };
281         if ( $format eq 'html' ) {
282             $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
283             $args->{contenttype} = 'text/html';
284         }
285         my $email = Koha::Email->new();
286         my %mail  = $email->create_message_headers($args);
287         $mail{Data} = $message;
288         $mail{Auth} = { user => $username, pass => $password, method => $method } if $username;
289
290         my $msg = MIME::Lite->new(%mail);
291
292         $msg->attach(
293             Type        => "text/$format",
294             Data        => encode( 'utf8', $message ),
295             Filename    => "report$report_id-$date.$format",
296             Disposition => 'attachment',
297         ) if $attachment;
298
299         $msg->send();
300         carp "Mail not sent" unless $msg->last_send_successful();
301     }
302     else {
303         print $message;
304     }
305 }