]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
LP2061136 - Stamping 1405 DB upgrade script
[working/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 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 = $self->ctx->{sso_org};
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
326     $self->ctx->{page} = $page;
327     $self->ctx->{search_ou} = $self->_get_search_lib();
328
329     return Apache2::Const::OK;
330 }
331
332 # -----------------------------------------------------------------------------
333 # Tests to see if the user is authenticated and sets some common context values
334 # -----------------------------------------------------------------------------
335 sub load_common {
336     my $self = shift;
337
338     my $e = $self->editor;
339     my $ctx = $self->ctx;
340
341     # redirect non-https to https if we think we are already logged in
342     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
343         return $self->redirect_ssl unless $self->cgi->https;
344     }
345
346     # XXX Cache this? Makes testing difficult as apache needs a restart.
347     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
348     $ctx->{default_sort} =
349         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
350
351     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
352     $ctx->{referer} = $self->cgi->referer;
353     $ctx->{path_info} = $self->cgi->path_info;
354     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
355     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
356     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
357
358     $ctx->{original_tz} = $ENV{TZ};
359     $ENV{TZ} = $ctx->{client_tz};
360
361     my $xul_wrapper = 
362         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
363
364     if ($xul_wrapper) {
365         # XUL client
366         $ctx->{is_staff} = 1;
367         $ctx->{proto} = 'oils';
368         $ctx->{hostname} = 'remote';
369     }
370
371     $ctx->{carousel_loc} = $self->get_carousel_loc;
372     $ctx->{physical_loc} = $self->get_physical_loc;
373     my $geo_sort = $e->retrieve_config_global_flag('opac.use_geolocation');
374     $geo_sort = ($geo_sort && $U->is_true($geo_sort->enabled));
375     my $geo_org = $ctx->{physical_loc} || $self->cgi->param('loc') || $ctx->{aou_tree}->()->id;
376     my $geo_sort_for_org = $ctx->{get_org_setting}->($geo_org, 'opac.holdings_sort_by_geographic_proximity');
377     $ctx->{geo_sort} = $geo_sort && $U->is_true($geo_sort_for_org);
378     my $part_required_flag = $e->retrieve_config_global_flag('circ.holds.api_require_monographic_part_when_present');
379     $part_required_flag = ($part_required_flag and $U->is_true($part_required_flag->enabled));
380     $ctx->{part_required_when_present_global_flag} = $part_required_flag;
381
382     # capture some commonly accessed pages
383     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
384     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
385
386     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
387
388         if($e->checkauth) {
389
390             $ctx->{authtoken} = $e->authtoken;
391             $ctx->{authtime} = $e->authtime;
392             $ctx->{user} = $e->requestor;
393             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
394             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
395             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
396
397             # The browser client does not set an OILS-Wrapper header (above).
398             # The presence of a workstation and no header indicates staff mode.
399             # FIXME: this approach leaves un-wrapped TPAC's within the same
400             # browser (and hence same ses cookie) in an unnatural is_staff
401             # state.  Consider alternatives for determining is_staff / 
402             # is_browser_staff when $xul_wrapper is false.
403             if (!$xul_wrapper and $e->requestor->wsid) {
404                 $ctx->{is_staff} = 1;
405                 $ctx->{is_browser_staff} = 1;
406             }
407
408             $self->update_dashboard_stats();
409
410         } else {
411
412             # if we encounter a stale authtoken, call load_logout 
413             # to clean up the cookie, then redirect the user to the
414             # originally requested page
415             return $self->load_logout($self->apache->unparsed_uri);
416         }
417     }
418
419     # List of <meta> and <link> elements to populate
420     $ctx->{metalinks} = [];
421
422     $self->extract_copy_location_group_info;
423     $ctx->{search_ou} = $self->_get_search_lib();
424     if (!$ctx->{search_scope}) { # didn't get it from locg above in extract_...
425         $ctx->{search_scope} = $self->cgi->param('search_scope');
426         if ($ctx->{search_scope} =~ /^lasso\(([^)]+)\)/) {
427             $ctx->{search_lasso} = $1; # make it visible to basic search
428         }
429     }
430     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
431     $self->load_eg_cache_hash;
432     $self->load_copy_location_groups;
433     $self->load_my_hold_subscriptions;
434     $self->load_hold_subscriptions if $ctx->{is_staff};
435     $self->load_lassos;
436     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
437     $self->load_search_filter_groups($ctx->{search_ou});
438     $self->load_org_util_funcs;
439     $self->load_perm_funcs;
440
441     $ctx->{get_visible_carousels} = sub {
442         my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
443         return $U->simplereq(
444             'open-ils.actor',
445             'open-ils.actor.carousel.retrieve_by_org',
446             $org_unit
447         );
448     };
449     $ctx->{get_carousel} = sub {
450         my $id = shift;
451         return $U->simplereq(
452             'open-ils.actor',
453             'open-ils.actor.carousel.get_contents',
454             $id
455         );
456     };
457
458     $ctx->{fetch_display_fields} = sub {
459         my $id = shift;
460
461         if (@$id == 1) {
462             return $ctx->{_hl_data}{''.$$id[0]}
463                 if ($ctx->{_hl_data}{''.$$id[0]});
464         }
465
466         $self->timelog("HL data not cached, fetching from server.");
467
468         my $rows = $U->simplereq(
469             'open-ils.search', 
470             'open-ils.search.fetch.metabib.display_field.highlight',
471             $ctx->{query_struct}{additional_data}{highlight_map},
472             map {int($_)} @$id
473         );
474
475         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
476
477         return $rows;
478     };
479
480     $ctx->{course_ou} = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
481     $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
482
483     $ctx->{sso_org} = $ENV{sso_loc} || $ctx->{physical_loc} || $ctx->{search_ou};
484
485     return Apache2::Const::OK;
486 }
487
488 sub update_dashboard_stats {
489     my $self = shift;
490
491     my $e = $self->editor;
492     my $ctx = $self->ctx;
493
494     $ctx->{user_stats} = $U->simplereq(
495         'open-ils.actor', 
496         'open-ils.actor.user.opac.vital_stats', 
497         $e->authtoken, $e->requestor->id);
498 }
499
500 sub staff_saved_searches_set_expansion_state {
501     my $self = shift;
502
503     my $param = $self->cgi->param('sss_expand');
504     my $value;
505     
506     if (defined $param) {
507         $value = ($param ? 1 : 0);
508         $self->apache->headers_out->add(
509             "Set-Cookie" => $self->cgi->cookie(
510                 -name => COOKIE_SSS_EXPAND,
511                 -path => $self->ctx->{base_path},
512                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
513                 -value => $value,
514                 -expires => undef
515             )
516         );
517     } else {
518         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
519     }
520
521     $self->ctx->{saved_searches_expanded} = $value;
522 }
523
524 # physical_loc (i.e. "original location") passed in as a URL 
525 # param will replace any existing physical_loc stored as a cookie.
526 # If specified via ENV that rules over all and we don't set cookies.
527 sub get_physical_loc {
528     my $self = shift;
529
530     return $ENV{physical_loc} if($ENV{physical_loc});
531
532     if(my $physical_loc = $self->cgi->param('physical_loc')) {
533         $self->apache->headers_out->add(
534             "Set-Cookie" => $self->cgi->cookie(
535                 -name => COOKIE_PHYSICAL_LOC,
536                 -path => $self->ctx->{base_path},
537                 -value => $physical_loc,
538                 -expires => undef
539             )
540         );
541         return $physical_loc;
542     }
543
544     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
545 }
546
547 sub get_carousel_loc {
548     my $self = shift;
549     return $self->cgi->param('carousel_loc') || $ENV{carousel_loc};
550 }
551
552 # -----------------------------------------------------------------------------
553 # Log in and redirect to the redirect_to URL (or home)
554 # -----------------------------------------------------------------------------
555 sub load_login {
556     my $self = shift;
557     my $cgi = $self->cgi;
558     my $ctx = $self->ctx;
559
560     $self->timelog("Load login begins");
561
562     my $sso_org = $ctx->{sso_org};
563
564     my $sso_enabled = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
565     my $sso_native = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
566     my $sso_eg_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.evergreen_matchpoint') || 'usrname';
567     my $sso_shib_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
568
569     $ctx->{page} = 'login';
570
571     my $username = $cgi->param('username') || '';
572     $username =~ s/\s//g;  # Remove blanks
573     my $password = $cgi->param('password');
574     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
575     my $persist = $cgi->param('persist');
576     my $client_tz = $cgi->param('client_tz');
577
578     my $sso_user_match_value = $ENV{$sso_shib_match};
579     my $response;
580     my $sso_logged_in;
581     $self->timelog("SSO is enabled") if ($sso_enabled);
582     if ($sso_enabled
583         and $sso_user_match_value
584         and (!$self->cgi->cookie(COOKIE_SHIB_LOGGEDOUT) or $self->{_ignore_shib_logged_out_cookie})
585     ) { # we have a shib session, and have not cleared a previous shib-login cookie
586         $self->{_ignore_shib_logged_out_cookie} = 0; # only set by an intermediate call that internally redirected here
587         $self->timelog("Have an SSO user match value: $sso_user_match_value");
588
589         if ($sso_eg_match eq 'barcode') { # barcode is special
590             my $card = $self->editor->search_actor_card({barcode => $sso_user_match_value})->[0];
591             $sso_user_match_value = $card ? $card->usr : undef;
592             $sso_eg_match = 'id';
593         }
594
595         if ($sso_user_match_value && $sso_eg_match) {
596             my $user = $self->editor->search_actor_user({ $sso_eg_match => $sso_user_match_value })->[0];
597             if ($user) { # create a session
598                 $response = $U->simplereq(
599                     'open-ils.auth_internal',
600                     'open-ils.auth_internal.session.create',
601                     { user_id => $user->id, login_type => 'opac' }
602                 );
603                 $sso_logged_in = $response ? 1 : 0;
604             }
605         }
606
607         $self->timelog("Checked for SSO login");
608     }
609
610     if (!$sso_enabled || (!$response && $sso_native)) {
611         # initial log form only
612         return Apache2::Const::OK unless $username and $password;
613
614         my $auth_proxy_enabled = 0; # default false
615         try { # if the service is not running, just let this fail silently
616             $auth_proxy_enabled = $U->simplereq(
617                 'open-ils.auth_proxy',
618                 'open-ils.auth_proxy.enabled');
619         } catch Error with {};
620
621         $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
622
623         my $args = {
624             type => ($persist) ? 'persist' : 'opac',
625             org => $org_unit,
626             agent => 'opac'
627         };
628
629         my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
630
631         # To avoid surprises, default to "Barcodes start with digits"
632         $bc_regex = '^\d' unless $bc_regex;
633
634         if ($bc_regex and ($username =~ /$bc_regex/)) {
635             $args->{barcode} = $username;
636         } else {
637             $args->{username} = $username;
638         }
639
640         if (!$auth_proxy_enabled) {
641             my $seed = $U->simplereq(
642                 'open-ils.auth',
643                 'open-ils.auth.authenticate.init', $username);
644             $args->{password} = md5_hex($seed . md5_hex($password));
645             $response = $U->simplereq(
646                 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
647         } else {
648             $args->{password} = $password;
649             $response = $U->simplereq(
650                 'open-ils.auth_proxy',
651                 'open-ils.auth_proxy.login', $args);
652         }
653         $self->timelog("Checked password");
654     } else {
655         $response ||= OpenILS::Event->new( 'LOGIN_FAILED' ); # assume failure
656     }
657
658     if($U->event_code($response)) { 
659         # login failed, report the reason to the template
660         $ctx->{login_failed_event} = $response;
661         return Apache2::Const::OK;
662     }
663
664     # login succeeded, redirect as necessary
665
666     my $acct = $self->apache->unparsed_uri;
667     $acct =~ s|/login|/myopac/main|;
668
669     # both login-related cookies should expire at the same time
670     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
671
672     my $cookie_list = [
673         # contains the actual auth token and should be sent only over https
674         $cgi->cookie(
675             -name => COOKIE_SES,
676             -path => '/',
677             -secure => 1,
678             -value => $response->{payload}->{authtoken},
679             -expires => $login_cookie_expires
680         ),
681         # contains only a hint that we are logged in, and is used to
682         # trigger a redirect to https
683         $cgi->cookie(
684             -name => COOKIE_LOGGEDIN,
685             -path => '/',
686             -secure => 0,
687             -value => '1',
688             -expires => $login_cookie_expires
689         )
690     ];
691
692     if ($client_tz) {
693         # contains the client's tz, as passed by the client
694         # trigger a redirect to https
695         push @$cookie_list, $cgi->cookie(
696             -name => COOKIE_TZ,
697             -path => '/',
698             -secure => 0,
699             -value => $client_tz,
700             -expires => $login_cookie_expires
701         );
702     }
703
704     if ($sso_logged_in) {
705         # tells us if we're logged in via shib, so we can decide whether to try logging in again.
706         push @$cookie_list, $cgi->cookie(
707             -name => COOKIE_SHIB_LOGGEDOUT,
708             -path => '/',
709             -secure => 0,
710             -value => '0',
711             -expires => '-1h'
712         );
713         push @$cookie_list, $cgi->cookie(
714             -name => COOKIE_SHIB_LOGGEDIN,
715             -path => '/',
716             -secure => 0,
717             -value => '1',
718             -expires => $login_cookie_expires
719         );
720     }
721
722     # TODO: maybe move this logic to generic_redirect()?
723     my $redirect_to = $cgi->param('redirect_to') || $acct;
724     if (my $login_redirect_gf = $self->editor->retrieve_config_global_flag('opac.login_redirect_domains')) {
725         if ($login_redirect_gf->enabled eq 't') {
726
727             my @redir_hosts = ();
728             if ($login_redirect_gf->value) {
729                 @redir_hosts = map { '(?:[^/.]+\.)*' . quotemeta($_) } grep { $_ } split(/,\s*/, $login_redirect_gf->value);
730             }
731             unshift @redir_hosts, quotemeta($ctx->{hostname});
732
733             my $hn = join('|', @redir_hosts);
734             my $relative_redir = qr#^(?:(?:(?:(?:f|ht)tps?:)?(?://(?:$hn))(?:/|$))|/$|/[^/]+)#;
735
736             if ($redirect_to !~ $relative_redir) {
737                 $logger->warn(
738                     "Login redirection of [$redirect_to] ".
739                     "disallowed based on Global Flag opac.".
740                     "login_redirect_domains RE [$relative_redir]"
741                 );
742                 $redirect_to = $acct; # fall back to myopac/main
743             }
744         }
745     }
746
747     return
748         $self->_perform_any_sso_required($response, $redirect_to, $cookie_list)
749         || $self->generic_redirect(
750             $redirect_to,
751             $cookie_list
752         );
753 }
754
755 sub load_manual_shib_login {
756     my $self = shift;
757     my $redirect_to = shift || $self->cgi->param('redirect_to');
758
759     my $sso_org = $self->ctx->{sso_org};
760     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
761     my $sso_shib_match = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
762
763
764     if ($ENV{$sso_shib_match}) {
765         $self->{_ignore_shib_logged_out_cookie} = 1;
766         return $self->load_login;
767     }
768
769     my $url = '/Shibboleth.sso/Login?target=' . ($redirect_to || $self->ctx->{home_page});
770     if ($sso_entity_id) {
771         $url .= '&entityID=' . $sso_entity_id;
772     }
773
774     return $self->generic_redirect( $url,
775         [
776             $self->cgi->cookie(
777                 -name => COOKIE_SHIB_LOGGEDOUT,
778                 -path => '/',
779                 -value => '0',
780                 -expires => '-1h'
781             )
782         ]
783     );
784 }
785
786 # -----------------------------------------------------------------------------
787 # Log out and redirect to the home page
788 # -----------------------------------------------------------------------------
789 sub load_logout {
790     my $self = shift;
791     my $redirect_to = shift || $self->cgi->param('redirect_to')
792         || $self->ctx->{home_page};
793     my $active_logout = $self->cgi->param('active_logout');
794
795     my $sso_org = $self->ctx->{sso_org};
796
797     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
798     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
799     my $sso_logout = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.logout');
800
801     # If using SSO, and actively logging out of EG /or/ opac.login.shib_sso.logout is true then
802     # log out of the SP (and, depending on Shib config, maybe the IdP or globally).
803     if ($sso_enabled and ($sso_logout or $active_logout)) {
804         $redirect_to = '/Shibboleth.sso/Logout?return=' . ($redirect_to || $self->ctx->{home_page});
805         if ($sso_entity_id) {
806             $redirect_to .= '&entityID=' . $sso_entity_id;
807         }
808     }
809
810     # If the user was adding anyting to an anonymous cache 
811     # while logged in, go ahead and clear it out.
812     $self->clear_anon_cache;
813
814     try { # a missing auth token will cause an ugly explosion
815         $U->simplereq(
816             'open-ils.auth',
817             'open-ils.auth.session.delete',
818             $self->cgi->cookie(COOKIE_SES)
819         );
820     } catch Error with {};
821
822     # clear value of and expire both of these login-related cookies
823     my $cookie_list = [
824         $self->cgi->cookie(
825             -name => COOKIE_SES,
826             -path => '/',
827             -value => '',
828             -expires => '-1h'
829         ),
830         $self->cgi->cookie(
831             -name => COOKIE_LOGGEDIN,
832             -path => '/',
833             -value => '',
834             -expires => '-1h'
835         ),
836         ($active_logout ? ($self->cgi->cookie(
837             -name => COOKIE_SHIB_LOGGEDOUT,
838             -path => '/',
839             -value => '1',
840             -expires => '2147483647'
841         )) : ()),
842         $self->cgi->cookie(
843             -name => COOKIE_SHIB_LOGGEDIN,
844             -path => '/',
845             -value => '0',
846             -expires => '-1h'
847         )
848     ];
849
850     return 
851         $self->_perform_any_sso_signout_required($redirect_to, $cookie_list)
852         || $self->generic_redirect(
853             $redirect_to,
854             $cookie_list
855         );
856 }
857
858 # -----------------------------------------------------------------------------
859 # Signs the user in to any third party services that their org unit is
860 # configured for.
861 # -----------------------------------------------------------------------------
862 sub _perform_any_sso_required {
863     my ($self, $auth_response, $redirect_to, $cookie_list) = @_;
864
865     return $self->perform_openathens_sso_if_required(
866         $auth_response,
867         $redirect_to,
868         $cookie_list
869     );
870 }
871
872 # -----------------------------------------------------------------------------
873 # Signs the user out of any third party services that their org unit is
874 # configured for.
875 # -----------------------------------------------------------------------------
876 sub _perform_any_sso_signout_required {
877     my ($self, $redirect_to, $cookie_list) = @_;
878
879     return $self->perform_openathens_signout_if_required(
880         $redirect_to,
881         $cookie_list
882     );
883 }
884
885 1;
886