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