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

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

Return to bug 13499