Merge remote-tracking branch 'origin/new/bug_8597'
[koha.git] / misc / cronjobs / runreport.pl
index ebbaa6e..690f216 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/perl -w
+#!/usr/bin/perl
 #
 # Copyright 2008 Liblime
 #
@@ -13,9 +13,9 @@
 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along with
-# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU General Public License along
+# with Koha; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
 use strict;
 use warnings;
@@ -28,6 +28,7 @@ use Pod::Usage;
 use Mail::Sendmail;
 use Text::CSV_XS;
 use CGI;
+use Carp;
 
 use vars qw($VERSION);
 
@@ -36,25 +37,36 @@ BEGIN {
     # test carefully before changing this
     use FindBin;
     eval { require "$FindBin::Bin/../kohalib.pl" };
-    $VERSION = 0.21;
+    $VERSION = 0.22;
 }
 
 =head1 NAME
 
-runreport.pl - Run a pre-existing saved report.
+runreport.pl - Run pre-existing saved reports
 
 =head1 SYNOPSIS
 
-runreport.pl [ -v ] 
+runreport.pl [ -h | -m ] [ -v ] reportID [ reportID ... ]
 
  Options:
-   -h --help             brief help message
-   -m --man              full documentation, same as --help --verbose
-   -v --verbose          verbose output
+   -h --help       brief help message
+   -m --man        full documentation, same as --help --verbose
+   -v --verbose    verbose output
+
+   --format=s      selects format. Choice of text, html, csv, or tsv
+
+   -e --email      whether to use e-mail (implied by --to or --from)
+   --to=s          e-mail address to send report to
+   --from=s        e-mail address to send report from
+   --subject=s     subject for the e-mail
+
+
+ Arguments:
+   reportID        report ID Number from saved_sql.id, multiple ID's may be specified
 
 =head1 OPTIONS
 
-=over 8
+=over
 
 =item B<-help>
 
@@ -68,19 +80,55 @@ Prints the manual page and exits.
 
 Verbose. Without this flag set, only fatal errors are reported.
 
+=item B<-format>
+
+Current options are text, html, csv, and tsv. At the moment, text and tsv both produce tab-separated tab-separated output.
+
+=item B<-email>
+
+Whether to use e-mail (implied by --to or --from).
+
+=item B<-to>
+
+E-mail address to send report to. Defaults to KohaAdminEmailAddress.
+
+=item B<-from>
+
+E-mail address to send report from. Defaults to KohaAdminEmailAddress.
+
+=item B<-subject>
+
+Subject for the e-mail message. Defaults to "Koha Saved Report"
+
 =back
 
 =head1 DESCRIPTION
 
-This script is designed to run an existing Saved Report.
+This script is designed to run existing Saved Reports.
 
 =head1 USAGE EXAMPLES
 
-B<runreport.pl> 16
+B<runreport.pl 16>
 
 In the most basic form, runs the report specified by ID number from 
 saved_sql.id, in this case #16, outputting the results to STDOUT.  
 
+B<runreport.pl 16 17>
+
+Same as above, but also runs report #17. 
+
+=head1 TO DO
+
+=over
+
+
+=item *
+
+Allow Saved Results option.
+
+
+=back
+
 =head1 SEE ALSO
 
 Reports - Guided Reports
@@ -93,18 +141,23 @@ Reports - Guided Reports
 my $help    = 0;
 my $man     = 0;
 my $verbose = 0;
-my $format  = "";
-my $to      = C4::Context->preference('KohaAdminEmailAddress');
-my $from    = C4::Context->preference('KohaAdminEmailAddress');
+my $email   = 0;
+my $format  = "text";
+my $to      = "";
+my $from    = "";
 my $subject = 'Koha Saved Report';
+my $separator = ',';
+my $quote = '"';
 
 GetOptions(
     'help|?'     => \$help,
     'man'        => \$man,
     'verbose'    => \$verbose,
-    'format'     => \$format,
-    'to'         => \$to,
-    'from'       => \$from,
+    'format=s'   => \$format,
+    'to=s'       => \$to,
+    'from=s'     => \$from,
+    'subject=s'  => \$subject,
+    'email'      => \$email,
 ) or pod2usage(2);
 pod2usage( -verbose => 2 ) if ($man);
 pod2usage( -verbose => 2 ) if ($help and $verbose);
@@ -112,26 +165,47 @@ pod2usage(1) if $help;
 
 unless ($format) {
     $verbose and print STDERR "No format specified, assuming 'text'\n";
-    $format = '';
-    # $format = 'text';
+    $format = 'text';
+}
+
+if ($format eq 'tsv' || $format eq 'text') {
+    $format = 'csv';
+    $separator = "\t";
+}
+
+if ($to or $from or $email) {
+    $email = 1;
+    $from or $from = C4::Context->preference('KohaAdminEmailAddress');
+    $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
 }
 
 unless (scalar(@ARGV)) {
-    print STDERR "ERROR: No reports specified\n";
+    print STDERR "ERROR: No reportID(s) specified\n";
     pod2usage(1);
 }
-print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
+($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
 
-my $email;
 
-foreach my $report (@ARGV) {
-    my ($sql, $type) = get_saved_report($report);
-    unless ($sql) {
-        warn "ERROR: No saved report $report found";
+foreach my $report_id (@ARGV) {
+    my $report = get_saved_report($report_id);
+    unless ($report) {
+        warn "ERROR: No saved report $report_id found";
         next;
     }
+    my $sql         => $report->{savedsql};
+    my $report_name => $report->{report_name};
+    my $type        => $report->{type};
+
     $verbose and print "SQL: $sql\n\n";
-    # my $results = execute_query($sql, undef, 0, 99999, $format, $report); 
+    if (defined($report_name) and $report_name ne "")
+    {
+        $subject = $report_name ;
+    }
+    else
+    {
+        $subject = 'Koha Saved Report';
+    }
+    # my $results = execute_query($sql, undef, 0, 99999, $format, $report_id);
     my ($sth) = execute_query($sql);
     # execute_query(sql, , 0, 20, , )
     my $count = scalar($sth->rows);
@@ -141,13 +215,31 @@ foreach my $report (@ARGV) {
     }
     $verbose and print "$count results from execute_query\n";
 
-    my $cgi = CGI->new();
-    my @rows = ();
-    while (my $line = $sth->fetchrow_arrayref) {
-        foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
-        push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
+    my $message;
+    if ($format eq 'html') {
+        my $cgi = CGI->new();
+        my @rows = ();
+        while (my $line = $sth->fetchrow_arrayref) {
+            foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
+            push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
+        }
+        $message = $cgi->table(join "", @rows);
+    } elsif ($format eq 'csv') {
+        my $csv = Text::CSV_XS->new({
+            quote_char  => $quote,
+            sep_char    => $separator,
+            });
+        while (my $line = $sth->fetchrow_arrayref) {
+            $csv->combine(@$line);
+#            foreach (@$line) {
+#                defined($_) or $_ = '';
+#                $_ =~ s/$quote/\\$quote/g;
+#                $_ = "$quote$_$quote";
+#            }    # catch undef values, replace w/ ''
+#            $message .= join ($separator, @$line) . "\n";
+            $message .= $csv->string() . "\n";
+        }
     }
-    my $message = $cgi->table(join "", @rows);
 
     if ($email){
         my %mail = (
@@ -156,7 +248,7 @@ foreach my $report (@ARGV) {
             Subject => $subject,
             Message => $message 
         );
-        sendmail(%mail) or warn "mail not sent";
+        sendmail(%mail) or carp 'mail not sent:' . $Mail::Sendmail::error;
     } else {
         print $message;
     }