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