]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
LP#1951318: API call to retrieve (publicly-visible) carousel contents
[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_bookbags if $path =~ m|opac/myopac/lists|;
272     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
273     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
274     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
275     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
276     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
277     return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
278     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
279     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
280     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
281     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
282     return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
283
284     return Apache2::Const::OK;
285 }
286
287
288 # -----------------------------------------------------------------------------
289 # Redirect to SSL equivalent of a given page
290 # -----------------------------------------------------------------------------
291 sub redirect_ssl {
292     my $self = shift;
293     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
294     return $self->generic_redirect($new_page);
295 }
296
297 # -----------------------------------------------------------------------------
298 # If an authnticated resource is requested w/o auth, redirect to the login page,
299 # then return to the originally requrested resource upon successful login.
300 # -----------------------------------------------------------------------------
301 sub redirect_auth {
302     my $self = shift;
303
304     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
305     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
306     my $sso_native = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
307
308     my $login_type = ($sso_enabled and !$sso_native) ? 'manual_shib_login' : 'login';
309     my $login_page = sprintf('%s://%s%s/%s',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root}, $login_type);
310     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
311     my $redirect_url = "$login_page?redirect_to=$redirect_to";
312
313     return $self->generic_redirect($redirect_url);
314 }
315
316 # -----------------------------------------------------------------------------
317 # Fall-through for loading a basic page
318 # -----------------------------------------------------------------------------
319 sub load_simple {
320     my ($self, $page) = @_;
321     $self->ctx->{page} = $page;
322     $self->ctx->{search_ou} = $self->_get_search_lib();
323
324     return Apache2::Const::OK;
325 }
326
327 # -----------------------------------------------------------------------------
328 # Tests to see if the user is authenticated and sets some common context values
329 # -----------------------------------------------------------------------------
330 sub load_common {
331     my $self = shift;
332
333     my $e = $self->editor;
334     my $ctx = $self->ctx;
335
336     # redirect non-https to https if we think we are already logged in
337     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
338         return $self->redirect_ssl unless $self->cgi->https;
339     }
340
341     # XXX Cache this? Makes testing difficult as apache needs a restart.
342     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
343     $ctx->{default_sort} =
344         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
345
346     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
347     $ctx->{referer} = $self->cgi->referer;
348     $ctx->{path_info} = $self->cgi->path_info;
349     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
350     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
351     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
352
353     $ctx->{original_tz} = $ENV{TZ};
354     $ENV{TZ} = $ctx->{client_tz};
355
356     my $xul_wrapper = 
357         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
358
359     if ($xul_wrapper) {
360         # XUL client
361         $ctx->{is_staff} = 1;
362         $ctx->{proto} = 'oils';
363         $ctx->{hostname} = 'remote';
364     }
365
366     $ctx->{carousel_loc} = $self->get_carousel_loc;
367     $ctx->{physical_loc} = $self->get_physical_loc;
368     my $geo_sort = $e->retrieve_config_global_flag('opac.use_geolocation');
369     $geo_sort = ($geo_sort && $U->is_true($geo_sort->enabled));
370     my $geo_org = $ctx->{physical_loc} || $self->cgi->param('loc') || $ctx->{aou_tree}->()->id;
371     my $geo_sort_for_org = $ctx->{get_org_setting}->($geo_org, 'opac.holdings_sort_by_geographic_proximity');
372     $ctx->{geo_sort} = $geo_sort && $U->is_true($geo_sort_for_org);
373
374     # capture some commonly accessed pages
375     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
376     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
377
378     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
379
380         if($e->checkauth) {
381
382             $ctx->{authtoken} = $e->authtoken;
383             $ctx->{authtime} = $e->authtime;
384             $ctx->{user} = $e->requestor;
385             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
386             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
387             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
388
389             # The browser client does not set an OILS-Wrapper header (above).
390             # The presence of a workstation and no header indicates staff mode.
391             # FIXME: this approach leaves un-wrapped TPAC's within the same
392             # browser (and hence same ses cookie) in an unnatural is_staff
393             # state.  Consider alternatives for determining is_staff / 
394             # is_browser_staff when $xul_wrapper is false.
395             if (!$xul_wrapper and $e->requestor->wsid) {
396                 $ctx->{is_staff} = 1;
397                 $ctx->{is_browser_staff} = 1;
398             }
399
400             $self->update_dashboard_stats();
401
402         } else {
403
404             # if we encounter a stale authtoken, call load_logout 
405             # to clean up the cookie, then redirect the user to the
406             # originally requested page
407             return $self->load_logout($self->apache->unparsed_uri);
408         }
409     }
410
411     # List of <meta> and <link> elements to populate
412     $ctx->{metalinks} = [];
413
414     $self->extract_copy_location_group_info;
415     $ctx->{search_ou} = $self->_get_search_lib();
416     if (!$ctx->{search_scope}) { # didn't get it from locg above in extract_...
417         $ctx->{search_scope} = $self->cgi->param('search_scope');
418         if ($ctx->{search_scope} =~ /^lasso\(([^)]+)\)/) {
419             $ctx->{search_lasso} = $1; # make it visible to basic search
420         }
421     }
422     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
423     $self->load_eg_cache_hash;
424     $self->load_copy_location_groups;
425     $self->load_my_hold_subscriptions;
426     $self->load_hold_subscriptions if $ctx->{is_staff};
427     $self->load_lassos;
428     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
429     $self->load_search_filter_groups($ctx->{search_ou});
430     $self->load_org_util_funcs;
431     $self->load_perm_funcs;
432
433     $ctx->{get_visible_carousels} = sub {
434         my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
435         return $U->simplereq(
436             'open-ils.actor',
437             'open-ils.actor.carousel.retrieve_by_org',
438             $org_unit
439         );
440     };
441     $ctx->{get_carousel} = sub {
442         my $id = shift;
443         return $U->simplereq(
444             'open-ils.actor',
445             'open-ils.actor.carousel.get_contents',
446             $id
447         );
448     };
449
450     $ctx->{fetch_display_fields} = sub {
451         my $id = shift;
452
453         if (@$id == 1) {
454             return $ctx->{_hl_data}{''.$$id[0]}
455                 if ($ctx->{_hl_data}{''.$$id[0]});
456         }
457
458         $self->timelog("HL data not cached, fetching from server.");
459
460         my $rows = $U->simplereq(
461             'open-ils.search', 
462             'open-ils.search.fetch.metabib.display_field.highlight',
463             $ctx->{query_struct}{additional_data}{highlight_map},
464             map {int($_)} @$id
465         );
466
467         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
468
469         return $rows;
470     };
471
472     $ctx->{course_ou} = int($self->cgi->param('locg')) || $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id;
473     $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
474
475     return Apache2::Const::OK;
476 }
477
478 sub update_dashboard_stats {
479     my $self = shift;
480
481     my $e = $self->editor;
482     my $ctx = $self->ctx;
483
484     $ctx->{user_stats} = $U->simplereq(
485         'open-ils.actor', 
486         'open-ils.actor.user.opac.vital_stats', 
487         $e->authtoken, $e->requestor->id);
488 }
489
490 sub staff_saved_searches_set_expansion_state {
491     my $self = shift;
492
493     my $param = $self->cgi->param('sss_expand');
494     my $value;
495     
496     if (defined $param) {
497         $value = ($param ? 1 : 0);
498         $self->apache->headers_out->add(
499             "Set-Cookie" => $self->cgi->cookie(
500                 -name => COOKIE_SSS_EXPAND,
501                 -path => $self->ctx->{base_path},
502                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
503                 -value => $value,
504                 -expires => undef
505             )
506         );
507     } else {
508         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
509     }
510
511     $self->ctx->{saved_searches_expanded} = $value;
512 }
513
514 # physical_loc (i.e. "original location") passed in as a URL 
515 # param will replace any existing physical_loc stored as a cookie.
516 # If specified via ENV that rules over all and we don't set cookies.
517 sub get_physical_loc {
518     my $self = shift;
519
520     return $ENV{physical_loc} if($ENV{physical_loc});
521
522     if(my $physical_loc = $self->cgi->param('physical_loc')) {
523         $self->apache->headers_out->add(
524             "Set-Cookie" => $self->cgi->cookie(
525                 -name => COOKIE_PHYSICAL_LOC,
526                 -path => $self->ctx->{base_path},
527                 -value => $physical_loc,
528                 -expires => undef
529             )
530         );
531         return $physical_loc;
532     }
533
534     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
535 }
536
537 sub get_carousel_loc {
538     my $self = shift;
539     return $self->cgi->param('carousel_loc') || $ENV{carousel_loc};
540 }
541
542 # -----------------------------------------------------------------------------
543 # Log in and redirect to the redirect_to URL (or home)
544 # -----------------------------------------------------------------------------
545 sub load_login {
546     my $self = shift;
547     my $cgi = $self->cgi;
548     my $ctx = $self->ctx;
549
550     $self->timelog("Load login begins");
551
552     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
553     $ctx->{sso_org} = $sso_org;
554     my $sso_enabled = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
555     my $sso_native = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
556     my $sso_eg_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.evergreen_matchpoint') || 'usrname';
557     my $sso_shib_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
558
559     $ctx->{page} = 'login';
560
561     my $username = $cgi->param('username') || '';
562     $username =~ s/\s//g;  # Remove blanks
563     my $password = $cgi->param('password');
564     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
565     my $persist = $cgi->param('persist');
566     my $client_tz = $cgi->param('client_tz');
567
568     my $sso_user_match_value;
569     my $response;
570     my $sso_logged_in;
571     $self->timelog("SSO is enabled") if ($sso_enabled);
572     if ($sso_enabled
573         and $sso_user_match_value = $ENV{$sso_shib_match}
574         and !$self->cgi->cookie(COOKIE_SHIB_LOGGEDOUT)
575     ) { # we have a shib session, and have not cleared a previous shib-login cookie
576         $self->timelog("Have an SSO user match value: $sso_user_match_value");
577
578         if ($sso_eg_match eq 'barcode') { # barcode is special
579             my $card = $self->editor->search_actor_card({barcode => $sso_user_match_value})->[0];
580             $sso_user_match_value = $card ? $card->usr : undef;
581             $sso_eg_match = 'id';
582         }
583
584         if ($sso_user_match_value && $sso_eg_match) {
585             my $user = $self->editor->search_actor_user({ $sso_eg_match => $sso_user_match_value })->[0];
586             if ($user) { # create a session
587                 $response = $U->simplereq(
588                     'open-ils.auth_internal',
589                     'open-ils.auth_internal.session.create',
590                     { user_id => $user->id, login_type => 'opac' }
591                 );
592                 $sso_logged_in = $response ? 1 : 0;
593             }
594         }
595
596         $self->timelog("Checked for SSO login");
597     }
598
599     if (!$sso_enabled || (!$response && $sso_native)) {
600         # initial log form only
601         return Apache2::Const::OK unless $username and $password;
602
603         my $auth_proxy_enabled = 0; # default false
604         try { # if the service is not running, just let this fail silently
605             $auth_proxy_enabled = $U->simplereq(
606                 'open-ils.auth_proxy',
607                 'open-ils.auth_proxy.enabled');
608         } catch Error with {};
609
610         $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
611
612         my $args = {
613             type => ($persist) ? 'persist' : 'opac',
614             org => $org_unit,
615             agent => 'opac'
616         };
617
618         my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
619
620         # To avoid surprises, default to "Barcodes start with digits"
621         $bc_regex = '^\d' unless $bc_regex;
622
623         if ($bc_regex and ($username =~ /$bc_regex/)) {
624             $args->{barcode} = $username;
625         } else {
626             $args->{username} = $username;
627         }
628
629         if (!$auth_proxy_enabled) {
630             my $seed = $U->simplereq(
631                 'open-ils.auth',
632                 'open-ils.auth.authenticate.init', $username);
633             $args->{password} = md5_hex($seed . md5_hex($password));
634             $response = $U->simplereq(
635                 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
636         } else {
637             $args->{password} = $password;
638             $response = $U->simplereq(
639                 'open-ils.auth_proxy',
640                 'open-ils.auth_proxy.login', $args);
641         }
642         $self->timelog("Checked password");
643     } else {
644         $response ||= OpenILS::Event->new( 'LOGIN_FAILED' ); # assume failure
645     }
646
647     if($U->event_code($response)) { 
648         # login failed, report the reason to the template
649         $ctx->{login_failed_event} = $response;
650         return Apache2::Const::OK;
651     }
652
653     # login succeeded, redirect as necessary
654
655     my $acct = $self->apache->unparsed_uri;
656     $acct =~ s|/login|/myopac/main|;
657
658     # both login-related cookies should expire at the same time
659     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
660
661     my $cookie_list = [
662         # contains the actual auth token and should be sent only over https
663         $cgi->cookie(
664             -name => COOKIE_SES,
665             -path => '/',
666             -secure => 1,
667             -value => $response->{payload}->{authtoken},
668             -expires => $login_cookie_expires
669         ),
670         # contains only a hint that we are logged in, and is used to
671         # trigger a redirect to https
672         $cgi->cookie(
673             -name => COOKIE_LOGGEDIN,
674             -path => '/',
675             -secure => 0,
676             -value => '1',
677             -expires => $login_cookie_expires
678         )
679     ];
680
681     if ($client_tz) {
682         # contains the client's tz, as passed by the client
683         # trigger a redirect to https
684         push @$cookie_list, $cgi->cookie(
685             -name => COOKIE_TZ,
686             -path => '/',
687             -secure => 0,
688             -value => $client_tz,
689             -expires => $login_cookie_expires
690         );
691     }
692
693     if ($sso_logged_in) {
694         # tells us if we're logged in via shib, so we can decide whether to try logging in again.
695         push @$cookie_list, $cgi->cookie(
696             -name => COOKIE_SHIB_LOGGEDOUT,
697             -path => '/',
698             -secure => 0,
699             -value => '0',
700             -expires => '-1h'
701         );
702         push @$cookie_list, $cgi->cookie(
703             -name => COOKIE_SHIB_LOGGEDIN,
704             -path => '/',
705             -secure => 0,
706             -value => '1',
707             -expires => $login_cookie_expires
708         );
709     }
710
711     return $self->generic_redirect(
712         $cgi->param('redirect_to') || $acct,
713         $cookie_list
714     );
715 }
716
717 sub load_manual_shib_login {
718     my $self = shift;
719     my $redirect_to = shift || $self->cgi->param('redirect_to');
720
721     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
722     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
723     my $sso_shib_match = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
724
725     return $self->load_login if ($ENV{$sso_shib_match});
726
727     my $url = '/Shibboleth.sso/Login?target=' . ($redirect_to || $self->ctx->{home_page});
728     if ($sso_entity_id) {
729         $url .= '&entityID=' . $sso_entity_id;
730     }
731
732     return $self->generic_redirect( $url,
733         [
734             $self->cgi->cookie(
735                 -name => COOKIE_SHIB_LOGGEDOUT,
736                 -path => '/',
737                 -value => '0',
738                 -expires => '-1h'
739             )
740         ]
741     );
742 }
743
744 # -----------------------------------------------------------------------------
745 # Log out and redirect to the home page
746 # -----------------------------------------------------------------------------
747 sub load_logout {
748     my $self = shift;
749     my $redirect_to = shift || $self->cgi->param('redirect_to');
750     my $active_logout = $self->cgi->param('active_logout');
751
752     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
753     $self->ctx->{sso_org} = $sso_org;
754     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
755     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
756     my $sso_logout = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.logout');
757     if ($sso_enabled && $sso_logout) {
758         $redirect_to = '/Shibboleth.sso/Logout?return=' . ($redirect_to || $self->ctx->{home_page});
759         if ($sso_entity_id) {
760             $redirect_to .= '&entityID=' . $sso_entity_id;
761         }
762     }
763
764     # If the user was adding anyting to an anonymous cache 
765     # while logged in, go ahead and clear it out.
766     $self->clear_anon_cache;
767
768     try { # a missing auth token will cause an ugly explosion
769         $U->simplereq(
770             'open-ils.auth',
771             'open-ils.auth.session.delete',
772             $self->cgi->cookie(COOKIE_SES)
773         );
774     } catch Error with {};
775
776     return $self->generic_redirect(
777         $redirect_to || $self->ctx->{home_page},
778         [
779             # clear value of and expire both of these login-related cookies
780             $self->cgi->cookie(
781                 -name => COOKIE_SES,
782                 -path => '/',
783                 -value => '',
784                 -expires => '-1h'
785             ),
786             $self->cgi->cookie(
787                 -name => COOKIE_LOGGEDIN,
788                 -path => '/',
789                 -value => '',
790                 -expires => '-1h'
791             ),
792             ($active_logout ? ($self->cgi->cookie(
793                 -name => COOKIE_SHIB_LOGGEDOUT,
794                 -path => '/',
795                 -value => '1',
796                 -expires => '2147483647'
797             )) : ()),
798             $self->cgi->cookie(
799                 -name => COOKIE_SHIB_LOGGEDIN,
800                 -path => '/',
801                 -value => '0',
802                 -expires => '-1h'
803             )
804         ]
805     );
806 }
807
808 1;
809