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