0af9399168d0271ab0cc19bfc042efa274f5129a
[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 OpenSRF::Utils 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 DateTime::Format::ISO8601;
16 use CGI qw(:all -utf8);
17 use Time::HiRes;
18
19 # EGCatLoader sub-modules 
20 use OpenILS::WWW::EGCatLoader::Util;
21 use OpenILS::WWW::EGCatLoader::Account;
22 use OpenILS::WWW::EGCatLoader::Browse;
23 use OpenILS::WWW::EGCatLoader::Search;
24 use OpenILS::WWW::EGCatLoader::Record;
25 use OpenILS::WWW::EGCatLoader::Container;
26 use OpenILS::WWW::EGCatLoader::SMS;
27 use OpenILS::WWW::EGCatLoader::Register;
28
29 my $U = 'OpenILS::Application::AppUtils';
30
31 use constant COOKIE_SES => 'ses';
32 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
33 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
34 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
35
36 use constant COOKIE_ANON_CACHE => 'anoncache';
37 use constant ANON_CACHE_MYLIST => 'mylist';
38 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
39
40 use constant DEBUG_TIMING => 0;
41
42 sub new {
43     my($class, $apache, $ctx) = @_;
44
45     my $self = bless({}, ref($class) || $class);
46
47     $self->apache($apache);
48     $self->ctx($ctx);
49     $self->cgi(new CGI);
50     $self->timelog("New page");
51
52     OpenILS::Utils::CStoreEditor->init; # just in case
53     $self->editor(new_editor());
54
55     return $self;
56 }
57
58
59 # current Apache2::RequestRec;
60 sub apache {
61     my($self, $apache) = @_;
62     $self->{apache} = $apache if $apache;
63     return $self->{apache};
64 }
65
66 # runtime / template context
67 sub ctx {
68     my($self, $ctx) = @_;
69     $self->{ctx} = $ctx if $ctx;
70     return $self->{ctx};
71 }
72
73 # cstore editor
74 sub editor {
75     my($self, $editor) = @_;
76     $self->{editor} = $editor if $editor;
77     return $self->{editor};
78 }
79
80 # CGI handle
81 sub cgi {
82     my($self, $cgi) = @_;
83     $self->{cgi} = $cgi if $cgi;
84     return $self->{cgi};
85 }
86
87 sub timelog {
88     my($self, $description) = @_;
89
90     return unless DEBUG_TIMING;
91     return unless $description;
92     $self->ctx->{timing} ||= [];
93     
94     my $timer = [Time::HiRes::gettimeofday()];
95     $self->ctx->{time_begin} ||= $timer;
96
97     push @{$self->ctx->{timing}}, [
98         Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
99     ];
100 }
101
102 # -----------------------------------------------------------------------------
103 # Perform initial setup, load common data, then load page data
104 # -----------------------------------------------------------------------------
105 sub load {
106     my $self = shift;
107
108     $self->init_ro_object_cache;
109     $self->timelog("Initial load");
110
111     my $stat = $self->load_common;
112     return $stat unless $stat == Apache2::Const::OK;
113
114     my $path = $self->apache->path_info;
115
116     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
117         $path =~ /opac\/my(opac\/lists|list)/;
118
119     return $self->load_simple("home") if $path =~ m|opac/home|;
120     return $self->load_simple("css") if $path =~ m|opac/css|;
121     return $self->load_simple("advanced") if
122         $path =~ m:opac/(advanced|numeric|expert):;
123
124     return $self->load_rresults if $path =~ m|opac/results|;
125     return $self->load_print_record if $path =~ m|opac/record/print|;
126     return $self->load_record if $path =~ m|opac/record/\d|;
127     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
128     return $self->load_browse if $path =~ m|opac/browse|;
129
130     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
131     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
132     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
133     return $self->load_mylist if $path =~ m|opac/mylist|;
134     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
135     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
136     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
137
138     # ----------------------------------------------------------------
139     #  Everything below here requires SSL
140     # ----------------------------------------------------------------
141     return $self->redirect_ssl unless $self->cgi->https;
142     return $self->load_password_reset if $path =~ m|opac/password_reset|;
143     return $self->load_logout if $path =~ m|opac/logout|;
144     return $self->load_patron_reg if $path =~ m|opac/register|;
145
146     if($path =~ m|opac/login|) {
147         return $self->load_login unless $self->editor->requestor; # already logged in?
148
149         # This will be less confusing to users than to be shown a login form
150         # when they're already logged in.
151         return $self->generic_redirect(
152             sprintf(
153                 "%s://%s%s/myopac/main",
154                 $self->ctx->{proto},
155                 $self->ctx->{hostname}, $self->ctx->{opac_root}
156             )
157         );
158     }
159
160     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
161         my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
162         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
163         return $self->load_sms_cn if $skip_sms_auth;
164     }
165
166     # ----------------------------------------------------------------
167     #  Everything below here requires authentication
168     # ----------------------------------------------------------------
169     return $self->redirect_auth unless $self->editor->requestor;
170
171     # Don't cache anything requiring auth for security reasons
172     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
173     $self->apache->headers_out->add("expires" => "-1");
174
175     return $self->load_email_record if $path =~ m|opac/record/email|;
176
177     return $self->load_place_hold if $path =~ m|opac/place_hold|;
178     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
179     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
180     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
181     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
182     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
183     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
184     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
185     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
186     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
187     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
188     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
189     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
190     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
191     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
192     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
193     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
194     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
195     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
196     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
197     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
198     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
199     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
200     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
201
202     return Apache2::Const::OK;
203 }
204
205
206 # -----------------------------------------------------------------------------
207 # Redirect to SSL equivalent of a given page
208 # -----------------------------------------------------------------------------
209 sub redirect_ssl {
210     my $self = shift;
211     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
212     return $self->generic_redirect($new_page);
213 }
214
215 # -----------------------------------------------------------------------------
216 # If an authnticated resource is requested w/o auth, redirect to the login page,
217 # then return to the originally requrested resource upon successful login.
218 # -----------------------------------------------------------------------------
219 sub redirect_auth {
220     my $self = shift;
221     my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
222     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
223     return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
224 }
225
226 # -----------------------------------------------------------------------------
227 # Fall-through for loading a basic page
228 # -----------------------------------------------------------------------------
229 sub load_simple {
230     my ($self, $page) = @_;
231     $self->ctx->{page} = $page;
232     $self->ctx->{search_ou} = $self->_get_search_lib();
233
234     return Apache2::Const::OK;
235 }
236
237 # -----------------------------------------------------------------------------
238 # Tests to see if the user is authenticated and sets some common context values
239 # -----------------------------------------------------------------------------
240 sub load_common {
241     my $self = shift;
242
243     my $e = $self->editor;
244     my $ctx = $self->ctx;
245
246     # redirect non-https to https if we think we are already logged in
247     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
248         return $self->redirect_ssl unless $self->cgi->https;
249     }
250
251     $ctx->{referer} = $self->cgi->referer;
252     $ctx->{path_info} = $self->cgi->path_info;
253     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
254     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
255     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
256     my $oils_wrapper = $self->apache->headers_in->get('OILS-Wrapper') || '';
257     $ctx->{is_staff} = ($oils_wrapper =~ /true/);
258     $ctx->{proto} = 'oils' if $ctx->{is_staff};
259     $ctx->{hostname} = 'remote' if $ctx->{is_staff};
260     $ctx->{physical_loc} = $self->get_physical_loc;
261
262     # capture some commonly accessed pages
263     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
264     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
265
266     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
267
268         if($e->checkauth) {
269
270             $ctx->{authtoken} = $e->authtoken;
271             $ctx->{authtime} = $e->authtime;
272             $ctx->{user} = $e->requestor;
273             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
274
275             $ctx->{user_stats} = $U->simplereq(
276                 'open-ils.actor', 
277                 'open-ils.actor.user.opac.vital_stats', 
278                 $e->authtoken, $e->requestor->id);
279
280         } else {
281
282             # if we encounter a stale authtoken, call load_logout 
283             # to clean up the cookie, then redirect the user to the
284             # originally requested page
285             return $self->load_logout($self->apache->unparsed_uri);
286         }
287     }
288
289     $self->extract_copy_location_group_info;
290     $ctx->{search_ou} = $self->_get_search_lib();
291     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
292     $self->load_eg_cache_hash;
293     $self->load_copy_location_groups;
294     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
295     $self->load_search_filter_groups($ctx->{search_ou});
296     $self->load_org_util_funcs;
297
298     return Apache2::Const::OK;
299 }
300
301 sub staff_saved_searches_set_expansion_state {
302     my $self = shift;
303
304     my $param = $self->cgi->param('sss_expand');
305     my $value;
306     
307     if (defined $param) {
308         $value = ($param ? 1 : 0);
309         $self->apache->headers_out->add(
310             "Set-Cookie" => $self->cgi->cookie(
311                 -name => COOKIE_SSS_EXPAND,
312                 -path => $self->ctx->{base_path},
313                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
314                 -value => $value,
315                 -expires => undef
316             )
317         );
318     } else {
319         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
320     }
321
322     $self->ctx->{saved_searches_expanded} = $value;
323 }
324
325 # physical_loc (i.e. "original location") passed in as a URL 
326 # param will replace any existing physical_loc stored as a cookie.
327 # If specified via ENV that rules over all and we don't set cookies.
328 sub get_physical_loc {
329     my $self = shift;
330
331     return $ENV{physical_loc} if($ENV{physical_loc});
332
333     if(my $physical_loc = $self->cgi->param('physical_loc')) {
334         $self->apache->headers_out->add(
335             "Set-Cookie" => $self->cgi->cookie(
336                 -name => COOKIE_PHYSICAL_LOC,
337                 -path => $self->ctx->{base_path},
338                 -value => $physical_loc,
339                 -expires => undef
340             )
341         );
342         return $physical_loc;
343     }
344
345     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
346 }
347
348 # -----------------------------------------------------------------------------
349 # Log in and redirect to the redirect_to URL (or home)
350 # -----------------------------------------------------------------------------
351 sub load_login {
352     my $self = shift;
353     my $cgi = $self->cgi;
354     my $ctx = $self->ctx;
355
356     $self->timelog("Load login begins");
357
358     $ctx->{page} = 'login';
359
360     my $username = $cgi->param('username');
361     $username =~ s/\s//g;  # Remove blanks
362     my $password = $cgi->param('password');
363     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
364     my $persist = $cgi->param('persist');
365
366     # initial log form only
367     return Apache2::Const::OK unless $username and $password;
368
369     my $auth_proxy_enabled = 0; # default false
370     try { # if the service is not running, just let this fail silently
371         $auth_proxy_enabled = $U->simplereq(
372             'open-ils.auth_proxy',
373             'open-ils.auth_proxy.enabled');
374     } catch Error with {};
375
376     $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
377
378     my $args = {
379         type => ($persist) ? 'persist' : 'opac',
380         org => $org_unit,
381         agent => 'opac'
382     };
383
384     my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
385
386     # To avoid surprises, default to "Barcodes start with digits"
387     $bc_regex = '^\d' unless $bc_regex;
388
389     if ($bc_regex and ($username =~ /$bc_regex/)) {
390         $args->{barcode} = $username;
391     } else {
392         $args->{username} = $username;
393     }
394
395     my $response;
396     if (!$auth_proxy_enabled) {
397         my $seed = $U->simplereq(
398             'open-ils.auth',
399             'open-ils.auth.authenticate.init', $username);
400         $args->{password} = md5_hex($seed . md5_hex($password));
401         $response = $U->simplereq(
402             'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
403     } else {
404         $args->{password} = $password;
405         $response = $U->simplereq(
406             'open-ils.auth_proxy',
407             'open-ils.auth_proxy.login', $args);
408     }
409     $self->timelog("Checked password");
410
411     if($U->event_code($response)) { 
412         # login failed, report the reason to the template
413         $ctx->{login_failed_event} = $response;
414         return Apache2::Const::OK;
415     }
416
417     # login succeeded, redirect as necessary
418
419     my $acct = $self->apache->unparsed_uri;
420     $acct =~ s|/login|/myopac/main|;
421
422     # both login-related cookies should expire at the same time
423     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
424
425     return $self->generic_redirect(
426         $cgi->param('redirect_to') || $acct,
427         [
428             # contains the actual auth token and should be sent only over https
429             $cgi->cookie(
430                 -name => COOKIE_SES,
431                 -path => '/',
432                 -secure => 1,
433                 -value => $response->{payload}->{authtoken},
434                 -expires => $login_cookie_expires
435             ),
436             # contains only a hint that we are logged in, and is used to
437             # trigger a redirect to https
438             $cgi->cookie(
439                 -name => COOKIE_LOGGEDIN,
440                 -path => '/',
441                 -secure => 0,
442                 -value => '1',
443                 -expires => $login_cookie_expires
444             )
445         ]
446     );
447 }
448
449 # -----------------------------------------------------------------------------
450 # Log out and redirect to the home page
451 # -----------------------------------------------------------------------------
452 sub load_logout {
453     my $self = shift;
454     my $redirect_to = shift || $self->cgi->param('redirect_to');
455
456     # If the user was adding anyting to an anonymous cache 
457     # while logged in, go ahead and clear it out.
458     $self->clear_anon_cache;
459
460     return $self->generic_redirect(
461         $redirect_to || $self->ctx->{home_page},
462         [
463             # clear value of and expire both of these login-related cookies
464             $self->cgi->cookie(
465                 -name => COOKIE_SES,
466                 -path => '/',
467                 -value => '',
468                 -expires => '-1h'
469             ),
470             $self->cgi->cookie(
471                 -name => COOKIE_LOGGEDIN,
472                 -path => '/',
473                 -value => '',
474                 -expires => '-1h'
475             )
476         ]
477     );
478 }
479
480 1;
481