]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
LP2045292 Color contrast for AngularJS patron bills
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use XML::LibXML;
4 use URI::Escape;
5 use Digest::MD5 qw(md5_hex);
6 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
7 use OpenSRF::AppSession;
8 use OpenSRF::EX qw/:try/;
9 use OpenILS::Utils::DateTime qw/:datetime/;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use OpenILS::Utils::Fieldmapper;
15 use OpenSRF::Utils::Cache;
16 use OpenILS::Event;
17 use DateTime::Format::ISO8601;
18 use CGI qw(:all -utf8);
19 use Time::HiRes;
20
21 # EGCatLoader sub-modules 
22 use OpenILS::WWW::EGCatLoader::Util;
23 use OpenILS::WWW::EGCatLoader::Account;
24 use OpenILS::WWW::EGCatLoader::Browse;
25 use OpenILS::WWW::EGCatLoader::Library;
26 use OpenILS::WWW::EGCatLoader::Search;
27 use OpenILS::WWW::EGCatLoader::Record;
28 use OpenILS::WWW::EGCatLoader::Course;
29 use OpenILS::WWW::EGCatLoader::Container;
30 use OpenILS::WWW::EGCatLoader::SMS;
31 use OpenILS::WWW::EGCatLoader::Register;
32
33 my $U = 'OpenILS::Application::AppUtils';
34
35 use constant COOKIE_SES => 'ses';
36 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
37 use constant COOKIE_SHIB_LOGGEDOUT => 'eg_shib_logged_out';
38 use constant COOKIE_SHIB_LOGGEDIN => 'eg_shib_logged_in';
39 use constant COOKIE_TZ => 'client_tz';
40 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
41 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
42
43 use constant COOKIE_ANON_CACHE => 'anoncache';
44 use constant COOKIE_CART_CACHE => 'cartcache';
45 use constant CART_CACHE_MYLIST => 'mylist';
46 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
47
48 use constant DEBUG_TIMING => 0;
49
50 sub new {
51     my($class, $apache, $ctx) = @_;
52
53     my $self = bless({}, ref($class) || $class);
54
55     $self->apache($apache);
56     $self->ctx($ctx);
57     $self->cgi(new CGI);
58     $self->timelog("New page");
59
60     # Add a timelog helper to the context
61     $self->ctx->{timelog} = sub { return $self->timelog(@_) };
62
63     OpenILS::Utils::CStoreEditor->init; # just in case
64     $self->editor(new_editor());
65
66     return $self;
67 }
68
69 sub DESTROY {
70     my $self = shift;
71     $ENV{TZ} = $self->ctx->{original_tz}
72         if ($self->ctx && exists $self->ctx->{original_tz});
73 }
74
75 # current Apache2::RequestRec;
76 sub apache {
77     my($self, $apache) = @_;
78     $self->{apache} = $apache if $apache;
79     return $self->{apache};
80 }
81
82 # runtime / template context
83 sub ctx {
84     my($self, $ctx) = @_;
85     $self->{ctx} = $ctx if $ctx;
86     return $self->{ctx};
87 }
88
89 # cstore editor
90 sub editor {
91     my($self, $editor) = @_;
92     $self->{editor} = $editor if $editor;
93     return $self->{editor};
94 }
95
96 # CGI handle
97 sub cgi {
98     my($self, $cgi) = @_;
99     $self->{cgi} = $cgi if $cgi;
100     return $self->{cgi};
101 }
102
103 sub timelog {
104     my($self, $description) = @_;
105
106     return unless DEBUG_TIMING;
107     return unless $description;
108     $self->ctx->{timing} ||= [];
109     
110     my $timer = [Time::HiRes::gettimeofday()];
111     $self->ctx->{time_begin} ||= $timer;
112
113     push @{$self->ctx->{timing}}, [
114         Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
115     ];
116 }
117
118 # -----------------------------------------------------------------------------
119 # Perform initial setup, load common data, then load page data
120 # -----------------------------------------------------------------------------
121 sub load {
122     my $self = shift;
123
124     $self->init_ro_object_cache;
125     $self->timelog("Initial load");
126
127     my $stat = $self->load_common;
128     return $stat unless $stat == Apache2::Const::OK;
129
130     my $path = $self->apache->path_info;
131
132     if ($path =~ m|opac/?$|) {
133         # nowhere specified, just go home
134         return $self->generic_redirect($self->ctx->{home_page});
135     }
136
137     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
138         $path =~ /opac\/my(opac\/lists|list)/ ||
139         $path =~ m!opac/api/mylist!;
140
141     my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('context_org') || $self->_get_search_lib;
142     $self->ctx->{selected_print_email_loc} = $org_unit;
143
144     return $self->load_api_mylist_retrieve if $path =~ m|opac/api/mylist/retrieve|;
145     return $self->load_api_mylist_add if $path =~ m|opac/api/mylist/add|;
146     return $self->load_api_mylist_delete if $path =~ m|opac/api/mylist/delete|;
147     return $self->load_api_mylist_clear if $path =~ m|opac/api/mylist/clear|;
148
149     return $self->load_simple("home") if $path =~ m|opac/home|;
150     return $self->load_simple("css") if $path =~ m|opac/css|;
151     return $self->load_cresults if $path =~ m|opac/course/results|;
152     return $self->load_simple("course_search") if $path =~ m|opac/course_search|;
153     return $self->load_simple("advanced") if
154         $path =~ m:opac/(advanced|numeric|expert):;
155
156     return $self->load_library if $path =~ m|opac/library|;
157     return $self->load_rresults if $path =~ m|opac/results|;
158     return $self->load_print_or_email_preview('print') if $path =~ m|opac/record/print_preview|;
159     return $self->load_print_record if $path =~ m|opac/record/print|;
160     return $self->load_record if $path =~ m|opac/record/\d|;
161     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
162     return $self->load_browse if $path =~ m|opac/browse|;
163     return $self->load_course_browse if $path =~ m|opac/course_browse|;
164     return $self->load_course if $path =~ m|opac/course|;
165
166     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
167     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
168     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
169     return $self->load_mylist_print if $path =~ m|opac/mylist/doprint|;
170     return $self->load_mylist if $path =~ m|opac/mylist| && $path !~ m|opac/mylist/email| && $path !~ m|opac/mylist/doemail|;
171     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
172     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
173     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
174     return $self->load_simple("carousel") if $path =~ m|opac/carousel|;
175
176     # ----------------------------------------------------------------
177     #  Everything below here requires SSL
178     # ----------------------------------------------------------------
179     return $self->redirect_ssl unless $self->cgi->https;
180     return $self->load_password_reset if $path =~ m|opac/password_reset|;
181     return $self->load_logout if $path =~ m|opac/logout|;
182     return $self->load_patron_reg if $path =~ m|opac/register|;
183
184     $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
185
186     if($path =~ m|opac/login|) {
187         return $self->load_login unless $self->editor->requestor; # already logged in?
188
189         # This will be less confusing to users than to be shown a login form
190         # when they're already logged in.
191         return $self->generic_redirect(
192             sprintf(
193                 "%s://%s%s/myopac/main",
194                 $self->ctx->{proto},
195                 $self->ctx->{hostname}, $self->ctx->{opac_root}
196             )
197         );
198     }
199
200     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
201         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
202         return $self->load_sms_cn if $skip_sms_auth;
203     }
204
205     if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
206         if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
207             my $cache = OpenSRF::Utils::Cache->new('global');
208
209             if ($path !~ m|preview|) { # the real thing!
210                 $logger->info("not preview");
211                 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
212                 $logger->info("got cap_key $cap_key");
213                 if ($cap_key) {
214                     my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
215                     my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
216                     $logger->info("got answers $cap_answer $real_answer");
217                     return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
218                 }
219             }
220
221             my $captcha = {};
222             $$captcha{key} = time() . $$ . rand();
223             $$captcha{left} = int(rand(10));
224             $$captcha{right} = int(rand(10));
225             $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
226             $self->ctx->{captcha} = $captcha;
227             return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
228         }
229     }
230
231     return $self->load_manual_shib_login if $path =~ m|opac/manual_shib_login|;
232     # ----------------------------------------------------------------
233     #  Everything below here requires authentication
234     # ----------------------------------------------------------------
235     return $self->redirect_auth unless $self->editor->requestor;
236
237     # Don't cache anything requiring auth for security reasons
238     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
239     $self->apache->headers_out->add("expires" => "-1");
240
241     if ($path =~ m|opac/mylist/email|) {
242         (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
243     }
244     $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
245     return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
246     return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
247     return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
248     return $self->load_email_record if $path =~ m|opac/record/email|;
249     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
250
251     return $self->load_place_hold if $path =~ m|opac/place_hold|;
252  
253     # centralize check for curbside tab display
254     $self->load_current_curbside_libs;
255
256     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
257     return $self->load_myopac_hold_subscriptions if $path =~ m|opac/myopac/hold_subscriptions|;
258     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
259     return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
260     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
261     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
262     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
263     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
264     return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
265     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
266     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
267     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
268     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
269     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
270     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
271     return $self->load_myopac_update_locale if $path =~ m|opac/myopac/update_locale|;
272     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
273     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
274     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
275     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
276     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
277     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
278     return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
279     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
280     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
281     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
282     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
283     return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
284
285     return Apache2::Const::OK;
286 }
287
288
289 # -----------------------------------------------------------------------------
290 # Redirect to SSL equivalent of a given page
291 # -----------------------------------------------------------------------------
292 sub redirect_ssl {
293     my $self = shift;
294     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
295     return $self->generic_redirect($new_page);
296 }
297
298 # -----------------------------------------------------------------------------
299 # If an authnticated resource is requested w/o auth, redirect to the login page,
300 # then return to the originally requrested resource upon successful login.
301 # -----------------------------------------------------------------------------
302 sub redirect_auth {
303     my $self = shift;
304
305     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
306     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
307     my $sso_native = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
308
309     my $login_type = ($sso_enabled and !$sso_native) ? 'manual_shib_login' : 'login';
310     my $login_page = sprintf('%s://%s%s/%s',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root}, $login_type);
311     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
312     my $redirect_url = "$login_page?redirect_to=$redirect_to";
313
314     return $self->generic_redirect($redirect_url);
315 }
316
317 # -----------------------------------------------------------------------------
318 # Fall-through for loading a basic page
319 # -----------------------------------------------------------------------------
320 sub load_simple {
321     my ($self, $page) = @_;
322     $self->ctx->{page} = $page;
323     $self->ctx->{search_ou} = $self->_get_search_lib();
324
325     return Apache2::Const::OK;
326 }
327
328 # -----------------------------------------------------------------------------
329 # Tests to see if the user is authenticated and sets some common context values
330 # -----------------------------------------------------------------------------
331 sub load_common {
332     my $self = shift;
333
334     my $e = $self->editor;
335     my $ctx = $self->ctx;
336
337     # redirect non-https to https if we think we are already logged in
338     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
339         return $self->redirect_ssl unless $self->cgi->https;
340     }
341
342     # XXX Cache this? Makes testing difficult as apache needs a restart.
343     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
344     $ctx->{default_sort} =
345         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
346
347     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
348     $ctx->{referer} = $self->cgi->referer;
349     $ctx->{path_info} = $self->cgi->path_info;
350     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
351     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
352     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
353
354     $ctx->{original_tz} = $ENV{TZ};
355     $ENV{TZ} = $ctx->{client_tz};
356
357     my $xul_wrapper = 
358         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
359
360     if ($xul_wrapper) {
361         # XUL client
362         $ctx->{is_staff} = 1;
363         $ctx->{proto} = 'oils';
364         $ctx->{hostname} = 'remote';
365     }
366
367     $ctx->{carousel_loc} = $self->get_carousel_loc;
368     $ctx->{physical_loc} = $self->get_physical_loc;
369     my $geo_sort = $e->retrieve_config_global_flag('opac.use_geolocation');
370     $geo_sort = ($geo_sort && $U->is_true($geo_sort->enabled));
371     my $geo_org = $ctx->{physical_loc} || $self->cgi->param('loc') || $ctx->{aou_tree}->()->id;
372     my $geo_sort_for_org = $ctx->{get_org_setting}->($geo_org, 'opac.holdings_sort_by_geographic_proximity');
373     $ctx->{geo_sort} = $geo_sort && $U->is_true($geo_sort_for_org);
374
375     # capture some commonly accessed pages
376     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
377     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
378
379     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
380
381         if($e->checkauth) {
382
383             $ctx->{authtoken} = $e->authtoken;
384             $ctx->{authtime} = $e->authtime;
385             $ctx->{user} = $e->requestor;
386             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
387             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
388             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
389
390             # The browser client does not set an OILS-Wrapper header (above).
391             # The presence of a workstation and no header indicates staff mode.
392             # FIXME: this approach leaves un-wrapped TPAC's within the same
393             # browser (and hence same ses cookie) in an unnatural is_staff
394             # state.  Consider alternatives for determining is_staff / 
395             # is_browser_staff when $xul_wrapper is false.
396             if (!$xul_wrapper and $e->requestor->wsid) {
397                 $ctx->{is_staff} = 1;
398                 $ctx->{is_browser_staff} = 1;
399             }
400
401             $self->update_dashboard_stats();
402
403         } else {
404
405             # if we encounter a stale authtoken, call load_logout 
406             # to clean up the cookie, then redirect the user to the
407             # originally requested page
408             return $self->load_logout($self->apache->unparsed_uri);
409         }
410     }
411
412     # List of <meta> and <link> elements to populate
413     $ctx->{metalinks} = [];
414
415     $self->extract_copy_location_group_info;
416     $ctx->{search_ou} = $self->_get_search_lib();
417     if (!$ctx->{search_scope}) { # didn't get it from locg above in extract_...
418         $ctx->{search_scope} = $self->cgi->param('search_scope');
419         if ($ctx->{search_scope} =~ /^lasso\(([^)]+)\)/) {
420             $ctx->{search_lasso} = $1; # make it visible to basic search
421         }
422     }
423     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
424     $self->load_eg_cache_hash;
425     $self->load_copy_location_groups;
426     $self->load_my_hold_subscriptions;
427     $self->load_hold_subscriptions if $ctx->{is_staff};
428     $self->load_lassos;
429     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
430     $self->load_search_filter_groups($ctx->{search_ou});
431     $self->load_org_util_funcs;
432     $self->load_perm_funcs;
433
434     $ctx->{get_visible_carousels} = sub {
435         my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
436         return $U->simplereq(
437             'open-ils.actor',
438             'open-ils.actor.carousel.retrieve_by_org',
439             $org_unit
440         );
441     };
442     $ctx->{get_carousel} = sub {
443         my $id = shift;
444         return $U->simplereq(
445             'open-ils.actor',
446             'open-ils.actor.carousel.get_contents',
447             $id
448         );
449     };
450
451     $ctx->{fetch_display_fields} = sub {
452         my $id = shift;
453
454         if (@$id == 1) {
455             return $ctx->{_hl_data}{''.$$id[0]}
456                 if ($ctx->{_hl_data}{''.$$id[0]});
457         }
458
459         $self->timelog("HL data not cached, fetching from server.");
460
461         my $rows = $U->simplereq(
462             'open-ils.search', 
463             'open-ils.search.fetch.metabib.display_field.highlight',
464             $ctx->{query_struct}{additional_data}{highlight_map},
465             map {int($_)} @$id
466         );
467
468         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
469
470         return $rows;
471     };
472
473     $ctx->{course_ou} = int($self->cgi->param('locg')) || $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id;
474     $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
475
476     return Apache2::Const::OK;
477 }
478
479 sub update_dashboard_stats {
480     my $self = shift;
481
482     my $e = $self->editor;
483     my $ctx = $self->ctx;
484
485     $ctx->{user_stats} = $U->simplereq(
486         'open-ils.actor', 
487         'open-ils.actor.user.opac.vital_stats', 
488         $e->authtoken, $e->requestor->id);
489 }
490
491 sub staff_saved_searches_set_expansion_state {
492     my $self = shift;
493
494     my $param = $self->cgi->param('sss_expand');
495     my $value;
496     
497     if (defined $param) {
498         $value = ($param ? 1 : 0);
499         $self->apache->headers_out->add(
500             "Set-Cookie" => $self->cgi->cookie(
501                 -name => COOKIE_SSS_EXPAND,
502                 -path => $self->ctx->{base_path},
503                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
504                 -value => $value,
505                 -expires => undef
506             )
507         );
508     } else {
509         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
510     }
511
512     $self->ctx->{saved_searches_expanded} = $value;
513 }
514
515 # physical_loc (i.e. "original location") passed in as a URL 
516 # param will replace any existing physical_loc stored as a cookie.
517 # If specified via ENV that rules over all and we don't set cookies.
518 sub get_physical_loc {
519     my $self = shift;
520
521     return $ENV{physical_loc} if($ENV{physical_loc});
522
523     if(my $physical_loc = $self->cgi->param('physical_loc')) {
524         $self->apache->headers_out->add(
525             "Set-Cookie" => $self->cgi->cookie(
526                 -name => COOKIE_PHYSICAL_LOC,
527                 -path => $self->ctx->{base_path},
528                 -value => $physical_loc,
529                 -expires => undef
530             )
531         );
532         return $physical_loc;
533     }
534
535     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
536 }
537
538 sub get_carousel_loc {
539     my $self = shift;
540     return $self->cgi->param('carousel_loc') || $ENV{carousel_loc};
541 }
542
543 # -----------------------------------------------------------------------------
544 # Log in and redirect to the redirect_to URL (or home)
545 # -----------------------------------------------------------------------------
546 sub load_login {
547     my $self = shift;
548     my $cgi = $self->cgi;
549     my $ctx = $self->ctx;
550
551     $self->timelog("Load login begins");
552
553     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
554     $ctx->{sso_org} = $sso_org;
555     my $sso_enabled = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
556     my $sso_native = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
557     my $sso_eg_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.evergreen_matchpoint') || 'usrname';
558     my $sso_shib_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
559
560     $ctx->{page} = 'login';
561
562     my $username = $cgi->param('username') || '';
563     $username =~ s/\s//g;  # Remove blanks
564     my $password = $cgi->param('password');
565     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
566     my $persist = $cgi->param('persist');
567     my $client_tz = $cgi->param('client_tz');
568
569     my $sso_user_match_value;
570     my $response;
571     my $sso_logged_in;
572     $self->timelog("SSO is enabled") if ($sso_enabled);
573     if ($sso_enabled
574         and $sso_user_match_value = $ENV{$sso_shib_match}
575         and !$self->cgi->cookie(COOKIE_SHIB_LOGGEDOUT)
576     ) { # we have a shib session, and have not cleared a previous shib-login cookie
577         $self->timelog("Have an SSO user match value: $sso_user_match_value");
578
579         if ($sso_eg_match eq 'barcode') { # barcode is special
580             my $card = $self->editor->search_actor_card({barcode => $sso_user_match_value})->[0];
581             $sso_user_match_value = $card ? $card->usr : undef;
582             $sso_eg_match = 'id';
583         }
584
585         if ($sso_user_match_value && $sso_eg_match) {
586             my $user = $self->editor->search_actor_user({ $sso_eg_match => $sso_user_match_value })->[0];
587             if ($user) { # create a session
588                 $response = $U->simplereq(
589                     'open-ils.auth_internal',
590                     'open-ils.auth_internal.session.create',
591                     { user_id => $user->id, login_type => 'opac' }
592                 );
593                 $sso_logged_in = $response ? 1 : 0;
594             }
595         }
596
597         $self->timelog("Checked for SSO login");
598     }
599
600     if (!$sso_enabled || (!$response && $sso_native)) {
601         # initial log form only
602         return Apache2::Const::OK unless $username and $password;
603
604         my $auth_proxy_enabled = 0; # default false
605         try { # if the service is not running, just let this fail silently
606             $auth_proxy_enabled = $U->simplereq(
607                 'open-ils.auth_proxy',
608                 'open-ils.auth_proxy.enabled');
609         } catch Error with {};
610
611         $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
612
613         my $args = {
614             type => ($persist) ? 'persist' : 'opac',
615             org => $org_unit,
616             agent => 'opac'
617         };
618
619         my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
620
621         # To avoid surprises, default to "Barcodes start with digits"
622         $bc_regex = '^\d' unless $bc_regex;
623
624         if ($bc_regex and ($username =~ /$bc_regex/)) {
625             $args->{barcode} = $username;
626         } else {
627             $args->{username} = $username;
628         }
629
630         if (!$auth_proxy_enabled) {
631             my $seed = $U->simplereq(
632                 'open-ils.auth',
633                 'open-ils.auth.authenticate.init', $username);
634             $args->{password} = md5_hex($seed . md5_hex($password));
635             $response = $U->simplereq(
636                 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
637         } else {
638             $args->{password} = $password;
639             $response = $U->simplereq(
640                 'open-ils.auth_proxy',
641                 'open-ils.auth_proxy.login', $args);
642         }
643         $self->timelog("Checked password");
644     } else {
645         $response ||= OpenILS::Event->new( 'LOGIN_FAILED' ); # assume failure
646     }
647
648     if($U->event_code($response)) { 
649         # login failed, report the reason to the template
650         $ctx->{login_failed_event} = $response;
651         return Apache2::Const::OK;
652     }
653
654     # login succeeded, redirect as necessary
655
656     my $acct = $self->apache->unparsed_uri;
657     $acct =~ s|/login|/myopac/main|;
658
659     # both login-related cookies should expire at the same time
660     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
661
662     my $cookie_list = [
663         # contains the actual auth token and should be sent only over https
664         $cgi->cookie(
665             -name => COOKIE_SES,
666             -path => '/',
667             -secure => 1,
668             -value => $response->{payload}->{authtoken},
669             -expires => $login_cookie_expires
670         ),
671         # contains only a hint that we are logged in, and is used to
672         # trigger a redirect to https
673         $cgi->cookie(
674             -name => COOKIE_LOGGEDIN,
675             -path => '/',
676             -secure => 0,
677             -value => '1',
678             -expires => $login_cookie_expires
679         )
680     ];
681
682     if ($client_tz) {
683         # contains the client's tz, as passed by the client
684         # trigger a redirect to https
685         push @$cookie_list, $cgi->cookie(
686             -name => COOKIE_TZ,
687             -path => '/',
688             -secure => 0,
689             -value => $client_tz,
690             -expires => $login_cookie_expires
691         );
692     }
693
694     if ($sso_logged_in) {
695         # tells us if we're logged in via shib, so we can decide whether to try logging in again.
696         push @$cookie_list, $cgi->cookie(
697             -name => COOKIE_SHIB_LOGGEDOUT,
698             -path => '/',
699             -secure => 0,
700             -value => '0',
701             -expires => '-1h'
702         );
703         push @$cookie_list, $cgi->cookie(
704             -name => COOKIE_SHIB_LOGGEDIN,
705             -path => '/',
706             -secure => 0,
707             -value => '1',
708             -expires => $login_cookie_expires
709         );
710     }
711
712     return $self->generic_redirect(
713         $cgi->param('redirect_to') || $acct,
714         $cookie_list
715     );
716 }
717
718 sub load_manual_shib_login {
719     my $self = shift;
720     my $redirect_to = shift || $self->cgi->param('redirect_to');
721
722     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
723     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
724     my $sso_shib_match = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
725
726     return $self->load_login if ($ENV{$sso_shib_match});
727
728     my $url = '/Shibboleth.sso/Login?target=' . ($redirect_to || $self->ctx->{home_page});
729     if ($sso_entity_id) {
730         $url .= '&entityID=' . $sso_entity_id;
731     }
732
733     return $self->generic_redirect( $url,
734         [
735             $self->cgi->cookie(
736                 -name => COOKIE_SHIB_LOGGEDOUT,
737                 -path => '/',
738                 -value => '0',
739                 -expires => '-1h'
740             )
741         ]
742     );
743 }
744
745 # -----------------------------------------------------------------------------
746 # Log out and redirect to the home page
747 # -----------------------------------------------------------------------------
748 sub load_logout {
749     my $self = shift;
750     my $redirect_to = shift || $self->cgi->param('redirect_to');
751     my $active_logout = $self->cgi->param('active_logout');
752
753     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
754     $self->ctx->{sso_org} = $sso_org;
755     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
756     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
757     my $sso_logout = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.logout');
758     if ($sso_enabled && $sso_logout) {
759         $redirect_to = '/Shibboleth.sso/Logout?return=' . ($redirect_to || $self->ctx->{home_page});
760         if ($sso_entity_id) {
761             $redirect_to .= '&entityID=' . $sso_entity_id;
762         }
763     }
764
765     # If the user was adding anyting to an anonymous cache 
766     # while logged in, go ahead and clear it out.
767     $self->clear_anon_cache;
768
769     try { # a missing auth token will cause an ugly explosion
770         $U->simplereq(
771             'open-ils.auth',
772             'open-ils.auth.session.delete',
773             $self->cgi->cookie(COOKIE_SES)
774         );
775     } catch Error with {};
776
777     return $self->generic_redirect(
778         $redirect_to || $self->ctx->{home_page},
779         [
780             # clear value of and expire both of these login-related cookies
781             $self->cgi->cookie(
782                 -name => COOKIE_SES,
783                 -path => '/',
784                 -value => '',
785                 -expires => '-1h'
786             ),
787             $self->cgi->cookie(
788                 -name => COOKIE_LOGGEDIN,
789                 -path => '/',
790                 -value => '',
791                 -expires => '-1h'
792             ),
793             ($active_logout ? ($self->cgi->cookie(
794                 -name => COOKIE_SHIB_LOGGEDOUT,
795                 -path => '/',
796                 -value => '1',
797                 -expires => '2147483647'
798             )) : ()),
799             $self->cgi->cookie(
800                 -name => COOKIE_SHIB_LOGGEDIN,
801                 -path => '/',
802                 -value => '0',
803                 -expires => '-1h'
804             )
805         ]
806     );
807 }
808
809 1;
810