Bug 5010: Fix OPACBaseURL to include protocol
[koha.git] / C4 / Auth.pm
1 package C4::Auth;
2
3 # Copyright 2000-2002 Katipo Communications
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 strict;
21 use warnings;
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json/;
24 use URI::Escape;
25 use CGI::Session;
26
27 require Exporter;
28 use C4::Context;
29 use C4::Templates;    # to get the template
30 use C4::Languages;
31 use C4::Branch;       # GetBranches
32 use C4::Search::History;
33 use Koha;
34 use Koha::AuthUtils qw(hash_password);
35 use POSIX qw/strftime/;
36 use List::MoreUtils qw/ any /;
37 use Encode qw( encode is_utf8);
38
39 # use utf8;
40 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
41
42 BEGIN {
43     sub psgi_env { any { /^psgi\./ } keys %ENV }
44
45     sub safe_exit {
46         if   (psgi_env) { die 'psgi:exit' }
47         else            { exit }
48     }
49     $VERSION = 3.07.00.049;    # set version for version checking
50
51     $debug     = $ENV{DEBUG};
52     @ISA       = qw(Exporter);
53     @EXPORT    = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
54     @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
55       &get_all_subpermissions &get_user_subpermissions
56     );
57     %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
58     $ldap      = C4::Context->config('useldapserver') || 0;
59     $cas       = C4::Context->preference('casAuthentication');
60     $shib      = C4::Context->config('useshibboleth') || 0;
61     $caslogout = C4::Context->preference('casLogout');
62     require C4::Auth_with_cas;    # no import
63
64     if ($ldap) {
65         require C4::Auth_with_ldap;
66         import C4::Auth_with_ldap qw(checkpw_ldap);
67     }
68     if ($shib) {
69         require C4::Auth_with_shibboleth;
70         import C4::Auth_with_shibboleth
71           qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
72
73         # Check for good config
74         if ( shib_ok() ) {
75
76             # Get shibboleth login attribute
77             $shib_login = get_login_shib();
78         }
79
80         # Bad config, disable shibboleth
81         else {
82             $shib = 0;
83         }
84     }
85     if ($cas) {
86         import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
87     }
88
89 }
90
91 =head1 NAME
92
93 C4::Auth - Authenticates Koha users
94
95 =head1 SYNOPSIS
96
97   use CGI qw ( -utf8 );
98   use C4::Auth;
99   use C4::Output;
100
101   my $query = new CGI;
102
103   my ($template, $borrowernumber, $cookie)
104     = get_template_and_user(
105         {
106             template_name   => "opac-main.tt",
107             query           => $query,
108       type            => "opac",
109       authnotrequired => 0,
110       flagsrequired   => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
111   }
112     );
113
114   output_html_with_http_headers $query, $cookie, $template->output;
115
116 =head1 DESCRIPTION
117
118 The main function of this module is to provide
119 authentification. However the get_template_and_user function has
120 been provided so that a users login information is passed along
121 automatically. This gets loaded into the template.
122
123 =head1 FUNCTIONS
124
125 =head2 get_template_and_user
126
127  my ($template, $borrowernumber, $cookie)
128      = get_template_and_user(
129        {
130          template_name   => "opac-main.tt",
131          query           => $query,
132          type            => "opac",
133          authnotrequired => 0,
134          flagsrequired   => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
135        }
136      );
137
138 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
139 to C<&checkauth> (in this module) to perform authentification.
140 See C<&checkauth> for an explanation of these parameters.
141
142 The C<template_name> is then used to find the correct template for
143 the page. The authenticated users details are loaded onto the
144 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
145 C<sessionID> is passed to the template. This can be used in templates
146 if cookies are disabled. It needs to be put as and input to every
147 authenticated page.
148
149 More information on the C<gettemplate> sub can be found in the
150 Output.pm module.
151
152 =cut
153
154 sub get_template_and_user {
155
156     my $in = shift;
157     my ( $user, $cookie, $sessionID, $flags );
158
159     C4::Context->interface( $in->{type} );
160
161     $in->{'authnotrequired'} ||= 0;
162     my $template = C4::Templates::gettemplate(
163         $in->{'template_name'},
164         $in->{'type'},
165         $in->{'query'},
166         $in->{'is_plugin'}
167     );
168
169     if ( $in->{'template_name'} !~ m/maintenance/ ) {
170         ( $user, $cookie, $sessionID, $flags ) = checkauth(
171             $in->{'query'},
172             $in->{'authnotrequired'},
173             $in->{'flagsrequired'},
174             $in->{'type'}
175         );
176     }
177
178     my $borrowernumber;
179     if ($user) {
180         require C4::Members;
181
182         # It's possible for $user to be the borrowernumber if they don't have a
183         # userid defined (and are logging in through some other method, such
184         # as SSL certs against an email address)
185         $borrowernumber = getborrowernumber($user) if defined($user);
186         if ( !defined($borrowernumber) && defined($user) ) {
187             my $borrower = C4::Members::GetMember( borrowernumber => $user );
188             if ($borrower) {
189                 $borrowernumber = $user;
190
191                 # A bit of a hack, but I don't know there's a nicer way
192                 # to do it.
193                 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
194             }
195         }
196
197         # user info
198         $template->param( loggedinusername   => $user );
199         $template->param( loggedinusernumber => $borrowernumber );
200         $template->param( sessionID          => $sessionID );
201
202         if ( $in->{'type'} eq 'opac' ) {
203             require C4::VirtualShelves;
204             my ( $total, $pubshelves, $barshelves ) = C4::VirtualShelves::GetSomeShelfNames( $borrowernumber, 'MASTHEAD' );
205             $template->param(
206                 pubshelves     => $total->{pubtotal},
207                 pubshelvesloop => $pubshelves,
208                 barshelves     => $total->{bartotal},
209                 barshelvesloop => $barshelves,
210             );
211         }
212
213         my ($borr) = C4::Members::GetMemberDetails($borrowernumber);
214         my @bordat;
215         $bordat[0] = $borr;
216         $template->param( "USER_INFO" => \@bordat );
217
218         my $all_perms = get_all_subpermissions();
219
220         my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
221           editcatalogue updatecharges management tools editauthorities serials reports acquisition);
222
223         # We are going to use the $flags returned by checkauth
224         # to create the template's parameters that will indicate
225         # which menus the user can access.
226         if ( $flags && $flags->{superlibrarian} == 1 ) {
227             $template->param( CAN_user_circulate        => 1 );
228             $template->param( CAN_user_catalogue        => 1 );
229             $template->param( CAN_user_parameters       => 1 );
230             $template->param( CAN_user_borrowers        => 1 );
231             $template->param( CAN_user_permissions      => 1 );
232             $template->param( CAN_user_reserveforothers => 1 );
233             $template->param( CAN_user_borrow           => 1 );
234             $template->param( CAN_user_editcatalogue    => 1 );
235             $template->param( CAN_user_updatecharges    => 1 );
236             $template->param( CAN_user_acquisition      => 1 );
237             $template->param( CAN_user_management       => 1 );
238             $template->param( CAN_user_tools            => 1 );
239             $template->param( CAN_user_editauthorities  => 1 );
240             $template->param( CAN_user_serials          => 1 );
241             $template->param( CAN_user_reports          => 1 );
242             $template->param( CAN_user_staffaccess      => 1 );
243             $template->param( CAN_user_plugins          => 1 );
244             $template->param( CAN_user_coursereserves   => 1 );
245             foreach my $module ( keys %$all_perms ) {
246
247                 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
248                     $template->param( "CAN_user_${module}_${subperm}" => 1 );
249                 }
250             }
251         }
252
253         if ($flags) {
254             foreach my $module ( keys %$all_perms ) {
255                 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
256                     foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
257                         $template->param( "CAN_user_${module}_${subperm}" => 1 );
258                     }
259                 } elsif ( ref( $flags->{$module} ) ) {
260                     foreach my $subperm ( keys %{ $flags->{$module} } ) {
261                         $template->param( "CAN_user_${module}_${subperm}" => 1 );
262                     }
263                 }
264             }
265         }
266
267         if ($flags) {
268             foreach my $module ( keys %$flags ) {
269                 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
270                     $template->param( "CAN_user_$module" => 1 );
271                     if ( $module eq "parameters" ) {
272                         $template->param( CAN_user_management => 1 );
273                     }
274                 }
275             }
276         }
277
278         # Logged-in opac search history
279         # If the requested template is an opac one and opac search history is enabled
280         if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
281             my $dbh   = C4::Context->dbh;
282             my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
283             my $sth   = $dbh->prepare($query);
284             $sth->execute($borrowernumber);
285
286             # If at least one search has already been performed
287             if ( $sth->fetchrow_array > 0 ) {
288
289                 # We show the link in opac
290                 $template->param( EnableOpacSearchHistory => 1 );
291             }
292
293             # And if there are searches performed when the user was not logged in,
294             # we add them to the logged-in search history
295             my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
296             if (@recentSearches) {
297                 my $dbh   = C4::Context->dbh;
298                 my $query = q{
299                     INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type,  total, time )
300                     VALUES (?, ?, ?, ?, ?, ?, ?)
301                 };
302
303                 my $sth = $dbh->prepare($query);
304                 $sth->execute( $borrowernumber,
305                     $in->{query}->cookie("CGISESSID"),
306                     $_->{query_desc},
307                     $_->{query_cgi},
308                     $_->{type} || 'biblio',
309                     $_->{total},
310                     $_->{time},
311                 ) foreach @recentSearches;
312
313                 # clear out the search history from the session now that
314                 # we've saved it to the database
315                 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
316             }
317         } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
318             $template->param( EnableSearchHistory => 1 );
319         }
320     }
321     else {    # if this is an anonymous session, setup to display public lists...
322
323         # If shibboleth is enabled, and we're in an anonymous session, we should allow
324         # the user to attemp login via shibboleth.
325         if ($shib) {
326             $template->param( shibbolethAuthentication => $shib,
327                 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
328             );
329
330             # If shibboleth is enabled and we have a shibboleth login attribute,
331             # but we are in an anonymous session, then we clearly have an invalid
332             # shibboleth koha account.
333             if ($shib_login) {
334                 $template->param( invalidShibLogin => '1' );
335             }
336         }
337
338         $template->param( sessionID => $sessionID );
339
340         if ( $in->{'type'} eq 'opac' ){
341             require C4::VirtualShelves;
342             my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
343             $template->param(
344                 pubshelves     => $total->{pubtotal},
345                 pubshelvesloop => $pubshelves,
346             );
347         }
348     }
349
350     # Anonymous opac search history
351     # If opac search history is enabled and at least one search has already been performed
352     if ( C4::Context->preference('EnableOpacSearchHistory') ) {
353         my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
354         if (@recentSearches) {
355             $template->param( EnableOpacSearchHistory => 1 );
356         }
357     }
358
359     if ( C4::Context->preference('dateformat') ) {
360         $template->param( dateformat => C4::Context->preference('dateformat') );
361     }
362
363     # these template parameters are set the same regardless of $in->{'type'}
364
365     # Set the using_https variable for templates
366     # FIXME Under Plack the CGI->https method always returns 'OFF'
367     my $https = $in->{query}->https();
368     my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
369
370     $template->param(
371         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
372         EnhancedMessagingPreferences                                       => C4::Context->preference('EnhancedMessagingPreferences'),
373         GoogleJackets                                                      => C4::Context->preference("GoogleJackets"),
374         OpenLibraryCovers                                                  => C4::Context->preference("OpenLibraryCovers"),
375         KohaAdminEmailAddress                                              => "" . C4::Context->preference("KohaAdminEmailAddress"),
376         LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"}    : undef ),
377         LoginFirstname  => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
378         LoginSurname    => C4::Context->userenv ? C4::Context->userenv->{"surname"}      : "Inconnu",
379         emailaddress    => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
380         loggedinpersona => C4::Context->userenv ? C4::Context->userenv->{"persona"}      : undef,
381         TagsEnabled     => C4::Context->preference("TagsEnabled"),
382         hide_marc       => C4::Context->preference("hide_marc"),
383         item_level_itypes  => C4::Context->preference('item-level_itypes'),
384         patronimages       => C4::Context->preference("patronimages"),
385         singleBranchMode   => C4::Context->preference("singleBranchMode"),
386         XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
387         XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
388         using_https        => $using_https,
389         noItemTypeImages   => C4::Context->preference("noItemTypeImages"),
390         marcflavour        => C4::Context->preference("marcflavour"),
391         persona            => C4::Context->preference("persona"),
392         OPACBaseURL        => C4::Context->preference('OPACBaseURL'),
393     );
394     if ( $in->{'type'} eq "intranet" ) {
395         $template->param(
396             AmazonCoverImages                                                          => C4::Context->preference("AmazonCoverImages"),
397             AutoLocation                                                               => C4::Context->preference("AutoLocation"),
398             "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
399             CalendarFirstDayOfWeek                                                     => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
400             CircAutocompl                                                              => C4::Context->preference("CircAutocompl"),
401             FRBRizeEditions                                                            => C4::Context->preference("FRBRizeEditions"),
402             IndependentBranches                                                        => C4::Context->preference("IndependentBranches"),
403             IntranetNav                                                                => C4::Context->preference("IntranetNav"),
404             IntranetmainUserblock                                                      => C4::Context->preference("IntranetmainUserblock"),
405             LibraryName                                                                => C4::Context->preference("LibraryName"),
406             LoginBranchname                                                            => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
407             advancedMARCEditor                                                         => C4::Context->preference("advancedMARCEditor"),
408             canreservefromotherbranches                                                => C4::Context->preference('canreservefromotherbranches'),
409             intranetcolorstylesheet                                                    => C4::Context->preference("intranetcolorstylesheet"),
410             IntranetFavicon                                                            => C4::Context->preference("IntranetFavicon"),
411             intranetreadinghistory                                                     => C4::Context->preference("intranetreadinghistory"),
412             intranetstylesheet                                                         => C4::Context->preference("intranetstylesheet"),
413             IntranetUserCSS                                                            => C4::Context->preference("IntranetUserCSS"),
414             IntranetUserJS                                                             => C4::Context->preference("IntranetUserJS"),
415             intranetbookbag                                                            => C4::Context->preference("intranetbookbag"),
416             suggestion                                                                 => C4::Context->preference("suggestion"),
417             virtualshelves                                                             => C4::Context->preference("virtualshelves"),
418             StaffSerialIssueDisplayCount                                               => C4::Context->preference("StaffSerialIssueDisplayCount"),
419             EasyAnalyticalRecords                                                      => C4::Context->preference('EasyAnalyticalRecords'),
420             LocalCoverImages                                                           => C4::Context->preference('LocalCoverImages'),
421             OPACLocalCoverImages                                                       => C4::Context->preference('OPACLocalCoverImages'),
422             AllowMultipleCovers                                                        => C4::Context->preference('AllowMultipleCovers'),
423             EnableBorrowerFiles                                                        => C4::Context->preference('EnableBorrowerFiles'),
424             UseKohaPlugins                                                             => C4::Context->preference('UseKohaPlugins'),
425             UseCourseReserves                                                          => C4::Context->preference("UseCourseReserves"),
426             useDischarge                                                               => C4::Context->preference('useDischarge'),
427         );
428     }
429     else {
430         warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
431
432         #TODO : replace LibraryName syspref with 'system name', and remove this html processing
433         my $LibraryNameTitle = C4::Context->preference("LibraryName");
434         $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
435         $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
436
437         # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
438         if ( C4::Context->preference("OpacBrowseResults")
439             && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
440             my $pagename = $1;
441             unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
442                 or $pagename =~ /^addbybiblionumber$/ ) {
443                 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
444                 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
445             }
446         }
447
448         # variables passed from CGI: opac_css_override and opac_search_limits.
449         my $opac_search_limit   = $ENV{'OPAC_SEARCH_LIMIT'};
450         my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
451         my $opac_name           = '';
452         if (
453             ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
454             ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
455             ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
456           ) {
457             $opac_name = $1;    # opac_search_limit is a branch, so we use it.
458         } elsif ( $in->{'query'}->param('multibranchlimit') ) {
459             $opac_name = $in->{'query'}->param('multibranchlimit');
460         } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
461             $opac_name = C4::Context->userenv->{'branch'};
462         }
463
464         $template->param(
465             OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
466             AnonSuggestions                       => "" . C4::Context->preference("AnonSuggestions"),
467             AuthorisedValueImages                 => C4::Context->preference("AuthorisedValueImages"),
468             BranchesLoop                          => GetBranchesLoop($opac_name),
469             BranchCategoriesLoop                  => GetBranchCategories( 'searchdomain', 1, $opac_name ),
470             CalendarFirstDayOfWeek                => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
471             LibraryName                           => "" . C4::Context->preference("LibraryName"),
472             LibraryNameTitle                      => "" . $LibraryNameTitle,
473             LoginBranchname                       => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
474             OPACAmazonCoverImages                 => C4::Context->preference("OPACAmazonCoverImages"),
475             OPACFRBRizeEditions                   => C4::Context->preference("OPACFRBRizeEditions"),
476             OpacHighlightedWords                  => C4::Context->preference("OpacHighlightedWords"),
477             OPACShelfBrowser                      => "" . C4::Context->preference("OPACShelfBrowser"),
478             OPACURLOpenInNewWindow                => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
479             OPACUserCSS                           => "" . C4::Context->preference("OPACUserCSS"),
480             OPACViewOthersSuggestions             => "" . C4::Context->preference("OPACViewOthersSuggestions"),
481             OpacAuthorities                       => C4::Context->preference("OpacAuthorities"),
482             opac_css_override                     => $ENV{'OPAC_CSS_OVERRIDE'},
483             opac_search_limit                     => $opac_search_limit,
484             opac_limit_override                   => $opac_limit_override,
485             OpacBrowser                           => C4::Context->preference("OpacBrowser"),
486             OpacCloud                             => C4::Context->preference("OpacCloud"),
487             OpacKohaUrl                           => C4::Context->preference("OpacKohaUrl"),
488             OpacMainUserBlock                     => "" . C4::Context->preference("OpacMainUserBlock"),
489             OpacNav                               => "" . C4::Context->preference("OpacNav"),
490             OpacNavRight                          => "" . C4::Context->preference("OpacNavRight"),
491             OpacNavBottom                         => "" . C4::Context->preference("OpacNavBottom"),
492             OpacPasswordChange                    => C4::Context->preference("OpacPasswordChange"),
493             OPACPatronDetails                     => C4::Context->preference("OPACPatronDetails"),
494             OPACPrivacy                           => C4::Context->preference("OPACPrivacy"),
495             OPACFinesTab                          => C4::Context->preference("OPACFinesTab"),
496             OpacTopissue                          => C4::Context->preference("OpacTopissue"),
497             RequestOnOpac                         => C4::Context->preference("RequestOnOpac"),
498             'Version'                             => C4::Context->preference('Version'),
499             hidelostitems                         => C4::Context->preference("hidelostitems"),
500             mylibraryfirst                        => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
501             opaclayoutstylesheet                  => "" . C4::Context->preference("opaclayoutstylesheet"),
502             opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
503             opaccredits                           => "" . C4::Context->preference("opaccredits"),
504             OpacFavicon                           => C4::Context->preference("OpacFavicon"),
505             opacheader                            => "" . C4::Context->preference("opacheader"),
506             opaclanguagesdisplay                  => "" . C4::Context->preference("opaclanguagesdisplay"),
507             opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
508             OPACUserJS                            => C4::Context->preference("OPACUserJS"),
509             opacuserlogin                         => "" . C4::Context->preference("opacuserlogin"),
510             ShowReviewer                          => C4::Context->preference("ShowReviewer"),
511             ShowReviewerPhoto                     => C4::Context->preference("ShowReviewerPhoto"),
512             suggestion                            => "" . C4::Context->preference("suggestion"),
513             virtualshelves                        => "" . C4::Context->preference("virtualshelves"),
514             OPACSerialIssueDisplayCount           => C4::Context->preference("OPACSerialIssueDisplayCount"),
515             OPACXSLTDetailsDisplay                => C4::Context->preference("OPACXSLTDetailsDisplay"),
516             OPACXSLTResultsDisplay                => C4::Context->preference("OPACXSLTResultsDisplay"),
517             SyndeticsClientCode                   => C4::Context->preference("SyndeticsClientCode"),
518             SyndeticsEnabled                      => C4::Context->preference("SyndeticsEnabled"),
519             SyndeticsCoverImages                  => C4::Context->preference("SyndeticsCoverImages"),
520             SyndeticsTOC                          => C4::Context->preference("SyndeticsTOC"),
521             SyndeticsSummary                      => C4::Context->preference("SyndeticsSummary"),
522             SyndeticsEditions                     => C4::Context->preference("SyndeticsEditions"),
523             SyndeticsExcerpt                      => C4::Context->preference("SyndeticsExcerpt"),
524             SyndeticsReviews                      => C4::Context->preference("SyndeticsReviews"),
525             SyndeticsAuthorNotes                  => C4::Context->preference("SyndeticsAuthorNotes"),
526             SyndeticsAwards                       => C4::Context->preference("SyndeticsAwards"),
527             SyndeticsSeries                       => C4::Context->preference("SyndeticsSeries"),
528             SyndeticsCoverImageSize               => C4::Context->preference("SyndeticsCoverImageSize"),
529             OPACLocalCoverImages                  => C4::Context->preference("OPACLocalCoverImages"),
530             PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
531             PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
532             useDischarge                 => C4::Context->preference('useDischarge'),
533         );
534
535         $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
536     }
537
538     # Check if we were asked using parameters to force a specific language
539     if ( defined $in->{'query'}->param('language') ) {
540
541         # Extract the language, let C4::Languages::getlanguage choose
542         # what to do
543         my $language = C4::Languages::getlanguage( $in->{'query'} );
544         my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
545         if ( ref $cookie eq 'ARRAY' ) {
546             push @{$cookie}, $languagecookie;
547         } else {
548             $cookie = [ $cookie, $languagecookie ];
549         }
550     }
551
552     return ( $template, $borrowernumber, $cookie, $flags );
553 }
554
555 =head2 checkauth
556
557   ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
558
559 Verifies that the user is authorized to run this script.  If
560 the user is authorized, a (userid, cookie, session-id, flags)
561 quadruple is returned.  If the user is not authorized but does
562 not have the required privilege (see $flagsrequired below), it
563 displays an error page and exits.  Otherwise, it displays the
564 login page and exits.
565
566 Note that C<&checkauth> will return if and only if the user
567 is authorized, so it should be called early on, before any
568 unfinished operations (e.g., if you've opened a file, then
569 C<&checkauth> won't close it for you).
570
571 C<$query> is the CGI object for the script calling C<&checkauth>.
572
573 The C<$noauth> argument is optional. If it is set, then no
574 authorization is required for the script.
575
576 C<&checkauth> fetches user and session information from C<$query> and
577 ensures that the user is authorized to run scripts that require
578 authorization.
579
580 The C<$flagsrequired> argument specifies the required privileges
581 the user must have if the username and password are correct.
582 It should be specified as a reference-to-hash; keys in the hash
583 should be the "flags" for the user, as specified in the Members
584 intranet module. Any key specified must correspond to a "flag"
585 in the userflags table. E.g., { circulate => 1 } would specify
586 that the user must have the "circulate" privilege in order to
587 proceed. To make sure that access control is correct, the
588 C<$flagsrequired> parameter must be specified correctly.
589
590 Koha also has a concept of sub-permissions, also known as
591 granular permissions.  This makes the value of each key
592 in the C<flagsrequired> hash take on an additional
593 meaning, i.e.,
594
595  1
596
597 The user must have access to all subfunctions of the module
598 specified by the hash key.
599
600  *
601
602 The user must have access to at least one subfunction of the module
603 specified by the hash key.
604
605  specific permission, e.g., 'export_catalog'
606
607 The user must have access to the specific subfunction list, which
608 must correspond to a row in the permissions table.
609
610 The C<$type> argument specifies whether the template should be
611 retrieved from the opac or intranet directory tree.  "opac" is
612 assumed if it is not specified; however, if C<$type> is specified,
613 "intranet" is assumed if it is not "opac".
614
615 If C<$query> does not have a valid session ID associated with it
616 (i.e., the user has not logged in) or if the session has expired,
617 C<&checkauth> presents the user with a login page (from the point of
618 view of the original script, C<&checkauth> does not return). Once the
619 user has authenticated, C<&checkauth> restarts the original script
620 (this time, C<&checkauth> returns).
621
622 The login page is provided using a HTML::Template, which is set in the
623 systempreferences table or at the top of this file. The variable C<$type>
624 selects which template to use, either the opac or the intranet
625 authentification template.
626
627 C<&checkauth> returns a user ID, a cookie, and a session ID. The
628 cookie should be sent back to the browser; it verifies that the user
629 has authenticated.
630
631 =cut
632
633 sub _version_check {
634     my $type  = shift;
635     my $query = shift;
636     my $version;
637
638     # If Version syspref is unavailable, it means Koha is beeing installed,
639     # and so we must redirect to OPAC maintenance page or to the WebInstaller
640     # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
641     if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
642         warn "OPAC Install required, redirecting to maintenance";
643         print $query->redirect("/cgi-bin/koha/maintenance.pl");
644         safe_exit;
645     }
646     unless ( $version = C4::Context->preference('Version') ) {    # assignment, not comparison
647         if ( $type ne 'opac' ) {
648             warn "Install required, redirecting to Installer";
649             print $query->redirect("/cgi-bin/koha/installer/install.pl");
650         } else {
651             warn "OPAC Install required, redirecting to maintenance";
652             print $query->redirect("/cgi-bin/koha/maintenance.pl");
653         }
654         safe_exit;
655     }
656
657     # check that database and koha version are the same
658     # there is no DB version, it's a fresh install,
659     # go to web installer
660     # there is a DB version, compare it to the code version
661     my $kohaversion = Koha::version();
662
663     # remove the 3 last . to have a Perl number
664     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
665     $debug and print STDERR "kohaversion : $kohaversion\n";
666     if ( $version < $kohaversion ) {
667         my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
668         if ( $type ne 'opac' ) {
669             warn sprintf( $warning, 'Installer' );
670             print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
671         } else {
672             warn sprintf( "OPAC: " . $warning, 'maintenance' );
673             print $query->redirect("/cgi-bin/koha/maintenance.pl");
674         }
675         safe_exit;
676     }
677 }
678
679 sub _session_log {
680     (@_) or return 0;
681     open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
682     printf $fh join( "\n", @_ );
683     close $fh;
684 }
685
686 sub _timeout_syspref {
687     my $timeout = C4::Context->preference('timeout') || 600;
688
689     # value in days, convert in seconds
690     if ( $timeout =~ /(\d+)[dD]/ ) {
691         $timeout = $1 * 86400;
692     }
693     return $timeout;
694 }
695
696 sub checkauth {
697     my $query = shift;
698     $debug and warn "Checking Auth";
699
700     # $authnotrequired will be set for scripts which will run without authentication
701     my $authnotrequired = shift;
702     my $flagsrequired   = shift;
703     my $type            = shift;
704     my $persona         = shift;
705     $type = 'opac' unless $type;
706
707     my $dbh     = C4::Context->dbh;
708     my $timeout = _timeout_syspref();
709
710     _version_check( $type, $query );
711
712     # state variables
713     my $loggedin = 0;
714     my %info;
715     my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
716     my $logout = $query->param('logout.x');
717
718     my $anon_search_history;
719
720     # This parameter is the name of the CAS server we want to authenticate against,
721     # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
722     my $casparam = $query->param('cas');
723     my $q_userid = $query->param('userid') // '';
724
725     # Basic authentication is incompatible with the use of Shibboleth,
726     # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
727     # and it may not be the attribute we want to use to match the koha login.
728     #
729     # Also, do not consider an empty REMOTE_USER.
730     #
731     # Finally, after those tests, we can assume (although if it would be better with
732     # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
733     # and we can affect it to $userid.
734     if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
735
736         # Using Basic Authentication, no cookies required
737         $cookie = $query->cookie(
738             -name     => 'CGISESSID',
739             -value    => '',
740             -expires  => '',
741             -HttpOnly => 1,
742         );
743         $loggedin = 1;
744     }
745     elsif ($persona) {
746
747         # we dont want to set a session because we are being called by a persona callback
748     }
749     elsif ( $sessionID = $query->cookie("CGISESSID") )
750     {    # assignment, not comparison
751         my $session = get_session($sessionID);
752         C4::Context->_new_userenv($sessionID);
753         my ( $ip, $lasttime, $sessiontype );
754         my $s_userid = '';
755         if ($session) {
756             $s_userid = $session->param('id') // '';
757             C4::Context->set_userenv(
758                 $session->param('number'),       $s_userid,
759                 $session->param('cardnumber'),   $session->param('firstname'),
760                 $session->param('surname'),      $session->param('branch'),
761                 $session->param('branchname'),   $session->param('flags'),
762                 $session->param('emailaddress'), $session->param('branchprinter'),
763                 $session->param('persona'),      $session->param('shibboleth')
764             );
765             C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
766             C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
767             C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
768             $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
769             $ip          = $session->param('ip');
770             $lasttime    = $session->param('lasttime');
771             $userid      = $s_userid;
772             $sessiontype = $session->param('sessiontype') || '';
773         }
774         if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
775             || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} ) || ( $shib && $shib_login && !$logout ) ) {
776
777             #if a user enters an id ne to the id in the current session, we need to log them in...
778             #first we need to clear the anonymous session...
779             $debug and warn "query id = $q_userid but session id = $s_userid";
780             $anon_search_history = $session->param('search_history');
781             $session->delete();
782             $session->flush;
783             C4::Context->_unset_userenv($sessionID);
784             $sessionID = undef;
785             $userid    = undef;
786         }
787         elsif ($logout) {
788
789             # voluntary logout the user
790             # check wether the user was using their shibboleth session or a local one
791             my $shibSuccess = C4::Context->userenv->{'shibboleth'};
792             $session->delete();
793             $session->flush;
794             C4::Context->_unset_userenv($sessionID);
795
796             #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
797             $sessionID = undef;
798             $userid    = undef;
799
800             if ($cas and $caslogout) {
801                 logout_cas($query, $type);
802             }
803
804             # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
805             if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
806
807                 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
808                 logout_shib($query);
809             }
810         }
811         elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
812
813             # timed logout
814             $info{'timed_out'} = 1;
815             if ($session) {
816                 $session->delete();
817                 $session->flush;
818             }
819             C4::Context->_unset_userenv($sessionID);
820
821             #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
822             $userid    = undef;
823             $sessionID = undef;
824         }
825         elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
826
827             # Different ip than originally logged in from
828             $info{'oldip'}        = $ip;
829             $info{'newip'}        = $ENV{'REMOTE_ADDR'};
830             $info{'different_ip'} = 1;
831             $session->delete();
832             $session->flush;
833             C4::Context->_unset_userenv($sessionID);
834
835             #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
836             $sessionID = undef;
837             $userid    = undef;
838         }
839         else {
840             $cookie = $query->cookie(
841                 -name     => 'CGISESSID',
842                 -value    => $session->id,
843                 -HttpOnly => 1
844             );
845             $session->param( 'lasttime', time() );
846             unless ( $sessiontype && $sessiontype eq 'anon' ) {    #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
847                 $flags = haspermission( $userid, $flagsrequired );
848                 if ($flags) {
849                     $loggedin = 1;
850                 } else {
851                     $info{'nopermission'} = 1;
852                 }
853             }
854         }
855     }
856     unless ( $userid || $sessionID ) {
857
858         #we initiate a session prior to checking for a username to allow for anonymous sessions...
859         my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
860
861         # Save anonymous search history in new session so it can be retrieved
862         # by get_template_and_user to store it in user's search history after
863         # a successful login.
864         if ($anon_search_history) {
865             $session->param( 'search_history', $anon_search_history );
866         }
867
868         my $sessionID = $session->id;
869         C4::Context->_new_userenv($sessionID);
870         $cookie = $query->cookie(
871             -name     => 'CGISESSID',
872             -value    => $session->id,
873             -HttpOnly => 1
874         );
875         $userid = $q_userid;
876         my $pki_field = C4::Context->preference('AllowPKIAuth');
877         if ( !defined($pki_field) ) {
878             print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
879             $pki_field = 'None';
880         }
881         if ( ( $cas && $query->param('ticket') )
882             || $userid
883             || ( $shib && $shib_login )
884             || $pki_field ne 'None'
885             || $persona )
886         {
887             my $password    = $query->param('password');
888             my $shibSuccess = 0;
889
890             my ( $return, $cardnumber );
891
892             # If shib is enabled and we have a shib login, does the login match a valid koha user
893             if ( $shib && $shib_login && $type eq 'opac' ) {
894                 my $retuserid;
895
896                 # Do not pass password here, else shib will not be checked in checkpw.
897                 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, undef, $query );
898                 $userid      = $retuserid;
899                 $shibSuccess = $return;
900                 $info{'invalidShibLogin'} = 1 unless ($return);
901             }
902
903             # If shib login and match were successfull, skip further login methods
904             unless ($shibSuccess) {
905                 if ( $cas && $query->param('ticket') ) {
906                     my $retuserid;
907                     ( $return, $cardnumber, $retuserid ) =
908                       checkpw( $dbh, $userid, $password, $query, $type );
909                     $userid = $retuserid;
910                     $info{'invalidCasLogin'} = 1 unless ($return);
911                 }
912
913                 elsif ($persona) {
914                     my $value = $persona;
915
916                     # If we're looking up the email, there's a chance that the person
917                     # doesn't have a userid. So if there is none, we pass along the
918                     # borrower number, and the bits of code that need to know the user
919                     # ID will have to be smart enough to handle that.
920                     require C4::Members;
921                     my @users_info = C4::Members::GetBorrowersWithEmail($value);
922                     if (@users_info) {
923
924                         # First the userid, then the borrowernum
925                         $value = $users_info[0][1] || $users_info[0][0];
926                     }
927                     else {
928                         undef $value;
929                     }
930                     $return = $value ? 1 : 0;
931                     $userid = $value;
932                 }
933
934                 elsif (
935                     ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
936                     || ( $pki_field eq 'emailAddress'
937                         && $ENV{'SSL_CLIENT_S_DN_Email'} )
938                   )
939                 {
940                     my $value;
941                     if ( $pki_field eq 'Common Name' ) {
942                         $value = $ENV{'SSL_CLIENT_S_DN_CN'};
943                     }
944                     elsif ( $pki_field eq 'emailAddress' ) {
945                         $value = $ENV{'SSL_CLIENT_S_DN_Email'};
946
947                         # If we're looking up the email, there's a chance that the person
948                         # doesn't have a userid. So if there is none, we pass along the
949                         # borrower number, and the bits of code that need to know the user
950                         # ID will have to be smart enough to handle that.
951                         require C4::Members;
952                         my @users_info = C4::Members::GetBorrowersWithEmail($value);
953                         if (@users_info) {
954
955                             # First the userid, then the borrowernum
956                             $value = $users_info[0][1] || $users_info[0][0];
957                         } else {
958                             undef $value;
959                         }
960                     }
961
962                     $return = $value ? 1 : 0;
963                     $userid = $value;
964
965                 }
966                 else {
967                     my $retuserid;
968                     ( $return, $cardnumber, $retuserid ) =
969                       checkpw( $dbh, $userid, $password, $query, $type );
970                     $userid = $retuserid if ($retuserid);
971                     $info{'invalid_username_or_password'} = 1 unless ($return);
972                 }
973             }
974
975             # $return: 1 = valid user, 2 = superlibrarian
976             if ($return) {
977
978                 #_session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
979                 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
980                     $loggedin = 1;
981                 }
982                 else {
983                     $info{'nopermission'} = 1;
984                     C4::Context->_unset_userenv($sessionID);
985                 }
986                 my ( $borrowernumber, $firstname, $surname, $userflags,
987                     $branchcode, $branchname, $branchprinter, $emailaddress );
988
989                 if ( $return == 1 ) {
990                     my $select = "
991                     SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
992                     branches.branchname    as branchname,
993                     branches.branchprinter as branchprinter,
994                     email
995                     FROM borrowers
996                     LEFT JOIN branches on borrowers.branchcode=branches.branchcode
997                     ";
998                     my $sth = $dbh->prepare("$select where userid=?");
999                     $sth->execute($userid);
1000                     unless ( $sth->rows ) {
1001                         $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1002                         $sth = $dbh->prepare("$select where cardnumber=?");
1003                         $sth->execute($cardnumber);
1004
1005                         unless ( $sth->rows ) {
1006                             $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1007                             $sth->execute($userid);
1008                             unless ( $sth->rows ) {
1009                                 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1010                             }
1011                         }
1012                     }
1013                     if ( $sth->rows ) {
1014                         ( $borrowernumber, $firstname, $surname, $userflags,
1015                             $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1016                         $debug and print STDERR "AUTH_3 results: " .
1017                           "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1018                     } else {
1019                         print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1020                     }
1021
1022                     # launch a sequence to check if we have a ip for the branch, i
1023                     # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1024
1025                     my $ip = $ENV{'REMOTE_ADDR'};
1026
1027                     # if they specify at login, use that
1028                     if ( $query->param('branch') ) {
1029                         $branchcode = $query->param('branch');
1030                         $branchname = GetBranchName($branchcode);
1031                     }
1032                     my $branches = GetBranches();
1033                     if ( C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation') ) {
1034
1035                         # we have to check they are coming from the right ip range
1036                         my $domain = $branches->{$branchcode}->{'branchip'};
1037                         if ( $ip !~ /^$domain/ ) {
1038                             $loggedin = 0;
1039                             $info{'wrongip'} = 1;
1040                         }
1041                     }
1042
1043                     my @branchesloop;
1044                     foreach my $br ( keys %$branches ) {
1045
1046                         #     now we work with the treatment of ip
1047                         my $domain = $branches->{$br}->{'branchip'};
1048                         if ( $domain && $ip =~ /^$domain/ ) {
1049                             $branchcode = $branches->{$br}->{'branchcode'};
1050
1051                             # new op dev : add the branchprinter and branchname in the cookie
1052                             $branchprinter = $branches->{$br}->{'branchprinter'};
1053                             $branchname    = $branches->{$br}->{'branchname'};
1054                         }
1055                     }
1056                     $session->param( 'number',       $borrowernumber );
1057                     $session->param( 'id',           $userid );
1058                     $session->param( 'cardnumber',   $cardnumber );
1059                     $session->param( 'firstname',    $firstname );
1060                     $session->param( 'surname',      $surname );
1061                     $session->param( 'branch',       $branchcode );
1062                     $session->param( 'branchname',   $branchname );
1063                     $session->param( 'flags',        $userflags );
1064                     $session->param( 'emailaddress', $emailaddress );
1065                     $session->param( 'ip',           $session->remote_addr() );
1066                     $session->param( 'lasttime',     time() );
1067                     $session->param( 'shibboleth',   $shibSuccess );
1068                     $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1069                 }
1070                 elsif ( $return == 2 ) {
1071
1072                     #We suppose the user is the superlibrarian
1073                     $borrowernumber = 0;
1074                     $session->param( 'number',       0 );
1075                     $session->param( 'id',           C4::Context->config('user') );
1076                     $session->param( 'cardnumber',   C4::Context->config('user') );
1077                     $session->param( 'firstname',    C4::Context->config('user') );
1078                     $session->param( 'surname',      C4::Context->config('user') );
1079                     $session->param( 'branch',       'NO_LIBRARY_SET' );
1080                     $session->param( 'branchname',   'NO_LIBRARY_SET' );
1081                     $session->param( 'flags',        1 );
1082                     $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1083                     $session->param( 'ip',           $session->remote_addr() );
1084                     $session->param( 'lasttime',     time() );
1085                 }
1086                 if ($persona) {
1087                     $session->param( 'persona', 1 );
1088                 }
1089                 C4::Context->set_userenv(
1090                     $session->param('number'),       $session->param('id'),
1091                     $session->param('cardnumber'),   $session->param('firstname'),
1092                     $session->param('surname'),      $session->param('branch'),
1093                     $session->param('branchname'),   $session->param('flags'),
1094                     $session->param('emailaddress'), $session->param('branchprinter'),
1095                     $session->param('persona'),      $session->param('shibboleth')
1096                 );
1097
1098             }
1099             # $return: 0 = invalid user
1100             # reset to anonymous session
1101             else {
1102                 $debug and warn "Login failed, resetting anonymous session...";
1103                 if ($userid) {
1104                     $info{'invalid_username_or_password'} = 1;
1105                     C4::Context->_unset_userenv($sessionID);
1106                 }
1107                 $session->param( 'lasttime', time() );
1108                 $session->param( 'ip',       $session->remote_addr() );
1109                 $session->param( 'sessiontype', 'anon' );
1110             }
1111         }    # END if ( $userid    = $query->param('userid') )
1112         elsif ( $type eq "opac" ) {
1113
1114             # if we are here this is an anonymous session; add public lists to it and a few other items...
1115             # anonymous sessions are created only for the OPAC
1116             $debug and warn "Initiating an anonymous session...";
1117
1118             # setting a couple of other session vars...
1119             $session->param( 'ip',          $session->remote_addr() );
1120             $session->param( 'lasttime',    time() );
1121             $session->param( 'sessiontype', 'anon' );
1122         }
1123     }    # END unless ($userid)
1124
1125     # finished authentification, now respond
1126     if ( $loggedin || $authnotrequired )
1127     {
1128         # successful login
1129         unless ($cookie) {
1130             $cookie = $query->cookie(
1131                 -name     => 'CGISESSID',
1132                 -value    => '',
1133                 -HttpOnly => 1
1134             );
1135         }
1136         return ( $userid, $cookie, $sessionID, $flags );
1137     }
1138
1139     #
1140     #
1141     # AUTH rejected, show the login/password template, after checking the DB.
1142     #
1143     #
1144
1145     # get the inputs from the incoming query
1146     my @inputs = ();
1147     foreach my $name ( param $query) {
1148         (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1149         my $value = $query->param($name);
1150         push @inputs, { name => $name, value => $value };
1151     }
1152
1153     my $LibraryNameTitle = C4::Context->preference("LibraryName");
1154     $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1155     $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1156
1157     my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1158     my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1159     $template->param(
1160         branchloop                            => GetBranchesLoop(),
1161         OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
1162         opaclayoutstylesheet                  => C4::Context->preference("opaclayoutstylesheet"),
1163         login                                 => 1,
1164         INPUTS                                => \@inputs,
1165         casAuthentication                     => C4::Context->preference("casAuthentication"),
1166         shibbolethAuthentication              => $shib,
1167         SessionRestrictionByIP                => C4::Context->preference("SessionRestrictionByIP"),
1168         suggestion                            => C4::Context->preference("suggestion"),
1169         virtualshelves                        => C4::Context->preference("virtualshelves"),
1170         LibraryName                           => "" . C4::Context->preference("LibraryName"),
1171         LibraryNameTitle                      => "" . $LibraryNameTitle,
1172         opacuserlogin                         => C4::Context->preference("opacuserlogin"),
1173         OpacNav                               => C4::Context->preference("OpacNav"),
1174         OpacNavRight                          => C4::Context->preference("OpacNavRight"),
1175         OpacNavBottom                         => C4::Context->preference("OpacNavBottom"),
1176         opaccredits                           => C4::Context->preference("opaccredits"),
1177         OpacFavicon                           => C4::Context->preference("OpacFavicon"),
1178         opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
1179         opaclanguagesdisplay                  => C4::Context->preference("opaclanguagesdisplay"),
1180         OPACUserJS                            => C4::Context->preference("OPACUserJS"),
1181         opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
1182         OpacCloud                             => C4::Context->preference("OpacCloud"),
1183         OpacTopissue                          => C4::Context->preference("OpacTopissue"),
1184         OpacAuthorities                       => C4::Context->preference("OpacAuthorities"),
1185         OpacBrowser                           => C4::Context->preference("OpacBrowser"),
1186         opacheader                            => C4::Context->preference("opacheader"),
1187         TagsEnabled                           => C4::Context->preference("TagsEnabled"),
1188         OPACUserCSS                           => C4::Context->preference("OPACUserCSS"),
1189         intranetcolorstylesheet               => C4::Context->preference("intranetcolorstylesheet"),
1190         intranetstylesheet                    => C4::Context->preference("intranetstylesheet"),
1191         intranetbookbag                       => C4::Context->preference("intranetbookbag"),
1192         IntranetNav                           => C4::Context->preference("IntranetNav"),
1193         IntranetFavicon                       => C4::Context->preference("IntranetFavicon"),
1194         IntranetUserJS                        => C4::Context->preference("IntranetUserJS"),
1195         IndependentBranches                   => C4::Context->preference("IndependentBranches"),
1196         AutoLocation                          => C4::Context->preference("AutoLocation"),
1197         wrongip                               => $info{'wrongip'},
1198         PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
1199         PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1200         persona                               => C4::Context->preference("Persona"),
1201         opac_css_override                     => $ENV{'OPAC_CSS_OVERRIDE'},
1202     );
1203
1204     $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1205     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1206
1207     if ( $type eq 'opac' ) {
1208         require C4::VirtualShelves;
1209         my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
1210         $template->param(
1211             pubshelves     => $total->{pubtotal},
1212             pubshelvesloop => $pubshelves,
1213         );
1214     }
1215
1216     if ($cas) {
1217
1218         # Is authentication against multiple CAS servers enabled?
1219         if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1220             my $casservers = C4::Auth_with_cas::getMultipleAuth();
1221             my @tmplservers;
1222             foreach my $key ( keys %$casservers ) {
1223                 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1224             }
1225             $template->param(
1226                 casServersLoop => \@tmplservers
1227             );
1228         } else {
1229             $template->param(
1230                 casServerUrl => login_cas_url($query, undef, $type),
1231             );
1232         }
1233
1234         $template->param(
1235             invalidCasLogin => $info{'invalidCasLogin'}
1236         );
1237     }
1238
1239     if ($shib) {
1240         $template->param(
1241             shibbolethAuthentication => $shib,
1242             shibbolethLoginUrl       => login_shib_url($query),
1243         );
1244     }
1245
1246     my $self_url = $query->url( -absolute => 1 );
1247     $template->param(
1248         url         => $self_url,
1249         LibraryName => C4::Context->preference("LibraryName"),
1250     );
1251     $template->param(%info);
1252
1253     #    $cookie = $query->cookie(CGISESSID => $session->id
1254     #   );
1255     print $query->header(
1256         -type    => 'text/html',
1257         -charset => 'utf-8',
1258         -cookie  => $cookie
1259       ),
1260       $template->output;
1261     safe_exit;
1262 }
1263
1264 =head2 check_api_auth
1265
1266   ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1267
1268 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1269 cookie, determine if the user has the privileges specified by C<$userflags>.
1270
1271 C<check_api_auth> is is meant for authenticating users of web services, and
1272 consequently will always return and will not attempt to redirect the user
1273 agent.
1274
1275 If a valid session cookie is already present, check_api_auth will return a status
1276 of "ok", the cookie, and the Koha session ID.
1277
1278 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1279 parameters and create a session cookie and Koha session if the supplied credentials
1280 are OK.
1281
1282 Possible return values in C<$status> are:
1283
1284 =over
1285
1286 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1287
1288 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1289
1290 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1291
1292 =item "expired -- session cookie has expired; API user should resubmit userid and password
1293
1294 =back
1295
1296 =cut
1297
1298 sub check_api_auth {
1299     my $query         = shift;
1300     my $flagsrequired = shift;
1301
1302     my $dbh     = C4::Context->dbh;
1303     my $timeout = _timeout_syspref();
1304
1305     unless ( C4::Context->preference('Version') ) {
1306
1307         # database has not been installed yet
1308         return ( "maintenance", undef, undef );
1309     }
1310     my $kohaversion = Koha::version();
1311     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1312     if ( C4::Context->preference('Version') < $kohaversion ) {
1313
1314         # database in need of version update; assume that
1315         # no API should be called while databsae is in
1316         # this condition.
1317         return ( "maintenance", undef, undef );
1318     }
1319
1320     # FIXME -- most of what follows is a copy-and-paste
1321     # of code from checkauth.  There is an obvious need
1322     # for refactoring to separate the various parts of
1323     # the authentication code, but as of 2007-11-19 this
1324     # is deferred so as to not introduce bugs into the
1325     # regular authentication code for Koha 3.0.
1326
1327     # see if we have a valid session cookie already
1328     # however, if a userid parameter is present (i.e., from
1329     # a form submission, assume that any current cookie
1330     # is to be ignored
1331     my $sessionID = undef;
1332     unless ( $query->param('userid') ) {
1333         $sessionID = $query->cookie("CGISESSID");
1334     }
1335     if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1336         my $session = get_session($sessionID);
1337         C4::Context->_new_userenv($sessionID);
1338         if ($session) {
1339             C4::Context->set_userenv(
1340                 $session->param('number'),       $session->param('id'),
1341                 $session->param('cardnumber'),   $session->param('firstname'),
1342                 $session->param('surname'),      $session->param('branch'),
1343                 $session->param('branchname'),   $session->param('flags'),
1344                 $session->param('emailaddress'), $session->param('branchprinter')
1345             );
1346
1347             my $ip       = $session->param('ip');
1348             my $lasttime = $session->param('lasttime');
1349             my $userid   = $session->param('id');
1350             if ( $lasttime < time() - $timeout ) {
1351
1352                 # time out
1353                 $session->delete();
1354                 $session->flush;
1355                 C4::Context->_unset_userenv($sessionID);
1356                 $userid    = undef;
1357                 $sessionID = undef;
1358                 return ( "expired", undef, undef );
1359             } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1360
1361                 # IP address changed
1362                 $session->delete();
1363                 $session->flush;
1364                 C4::Context->_unset_userenv($sessionID);
1365                 $userid    = undef;
1366                 $sessionID = undef;
1367                 return ( "expired", undef, undef );
1368             } else {
1369                 my $cookie = $query->cookie(
1370                     -name     => 'CGISESSID',
1371                     -value    => $session->id,
1372                     -HttpOnly => 1,
1373                 );
1374                 $session->param( 'lasttime', time() );
1375                 my $flags = haspermission( $userid, $flagsrequired );
1376                 if ($flags) {
1377                     return ( "ok", $cookie, $sessionID );
1378                 } else {
1379                     $session->delete();
1380                     $session->flush;
1381                     C4::Context->_unset_userenv($sessionID);
1382                     $userid    = undef;
1383                     $sessionID = undef;
1384                     return ( "failed", undef, undef );
1385                 }
1386             }
1387         } else {
1388             return ( "expired", undef, undef );
1389         }
1390     } else {
1391
1392         # new login
1393         my $userid   = $query->param('userid');
1394         my $password = $query->param('password');
1395         my ( $return, $cardnumber );
1396
1397         # Proxy CAS auth
1398         if ( $cas && $query->param('PT') ) {
1399             my $retuserid;
1400             $debug and print STDERR "## check_api_auth - checking CAS\n";
1401
1402             # In case of a CAS authentication, we use the ticket instead of the password
1403             my $PT = $query->param('PT');
1404             ( $return, $cardnumber, $userid ) = check_api_auth_cas( $dbh, $PT, $query );    # EXTERNAL AUTH
1405         } else {
1406
1407             # User / password auth
1408             unless ( $userid and $password ) {
1409
1410                 # caller did something wrong, fail the authenticateion
1411                 return ( "failed", undef, undef );
1412             }
1413             ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1414         }
1415
1416         if ( $return and haspermission( $userid, $flagsrequired ) ) {
1417             my $session = get_session("");
1418             return ( "failed", undef, undef ) unless $session;
1419
1420             my $sessionID = $session->id;
1421             C4::Context->_new_userenv($sessionID);
1422             my $cookie = $query->cookie(
1423                 -name     => 'CGISESSID',
1424                 -value    => $sessionID,
1425                 -HttpOnly => 1,
1426             );
1427             if ( $return == 1 ) {
1428                 my (
1429                     $borrowernumber, $firstname,  $surname,
1430                     $userflags,      $branchcode, $branchname,
1431                     $branchprinter,  $emailaddress
1432                 );
1433                 my $sth =
1434                   $dbh->prepare(
1435 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname,branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1436                   );
1437                 $sth->execute($userid);
1438                 (
1439                     $borrowernumber, $firstname,  $surname,
1440                     $userflags,      $branchcode, $branchname,
1441                     $branchprinter,  $emailaddress
1442                 ) = $sth->fetchrow if ( $sth->rows );
1443
1444                 unless ( $sth->rows ) {
1445                     my $sth = $dbh->prepare(
1446 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1447                     );
1448                     $sth->execute($cardnumber);
1449                     (
1450                         $borrowernumber, $firstname,  $surname,
1451                         $userflags,      $branchcode, $branchname,
1452                         $branchprinter,  $emailaddress
1453                     ) = $sth->fetchrow if ( $sth->rows );
1454
1455                     unless ( $sth->rows ) {
1456                         $sth->execute($userid);
1457                         (
1458                             $borrowernumber, $firstname,  $surname,       $userflags,
1459                             $branchcode,     $branchname, $branchprinter, $emailaddress
1460                         ) = $sth->fetchrow if ( $sth->rows );
1461                     }
1462                 }
1463
1464                 my $ip = $ENV{'REMOTE_ADDR'};
1465
1466                 # if they specify at login, use that
1467                 if ( $query->param('branch') ) {
1468                     $branchcode = $query->param('branch');
1469                     $branchname = GetBranchName($branchcode);
1470                 }
1471                 my $branches = GetBranches();
1472                 my @branchesloop;
1473                 foreach my $br ( keys %$branches ) {
1474
1475                     #     now we work with the treatment of ip
1476                     my $domain = $branches->{$br}->{'branchip'};
1477                     if ( $domain && $ip =~ /^$domain/ ) {
1478                         $branchcode = $branches->{$br}->{'branchcode'};
1479
1480                         # new op dev : add the branchprinter and branchname in the cookie
1481                         $branchprinter = $branches->{$br}->{'branchprinter'};
1482                         $branchname    = $branches->{$br}->{'branchname'};
1483                     }
1484                 }
1485                 $session->param( 'number',       $borrowernumber );
1486                 $session->param( 'id',           $userid );
1487                 $session->param( 'cardnumber',   $cardnumber );
1488                 $session->param( 'firstname',    $firstname );
1489                 $session->param( 'surname',      $surname );
1490                 $session->param( 'branch',       $branchcode );
1491                 $session->param( 'branchname',   $branchname );
1492                 $session->param( 'flags',        $userflags );
1493                 $session->param( 'emailaddress', $emailaddress );
1494                 $session->param( 'ip',           $session->remote_addr() );
1495                 $session->param( 'lasttime',     time() );
1496             } elsif ( $return == 2 ) {
1497
1498                 #We suppose the user is the superlibrarian
1499                 $session->param( 'number',       0 );
1500                 $session->param( 'id',           C4::Context->config('user') );
1501                 $session->param( 'cardnumber',   C4::Context->config('user') );
1502                 $session->param( 'firstname',    C4::Context->config('user') );
1503                 $session->param( 'surname',      C4::Context->config('user') );
1504                 $session->param( 'branch',       'NO_LIBRARY_SET' );
1505                 $session->param( 'branchname',   'NO_LIBRARY_SET' );
1506                 $session->param( 'flags',        1 );
1507                 $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1508                 $session->param( 'ip',           $session->remote_addr() );
1509                 $session->param( 'lasttime',     time() );
1510             }
1511             C4::Context->set_userenv(
1512                 $session->param('number'),       $session->param('id'),
1513                 $session->param('cardnumber'),   $session->param('firstname'),
1514                 $session->param('surname'),      $session->param('branch'),
1515                 $session->param('branchname'),   $session->param('flags'),
1516                 $session->param('emailaddress'), $session->param('branchprinter')
1517             );
1518             return ( "ok", $cookie, $sessionID );
1519         } else {
1520             return ( "failed", undef, undef );
1521         }
1522     }
1523 }
1524
1525 =head2 check_cookie_auth
1526
1527   ($status, $sessionId) = check_api_auth($cookie, $userflags);
1528
1529 Given a CGISESSID cookie set during a previous login to Koha, determine
1530 if the user has the privileges specified by C<$userflags>.
1531
1532 C<check_cookie_auth> is meant for authenticating special services
1533 such as tools/upload-file.pl that are invoked by other pages that
1534 have been authenticated in the usual way.
1535
1536 Possible return values in C<$status> are:
1537
1538 =over
1539
1540 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1541
1542 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1543
1544 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1545
1546 =item "expired -- session cookie has expired; API user should resubmit userid and password
1547
1548 =back
1549
1550 =cut
1551
1552 sub check_cookie_auth {
1553     my $cookie        = shift;
1554     my $flagsrequired = shift;
1555
1556     my $dbh     = C4::Context->dbh;
1557     my $timeout = _timeout_syspref();
1558
1559     unless ( C4::Context->preference('Version') ) {
1560
1561         # database has not been installed yet
1562         return ( "maintenance", undef );
1563     }
1564     my $kohaversion = Koha::version();
1565     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1566     if ( C4::Context->preference('Version') < $kohaversion ) {
1567
1568         # database in need of version update; assume that
1569         # no API should be called while databsae is in
1570         # this condition.
1571         return ( "maintenance", undef );
1572     }
1573
1574     # FIXME -- most of what follows is a copy-and-paste
1575     # of code from checkauth.  There is an obvious need
1576     # for refactoring to separate the various parts of
1577     # the authentication code, but as of 2007-11-23 this
1578     # is deferred so as to not introduce bugs into the
1579     # regular authentication code for Koha 3.0.
1580
1581     # see if we have a valid session cookie already
1582     # however, if a userid parameter is present (i.e., from
1583     # a form submission, assume that any current cookie
1584     # is to be ignored
1585     unless ( defined $cookie and $cookie ) {
1586         return ( "failed", undef );
1587     }
1588     my $sessionID = $cookie;
1589     my $session   = get_session($sessionID);
1590     C4::Context->_new_userenv($sessionID);
1591     if ($session) {
1592         C4::Context->set_userenv(
1593             $session->param('number'),       $session->param('id'),
1594             $session->param('cardnumber'),   $session->param('firstname'),
1595             $session->param('surname'),      $session->param('branch'),
1596             $session->param('branchname'),   $session->param('flags'),
1597             $session->param('emailaddress'), $session->param('branchprinter')
1598         );
1599
1600         my $ip       = $session->param('ip');
1601         my $lasttime = $session->param('lasttime');
1602         my $userid   = $session->param('id');
1603         if ( $lasttime < time() - $timeout ) {
1604
1605             # time out
1606             $session->delete();
1607             $session->flush;
1608             C4::Context->_unset_userenv($sessionID);
1609             $userid    = undef;
1610             $sessionID = undef;
1611             return ("expired", undef);
1612         } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1613
1614             # IP address changed
1615             $session->delete();
1616             $session->flush;
1617             C4::Context->_unset_userenv($sessionID);
1618             $userid    = undef;
1619             $sessionID = undef;
1620             return ( "expired", undef );
1621         } else {
1622             $session->param( 'lasttime', time() );
1623             my $flags = haspermission( $userid, $flagsrequired );
1624             if ($flags) {
1625                 return ( "ok", $sessionID );
1626             } else {
1627                 $session->delete();
1628                 $session->flush;
1629                 C4::Context->_unset_userenv($sessionID);
1630                 $userid    = undef;
1631                 $sessionID = undef;
1632                 return ( "failed", undef );
1633             }
1634         }
1635     } else {
1636         return ( "expired", undef );
1637     }
1638 }
1639
1640 =head2 get_session
1641
1642   use CGI::Session;
1643   my $session = get_session($sessionID);
1644
1645 Given a session ID, retrieve the CGI::Session object used to store
1646 the session's state.  The session object can be used to store
1647 data that needs to be accessed by different scripts during a
1648 user's session.
1649
1650 If the C<$sessionID> parameter is an empty string, a new session
1651 will be created.
1652
1653 =cut
1654
1655 sub get_session {
1656     my $sessionID      = shift;
1657     my $storage_method = C4::Context->preference('SessionStorage');
1658     my $dbh            = C4::Context->dbh;
1659     my $session;
1660     if ( $storage_method eq 'mysql' ) {
1661         $session = new CGI::Session( "driver:MySQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1662     }
1663     elsif ( $storage_method eq 'Pg' ) {
1664         $session = new CGI::Session( "driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1665     }
1666     elsif ( $storage_method eq 'memcached' && C4::Context->ismemcached ) {
1667         $session = new CGI::Session( "driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1668     }
1669     else {
1670         # catch all defaults to tmp should work on all systems
1671         $session = new CGI::Session( "driver:File;serializer:yaml;id:md5", $sessionID, { Directory => '/tmp' } );
1672     }
1673     return $session;
1674 }
1675
1676 sub checkpw {
1677     my ( $dbh, $userid, $password, $query, $type ) = @_;
1678     $type = 'opac' unless $type;
1679     if ($ldap) {
1680         $debug and print STDERR "## checkpw - checking LDAP\n";
1681         my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_);    # EXTERNAL AUTH
1682         return 0 if $retval == -1;                                  # Incorrect password for LDAP login attempt
1683         ($retval) and return ( $retval, $retcard, $retuserid );
1684     }
1685
1686     if ( $cas && $query && $query->param('ticket') ) {
1687         $debug and print STDERR "## checkpw - checking CAS\n";
1688
1689         # In case of a CAS authentication, we use the ticket instead of the password
1690         my $ticket = $query->param('ticket');
1691         $query->delete('ticket');                                   # remove ticket to come back to original URL
1692         my ( $retval, $retcard, $retuserid ) = checkpw_cas( $dbh, $ticket, $query, $type );    # EXTERNAL AUTH
1693         ($retval) and return ( $retval, $retcard, $retuserid );
1694         return 0;
1695     }
1696
1697     # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1698     # Check for password to asertain whether we want to be testing against shibboleth or another method this
1699     # time around.
1700     if ( $shib && $shib_login && !$password ) {
1701
1702         $debug and print STDERR "## checkpw - checking Shibboleth\n";
1703
1704         # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1705         # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1706         # shibboleth-authenticated user
1707
1708         # Then, we check if it matches a valid koha user
1709         if ($shib_login) {
1710             my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login);    # EXTERNAL AUTH
1711             ($retval) and return ( $retval, $retcard, $retuserid );
1712             return 0;
1713         }
1714     }
1715
1716     # INTERNAL AUTH
1717     return checkpw_internal(@_)
1718 }
1719
1720 sub checkpw_internal {
1721     my ( $dbh, $userid, $password ) = @_;
1722
1723     $password = Encode::encode( 'UTF-8', $password )
1724       if Encode::is_utf8($password);
1725
1726     if ( $userid && $userid eq C4::Context->config('user') ) {
1727         if ( $password && $password eq C4::Context->config('pass') ) {
1728
1729             # Koha superuser account
1730             #     C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1731             return 2;
1732         }
1733         else {
1734             return 0;
1735         }
1736     }
1737
1738     my $sth =
1739       $dbh->prepare(
1740         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1741       );
1742     $sth->execute($userid);
1743     if ( $sth->rows ) {
1744         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1745             $surname, $branchcode, $branchname, $flags )
1746           = $sth->fetchrow;
1747
1748         if ( checkpw_hash( $password, $stored_hash ) ) {
1749
1750             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1751                 $firstname, $surname, $branchcode, $branchname, $flags );
1752             return 1, $cardnumber, $userid;
1753         }
1754     }
1755     $sth =
1756       $dbh->prepare(
1757         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1758       );
1759     $sth->execute($userid);
1760     if ( $sth->rows ) {
1761         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1762             $surname, $branchcode, $branchname, $flags )
1763           = $sth->fetchrow;
1764
1765         if ( checkpw_hash( $password, $stored_hash ) ) {
1766
1767             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1768                 $firstname, $surname, $branchcode, $branchname, $flags );
1769             return 1, $cardnumber, $userid;
1770         }
1771     }
1772     if ( $userid && $userid eq 'demo'
1773         && "$password" eq 'demo'
1774         && C4::Context->config('demo') )
1775     {
1776
1777         # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1778         # some features won't be effective : modify systempref, modify MARC structure,
1779         return 2;
1780     }
1781     return 0;
1782 }
1783
1784 sub checkpw_hash {
1785     my ( $password, $stored_hash ) = @_;
1786
1787     return if $stored_hash eq '!';
1788
1789     # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1790     my $hash;
1791     if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1792         $hash = hash_password( $password, $stored_hash );
1793     } else {
1794         $hash = md5_base64($password);
1795     }
1796     return $hash eq $stored_hash;
1797 }
1798
1799 =head2 getuserflags
1800
1801     my $authflags = getuserflags($flags, $userid, [$dbh]);
1802
1803 Translates integer flags into permissions strings hash.
1804
1805 C<$flags> is the integer userflags value ( borrowers.userflags )
1806 C<$userid> is the members.userid, used for building subpermissions
1807 C<$authflags> is a hashref of permissions
1808
1809 =cut
1810
1811 sub getuserflags {
1812     my $flags  = shift;
1813     my $userid = shift;
1814     my $dbh    = @_ ? shift : C4::Context->dbh;
1815     my $userflags;
1816     {
1817         # I don't want to do this, but if someone logs in as the database
1818         # user, it would be preferable not to spam them to death with
1819         # numeric warnings. So, we make $flags numeric.
1820         no warnings 'numeric';
1821         $flags += 0;
1822     }
1823     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1824     $sth->execute;
1825
1826     while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1827         if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1828             $userflags->{$flag} = 1;
1829         }
1830         else {
1831             $userflags->{$flag} = 0;
1832         }
1833     }
1834
1835     # get subpermissions and merge with top-level permissions
1836     my $user_subperms = get_user_subpermissions($userid);
1837     foreach my $module ( keys %$user_subperms ) {
1838         next if $userflags->{$module} == 1;    # user already has permission for everything in this module
1839         $userflags->{$module} = $user_subperms->{$module};
1840     }
1841
1842     return $userflags;
1843 }
1844
1845 =head2 get_user_subpermissions
1846
1847   $user_perm_hashref = get_user_subpermissions($userid);
1848
1849 Given the userid (note, not the borrowernumber) of a staff user,
1850 return a hashref of hashrefs of the specific subpermissions
1851 accorded to the user.  An example return is
1852
1853  {
1854     tools => {
1855         export_catalog => 1,
1856         import_patrons => 1,
1857     }
1858  }
1859
1860 The top-level hash-key is a module or function code from
1861 userflags.flag, while the second-level key is a code
1862 from permissions.
1863
1864 The results of this function do not give a complete picture
1865 of the functions that a staff user can access; it is also
1866 necessary to check borrowers.flags.
1867
1868 =cut
1869
1870 sub get_user_subpermissions {
1871     my $userid = shift;
1872
1873     my $dbh = C4::Context->dbh;
1874     my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1875                              FROM user_permissions
1876                              JOIN permissions USING (module_bit, code)
1877                              JOIN userflags ON (module_bit = bit)
1878                              JOIN borrowers USING (borrowernumber)
1879                              WHERE userid = ?" );
1880     $sth->execute($userid);
1881
1882     my $user_perms = {};
1883     while ( my $perm = $sth->fetchrow_hashref ) {
1884         $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1885     }
1886     return $user_perms;
1887 }
1888
1889 =head2 get_all_subpermissions
1890
1891   my $perm_hashref = get_all_subpermissions();
1892
1893 Returns a hashref of hashrefs defining all specific
1894 permissions currently defined.  The return value
1895 has the same structure as that of C<get_user_subpermissions>,
1896 except that the innermost hash value is the description
1897 of the subpermission.
1898
1899 =cut
1900
1901 sub get_all_subpermissions {
1902     my $dbh = C4::Context->dbh;
1903     my $sth = $dbh->prepare( "SELECT flag, code, description
1904                              FROM permissions
1905                              JOIN userflags ON (module_bit = bit)" );
1906     $sth->execute();
1907
1908     my $all_perms = {};
1909     while ( my $perm = $sth->fetchrow_hashref ) {
1910         $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = $perm->{'description'};
1911     }
1912     return $all_perms;
1913 }
1914
1915 =head2 haspermission
1916
1917   $flags = ($userid, $flagsrequired);
1918
1919 C<$userid> the userid of the member
1920 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}> 
1921
1922 Returns member's flags or 0 if a permission is not met.
1923
1924 =cut
1925
1926 sub haspermission {
1927     my ( $userid, $flagsrequired ) = @_;
1928     my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1929     $sth->execute($userid);
1930     my $row = $sth->fetchrow();
1931     my $flags = getuserflags( $row, $userid );
1932     if ( $userid eq C4::Context->config('user') ) {
1933
1934         # Super User Account from /etc/koha.conf
1935         $flags->{'superlibrarian'} = 1;
1936     }
1937     elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1938
1939         # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1940         $flags->{'superlibrarian'} = 1;
1941     }
1942
1943     return $flags if $flags->{superlibrarian};
1944
1945     foreach my $module ( keys %$flagsrequired ) {
1946         my $subperm = $flagsrequired->{$module};
1947         if ( $subperm eq '*' ) {
1948             return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
1949         } else {
1950             return 0 unless (
1951                 ( defined $flags->{$module} and
1952                     $flags->{$module} == 1 )
1953                 or
1954                 ( ref( $flags->{$module} ) and
1955                     exists $flags->{$module}->{$subperm} and
1956                     $flags->{$module}->{$subperm} == 1 )
1957             );
1958         }
1959     }
1960     return $flags;
1961
1962     #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1963 }
1964
1965 sub getborrowernumber {
1966     my ($userid) = @_;
1967     my $userenv = C4::Context->userenv;
1968     if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
1969         return $userenv->{number};
1970     }
1971     my $dbh = C4::Context->dbh;
1972     for my $field ( 'userid', 'cardnumber' ) {
1973         my $sth =
1974           $dbh->prepare("select borrowernumber from borrowers where $field=?");
1975         $sth->execute($userid);
1976         if ( $sth->rows ) {
1977             my ($bnumber) = $sth->fetchrow;
1978             return $bnumber;
1979         }
1980     }
1981     return 0;
1982 }
1983
1984 END { }    # module clean-up code here (global destructor)
1985 1;
1986 __END__
1987
1988 =head1 SEE ALSO
1989
1990 CGI(3)
1991
1992 C4::Output(3)
1993
1994 Crypt::Eksblowfish::Bcrypt(3)
1995
1996 Digest::MD5(3)
1997
1998 =cut