Bug 11491: add option to supply field names in reports web service output
[koha.git] / 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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19 #
20
21 use strict;
22 use warnings;
23
24 use C4::Auth;
25 use C4::Reports::Guided;
26 use JSON;
27 use CGI;
28
29 use Koha::Cache;
30
31
32 my $query  = CGI->new();
33 my $report_id = $query->param('id');
34 my $report_name = $query->param('name');
35 my $report_annotation = $query->param('annotated');
36
37 my $report_rec = get_saved_report( $report_name ? { 'name' => $report_name } : { 'id' => $report_id } );
38 if (!$report_rec) { die "There is no such report.\n"; }
39
40 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
41     {
42         template_name   => "intranet-main.tmpl",
43         query           => $query,
44         type            => "intranet",
45         authnotrequired => 0,
46         flagsrequired   => { catalogue => 1, },
47     }
48 );
49
50 my $cache_active = Koha::Cache->is_cache_active;
51 my ($cache_key, $cache, $json_text);
52 if ($cache_active) {
53     $cache_key = "intranet:report:".($report_name ? "name:$report_name" : "id:$report_id");
54     $cache = Koha::Cache->new();
55     $json_text = $cache->get_from_cache($cache_key);
56 }
57
58 unless ($json_text) {
59     my $offset = 0;
60     my $limit  = C4::Context->preference("SvcMaxReportRows") || 10;
61     my ( $sth, $errors ) = execute_query( $report_rec->{savedsql}, $offset, $limit );
62     if ($sth) {
63         my $lines;
64         if ($report_annotation) {
65             $lines = $sth->fetchall_arrayref({});
66         }
67         else {
68             $lines = $sth->fetchall_arrayref;
69         }
70         $json_text = to_json($lines);
71
72         if ($cache_active) {
73             $cache->set_in_cache( $cache_key, $json_text, $report_rec->{cache_expiry} );
74         }
75     }
76     else {
77         $json_text = to_json($errors);
78     }
79 }
80
81 print $query->header;
82 print $json_text;