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