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