Split off koha-common.
[koha.git] / C4 / Service.pm
1 package C4::Service;
2 #
3 # Copyright 2008 LibLime
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 =head1 NAME
21
22 C4::Service - functions for JSON webservices.
23
24 =head1 SYNOPSIS
25
26 my ( $query, $response) = C4::Service->init( { circulate => 1 } );
27 my ( $borrowernumber) = C4::Service->require_params( 'borrowernumber' );
28
29 C4::Service->return_error( 'internal', 'Frobnication failed', frobnicator => 'foo' );
30
31 $response->param( frobnicated => 'You' );
32
33 C4::Service->return_success( $response );
34
35 =head1 DESCRIPTION
36
37 This module packages several useful functions for JSON webservices.
38
39 =cut
40
41 use strict;
42 use warnings;
43
44 use CGI;
45 use C4::Auth qw( check_api_auth );
46 use C4::Output qw( :ajax );
47 use C4::Output::JSONStream;
48 use JSON;
49
50 our $debug;
51
52 BEGIN {
53     $debug = $ENV{DEBUG} || 0;
54 }
55
56 our ( $query, $cookie );
57
58 =head1 METHODS
59
60 =head2 init
61
62 =over 4
63
64     our ( $query, $response ) = C4::Service->init( %needed_flags );
65
66 =back
67
68 Initialize the service and check for the permissions in C<%needed_flags>.
69
70 Also, check that the user is authorized and has a current session, and return an
71 'auth' error if not.
72
73 init() returns a C<CGI> object and a C<C4::Output::JSONStream>. The latter can
74 be used for both flat scripts and those that use dispatch(), and should be
75 passed to C<return_success()>.
76
77 =cut
78
79 sub init {
80     my ( $class, %needed_flags ) = @_;
81
82     our $query = new CGI;
83
84     my ( $status, $cookie_, $sessionID ) = check_api_auth( $query, \%needed_flags );
85
86     our $cookie = $cookie_; # I have no desire to offend the Perl scoping gods
87
88     $class->return_error( 'auth', $status ) if ( $status ne 'ok' );
89
90     return ( $query, new C4::Output::JSONStream );
91 }
92
93 =head2 return_error
94
95 =over 4
96
97     C4::Service->return_error( $type, $error, %flags );
98
99 =back
100
101 Exit the script with HTTP status 400, and return a JSON error object.
102
103 C<$type> should be a short, lower case code for the generic type of error (such
104 as 'auth' or 'input').
105
106 C<$error> should be a more specific code giving information on the error. If
107 multiple errors of the same type occurred, they should be joined by '|'; i.e.,
108 'expired|different_ip'. Information in C<$error> does not need to be
109 human-readable, as its formatting should be handled by the client.
110
111 Any additional information to be given in the response should be passed as
112 param => value pairs.
113
114 =cut
115
116 sub return_error {
117     my ( $class, $type, $error, %flags ) = @_;
118
119     my $response = new C4::Output::JSONStream;
120
121     $response->param( message => $error ) if ( $error );
122     $response->param( type => $type, %flags );
123
124     output_with_http_headers $query, $cookie, $response->output, 'json', '400 Bad Request';
125     exit;
126 }
127
128 =head2 return_multi
129
130 =over 4
131
132 C4::Service->return_multi( \@responses, %flags );
133
134 =back
135
136 return_multi is similar to return_success or return_error, but allows you to
137 return different statuses for several requests sent at once (using HTTP status
138 "207 Multi-Status", much like WebDAV). The toplevel hashref (turned into the
139 JSON response) looks something like this:
140
141 =over 4
142
143 { multi => JSON::true, responses => \@responses, %flags }
144
145 =back
146
147 Each element of @responses should be either a plain hashref or an arrayref. If
148 it is a hashref, it is sent to the browser as-is. If it is an arrayref, it is
149 assumed to be in the same form as the arguments to return_error, and is turned
150 into an error structure.
151
152 All key-value pairs %flags are, as stated above, put into the returned JSON
153 structure verbatim.
154
155 =cut
156
157 sub return_multi {
158     my ( $class, $responses, @flags ) = @_;
159
160     my $response = new C4::Output::JSONStream;
161
162     if ( !@$responses ) {
163         $class->return_success( $response );
164     } else {
165         my @responses_formatted;
166
167         foreach my $response ( @$responses ) {
168             if ( ref( $response ) eq 'ARRAY' ) {
169                 my ($type, $error, @error_flags) = @$response;
170
171                 push @responses_formatted, { is_error => JSON::true, type => $type, message => $error, @error_flags };
172             } else {
173                 push @responses_formatted, $response;
174             }
175         }
176
177         $response->param( 'multi' => JSON::true, responses => \@responses_formatted, @flags );
178         output_with_http_headers $query, $cookie, $response->output, 'json', '207 Multi-Status';
179     }
180
181     exit;
182 }
183
184 =head2 return_success
185
186 =over 4
187
188     C4::Service->return_success( $response );
189
190 =back
191
192 Print out the information in the C<C4::Output::JSONStream> C<$response>, then
193 exit with HTTP status 200.
194
195 =cut
196
197 sub return_success {
198     my ( $class, $response ) = @_;
199
200     output_with_http_headers $query, $cookie, $response->output, 'json';
201 }
202
203 =head2 require_params
204
205 =over 4
206
207     my @values = C4::Service->require_params( @params );
208
209 =back
210
211 Check that each of of the parameters specified in @params was sent in the
212 request, then return their values in that order.
213
214 If a required parameter is not found, send a 'param' error to the browser.
215
216 =cut
217
218 sub require_params {
219     my ( $class, @params ) = @_;
220
221     my @values;
222
223     for my $param ( @params ) {
224         $class->return_error( 'params', "Missing '$param'" ) if ( !defined( $query->param( $param ) ) );
225         push @values, $query->param( $param );
226     }
227
228     return @values;
229 }
230
231 =head2 dispatch
232
233 =over 4
234
235 C4::Service->dispatch(
236     [ $path_regex, \@required_params, \&handler ],
237     ...
238 );
239
240 =back
241
242 dispatch takes several array-refs, each one describing a 'route', to use the
243 Rails terminology.
244
245 $path_regex should be a string in regex-form, describing which methods and
246 paths this route handles. Each route is tested in order, from the top down, so
247 put more specific handlers first. Also, the regex is tested on the request
248 method, plus the path. For instance, you might use the route [ 'POST /', ... ]
249 to handle POST requests to your service.
250
251 Each named parameter in @required_params is tested for to make sure the route
252 matches, but does not raise an error if one is missing; it simply tests the next
253 route. If you would prefer to raise an error, instead use
254 C<C4::Service->require_params> inside your handler.
255
256 \&handler is called with each matched group in $path_regex in its arguments. For
257 example, if your service is accessed at the path /blah/123, and you call
258 C<dispatch> with the route [ 'GET /blah/(\\d+)', ... ], your handler will be called
259 with the argument '123'.
260
261 =cut
262
263 sub dispatch {
264     my $class = shift;
265
266     my $path_info = $query->path_info || '/';
267
268     ROUTE: foreach my $route ( @_ ) {
269         my ( $path, $params, $handler ) = @$route;
270
271         next unless ( my @match = ( ($query->request_method . ' ' . $path_info)   =~ m,^$path$, ) );
272
273         for my $param ( @$params ) {
274             next ROUTE if ( !defined( $query->param ( $param ) ) );
275         }
276
277         $debug and warn "Using $path";
278         $handler->( @match );
279         return;
280     }
281
282     $class->return_error( 'no_handler', '' );
283 }
284
285 1;
286
287 __END__
288
289 =head1 AUTHORS
290
291 Koha Development Team
292
293 Jesse Weaver <jesse.weaver@liblime.com>