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