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