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