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