]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
111ea8b4d852c4f94fb3411229f3f9658eeb2a59
[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_circs if $path =~ m|opac/myopac/circs|;
257     return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
258     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
259     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
260     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
261     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
262     return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
263     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
264     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
265     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
266     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
267     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
268     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
269     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
270     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
271     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
272     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
273     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
274     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
275     return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
276     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
277     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
278     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
279     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
280     return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
281
282     return Apache2::Const::OK;
283 }
284
285
286 # -----------------------------------------------------------------------------
287 # Redirect to SSL equivalent of a given page
288 # -----------------------------------------------------------------------------
289 sub redirect_ssl {
290     my $self = shift;
291     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
292     return $self->generic_redirect($new_page);
293 }
294
295 # -----------------------------------------------------------------------------
296 # If an authnticated resource is requested w/o auth, redirect to the login page,
297 # then return to the originally requrested resource upon successful login.
298 # -----------------------------------------------------------------------------
299 sub redirect_auth {
300     my $self = shift;
301
302     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
303     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
304     my $sso_native = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.allow_native');
305
306     my $login_type = ($sso_enabled and !$sso_native) ? 'manual_shib_login' : 'login';
307     my $login_page = sprintf('%s://%s%s/%s',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root}, $login_type);
308     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
309     my $redirect_url = "$login_page?redirect_to=$redirect_to";
310
311     return $self->generic_redirect($redirect_url);
312 }
313
314 # -----------------------------------------------------------------------------
315 # Fall-through for loading a basic page
316 # -----------------------------------------------------------------------------
317 sub load_simple {
318     my ($self, $page) = @_;
319     $self->ctx->{page} = $page;
320     $self->ctx->{search_ou} = $self->_get_search_lib();
321
322     return Apache2::Const::OK;
323 }
324
325 # -----------------------------------------------------------------------------
326 # Tests to see if the user is authenticated and sets some common context values
327 # -----------------------------------------------------------------------------
328 sub load_common {
329     my $self = shift;
330
331     my $e = $self->editor;
332     my $ctx = $self->ctx;
333
334     # redirect non-https to https if we think we are already logged in
335     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
336         return $self->redirect_ssl unless $self->cgi->https;
337     }
338
339     # XXX Cache this? Makes testing difficult as apache needs a restart.
340     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
341     $ctx->{default_sort} =
342         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
343
344     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
345     $ctx->{referer} = $self->cgi->referer;
346     $ctx->{path_info} = $self->cgi->path_info;
347     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
348     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
349     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
350
351     $ctx->{original_tz} = $ENV{TZ};
352     $ENV{TZ} = $ctx->{client_tz};
353
354     my $xul_wrapper = 
355         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
356
357     if ($xul_wrapper) {
358         # XUL client
359         $ctx->{is_staff} = 1;
360         $ctx->{proto} = 'oils';
361         $ctx->{hostname} = 'remote';
362     }
363
364     $ctx->{carousel_loc} = $self->get_carousel_loc;
365     $ctx->{physical_loc} = $self->get_physical_loc;
366
367     # capture some commonly accessed pages
368     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
369     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
370
371     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
372
373         if($e->checkauth) {
374
375             $ctx->{authtoken} = $e->authtoken;
376             $ctx->{authtime} = $e->authtime;
377             $ctx->{user} = $e->requestor;
378             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
379             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
380             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
381
382             # The browser client does not set an OILS-Wrapper header (above).
383             # The presence of a workstation and no header indicates staff mode.
384             # FIXME: this approach leaves un-wrapped TPAC's within the same
385             # browser (and hence same ses cookie) in an unnatural is_staff
386             # state.  Consider alternatives for determining is_staff / 
387             # is_browser_staff when $xul_wrapper is false.
388             if (!$xul_wrapper and $e->requestor->wsid) {
389                 $ctx->{is_staff} = 1;
390                 $ctx->{is_browser_staff} = 1;
391             }
392
393             $self->update_dashboard_stats();
394
395         } else {
396
397             # if we encounter a stale authtoken, call load_logout 
398             # to clean up the cookie, then redirect the user to the
399             # originally requested page
400             return $self->load_logout($self->apache->unparsed_uri);
401         }
402     }
403
404     # List of <meta> and <link> elements to populate
405     $ctx->{metalinks} = [];
406
407     $self->extract_copy_location_group_info;
408     $ctx->{search_ou} = $self->_get_search_lib();
409     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
410     $self->load_eg_cache_hash;
411     $self->load_copy_location_groups;
412     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
413     $self->load_search_filter_groups($ctx->{search_ou});
414     $self->load_org_util_funcs;
415     $self->load_perm_funcs;
416
417     # FIXME - move carousel helpers to a separate file
418     $ctx->{get_visible_carousels} = sub {
419         my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
420         return $U->simplereq(
421             'open-ils.actor',
422             'open-ils.actor.carousel.retrieve_by_org',
423             $org_unit
424         );
425     };
426     $ctx->{get_carousel} = sub {
427         my $id = shift;
428
429         my $carousel = $e->retrieve_container_carousel($id);
430         my $ret = {
431             id   => $id,
432             name => $carousel->name
433         };
434         my $q = {
435             select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
436             from   => {
437                 bre => {
438                     cbrebi => {
439                         join => {
440                             cbreb => {
441                                 join => { cc => {} }
442                             }
443                         }
444                     },
445                     mfde => {}
446                 }
447             },
448             where  => {
449                 '+cc' => { id => $id },
450                 '+bre' => { deleted => 'f' },
451                 '+mfde' => { name => 'title' }
452             },
453             order_by => {cbrebi => ['pos','create_time']}
454         };
455         my $r = $e->json_query($q);
456         $ret->{bibs} = $r;
457         return $ret;
458     };
459
460     $ctx->{fetch_display_fields} = sub {
461         my $id = shift;
462
463         if (@$id == 1) {
464             return $ctx->{_hl_data}{''.$$id[0]}
465                 if ($ctx->{_hl_data}{''.$$id[0]});
466         }
467
468         $self->timelog("HL data not cached, fetching from server.");
469
470         my $rows = $U->simplereq(
471             'open-ils.search', 
472             'open-ils.search.fetch.metabib.display_field.highlight',
473             $ctx->{query_struct}{additional_data}{highlight_map},
474             map {int($_)} @$id
475         );
476
477         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
478
479         return $rows;
480     };
481
482     $ctx->{course_ou} = int($self->cgi->param('locg')) || $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id;
483     $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
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 = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
563     $ctx->{sso_org} = $sso_org;
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;
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 = $ENV{$sso_shib_match}
584         and !$self->cgi->cookie(COOKIE_SHIB_LOGGEDOUT)
585     ) { # we have a shib session, and have not cleared a previous shib-login cookie
586         $self->timelog("Have an SSO user match value: $sso_user_match_value");
587
588         if ($sso_eg_match eq 'barcode') { # barcode is special
589             my $card = $self->editor->search_actor_card({barcode => $sso_user_match_value})->[0];
590             $sso_user_match_value = $card ? $card->usr : undef;
591             $sso_eg_match = 'id';
592         }
593
594         if ($sso_user_match_value && $sso_eg_match) {
595             my $user = $self->editor->search_actor_user({ $sso_eg_match => $sso_user_match_value })->[0];
596             if ($user) { # create a session
597                 $response = $U->simplereq(
598                     'open-ils.auth_internal',
599                     'open-ils.auth_internal.session.create',
600                     { user_id => $user->id, login_type => 'opac' }
601                 );
602                 $sso_logged_in = $response ? 1 : 0;
603             }
604         }
605
606         $self->timelog("Checked for SSO login");
607     }
608
609     if (!$sso_enabled || (!$response && $sso_native)) {
610         # initial log form only
611         return Apache2::Const::OK unless $username and $password;
612
613         my $auth_proxy_enabled = 0; # default false
614         try { # if the service is not running, just let this fail silently
615             $auth_proxy_enabled = $U->simplereq(
616                 'open-ils.auth_proxy',
617                 'open-ils.auth_proxy.enabled');
618         } catch Error with {};
619
620         $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
621
622         my $args = {
623             type => ($persist) ? 'persist' : 'opac',
624             org => $org_unit,
625             agent => 'opac'
626         };
627
628         my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
629
630         # To avoid surprises, default to "Barcodes start with digits"
631         $bc_regex = '^\d' unless $bc_regex;
632
633         if ($bc_regex and ($username =~ /$bc_regex/)) {
634             $args->{barcode} = $username;
635         } else {
636             $args->{username} = $username;
637         }
638
639         if (!$auth_proxy_enabled) {
640             my $seed = $U->simplereq(
641                 'open-ils.auth',
642                 'open-ils.auth.authenticate.init', $username);
643             $args->{password} = md5_hex($seed . md5_hex($password));
644             $response = $U->simplereq(
645                 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
646         } else {
647             $args->{password} = $password;
648             $response = $U->simplereq(
649                 'open-ils.auth_proxy',
650                 'open-ils.auth_proxy.login', $args);
651         }
652         $self->timelog("Checked password");
653     } else {
654         $response ||= OpenILS::Event->new( 'LOGIN_FAILED' ); # assume failure
655     }
656
657     if($U->event_code($response)) { 
658         # login failed, report the reason to the template
659         $ctx->{login_failed_event} = $response;
660         return Apache2::Const::OK;
661     }
662
663     # login succeeded, redirect as necessary
664
665     my $acct = $self->apache->unparsed_uri;
666     $acct =~ s|/login|/myopac/main|;
667
668     # both login-related cookies should expire at the same time
669     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
670
671     my $cookie_list = [
672         # contains the actual auth token and should be sent only over https
673         $cgi->cookie(
674             -name => COOKIE_SES,
675             -path => '/',
676             -secure => 1,
677             -value => $response->{payload}->{authtoken},
678             -expires => $login_cookie_expires
679         ),
680         # contains only a hint that we are logged in, and is used to
681         # trigger a redirect to https
682         $cgi->cookie(
683             -name => COOKIE_LOGGEDIN,
684             -path => '/',
685             -secure => 0,
686             -value => '1',
687             -expires => $login_cookie_expires
688         )
689     ];
690
691     if ($client_tz) {
692         # contains the client's tz, as passed by the client
693         # trigger a redirect to https
694         push @$cookie_list, $cgi->cookie(
695             -name => COOKIE_TZ,
696             -path => '/',
697             -secure => 0,
698             -value => $client_tz,
699             -expires => $login_cookie_expires
700         );
701     }
702
703     if ($sso_logged_in) {
704         # tells us if we're logged in via shib, so we can decide whether to try logging in again.
705         push @$cookie_list, $cgi->cookie(
706             -name => COOKIE_SHIB_LOGGEDOUT,
707             -path => '/',
708             -secure => 0,
709             -value => '0',
710             -expires => '-1h'
711         );
712         push @$cookie_list, $cgi->cookie(
713             -name => COOKIE_SHIB_LOGGEDIN,
714             -path => '/',
715             -secure => 0,
716             -value => '1',
717             -expires => $login_cookie_expires
718         );
719     }
720
721     return $self->generic_redirect(
722         $cgi->param('redirect_to') || $acct,
723         $cookie_list
724     );
725 }
726
727 sub load_manual_shib_login {
728     my $self = shift;
729     my $redirect_to = shift || $self->cgi->param('redirect_to');
730
731     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
732     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
733     my $sso_shib_match = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.shib_matchpoint') || 'uid';
734
735     return $self->load_login if ($ENV{$sso_shib_match});
736
737     my $url = '/Shibboleth.sso/Login?target=' . ($redirect_to || $self->ctx->{home_page});
738     if ($sso_entity_id) {
739         $url .= '&entityID=' . $sso_entity_id;
740     }
741
742     return $self->generic_redirect( $url,
743         [
744             $self->cgi->cookie(
745                 -name => COOKIE_SHIB_LOGGEDOUT,
746                 -path => '/',
747                 -value => '0',
748                 -expires => '-1h'
749             )
750         ]
751     );
752 }
753
754 # -----------------------------------------------------------------------------
755 # Log out and redirect to the home page
756 # -----------------------------------------------------------------------------
757 sub load_logout {
758     my $self = shift;
759     my $redirect_to = shift || $self->cgi->param('redirect_to');
760     my $active_logout = $self->cgi->param('active_logout');
761
762     my $sso_org = $ENV{sso_loc} || $self->get_physical_loc || $self->_get_search_lib();
763     $self->ctx->{sso_org} = $sso_org;
764     my $sso_enabled = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.enable');
765     my $sso_entity_id = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.entityId');
766     my $sso_logout = $self->ctx->{get_org_setting}->($sso_org, 'opac.login.shib_sso.logout');
767     if ($sso_enabled && $sso_logout) {
768         $redirect_to = '/Shibboleth.sso/Logout?return=' . ($redirect_to || $self->ctx->{home_page});
769         if ($sso_entity_id) {
770             $redirect_to .= '&entityID=' . $sso_entity_id;
771         }
772     }
773
774     # If the user was adding anyting to an anonymous cache 
775     # while logged in, go ahead and clear it out.
776     $self->clear_anon_cache;
777
778     try { # a missing auth token will cause an ugly explosion
779         $U->simplereq(
780             'open-ils.auth',
781             'open-ils.auth.session.delete',
782             $self->cgi->cookie(COOKIE_SES)
783         );
784     } catch Error with {};
785
786     return $self->generic_redirect(
787         $redirect_to || $self->ctx->{home_page},
788         [
789             # clear value of and expire both of these login-related cookies
790             $self->cgi->cookie(
791                 -name => COOKIE_SES,
792                 -path => '/',
793                 -value => '',
794                 -expires => '-1h'
795             ),
796             $self->cgi->cookie(
797                 -name => COOKIE_LOGGEDIN,
798                 -path => '/',
799                 -value => '',
800                 -expires => '-1h'
801             ),
802             ($active_logout ? ($self->cgi->cookie(
803                 -name => COOKIE_SHIB_LOGGEDOUT,
804                 -path => '/',
805                 -value => '1',
806                 -expires => '2147483647'
807             )) : ()),
808             $self->cgi->cookie(
809                 -name => COOKIE_SHIB_LOGGEDIN,
810                 -path => '/',
811                 -value => '0',
812                 -expires => '-1h'
813             )
814         ]
815     );
816 }
817
818 1;
819