Bug 32482: (follow-up) Add markup comments
[koha.git] / opac / ilsdi.pl
1 #!/usr/bin/perl
2
3 # Copyright 2009 SARL Biblibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use C4::ILSDI::Services;
23 use C4::Auth qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers );
25 use C4::Context;
26
27 use List::MoreUtils qw( any );
28 use XML::Simple qw( XMLout );
29 use CGI qw ( -utf8 );
30 use Net::Netmask;
31
32 =head1 DLF ILS-DI for Koha
33
34 This script is a basic implementation of ILS-DI protocol for Koha.
35 It acts like a dispatcher, that get the CGI request, check required and 
36 optionals arguments, call a function from C4::ILS-DI, and finally
37 outputs the returned hashref as XML.
38
39 =cut
40
41 # Instanciate the CGI request
42 my $cgi = CGI->new;
43
44 # List of available services, sorted by level
45 my @services = (
46     'Describe',    # Not part of ILS-DI, online API doc
47
48     #   Level 1: Basic Discovery Interfaces
49     #   'HarvestBibliographicRecords',       # OAI-PMH
50     #   'HarvestExpandedRecords',            # OAI-PMH
51     'GetAvailability',    # FIXME Add bibliographic level
52
53     #   'GoToBibliographicRequestPage'       # I don't understant this one
54     #   Level 2: Elementary OPAC supplement
55     #   'HarvestAuthorityRecords',           # OAI-PMH
56     #   'HarvestHoldingsRecords',            # OAI-PMH
57     'GetRecords',         # Note that we can use OAI-PMH for this too
58
59     #   'Search',                            # TODO
60     #   'Scan',                              # TODO
61     'GetAuthorityRecords',
62
63     #   'OutputRewritablePage',              # I don't understant this one
64     #   'OutputIntermediateFormat',          # I don't understant this one
65     #   Level 3: Elementary OPAC alternative
66     'LookupPatron',
67     'AuthenticatePatron',
68     'GetPatronInfo',
69     'GetPatronStatus',
70     'GetServices',    # FIXME Loans
71     'RenewLoan',
72     'HoldTitle',      # FIXME Add dates support
73     'HoldItem',       # FIXME Add dates support
74     'CancelHold',
75
76     #   'RecallItem',                        # Not supported by Koha
77     #   'CancelRecall',                      # Not supported by Koha
78     #   Level 4: Robust/domain specific discovery platforms
79     #   'SearchCourseReserves',              # TODO
80     #   'Explain'                            # TODO
81 );
82
83 # List of required arguments
84 my %required = (
85     'Describe'            => ['verb'],
86     'GetAvailability'     => [ 'id', 'id_type' ],
87     'GetRecords'          => ['id'],
88     'GetAuthorityRecords' => ['id'],
89     'LookupPatron'        => ['id'],
90     'AuthenticatePatron'  => [ 'username', 'password' ],
91     'GetPatronInfo'       => ['patron_id'],
92     'GetPatronStatus'     => ['patron_id'],
93     'GetServices'         => [ 'patron_id', 'item_id' ],
94     'RenewLoan'           => [ 'patron_id', 'item_id' ],
95     'HoldTitle'           => [ 'patron_id', 'bib_id', 'request_location' ],
96     'HoldItem'            => [ 'patron_id', 'bib_id', 'item_id' ],
97     'CancelHold' => [ 'patron_id', 'item_id' ],
98 );
99
100 # List of optional arguments
101 my %optional = (
102     'Describe'            => [],
103     'GetAvailability'     => [ 'return_type', 'return_fmt', 'language' ],
104     'GetRecords'          => ['schema'],
105     'GetAuthorityRecords' => ['schema'],
106     'LookupPatron'        => ['id_type'],
107     'AuthenticatePatron'  => [],
108     'GetPatronInfo'       => [ 'show_contact', 'show_fines', 'show_holds', 'show_loans', 'loans_per_page', 'loans_page', 'show_attributes' ],
109     'GetPatronStatus'     => [],
110     'GetServices'         => [],
111     'RenewLoan'           => ['desired_due_date'],
112     'HoldTitle'  => [ 'pickup_location', 'start_date', 'expiry_date' ],
113     'HoldItem'   => [ 'pickup_location', 'start_date', 'expiry_date' ],
114     'CancelHold' => [],
115 );
116
117 # If no service is requested, display the online documentation
118 unless ( $cgi->param('service') ) {
119     my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
120         {   template_name   => "ilsdi.tt",
121             query           => $cgi,
122             type            => "opac",
123             authnotrequired => 1,
124         }
125     );
126     output_html_with_http_headers $cgi, $cookie, $template->output;
127     exit 0;
128 }
129
130 # Set the userenv
131 C4::Context->_new_userenv( 'ILSDI_'.time() );
132 C4::Context->set_userenv(
133     undef, undef, undef, 'ILSDI', 'ILSDI',
134     undef, undef, undef, undef, undef,
135 );
136 C4::Context->interface('opac');
137
138 # If user requested a service description, then display it
139 if ( scalar $cgi->param('service') eq "Describe" and any { scalar $cgi->param('verb') eq $_ } @services ) {
140     my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
141         {   template_name   => "ilsdi.tt",
142             query           => $cgi,
143             type            => "opac",
144             authnotrequired => 1,
145         }
146     );
147     $template->param( scalar $cgi->param('verb') => 1 );
148     output_html_with_http_headers $cgi, $cookie, $template->output;
149     exit 0;
150 }
151
152 # any output after this point will be UTF-8 XML
153 binmode STDOUT, ':encoding(UTF-8)';
154 print CGI::header('-type'=>'text/xml', '-charset'=>'utf-8');
155
156 my $out;
157
158 # If ILS-DI module is disabled in System->Preferences, redirect to 404
159 unless ( C4::Context->preference('ILS-DI') ) {
160     $out->{'code'} = "NotAllowed";
161     $out->{'message'} = "ILS-DI is disabled.";
162 }
163
164 # If the remote address is not allowed, redirect to 403
165 my @AuthorizedIPs = split( /,/, C4::Context->preference('ILS-DI:AuthorizedIPs') );
166 if (@AuthorizedIPs) {    # If no filter set, allow access to everybody
167     my $authorized = 0;
168     foreach my $ip (@AuthorizedIPs) {
169         my $netmask = Net::Netmask->new2($ip);
170         if ( $netmask && $netmask->match( $ENV{REMOTE_ADDR} ) ) {
171             $authorized = 1;
172             last;
173         }
174     }
175     unless ($authorized) {
176         $out->{'code'} = "NotAllowed";
177         $out->{'message'} = "Unauthorized IP address: $ENV{REMOTE_ADDR}.";
178     }
179 }
180
181 my $service = $cgi->param('service') || "ilsdi";
182
183 # Check if the requested service is in the list
184 if ( $service and any { $service eq $_ } @services ) {
185
186     my @parmsrequired = @{ $required{$service} };
187     my @parmsoptional = @{ $optional{$service} };
188     my @parmsall      = ( @parmsrequired, @parmsoptional );
189     my @names         = $cgi->multi_param;
190     my %paramhash;
191     $paramhash{$_} = 1 for @names;
192
193     # check for missing parameters
194     for ( @parmsrequired ) {
195         unless ( exists $paramhash{$_} ) {
196             $out->{'code'} = "MissingParameter";
197             $out->{'message'} = "The required parameter ".$_." is missing.";
198         }
199     }
200
201     # check for illegal parameters
202     for my $name ( @names ) {
203         my $found = 0;
204         for my $name2 (@parmsall) {
205             if ( $name eq $name2 ) {
206                 $found = 1;
207             }
208         }
209         if ( $found == 0 && $name ne 'service' ) {
210             $out->{'code'} = "IllegalParameter";
211             $out->{'message'} = "The parameter ".$name." is illegal.";
212         }
213     }
214
215     # check for multiple parameters
216     for ( @names ) {
217         my @values = $cgi->multi_param($_);
218         if ( $#values != 0 ) {
219             $out->{'code'} = "MultipleValuesNotAllowed";
220             $out->{'message'} = "Multiple values not allowed for the parameter ".$_.".";
221         }
222     }
223
224     if ( !$out->{'message'} ) {
225
226         # GetAvailability is a special case, as it cannot use XML::Simple
227         if ( $service eq "GetAvailability" ) {
228             print C4::ILSDI::Services::GetAvailability($cgi);
229             exit 0;
230         } else {
231
232             # Variable functions
233             my $sub = do {
234 #                no strict 'refs';
235                 my $symbol = 'C4::ILSDI::Services::' . $service;
236                 \&{"$symbol"};
237             };
238
239             # Call the requested service, and get its return value
240             $out = &$sub($cgi);
241         }
242     }
243 } else {
244     $out->{'message'} = "NotSupported";
245 }
246
247 # Output XML by passing the hashref to XMLOut
248 print XMLout(
249     $out,
250     noattr        => 1,
251     nosort        => 1,
252     xmldecl       => '<?xml version="1.0" encoding="UTF-8" ?>',
253     RootName      => $service,
254     SuppressEmpty => 1
255 );
256 exit 0;
257