Bug 10080 - Change system pref IndependantBranches to IndependentBranches
[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( undef, undef, 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     );
1028
1029     $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1030     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1031
1032     if ($cas) {
1033
1034     # Is authentication against multiple CAS servers enabled?
1035         if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1036         my $casservers = C4::Auth_with_cas::getMultipleAuth();
1037         my @tmplservers;
1038         foreach my $key (keys %$casservers) {
1039         push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1040         }
1041         $template->param(
1042         casServersLoop => \@tmplservers
1043         );
1044     } else {
1045         $template->param(
1046             casServerUrl    => login_cas_url($query),
1047         );
1048     }
1049
1050     $template->param(
1051             invalidCasLogin => $info{'invalidCasLogin'}
1052         );
1053     }
1054
1055     my $self_url = $query->url( -absolute => 1 );
1056     $template->param(
1057         url         => $self_url,
1058         LibraryName => C4::Context->preference("LibraryName"),
1059     );
1060     $template->param( %info );
1061 #    $cookie = $query->cookie(CGISESSID => $session->id
1062 #   );
1063     print $query->header(
1064         -type   => 'text/html',
1065         -charset => 'utf-8',
1066         -cookie => $cookie
1067       ),
1068       $template->output;
1069     safe_exit;
1070 }
1071
1072 =head2 check_api_auth
1073
1074   ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1075
1076 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1077 cookie, determine if the user has the privileges specified by C<$userflags>.
1078
1079 C<check_api_auth> is is meant for authenticating users of web services, and
1080 consequently will always return and will not attempt to redirect the user
1081 agent.
1082
1083 If a valid session cookie is already present, check_api_auth will return a status
1084 of "ok", the cookie, and the Koha session ID.
1085
1086 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1087 parameters and create a session cookie and Koha session if the supplied credentials
1088 are OK.
1089
1090 Possible return values in C<$status> are:
1091
1092 =over
1093
1094 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1095
1096 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1097
1098 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1099
1100 =item "expired -- session cookie has expired; API user should resubmit userid and password
1101
1102 =back
1103
1104 =cut
1105
1106 sub check_api_auth {
1107     my $query = shift;
1108     my $flagsrequired = shift;
1109
1110     my $dbh     = C4::Context->dbh;
1111     my $timeout = _timeout_syspref();
1112
1113     unless (C4::Context->preference('Version')) {
1114         # database has not been installed yet
1115         return ("maintenance", undef, undef);
1116     }
1117     my $kohaversion=C4::Context::KOHAVERSION;
1118     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1119     if (C4::Context->preference('Version') < $kohaversion) {
1120         # database in need of version update; assume that
1121         # no API should be called while databsae is in
1122         # this condition.
1123         return ("maintenance", undef, undef);
1124     }
1125
1126     # FIXME -- most of what follows is a copy-and-paste
1127     # of code from checkauth.  There is an obvious need
1128     # for refactoring to separate the various parts of
1129     # the authentication code, but as of 2007-11-19 this
1130     # is deferred so as to not introduce bugs into the
1131     # regular authentication code for Koha 3.0.
1132
1133     # see if we have a valid session cookie already
1134     # however, if a userid parameter is present (i.e., from
1135     # a form submission, assume that any current cookie
1136     # is to be ignored
1137     my $sessionID = undef;
1138     unless ($query->param('userid')) {
1139         $sessionID = $query->cookie("CGISESSID");
1140     }
1141     if ($sessionID && not ($cas && $query->param('PT')) ) {
1142         my $session = get_session($sessionID);
1143         C4::Context->_new_userenv($sessionID);
1144         if ($session) {
1145             C4::Context::set_userenv(
1146                 $session->param('number'),       $session->param('id'),
1147                 $session->param('cardnumber'),   $session->param('firstname'),
1148                 $session->param('surname'),      $session->param('branch'),
1149                 $session->param('branchname'),   $session->param('flags'),
1150                 $session->param('emailaddress'), $session->param('branchprinter')
1151             );
1152
1153             my $ip = $session->param('ip');
1154             my $lasttime = $session->param('lasttime');
1155             my $userid = $session->param('id');
1156             if ( $lasttime < time() - $timeout ) {
1157                 # time out
1158                 $session->delete();
1159                 C4::Context->_unset_userenv($sessionID);
1160                 $userid    = undef;
1161                 $sessionID = undef;
1162                 return ("expired", undef, undef);
1163             } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1164                 # IP address changed
1165                 $session->delete();
1166                 C4::Context->_unset_userenv($sessionID);
1167                 $userid    = undef;
1168                 $sessionID = undef;
1169                 return ("expired", undef, undef);
1170             } else {
1171                 my $cookie = $query->cookie(
1172                     -name  => 'CGISESSID',
1173                     -value => $session->id,
1174                     -HttpOnly => 1,
1175                 );
1176                 $session->param('lasttime',time());
1177                 my $flags = haspermission($userid, $flagsrequired);
1178                 if ($flags) {
1179                     return ("ok", $cookie, $sessionID);
1180                 } else {
1181                     $session->delete();
1182                     C4::Context->_unset_userenv($sessionID);
1183                     $userid    = undef;
1184                     $sessionID = undef;
1185                     return ("failed", undef, undef);
1186                 }
1187             }
1188         } else {
1189             return ("expired", undef, undef);
1190         }
1191     } else {
1192         # new login
1193         my $userid = $query->param('userid');
1194         my $password = $query->param('password');
1195            my ($return, $cardnumber);
1196
1197     # Proxy CAS auth
1198     if ($cas && $query->param('PT')) {
1199         my $retuserid;
1200         $debug and print STDERR "## check_api_auth - checking CAS\n";
1201         # In case of a CAS authentication, we use the ticket instead of the password
1202         my $PT = $query->param('PT');
1203         ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query);    # EXTERNAL AUTH
1204     } else {
1205         # User / password auth
1206         unless ($userid and $password) {
1207         # caller did something wrong, fail the authenticateion
1208         return ("failed", undef, undef);
1209         }
1210         ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1211     }
1212
1213         if ($return and haspermission(  $userid, $flagsrequired)) {
1214             my $session = get_session("");
1215             return ("failed", undef, undef) unless $session;
1216
1217             my $sessionID = $session->id;
1218             C4::Context->_new_userenv($sessionID);
1219             my $cookie = $query->cookie(
1220                 -name  => 'CGISESSID',
1221                 -value => $sessionID,
1222                 -HttpOnly => 1,
1223             );
1224             if ( $return == 1 ) {
1225                 my (
1226                     $borrowernumber, $firstname,  $surname,
1227                     $userflags,      $branchcode, $branchname,
1228                     $branchprinter,  $emailaddress
1229                 );
1230                 my $sth =
1231                   $dbh->prepare(
1232 "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=?"
1233                   );
1234                 $sth->execute($userid);
1235                 (
1236                     $borrowernumber, $firstname,  $surname,
1237                     $userflags,      $branchcode, $branchname,
1238                     $branchprinter,  $emailaddress
1239                 ) = $sth->fetchrow if ( $sth->rows );
1240
1241                 unless ($sth->rows ) {
1242                     my $sth = $dbh->prepare(
1243 "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=?"
1244                       );
1245                     $sth->execute($cardnumber);
1246                     (
1247                         $borrowernumber, $firstname,  $surname,
1248                         $userflags,      $branchcode, $branchname,
1249                         $branchprinter,  $emailaddress
1250                     ) = $sth->fetchrow if ( $sth->rows );
1251
1252                     unless ( $sth->rows ) {
1253                         $sth->execute($userid);
1254                         (
1255                             $borrowernumber, $firstname, $surname, $userflags,
1256                             $branchcode, $branchname, $branchprinter, $emailaddress
1257                         ) = $sth->fetchrow if ( $sth->rows );
1258                     }
1259                 }
1260
1261                 my $ip       = $ENV{'REMOTE_ADDR'};
1262                 # if they specify at login, use that
1263                 if ($query->param('branch')) {
1264                     $branchcode  = $query->param('branch');
1265                     $branchname = GetBranchName($branchcode);
1266                 }
1267                 my $branches = GetBranches();
1268                 my @branchesloop;
1269                 foreach my $br ( keys %$branches ) {
1270                     #     now we work with the treatment of ip
1271                     my $domain = $branches->{$br}->{'branchip'};
1272                     if ( $domain && $ip =~ /^$domain/ ) {
1273                         $branchcode = $branches->{$br}->{'branchcode'};
1274
1275                         # new op dev : add the branchprinter and branchname in the cookie
1276                         $branchprinter = $branches->{$br}->{'branchprinter'};
1277                         $branchname    = $branches->{$br}->{'branchname'};
1278                     }
1279                 }
1280                 $session->param('number',$borrowernumber);
1281                 $session->param('id',$userid);
1282                 $session->param('cardnumber',$cardnumber);
1283                 $session->param('firstname',$firstname);
1284                 $session->param('surname',$surname);
1285                 $session->param('branch',$branchcode);
1286                 $session->param('branchname',$branchname);
1287                 $session->param('flags',$userflags);
1288                 $session->param('emailaddress',$emailaddress);
1289                 $session->param('ip',$session->remote_addr());
1290                 $session->param('lasttime',time());
1291             } elsif ( $return == 2 ) {
1292                 #We suppose the user is the superlibrarian
1293                 $session->param('number',0);
1294                 $session->param('id',C4::Context->config('user'));
1295                 $session->param('cardnumber',C4::Context->config('user'));
1296                 $session->param('firstname',C4::Context->config('user'));
1297                 $session->param('surname',C4::Context->config('user'));
1298                 $session->param('branch','NO_LIBRARY_SET');
1299                 $session->param('branchname','NO_LIBRARY_SET');
1300                 $session->param('flags',1);
1301                 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1302                 $session->param('ip',$session->remote_addr());
1303                 $session->param('lasttime',time());
1304             }
1305             C4::Context::set_userenv(
1306                 $session->param('number'),       $session->param('id'),
1307                 $session->param('cardnumber'),   $session->param('firstname'),
1308                 $session->param('surname'),      $session->param('branch'),
1309                 $session->param('branchname'),   $session->param('flags'),
1310                 $session->param('emailaddress'), $session->param('branchprinter')
1311             );
1312             return ("ok", $cookie, $sessionID);
1313         } else {
1314             return ("failed", undef, undef);
1315         }
1316     }
1317 }
1318
1319 =head2 check_cookie_auth
1320
1321   ($status, $sessionId) = check_api_auth($cookie, $userflags);
1322
1323 Given a CGISESSID cookie set during a previous login to Koha, determine
1324 if the user has the privileges specified by C<$userflags>.
1325
1326 C<check_cookie_auth> is meant for authenticating special services
1327 such as tools/upload-file.pl that are invoked by other pages that
1328 have been authenticated in the usual way.
1329
1330 Possible return values in C<$status> are:
1331
1332 =over
1333
1334 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1335
1336 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1337
1338 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1339
1340 =item "expired -- session cookie has expired; API user should resubmit userid and password
1341
1342 =back
1343
1344 =cut
1345
1346 sub check_cookie_auth {
1347     my $cookie = shift;
1348     my $flagsrequired = shift;
1349
1350     my $dbh     = C4::Context->dbh;
1351     my $timeout = _timeout_syspref();
1352
1353     unless (C4::Context->preference('Version')) {
1354         # database has not been installed yet
1355         return ("maintenance", undef);
1356     }
1357     my $kohaversion=C4::Context::KOHAVERSION;
1358     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1359     if (C4::Context->preference('Version') < $kohaversion) {
1360         # database in need of version update; assume that
1361         # no API should be called while databsae is in
1362         # this condition.
1363         return ("maintenance", undef);
1364     }
1365
1366     # FIXME -- most of what follows is a copy-and-paste
1367     # of code from checkauth.  There is an obvious need
1368     # for refactoring to separate the various parts of
1369     # the authentication code, but as of 2007-11-23 this
1370     # is deferred so as to not introduce bugs into the
1371     # regular authentication code for Koha 3.0.
1372
1373     # see if we have a valid session cookie already
1374     # however, if a userid parameter is present (i.e., from
1375     # a form submission, assume that any current cookie
1376     # is to be ignored
1377     unless (defined $cookie and $cookie) {
1378         return ("failed", undef);
1379     }
1380     my $sessionID = $cookie;
1381     my $session = get_session($sessionID);
1382     C4::Context->_new_userenv($sessionID);
1383     if ($session) {
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
1392         my $ip = $session->param('ip');
1393         my $lasttime = $session->param('lasttime');
1394         my $userid = $session->param('id');
1395         if ( $lasttime < time() - $timeout ) {
1396             # time out
1397             $session->delete();
1398             C4::Context->_unset_userenv($sessionID);
1399             $userid    = undef;
1400             $sessionID = undef;
1401             return ("expired", undef);
1402         } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1403             # IP address changed
1404             $session->delete();
1405             C4::Context->_unset_userenv($sessionID);
1406             $userid    = undef;
1407             $sessionID = undef;
1408             return ("expired", undef);
1409         } else {
1410             $session->param('lasttime',time());
1411             my $flags = haspermission($userid, $flagsrequired);
1412             if ($flags) {
1413                 return ("ok", $sessionID);
1414             } else {
1415                 $session->delete();
1416                 C4::Context->_unset_userenv($sessionID);
1417                 $userid    = undef;
1418                 $sessionID = undef;
1419                 return ("failed", undef);
1420             }
1421         }
1422     } else {
1423         return ("expired", undef);
1424     }
1425 }
1426
1427 =head2 get_session
1428
1429   use CGI::Session;
1430   my $session = get_session($sessionID);
1431
1432 Given a session ID, retrieve the CGI::Session object used to store
1433 the session's state.  The session object can be used to store
1434 data that needs to be accessed by different scripts during a
1435 user's session.
1436
1437 If the C<$sessionID> parameter is an empty string, a new session
1438 will be created.
1439
1440 =cut
1441
1442 sub get_session {
1443     my $sessionID = shift;
1444     my $storage_method = C4::Context->preference('SessionStorage');
1445     my $dbh = C4::Context->dbh;
1446     my $session;
1447     if ($storage_method eq 'mysql'){
1448         $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1449     }
1450     elsif ($storage_method eq 'Pg') {
1451         $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1452     }
1453     elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1454     $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1455     }
1456     else {
1457         # catch all defaults to tmp should work on all systems
1458         $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1459     }
1460     return $session;
1461 }
1462
1463 sub checkpw {
1464
1465     my ( $dbh, $userid, $password, $query ) = @_;
1466     if ($ldap) {
1467         $debug and print STDERR "## checkpw - checking LDAP\n";
1468         my ($retval,$retcard,$retuserid) = checkpw_ldap(@_);    # EXTERNAL AUTH
1469         ($retval) and return ($retval,$retcard,$retuserid);
1470     }
1471
1472     if ($cas && $query && $query->param('ticket')) {
1473         $debug and print STDERR "## checkpw - checking CAS\n";
1474     # In case of a CAS authentication, we use the ticket instead of the password
1475     my $ticket = $query->param('ticket');
1476         my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query);    # EXTERNAL AUTH
1477         ($retval) and return ($retval,$retcard,$retuserid);
1478     return 0;
1479     }
1480
1481     # INTERNAL AUTH
1482     my $sth =
1483       $dbh->prepare(
1484 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1485       );
1486     $sth->execute($userid);
1487     if ( $sth->rows ) {
1488         my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1489             $surname, $branchcode, $flags )
1490           = $sth->fetchrow;
1491         if ( md5_base64($password) eq $md5password and $md5password ne "!") {
1492
1493             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1494                 $firstname, $surname, $branchcode, $flags );
1495             return 1, $cardnumber, $userid;
1496         }
1497     }
1498     $sth =
1499       $dbh->prepare(
1500 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1501       );
1502     $sth->execute($userid);
1503     if ( $sth->rows ) {
1504         my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1505             $surname, $branchcode, $flags )
1506           = $sth->fetchrow;
1507         if ( md5_base64($password) eq $md5password ) {
1508
1509             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1510                 $firstname, $surname, $branchcode, $flags );
1511             return 1, $cardnumber, $userid;
1512         }
1513     }
1514     if (   $userid && $userid eq C4::Context->config('user')
1515         && "$password" eq C4::Context->config('pass') )
1516     {
1517
1518 # Koha superuser account
1519 #     C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1520         return 2;
1521     }
1522     if (   $userid && $userid eq 'demo'
1523         && "$password" eq 'demo'
1524         && C4::Context->config('demo') )
1525     {
1526
1527 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1528 # some features won't be effective : modify systempref, modify MARC structure,
1529         return 2;
1530     }
1531     return 0;
1532 }
1533
1534 =head2 getuserflags
1535
1536     my $authflags = getuserflags($flags, $userid, [$dbh]);
1537
1538 Translates integer flags into permissions strings hash.
1539
1540 C<$flags> is the integer userflags value ( borrowers.userflags )
1541 C<$userid> is the members.userid, used for building subpermissions
1542 C<$authflags> is a hashref of permissions
1543
1544 =cut
1545
1546 sub getuserflags {
1547     my $flags   = shift;
1548     my $userid  = shift;
1549     my $dbh     = @_ ? shift : C4::Context->dbh;
1550     my $userflags;
1551     {
1552         # I don't want to do this, but if someone logs in as the database
1553         # user, it would be preferable not to spam them to death with
1554         # numeric warnings. So, we make $flags numeric.
1555         no warnings 'numeric';
1556         $flags += 0;
1557     }
1558     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1559     $sth->execute;
1560
1561     while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1562         if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1563             $userflags->{$flag} = 1;
1564         }
1565         else {
1566             $userflags->{$flag} = 0;
1567         }
1568     }
1569
1570     # get subpermissions and merge with top-level permissions
1571     my $user_subperms = get_user_subpermissions($userid);
1572     foreach my $module (keys %$user_subperms) {
1573         next if $userflags->{$module} == 1; # user already has permission for everything in this module
1574         $userflags->{$module} = $user_subperms->{$module};
1575     }
1576
1577     return $userflags;
1578 }
1579
1580 =head2 get_user_subpermissions
1581
1582   $user_perm_hashref = get_user_subpermissions($userid);
1583
1584 Given the userid (note, not the borrowernumber) of a staff user,
1585 return a hashref of hashrefs of the specific subpermissions
1586 accorded to the user.  An example return is
1587
1588  {
1589     tools => {
1590         export_catalog => 1,
1591         import_patrons => 1,
1592     }
1593  }
1594
1595 The top-level hash-key is a module or function code from
1596 userflags.flag, while the second-level key is a code
1597 from permissions.
1598
1599 The results of this function do not give a complete picture
1600 of the functions that a staff user can access; it is also
1601 necessary to check borrowers.flags.
1602
1603 =cut
1604
1605 sub get_user_subpermissions {
1606     my $userid = shift;
1607
1608     my $dbh = C4::Context->dbh;
1609     my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1610                              FROM user_permissions
1611                              JOIN permissions USING (module_bit, code)
1612                              JOIN userflags ON (module_bit = bit)
1613                              JOIN borrowers USING (borrowernumber)
1614                              WHERE userid = ?");
1615     $sth->execute($userid);
1616
1617     my $user_perms = {};
1618     while (my $perm = $sth->fetchrow_hashref) {
1619         $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1620     }
1621     return $user_perms;
1622 }
1623
1624 =head2 get_all_subpermissions
1625
1626   my $perm_hashref = get_all_subpermissions();
1627
1628 Returns a hashref of hashrefs defining all specific
1629 permissions currently defined.  The return value
1630 has the same structure as that of C<get_user_subpermissions>,
1631 except that the innermost hash value is the description
1632 of the subpermission.
1633
1634 =cut
1635
1636 sub get_all_subpermissions {
1637     my $dbh = C4::Context->dbh;
1638     my $sth = $dbh->prepare("SELECT flag, code, description
1639                              FROM permissions
1640                              JOIN userflags ON (module_bit = bit)");
1641     $sth->execute();
1642
1643     my $all_perms = {};
1644     while (my $perm = $sth->fetchrow_hashref) {
1645         $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1646     }
1647     return $all_perms;
1648 }
1649
1650 =head2 haspermission
1651
1652   $flags = ($userid, $flagsrequired);
1653
1654 C<$userid> the userid of the member
1655 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}> 
1656
1657 Returns member's flags or 0 if a permission is not met.
1658
1659 =cut
1660
1661 sub haspermission {
1662     my ($userid, $flagsrequired) = @_;
1663     my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1664     $sth->execute($userid);
1665     my $flags = getuserflags($sth->fetchrow(), $userid);
1666     if ( $userid eq C4::Context->config('user') ) {
1667         # Super User Account from /etc/koha.conf
1668         $flags->{'superlibrarian'} = 1;
1669     }
1670     elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1671         # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1672         $flags->{'superlibrarian'} = 1;
1673     }
1674
1675     return $flags if $flags->{superlibrarian};
1676
1677     foreach my $module ( keys %$flagsrequired ) {
1678         my $subperm = $flagsrequired->{$module};
1679         if ($subperm eq '*') {
1680             return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1681         } else {
1682             return 0 unless ( $flags->{$module} == 1 or
1683                                 ( ref($flags->{$module}) and
1684                                   exists $flags->{$module}->{$subperm} and
1685                                   $flags->{$module}->{$subperm} == 1
1686                                 )
1687                             );
1688         }
1689     }
1690     return $flags;
1691     #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1692 }
1693
1694
1695 sub getborrowernumber {
1696     my ($userid) = @_;
1697     my $userenv = C4::Context->userenv;
1698     if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1699         return $userenv->{number};
1700     }
1701     my $dbh = C4::Context->dbh;
1702     for my $field ( 'userid', 'cardnumber' ) {
1703         my $sth =
1704           $dbh->prepare("select borrowernumber from borrowers where $field=?");
1705         $sth->execute($userid);
1706         if ( $sth->rows ) {
1707             my ($bnumber) = $sth->fetchrow;
1708             return $bnumber;
1709         }
1710     }
1711     return 0;
1712 }
1713
1714
1715 END { }    # module clean-up code here (global destructor)
1716 1;
1717 __END__
1718
1719 =head1 SEE ALSO
1720
1721 CGI(3)
1722
1723 C4::Output(3)
1724
1725 Digest::MD5(3)
1726
1727 =cut