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