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