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