]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
1c6cb78116ec28bf89f8fc455fbe729ae4548410
[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
175     # ----------------------------------------------------------------
176     #  Everything below here requires SSL
177     # ----------------------------------------------------------------
178     return $self->redirect_ssl unless $self->cgi->https;
179     return $self->load_password_reset if $path =~ m|opac/password_reset|;
180     return $self->load_logout if $path =~ m|opac/logout|;
181     return $self->load_patron_reg if $path =~ m|opac/register|;
182
183     $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
184
185     if($path =~ m|opac/login|) {
186         return $self->load_login unless $self->editor->requestor; # already logged in?
187
188         # This will be less confusing to users than to be shown a login form
189         # when they're already logged in.
190         return $self->generic_redirect(
191             sprintf(
192                 "%s://%s%s/myopac/main",
193                 $self->ctx->{proto},
194                 $self->ctx->{hostname}, $self->ctx->{opac_root}
195             )
196         );
197     }
198
199     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
200         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
201         return $self->load_sms_cn if $skip_sms_auth;
202     }
203
204     if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
205         if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
206             my $cache = OpenSRF::Utils::Cache->new('global');
207
208             if ($path !~ m|preview|) { # the real thing!
209                 $logger->info("not preview");
210                 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
211                 $logger->info("got cap_key $cap_key");
212                 if ($cap_key) {
213                     my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
214                     my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
215                     $logger->info("got answers $cap_answer $real_answer");
216                     return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
217                 }
218             }
219
220             my $captcha = {};
221             $$captcha{key} = time() . $$ . rand();
222             $$captcha{left} = int(rand(10));
223             $$captcha{right} = int(rand(10));
224             $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
225             $self->ctx->{captcha} = $captcha;
226             return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
227         }
228     }
229
230     return $self->load_manual_shib_login if $path =~ m|opac/manual_shib_login|;
231     # ----------------------------------------------------------------
232     #  Everything below here requires authentication
233     # ----------------------------------------------------------------
234     return $self->redirect_auth unless $self->editor->requestor;
235
236     # Don't cache anything requiring auth for security reasons
237     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
238     $self->apache->headers_out->add("expires" => "-1");
239
240     if ($path =~ m|opac/mylist/email|) {
241         (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
242     }
243     $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
244     return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
245     return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
246     return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
247     return $self->load_email_record if $path =~ m|opac/record/email|;
248     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
249
250     return $self->load_place_hold if $path =~ m|opac/place_hold|;
251  
252     # centralize check for curbside tab display
253     $self->load_current_curbside_libs;
254
255     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
256     return $self->load_myopac_hold_subscriptions if $path =~ m|opac/myopac/hold_subscriptions|;
257     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
258     return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
259     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
260     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
261     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
262     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
263     return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
264     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
265     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
266     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
267     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
268     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
269     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
270     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
271     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
272     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
273     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
274     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
275     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
276     return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
277     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
278     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
279     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
280     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
281     return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
282
283     return Apache2::Const::OK;
284 }
285
286
287 # -----------------------------------------------------------------------------
288 # Redirect to SSL equivalent of a given page
289 # -----------------------------------------------------------------------------
290 sub redirect_ssl {
291     my $self = shift;
292     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
293     return $self->generic_redirect($new_page);
294 }
295
296 # -----------------------------------------------------------------------------
297 # If an authnticated resource is requested w/o auth, redirect to the login page,
298 # then return to the originally requrested resource upon successful login.
299 # -----------------------------------------------------------------------------
300 sub redirect_auth {
301     my $self = shift;
302
303     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
304     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
305     my $sso_native = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
306
307     my $login_type = ($sso_enabled and !$sso_native) ? 'manual_shib_login' : 'login';
308     my $login_page = sprintf('%s://%s%s/%s',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root}, $login_type);
309     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
310     my $redirect_url = "$login_page?redirect_to=$redirect_to";
311
312     return $self->generic_redirect($redirect_url);
313 }
314
315 # -----------------------------------------------------------------------------
316 # Fall-through for loading a basic page
317 # -----------------------------------------------------------------------------
318 sub load_simple {
319     my ($self, $page) = @_;
320     $self->ctx->{page} = $page;
321     $self->ctx->{search_ou} = $self->_get_search_lib();
322
323     return Apache2::Const::OK;
324 }
325
326 # -----------------------------------------------------------------------------
327 # Tests to see if the user is authenticated and sets some common context values
328 # -----------------------------------------------------------------------------
329 sub load_common {
330     my $self = shift;
331
332     my $e = $self->editor;
333     my $ctx = $self->ctx;
334
335     # redirect non-https to https if we think we are already logged in
336     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
337         return $self->redirect_ssl unless $self->cgi->https;
338     }
339
340     # XXX Cache this? Makes testing difficult as apache needs a restart.
341     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
342     $ctx->{default_sort} =
343         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
344
345     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
346     $ctx->{referer} = $self->cgi->referer;
347     $ctx->{path_info} = $self->cgi->path_info;
348     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
349     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
350     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
351
352     $ctx->{original_tz} = $ENV{TZ};
353     $ENV{TZ} = $ctx->{client_tz};
354
355     my $xul_wrapper = 
356         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
357
358     if ($xul_wrapper) {
359         # XUL client
360         $ctx->{is_staff} = 1;
361         $ctx->{proto} = 'oils';
362         $ctx->{hostname} = 'remote';
363     }
364
365     $ctx->{carousel_loc} = $self->get_carousel_loc;
366     $ctx->{physical_loc} = $self->get_physical_loc;
367
368     # capture some commonly accessed pages
369     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
370     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
371
372     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
373
374         if($e->checkauth) {
375
376             $ctx->{authtoken} = $e->authtoken;
377             $ctx->{authtime} = $e->authtime;
378             $ctx->{user} = $e->requestor;
379             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
380             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
381             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
382
383             # The browser client does not set an OILS-Wrapper header (above).
384             # The presence of a workstation and no header indicates staff mode.
385             # FIXME: this approach leaves un-wrapped TPAC's within the same
386             # browser (and hence same ses cookie) in an unnatural is_staff
387             # state.  Consider alternatives for determining is_staff / 
388             # is_browser_staff when $xul_wrapper is false.
389             if (!$xul_wrapper and $e->requestor->wsid) {
390                 $ctx->{is_staff} = 1;
391                 $ctx->{is_browser_staff} = 1;
392             }
393
394             $self->update_dashboard_stats();
395
396         } else {
397
398             # if we encounter a stale authtoken, call load_logout 
399             # to clean up the cookie, then redirect the user to the
400             # originally requested page
401             return $self->load_logout($self->apache->unparsed_uri);
402         }
403     }
404
405     # List of <meta> and <link> elements to populate
406     $ctx->{metalinks} = [];
407
408     $self->extract_copy_location_group_info;
409     $ctx->{search_ou} = $self->_get_search_lib();
410     $ctx->{search_scope} = $self->cgi->param('search_scope');
411     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
412     $self->load_eg_cache_hash;
413     $self->load_copy_location_groups;
414     $self->load_my_hold_subscriptions;
415     $self->load_hold_subscriptions if $ctx->{is_staff};
416     $self->load_lassos;
417     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
418     $self->load_search_filter_groups($ctx->{search_ou});
419     $self->load_org_util_funcs;
420     $self->load_perm_funcs;
421
422     # FIXME - move carousel helpers to a separate file
423     $ctx->{get_visible_carousels} = sub {
424         my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
425         return $U->simplereq(
426             'open-ils.actor',
427             'open-ils.actor.carousel.retrieve_by_org',
428             $org_unit
429         );
430     };
431     $ctx->{get_carousel} = sub {
432         my $id = shift;
433
434         my $carousel = $e->retrieve_container_carousel($id);
435         my $ret = {
436             id   => $id,
437             name => $carousel->name
438         };
439         my $q = {
440             select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
441             from   => {
442                 bre => {
443                     cbrebi => {
444                         join => {
445                             cbreb => {
446                                 join => { cc => {} }
447                             }
448                         }
449                     },
450                     mfde => {}
451                 }
452             },
453             where  => {
454                 '+cc' => { id => $id },
455                 '+bre' => { deleted => 'f' },
456                 '+mfde' => { name => 'title' }
457             },
458             order_by => {cbrebi => ['pos','create_time']}
459         };
460         my $r = $e->json_query($q);
461         $ret->{bibs} = $r;
462         return $ret;
463     };
464
465     $ctx->{fetch_display_fields} = sub {
466         my $id = shift;
467
468         if (@$id == 1) {
469             return $ctx->{_hl_data}{''.$$id[0]}
470                 if ($ctx->{_hl_data}{''.$$id[0]});
471         }
472
473         $self->timelog("HL data not cached, fetching from server.");
474
475         my $rows = $U->simplereq(
476             'open-ils.search', 
477             'open-ils.search.fetch.metabib.display_field.highlight',
478             $ctx->{query_struct}{additional_data}{highlight_map},
479             map {int($_)} @$id
480         );
481
482         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
483
484         return $rows;
485     };
486
487     $ctx->{course_ou} = int($self->cgi->param('locg')) || $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id;
488     $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
489
490     return Apache2::Const::OK;
491 }
492
493 sub update_dashboard_stats {
494     my $self = shift;
495
496     my $e = $self->editor;
497     my $ctx = $self->ctx;
498
499     $ctx->{user_stats} = $U->simplereq(
500         'open-ils.actor', 
501         'open-ils.actor.user.opac.vital_stats', 
502         $e->authtoken, $e->requestor->id);
503 }
504
505 sub staff_saved_searches_set_expansion_state {
506     my $self = shift;
507
508     my $param = $self->cgi->param('sss_expand');
509     my $value;
510     
511     if (defined $param) {
512         $value = ($param ? 1 : 0);
513         $self->apache->headers_out->add(
514             "Set-Cookie" => $self->cgi->cookie(
515                 -name => COOKIE_SSS_EXPAND,
516                 -path => $self->ctx->{base_path},
517                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
518                 -value => $value,
519                 -expires => undef
520             )
521         );
522     } else {
523         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
524     }
525
526     $self->ctx->{saved_searches_expanded} = $value;
527 }
528
529 # physical_loc (i.e. "original location") passed in as a URL 
530 # param will replace any existing physical_loc stored as a cookie.
531 # If specified via ENV that rules over all and we don't set cookies.
532 sub get_physical_loc {
533     my $self = shift;
534
535     return $ENV{physical_loc} if($ENV{physical_loc});
536
537     if(my $physical_loc = $self->cgi->param('physical_loc')) {
538         $self->apache->headers_out->add(
539             "Set-Cookie" => $self->cgi->cookie(
540                 -name => COOKIE_PHYSICAL_LOC,
541                 -path => $self->ctx->{base_path},
542                 -value => $physical_loc,
543                 -expires => undef
544             )
545         );
546         return $physical_loc;
547     }
548
549     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
550 }
551
552 sub get_carousel_loc {
553     my $self = shift;
554     return $self->cgi->param('carousel_loc') || $ENV{carousel_loc};
555 }
556
557 # -----------------------------------------------------------------------------
558 # Log in and redirect to the redirect_to URL (or home)
559 # -----------------------------------------------------------------------------
560 sub load_login {
561     my $self = shift;
562     my $cgi = $self->cgi;
563     my $ctx = $self->ctx;
564
565     $self->timelog("Load login begins");
566
567     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
568     $ctx->{sso_org} = $sso_org;
569     my $sso_enabled = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
570     my $sso_native = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
571     my $sso_eg_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.evergreen_matchpoint') || 'usrname';
572     my $sso_shib_match = $ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
573
574     $ctx->{page} = 'login';
575
576     my $username = $cgi->param('username') || '';
577     $username =~ s/\s//g;  # Remove blanks
578     my $password = $cgi->param('password');
579     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
580     my $persist = $cgi->param('persist');
581     my $client_tz = $cgi->param('client_tz');
582
583     my $sso_user_match_value;
584     my $response;
585     my $sso_logged_in;
586     $self->timelog("SSO is enabled") if ($sso_enabled);
587     if ($sso_enabled
588         and $sso_user_match_value = $ENV{$sso_shib_match}
589         and !$self->cgi->cookie(COOKIE_SHIB_LOGGEDOUT)
590     ) { # we have a shib session, and have not cleared a previous shib-login cookie
591         $self->timelog("Have an SSO user match value: $sso_user_match_value");
592
593         if ($sso_eg_match eq 'barcode') { # barcode is special
594             my $card = $self->editor->search_actor_card({barcode => $sso_user_match_value})->[0];
595             $sso_user_match_value = $card ? $card->usr : undef;
596             $sso_eg_match = 'id';
597         }
598
599         if ($sso_user_match_value && $sso_eg_match) {
600             my $user = $self->editor->search_actor_user({ $sso_eg_match => $sso_user_match_value })->[0];
601             if ($user) { # create a session
602                 $response = $U->simplereq(
603                     'open-ils.auth_internal',
604                     'open-ils.auth_internal.session.create',
605                     { user_id => $user->id, login_type => 'opac' }
606                 );
607                 $sso_logged_in = $response ? 1 : 0;
608             }
609         }
610
611         $self->timelog("Checked for SSO login");
612     }
613
614     if (!$sso_enabled || (!$response && $sso_native)) {
615         # initial log form only
616         return Apache2::Const::OK unless $username and $password;
617
618         my $auth_proxy_enabled = 0; # default false
619         try { # if the service is not running, just let this fail silently
620             $auth_proxy_enabled = $U->simplereq(
621                 'open-ils.auth_proxy',
622                 'open-ils.auth_proxy.enabled');
623         } catch Error with {};
624
625         $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
626
627         my $args = {
628             type => ($persist) ? 'persist' : 'opac',
629             org => $org_unit,
630             agent => 'opac'
631         };
632
633         my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
634
635         # To avoid surprises, default to "Barcodes start with digits"
636         $bc_regex = '^\d' unless $bc_regex;
637
638         if ($bc_regex and ($username =~ /$bc_regex/)) {
639             $args->{barcode} = $username;
640         } else {
641             $args->{username} = $username;
642         }
643
644         if (!$auth_proxy_enabled) {
645             my $seed = $U->simplereq(
646                 'open-ils.auth',
647                 'open-ils.auth.authenticate.init', $username);
648             $args->{password} = md5_hex($seed . md5_hex($password));
649             $response = $U->simplereq(
650                 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
651         } else {
652             $args->{password} = $password;
653             $response = $U->simplereq(
654                 'open-ils.auth_proxy',
655                 'open-ils.auth_proxy.login', $args);
656         }
657         $self->timelog("Checked password");
658     } else {
659         $response ||= OpenILS::Event->new( 'LOGIN_FAILED' ); # assume failure
660     }
661
662     if($U->event_code($response)) { 
663         # login failed, report the reason to the template
664         $ctx->{login_failed_event} = $response;
665         return Apache2::Const::OK;
666     }
667
668     # login succeeded, redirect as necessary
669
670     my $acct = $self->apache->unparsed_uri;
671     $acct =~ s|/login|/myopac/main|;
672
673     # both login-related cookies should expire at the same time
674     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
675
676     my $cookie_list = [
677         # contains the actual auth token and should be sent only over https
678         $cgi->cookie(
679             -name => COOKIE_SES,
680             -path => '/',
681             -secure => 1,
682             -value => $response->{payload}->{authtoken},
683             -expires => $login_cookie_expires
684         ),
685         # contains only a hint that we are logged in, and is used to
686         # trigger a redirect to https
687         $cgi->cookie(
688             -name => COOKIE_LOGGEDIN,
689             -path => '/',
690             -secure => 0,
691             -value => '1',
692             -expires => $login_cookie_expires
693         )
694     ];
695
696     if ($client_tz) {
697         # contains the client's tz, as passed by the client
698         # trigger a redirect to https
699         push @$cookie_list, $cgi->cookie(
700             -name => COOKIE_TZ,
701             -path => '/',
702             -secure => 0,
703             -value => $client_tz,
704             -expires => $login_cookie_expires
705         );
706     }
707
708     if ($sso_logged_in) {
709         # tells us if we're logged in via shib, so we can decide whether to try logging in again.
710         push @$cookie_list, $cgi->cookie(
711             -name => COOKIE_SHIB_LOGGEDOUT,
712             -path => '/',
713             -secure => 0,
714             -value => '0',
715             -expires => '-1h'
716         );
717         push @$cookie_list, $cgi->cookie(
718             -name => COOKIE_SHIB_LOGGEDIN,
719             -path => '/',
720             -secure => 0,
721             -value => '1',
722             -expires => $login_cookie_expires
723         );
724     }
725
726     return $self->generic_redirect(
727         $cgi->param('redirect_to') || $acct,
728         $cookie_list
729     );
730 }
731
732 sub load_manual_shib_login {
733     my $self = shift;
734     my $redirect_to = shift || $self->cgi->param('redirect_to');
735
736     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
737     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
738     my $sso_shib_match = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
739
740     return $self->load_login if ($ENV{$sso_shib_match});
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     my $active_logout = $self->cgi->param('active_logout');
766
767     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
768     $self->ctx->{sso_org} = $sso_org;
769     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
770     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
771     my $sso_logout = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.logout');
772     if ($sso_enabled && $sso_logout) {
773         $redirect_to = '/Shibboleth.sso/Logout?return=' . ($redirect_to || $self->ctx->{home_page});
774         if ($sso_entity_id) {
775             $redirect_to .= '&entityID=' . $sso_entity_id;
776         }
777     }
778
779     # If the user was adding anyting to an anonymous cache 
780     # while logged in, go ahead and clear it out.
781     $self->clear_anon_cache;
782
783     try { # a missing auth token will cause an ugly explosion
784         $U->simplereq(
785             'open-ils.auth',
786             'open-ils.auth.session.delete',
787             $self->cgi->cookie(COOKIE_SES)
788         );
789     } catch Error with {};
790
791     return $self->generic_redirect(
792         $redirect_to || $self->ctx->{home_page},
793         [
794             # clear value of and expire both of these login-related cookies
795             $self->cgi->cookie(
796                 -name => COOKIE_SES,
797                 -path => '/',
798                 -value => '',
799                 -expires => '-1h'
800             ),
801             $self->cgi->cookie(
802                 -name => COOKIE_LOGGEDIN,
803                 -path => '/',
804                 -value => '',
805                 -expires => '-1h'
806             ),
807             ($active_logout ? ($self->cgi->cookie(
808                 -name => COOKIE_SHIB_LOGGEDOUT,
809                 -path => '/',
810                 -value => '1',
811                 -expires => '2147483647'
812             )) : ()),
813             $self->cgi->cookie(
814                 -name => COOKIE_SHIB_LOGGEDIN,
815                 -path => '/',
816                 -value => '0',
817                 -expires => '-1h'
818             )
819         ]
820     );
821 }
822
823 1;
824