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