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