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