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