Bug 9416: (follow-up) fix neworderempty and templates
[koha.git] / opac / svc / report
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) 2011  Chris Cormack <chris@bigballofwax.co.nz>
6 # Copyright (C) 2013  Mark Tompsett
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 Modern::Perl;
22
23 use C4::Reports::Guided;
24 use JSON;
25 use CGI;
26
27 use Koha::Cache;
28
29 my $query  = CGI->new();
30 my $report_id = $query->param('id');
31 my $report_name = $query->param('name');
32 my $report_annotation = $query->param('annotated');
33
34 my $report_rec = get_saved_report( $report_name ? { 'name' => $report_name } : { 'id' => $report_id } );
35 if (!$report_rec) { die "There is no such report.\n"; }
36
37 die "Sorry this report is not public\n" unless $report_rec->{public};
38
39 my $cache_active = Koha::Cache->is_cache_active;
40 my ($cache_key, $cache, $json_text);
41 if ($cache_active) {
42     $cache_key = "opac:report:".($report_name ? "name:$report_name" : "id:$report_id");
43     $cache = Koha::Cache->new();
44     $json_text = $cache->get_from_cache($cache_key);
45 }
46
47 unless ($json_text) {
48     my $offset = 0;
49     my $limit  = C4::Context->preference("SvcMaxReportRows") || 10;
50     my ( $sth, $errors ) = execute_query( $report_rec->{savedsql}, $offset, $limit );
51     if ($sth) {
52         my $lines;
53         if ($report_annotation) {
54             $lines = $sth->fetchall_arrayref({});
55         }
56         else {
57             $lines = $sth->fetchall_arrayref;
58         }
59         $json_text = to_json($lines);
60
61         if ($cache_active) {
62             $cache->set_in_cache( $cache_key, $json_text, $report_rec->{cache_expiry} );
63         }
64     }
65     else {
66         $json_text = to_json($errors);
67     }
68 }
69
70 print $query->header(
71     -charset    => 'UTF-8',
72     -type       => 'application/json'
73 );
74 print $json_text;