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