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