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