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