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