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