View | Details | Raw Unified | Return to bug 13499
Collapse All | Expand All

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

Return to bug 13499