Bug 11491: add option to supply field names in reports web service output
[koha.git] / opac / svc / report
1 #!/usr/bin/perl
2
3 # Copyright 2011 Chris Cormack <chris@bigballofwax.co.nz>
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
21 use strict;
22 use warnings;
23
24 use C4::Reports::Guided;
25 use JSON;
26 use CGI;
27
28 use Koha::Cache;
29
30 my $query  = CGI->new();
31 my $report_id = $query->param('id');
32 my $report_name = $query->param('name');
33 my $report_annotation = $query->param('annotated');
34
35 my $report_rec = get_saved_report( $report_name ? { 'name' => $report_name } : { 'id' => $report_id } );
36 if (!$report_rec) { die "There is no such report.\n"; }
37
38 die "Sorry this report is not public\n" unless $report_rec->{public};
39
40 my $cache_active = Koha::Cache->is_cache_active;
41 my ($cache_key, $cache, $json_text);
42 if ($cache_active) {
43     $cache_key = "opac:report:".($report_name ? "name:$report_name" : "id:$report_id");
44     $cache = Koha::Cache->new();
45     $json_text = $cache->get_from_cache($cache_key);
46 }
47
48 unless ($json_text) {
49     my $offset = 0;
50     my $limit  = C4::Context->preference("SvcMaxReportRows") || 10;
51     my ( $sth, $errors ) = execute_query( $report_rec->{savedsql}, $offset, $limit );
52     if ($sth) {
53         my $lines;
54         if ($report_annotation) {
55             $lines = $sth->fetchall_arrayref({});
56         }
57         else {
58             $lines = $sth->fetchall_arrayref;
59         }
60         $json_text = to_json($lines);
61
62         if ($cache_active) {
63             $cache->set_in_cache( $cache_key, $json_text, $report_rec->{cache_expiry} );
64         }
65     }
66     else {
67         $json_text = to_json($errors);
68     }
69 }
70
71 print $query->header;
72 print $json_text;