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