First inklings of schema.org support for library pages
[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_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     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
118         $path =~ /opac\/my(opac\/lists|list)/;
119
120     return $self->load_simple("home") if $path =~ m|opac/home|;
121     return $self->load_simple("css") if $path =~ m|opac/css|;
122     return $self->load_simple("advanced") if
123         $path =~ m:opac/(advanced|numeric|expert):;
124
125     return $self->load_library if $path =~ m|opac/library|;
126     return $self->load_rresults if $path =~ m|opac/results|;
127     return $self->load_print_record if $path =~ m|opac/record/print|;
128     return $self->load_record if $path =~ m|opac/record/\d|;
129     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
130     return $self->load_browse if $path =~ m|opac/browse|;
131
132     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
133     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
134     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
135     return $self->load_mylist if $path =~ m|opac/mylist|;
136     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
137     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
138     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
139
140     # ----------------------------------------------------------------
141     #  Everything below here requires SSL
142     # ----------------------------------------------------------------
143     return $self->redirect_ssl unless $self->cgi->https;
144     return $self->load_password_reset if $path =~ m|opac/password_reset|;
145     return $self->load_logout if $path =~ m|opac/logout|;
146     return $self->load_patron_reg if $path =~ m|opac/register|;
147
148     if($path =~ m|opac/login|) {
149         return $self->load_login unless $self->editor->requestor; # already logged in?
150
151         # This will be less confusing to users than to be shown a login form
152         # when they're already logged in.
153         return $self->generic_redirect(
154             sprintf(
155                 "%s://%s%s/myopac/main",
156                 $self->ctx->{proto},
157                 $self->ctx->{hostname}, $self->ctx->{opac_root}
158             )
159         );
160     }
161
162     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
163         my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
164         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
165         return $self->load_sms_cn if $skip_sms_auth;
166     }
167
168     # ----------------------------------------------------------------
169     #  Everything below here requires authentication
170     # ----------------------------------------------------------------
171     return $self->redirect_auth unless $self->editor->requestor;
172
173     # Don't cache anything requiring auth for security reasons
174     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
175     $self->apache->headers_out->add("expires" => "-1");
176
177     return $self->load_email_record if $path =~ m|opac/record/email|;
178
179     return $self->load_place_hold if $path =~ m|opac/place_hold|;
180     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
181     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
182     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
183     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
184     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
185     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
186     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
187     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
188     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
189     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
190     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
191     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
192     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
193     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
194     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
195     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
196     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
197     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
198     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
199     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
200     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
201     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
202     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
203
204     return Apache2::Const::OK;
205 }
206
207
208 # -----------------------------------------------------------------------------
209 # Redirect to SSL equivalent of a given page
210 # -----------------------------------------------------------------------------
211 sub redirect_ssl {
212     my $self = shift;
213     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
214     return $self->generic_redirect($new_page);
215 }
216
217 # -----------------------------------------------------------------------------
218 # If an authnticated resource is requested w/o auth, redirect to the login page,
219 # then return to the originally requrested resource upon successful login.
220 # -----------------------------------------------------------------------------
221 sub redirect_auth {
222     my $self = shift;
223     my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
224     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
225     return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
226 }
227
228 # -----------------------------------------------------------------------------
229 # Fall-through for loading a basic page
230 # -----------------------------------------------------------------------------
231 sub load_simple {
232     my ($self, $page) = @_;
233     $self->ctx->{page} = $page;
234     $self->ctx->{search_ou} = $self->_get_search_lib();
235
236     return Apache2::Const::OK;
237 }
238
239 # -----------------------------------------------------------------------------
240 # Tests to see if the user is authenticated and sets some common context values
241 # -----------------------------------------------------------------------------
242 sub load_common {
243     my $self = shift;
244
245     my $e = $self->editor;
246     my $ctx = $self->ctx;
247
248     # redirect non-https to https if we think we are already logged in
249     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
250         return $self->redirect_ssl unless $self->cgi->https;
251     }
252
253     $ctx->{referer} = $self->cgi->referer;
254     $ctx->{path_info} = $self->cgi->path_info;
255     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
256     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
257     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
258     my $oils_wrapper = $self->apache->headers_in->get('OILS-Wrapper') || '';
259     $ctx->{is_staff} = ($oils_wrapper =~ /true/);
260     $ctx->{proto} = 'oils' if $ctx->{is_staff};
261     $ctx->{hostname} = 'remote' if $ctx->{is_staff};
262     $ctx->{physical_loc} = $self->get_physical_loc;
263
264     # capture some commonly accessed pages
265     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
266     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
267
268     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
269
270         if($e->checkauth) {
271
272             $ctx->{authtoken} = $e->authtoken;
273             $ctx->{authtime} = $e->authtime;
274             $ctx->{user} = $e->requestor;
275             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
276
277             $ctx->{user_stats} = $U->simplereq(
278                 'open-ils.actor', 
279                 'open-ils.actor.user.opac.vital_stats', 
280                 $e->authtoken, $e->requestor->id);
281
282         } else {
283
284             # if we encounter a stale authtoken, call load_logout 
285             # to clean up the cookie, then redirect the user to the
286             # originally requested page
287             return $self->load_logout($self->apache->unparsed_uri);
288         }
289     }
290
291     $self->extract_copy_location_group_info;
292     $ctx->{search_ou} = $self->_get_search_lib();
293     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
294     $self->load_eg_cache_hash;
295     $self->load_copy_location_groups;
296     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
297     $self->load_search_filter_groups($ctx->{search_ou});
298     $self->load_org_util_funcs;
299
300     return Apache2::Const::OK;
301 }
302
303 sub staff_saved_searches_set_expansion_state {
304     my $self = shift;
305
306     my $param = $self->cgi->param('sss_expand');
307     my $value;
308     
309     if (defined $param) {
310         $value = ($param ? 1 : 0);
311         $self->apache->headers_out->add(
312             "Set-Cookie" => $self->cgi->cookie(
313                 -name => COOKIE_SSS_EXPAND,
314                 -path => $self->ctx->{base_path},
315                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
316                 -value => $value,
317                 -expires => undef
318             )
319         );
320     } else {
321         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
322     }
323
324     $self->ctx->{saved_searches_expanded} = $value;
325 }
326
327 # physical_loc (i.e. "original location") passed in as a URL 
328 # param will replace any existing physical_loc stored as a cookie.
329 # If specified via ENV that rules over all and we don't set cookies.
330 sub get_physical_loc {
331     my $self = shift;
332
333     return $ENV{physical_loc} if($ENV{physical_loc});
334
335     if(my $physical_loc = $self->cgi->param('physical_loc')) {
336         $self->apache->headers_out->add(
337             "Set-Cookie" => $self->cgi->cookie(
338                 -name => COOKIE_PHYSICAL_LOC,
339                 -path => $self->ctx->{base_path},
340                 -value => $physical_loc,
341                 -expires => undef
342             )
343         );
344         return $physical_loc;
345     }
346
347     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
348 }
349
350 # -----------------------------------------------------------------------------
351 # Log in and redirect to the redirect_to URL (or home)
352 # -----------------------------------------------------------------------------
353 sub load_login {
354     my $self = shift;
355     my $cgi = $self->cgi;
356     my $ctx = $self->ctx;
357
358     $self->timelog("Load login begins");
359
360     $ctx->{page} = 'login';
361
362     my $username = $cgi->param('username');
363     $username =~ s/\s//g;  # Remove blanks
364     my $password = $cgi->param('password');
365     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
366     my $persist = $cgi->param('persist');
367
368     # initial log form only
369     return Apache2::Const::OK unless $username and $password;
370
371     my $auth_proxy_enabled = 0; # default false
372     try { # if the service is not running, just let this fail silently
373         $auth_proxy_enabled = $U->simplereq(
374             'open-ils.auth_proxy',
375             'open-ils.auth_proxy.enabled');
376     } catch Error with {};
377
378     $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
379
380     my $args = {
381         type => ($persist) ? 'persist' : 'opac',
382         org => $org_unit,
383         agent => 'opac'
384     };
385
386     my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
387
388     # To avoid surprises, default to "Barcodes start with digits"
389     $bc_regex = '^\d' unless $bc_regex;
390
391     if ($bc_regex and ($username =~ /$bc_regex/)) {
392         $args->{barcode} = $username;
393     } else {
394         $args->{username} = $username;
395     }
396
397     my $response;
398     if (!$auth_proxy_enabled) {
399         my $seed = $U->simplereq(
400             'open-ils.auth',
401             'open-ils.auth.authenticate.init', $username);
402         $args->{password} = md5_hex($seed . md5_hex($password));
403         $response = $U->simplereq(
404             'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
405     } else {
406         $args->{password} = $password;
407         $response = $U->simplereq(
408             'open-ils.auth_proxy',
409             'open-ils.auth_proxy.login', $args);
410     }
411     $self->timelog("Checked password");
412
413     if($U->event_code($response)) { 
414         # login failed, report the reason to the template
415         $ctx->{login_failed_event} = $response;
416         return Apache2::Const::OK;
417     }
418
419     # login succeeded, redirect as necessary
420
421     my $acct = $self->apache->unparsed_uri;
422     $acct =~ s|/login|/myopac/main|;
423
424     # both login-related cookies should expire at the same time
425     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
426
427     return $self->generic_redirect(
428         $cgi->param('redirect_to') || $acct,
429         [
430             # contains the actual auth token and should be sent only over https
431             $cgi->cookie(
432                 -name => COOKIE_SES,
433                 -path => '/',
434                 -secure => 1,
435                 -value => $response->{payload}->{authtoken},
436                 -expires => $login_cookie_expires
437             ),
438             # contains only a hint that we are logged in, and is used to
439             # trigger a redirect to https
440             $cgi->cookie(
441                 -name => COOKIE_LOGGEDIN,
442                 -path => '/',
443                 -secure => 0,
444                 -value => '1',
445                 -expires => $login_cookie_expires
446             )
447         ]
448     );
449 }
450
451 # -----------------------------------------------------------------------------
452 # Log out and redirect to the home page
453 # -----------------------------------------------------------------------------
454 sub load_logout {
455     my $self = shift;
456     my $redirect_to = shift || $self->cgi->param('redirect_to');
457
458     # If the user was adding anyting to an anonymous cache 
459     # while logged in, go ahead and clear it out.
460     $self->clear_anon_cache;
461
462     return $self->generic_redirect(
463         $redirect_to || $self->ctx->{home_page},
464         [
465             # clear value of and expire both of these login-related cookies
466             $self->cgi->cookie(
467                 -name => COOKIE_SES,
468                 -path => '/',
469                 -value => '',
470                 -expires => '-1h'
471             ),
472             $self->cgi->cookie(
473                 -name => COOKIE_LOGGEDIN,
474                 -path => '/',
475                 -value => '',
476                 -expires => '-1h'
477             )
478         ]
479     );
480 }
481
482 1;
483