Reactor.pm untested

filter: Statementstmt 0.0% 0 / 714 Branchbran 0.0% 0 / 186 Conditioncond 0.0% 0 / 127 Subroutinesub 0.0% 0 / 106 Podpod 0.0% 0 / 93 totaltotal 0.0% 0 / 1226 CC 94 SCAR 49.9
CC
94
Cov
0%
main_process
870.0
render
210.0
new
30.0
CRAP 147.4
1 ##############################################################################
2 ##
3 ## Web::Reactor application machinery
4 ## 2013-2017 (c) Vladi Belperchinov-Shabanski "Cade"
5 ## <cade@bis.bg> <cade@biscom.net> <cade@cpan.org>
6 ##
7 ## LICENSE: GPLv2
8 ##
9 ##############################################################################
10 package Web::Reactor;
11 use strict;
12 use Storable qw( dclone freeze thaw ); # FIXME: move to Data::Tools (data_freeze/data_thaw)
13 use CGI 4.08;
14 use CGI::Cookie;
15 use Data::Tools;
16 use Exception::Sink;
17 use Data::Dumper;
18  
19 use Web::Reactor::Utils;
20 use Web::Reactor::HTML::Form;
21  
22 our $VERSION = '2.06';
23  
24 ##############################################################################
25  
26 #minimum config:
27 #my %cfg = (
28 # '' => ,
29 # );
30  
31 our @HTTP_VARS_CHECK = qw(
32 REMOTE_ADDR
33 HTTP_USER_AGENT
34 );
35  
36 our @HTTP_VARS_SAVE = qw(
37 REMOTE_ADDR
38 REMOTE_PORT
39 REQUEST_METHOD
40 REQUEST_URI
41 HTTP_REFERRER
42 QUERY_STRING
43 HTTP_COOKIE
44 HTTP_USER_AGENT
45 );
46  
47 our %ENV_ALLOWED_KEYS = {
48  
49 };
50  
51 ##############################################################################
52  
53 sub new
54 {
55 my $class = shift;
56 my %env = @_;
57  
58 # FIXME: verify %env content! Data::Validate::Struct
59  
60 $class = ref( $class ) || $class;
61 my $self = {
62 'ENV' => \%env,
63 };
64 bless $self, $class;
65  
66 # my $root = $self->{ 'ENV' }{ 'ROOT' };
67 # # autosetup defaults
68 # if( ! $self->{ 'ENV' }{ 'HTML_DIRS' } )
69 # {
70 # $self->{ 'ENV' }{ 'HTML_DIRS' } = [ "$root/html" ];
71 # }
72  
73 # FIXME: common directories setup code?
74 if( ! $env{ 'LIB_DIRS' } or @{ $env{ 'LIB_DIRS' } } < 1 )
75 {
76 my $root = $env{ 'APP_ROOT' };
77 $env{ 'LIB_DIRS' } = [ "$root/lib" ];
78 }
79  
80 my $lib_dirs = $env{ 'LIB_DIRS' } || [];
81 my $lib_dirs_ok = 0;
82 for my $lib_dir ( @$lib_dirs )
83 {
84 next unless -d $lib_dir;
85 push @INC, $lib_dir;
86 $lib_dirs_ok++;
87 }
88 boom "invalid or not accessible LIB_DIR's [@$lib_dirs]" unless $lib_dirs_ok;
89  
90 # sanity, remove '.' from include list, TODO: optionally remove other entries by config (%env)
91 for my $z ( 0 .. scalar( @INC ) - 1 )
92 {
93 next unless $INC[ $z ] eq '.';
94 splice @INC, $z, 1;
95 last;
96 }
97  
98 my $reo_sess_class = $env{ 'REO_SESS_CLASS' } ||= 'Web::Reactor::Sessions::Filesystem';
99 my $reo_prep_class = $env{ 'REO_PREP_CLASS' } ||= 'Web::Reactor::Preprocessor::Native';
100 my $reo_acts_class = $env{ 'REO_ACTS_CLASS' } ||= 'Web::Reactor::Actions::Native';
101  
102 my $reo_sess_class_file = perl_package_to_file( $reo_sess_class );
103 my $reo_prep_class_file = perl_package_to_file( $reo_prep_class );
104 my $reo_acts_class_file = perl_package_to_file( $reo_acts_class );
105  
106 require $reo_sess_class_file;
107 require $reo_prep_class_file;
108 require $reo_acts_class_file;
109  
110 # new objects for part slots
111 # FIXME: pass %env reference to use the same env hash
112 $self->{ 'REO_SESS' } = new $reo_sess_class %env;
113 $self->{ 'REO_PREP' } = new $reo_prep_class %env;
114 $self->{ 'REO_ACTS' } = new $reo_acts_class %env;
115  
116 # set backlinks to reactor
117 $self->{ 'REO_SESS' }->__set_reo( $self );
118 $self->{ 'REO_PREP' }->__set_reo( $self );
119 $self->{ 'REO_ACTS' }->__set_reo( $self );
120  
121 # debug setup
122 $self->log_debug( "debug: setup: " . Dumper( $self->{ 'ENV' } ) );
123  
124 return $self;
125 }
126  
127 #sub DESTROY
128 #{
129 # my $self = shift;
130 #
131 # print "DESTROY: Reactor: $self\n";
132 #}
133  
134 ##############################################################################
135  
136 sub run
137 {
138 my $self = shift;
139  
140 eval
141 {
142 $self->main_process();
143 };
144 if( surface( 'CONTENT' ) )
145 {
146 # nothing, should be ok
147 }
148 elsif( surface( '*' ) )
149 {
150 $self->log( "error: main process failed: $@" );
151 }
152 $self->save();
153  
154 if( $self->is_debug() )
155 {
156 my $psid = $self->get_page_session_id( 0 ) || 'empty';
157 my $rsid = $self->get_page_session_id( 1 ) || 'empty';
158 $self->log_dumper( "USER INPUT -----------------------------------", $self->get_user_input() );
159 $self->log_dumper( "SAFE INPUT -----------------------------------", $self->get_safe_input() );
160 $self->log_dumper( "FINAL PAGE SESSION [$psid]-----------------------------------", $self->get_page_session() );
161 $self->log_dumper( "FINAL REF SESSION [$rsid]-----------------------------------", $self->get_page_session( 1 ) );
162 #$self->log_dumper( "FINAL USER SESSION [$psid]-----------------------------------", $self->get_user_session() );
163 }
164  
165 }
166  
167 sub main_process
168 {
169 my $self = shift;
170  
171 # 0. load/setup env/config defaults
172 my $app_name = $self->{ 'ENV' }{ 'APP_NAME' } or $self->boom( "missing APP_NAME" );
173  
174 # 1. loading request header
175  
176 # 2. loading cookie
177 my $cookie_name = lc( $self->{ 'ENV' }{ 'COOKIE_NAME' } || "$app_name\_cookie" );
178 my $user_sid = $self->get_cookie( $cookie_name );
179  
180 # 3. loading user session, setup new session and cookie if needed
181 my $user_shr = {}; # user session hash ref
182 if( ! ( $user_sid =~ /^[a-zA-Z0-9]+$/ and $user_shr = $self->sess_load( 'USER', $user_sid ) ) )
183 {
184 # print STDERR Dumper( $user_sid, $user_shr );
185  
186 $self->log( "warning: invalid user session [$user_sid]" );
187  
188 ( $user_sid, $user_shr ) = $self->__create_new_user_session();
189 }
190 $self->{ 'SESSIONS' }{ 'SID' }{ 'USER' } = $user_sid;
191 $self->{ 'SESSIONS' }{ 'DATA' }{ 'USER' }{ $user_sid } = $user_shr;
192  
193 # read http environment data, used for checks and info
194 $user_shr->{ ":HTTP_ENV_HR" } = { map { $_ => $ENV{ $_ } } @HTTP_VARS_SAVE };
195  
196 if( ( $user_shr->{ ':LOGGED_IN' } and $user_shr->{ ':XTIME' } > 0 and time() > $user_shr->{ ':XTIME' } )
197 or
198 ( $user_shr->{ ':CLOSED' } ) )
199 {
200 $self->log( "status: user session expired or closed, sid [$user_sid]" );
201 # not logged-in sessions dont expire
202 $user_shr->{ ':XTIME_STR' } = scalar localtime() if time() > $user_shr->{ ':XTIME' };
203 $user_shr->{ ':CLOSED' } = 1;
204 $user_shr->{ ':ETIME' } = time();
205 $user_shr->{ ':ETIME_STR' } = scalar localtime();
206  
207 ( $user_sid, $user_shr ) = $self->__create_new_user_session();
208  
209 $self->render( PAGE => 'eexpired' );
210 }
211  
212 for my $k ( keys %{ $user_shr->{ ":HTTP_CHECK_HR" } } )
213 {
214 # check if session parameters are changed, stealing session?
215 next if $user_shr->{ ":HTTP_CHECK_HR" }{ $k } eq $ENV{ $k };
216  
217 $self->log( "status: user session parameter [$k] check failed, sid [$user_sid]" );
218 # FIXME: move to function: close_session();
219 $user_shr->{ ':CLOSED' } = 1;
220 $user_shr->{ ':ETIME' } = time();
221 $user_shr->{ ':ETIME_STR' } = scalar localtime();
222  
223 ( $user_sid, $user_shr ) = $self->__create_new_user_session();
224  
225 $self->render( PAGE => 'einvalid' );
226 last;
227 }
228  
229 # FIXME: move to single place
230 my $user_session_expire = $self->{ 'ENV' }{ 'USER_SESSION_EXPIRE' } || 600; # 10 minutes
231 $self->set_user_session_expire_time_in( $user_session_expire );
232  
233 $self->save();
234  
235 # 4. get input data, CGI::params, postdata
236 my $input_user_hr = $self->{ 'INPUT_USER_HR' } = {};
237 my $input_safe_hr = $self->{ 'INPUT_SAFE_HR' } = {};
238  
239 # FIXME: TODO: handle and URL params here. only for EX?
240 my $iconv;
241 my $app_charset = uc $self->{ 'ENV' }{ 'APP_CHARSET' } || 'UTF-8';
242  
243 if( $app_charset )
244 {
245 my $incoming_charset;
246 if( uc( CGI::http( 'HTTP_X_REQUESTED_WITH' ) ) eq 'XMLHTTPREQUEST' )
247 {
248 $incoming_charset = 'UTF-8';
249 }
250 if( $incoming_charset and $incoming_charset ne $app_charset )
251 {
252 eval
253 {
254 # FIXME: use Encode; instead
255 require 'Text/Iconv.pm';
256 $iconv = Text::Iconv->new( $incoming_charset, $app_charset );
257 };
258 if( $@ )
259 {
260 $self->log( "error: cannot convert charset from [$incoming_charset] to [$app_charset] error: $@" );
261 }
262 }
263 }
264  
265 # import plain parameters from GET/POST request
266 for my $n ( CGI::param() )
267 {
268 if( $n !~ /^[A-Za-z0-9\-\_\.\:]+$/o )
269 {
270 $self->log( "error: invalid CGI/input parameter name: [$n]" );
271 next;
272 }
273 my $v = CGI::param( $n );
274 my @v = CGI::multi_param( $n );
275  
276 if( $iconv )
277 {
278 $v = $iconv->convert( $v );
279 $_ = $iconv->convert( $_ ) for @v;
280 }
281  
282 $n = uc $n;
283  
284 $self->log_debug( "debug: CGI input param [$n] value [$v] [@v]" );
285  
286 if( $self->__input_cgi_skip_invalid_value( $n, $v ) )
287 {
288 $self->log( "error: invalid CGI/input value for parameter: [$n]" );
289 next;
290 }
291 $v = $self->__input_cgi_make_safe_value( $n, $v );
292 if ( $n =~ /BUTTON:([a-z0-9_\-]+)(:(.+?))?(\.[XY])?$/oi )
293 {
294 # regular button BUTTON:CANCEL
295 # button with id BUTTON:REDIRECT:USERID
296 $input_user_hr->{ 'BUTTON' } = uc $1;
297 $input_user_hr->{ 'BUTTON_ID' } = $3;
298 }
299 elsif( $n eq '_BUTTON_NAME' )
300 {
301 my ( undef, $b, $i ) = split /:/, $v, 3;
302 $input_user_hr->{ 'BUTTON' } = uc $b;
303 $input_user_hr->{ 'BUTTON_ID' } = $i;
304 }
305 else
306 {
307 $n = uc $n;
308 $input_user_hr->{ $n } = $v;
309 if( ref( $v ) eq 'Fh' )
310 {
311 # this is file upload, get more info
312 $input_user_hr->{ "$n:UPLOAD_INFO" } = CGI::uploadInfo( $v );
313 }
314 }
315 }
316  
317 my $safe_input_link_sess = $input_user_hr->{ '_' };
318 # parse link session: link-sid.link-key
319 if( $safe_input_link_sess =~ /^([a-zA-Z0-9]+)\.([a-zA-Z0-9]+)$/ )
320 {
321 my ( $link_sid, $link_key ) = ( $1, $2 );
322  
323 my $link_session_hr = $self->sess_load( 'LINK', $link_sid );
324  
325 my $link_data = $link_session_hr->{ $link_key };
326  
327 # merge safe input if valid
328 %$input_safe_hr = ( %$input_safe_hr, %$link_data ) if $link_data;
329 }
330 elsif( $safe_input_link_sess ne '' )
331 {
332 $self->log( "warning: invalid safe input link session.key [$safe_input_link_sess]" );
333 }
334  
335 # 5. loading page session
336 my $page_sid = $input_safe_hr->{ '_P' };
337 my $page_shr = {}; # user session hash ref
338 if( ! ( $page_sid =~ /^[a-zA-Z0-9]+$/ and $page_shr = $self->sess_load( 'PAGE', $page_sid ) ) )
339 {
340 $self->log( "warning: invalid page session [$page_sid]" );
341 $page_sid = $self->sess_create( 'PAGE', 8 );
342 $self->log( "warning: new page session created [$page_sid]" );
343 $page_shr = { ':ID' => $page_sid };
344 }
345 $self->{ 'SESSIONS' }{ 'SID' }{ 'PAGE' } = $page_sid;
346 $self->{ 'SESSIONS' }{ 'DATA' }{ 'PAGE' }{ $page_sid } = $page_shr;
347  
348  
349 my $ref_page_sid = $input_safe_hr->{ '_R' };
350 if( $ref_page_sid =~ /^[a-zA-Z0-9]+$/ )
351 {
352 $page_shr->{ ':REF_PAGE_SID' } = $ref_page_sid;
353 }
354  
355 # 6. remap form input data, post to safe input
356 my $form_name = $input_safe_hr->{ 'FORM_NAME' }; # FIXME: replace with _FO
357 if( $form_name and exists $page_shr->{ ':FORM_DEF' }{ $form_name } )
358 {
359 my $rm = $page_shr->{ ':FORM_DEF' }{ $form_name }{ 'RET_MAP' };
360  
361 for my $k ( keys %$rm )
362 {
363 next unless exists $input_user_hr->{ $k };
364 $input_safe_hr->{ $k } = $rm->{ $k }{ $input_user_hr->{ $k } };
365 delete $input_user_hr->{ $k };
366 }
367 }
368  
369 my $frame_name = $input_safe_hr->{ '_FR' };
370 if( $frame_name ne '' )
371 {
372 if( $frame_name =~ /^[a-zA-Z_0-9]+$/ )
373 {
374 $page_shr->{ ':FRAME_NAME' } = $frame_name;
375 }
376 else
377 {
378 $self->log( "error: invalid frame name [$frame_name]" );
379 }
380 }
381  
382 # 7. get action from input (USER/CGI) or page session
383 my $action_name = lc( $input_safe_hr->{ '_AN' } || $input_user_hr->{ '_AN' } || $page_shr->{ ':ACTION_NAME' } );
384 if( $action_name =~ /^[a-z_0-9]+$/ )
385 {
386 $page_shr->{ ':ACTION_NAME' } = $action_name;
387 }
388 else
389 {
390 # $self->log( "error: invalid action name [$action_name]" );
391 }
392  
393 # 8. get page from input (USER/CGI) or page session
394 my $page_name = lc( $input_safe_hr->{ '_PN' } || $input_user_hr->{ '_PN' } || $page_shr->{ ':PAGE_NAME' } || 'main' );
395 if( $page_name ne '' )
396 {
397 if( $page_name =~ /^[a-z_0-9]+$/ )
398 {
399 $page_shr->{ ':PAGE_NAME' } = $page_name;
400 }
401 else
402 {
403 $self->log( "error: invalid page name [$page_name]" );
404 }
405 }
406  
407 # pre-9. print debug status...
408 if( $self->is_debug() )
409 {
410 my $psid = $self->get_page_session_id( 0 ) || 'empty';
411 my $rsid = $self->get_page_session_id( 1 ) || 'empty';
412 $self->log_dumper( "USER INPUT-------------------------------------", $self->get_user_input() );
413 $self->log_dumper( "SAFE INPUT-------------------------------------", $self->get_safe_input() );
414 $self->log_dumper( "PAGE SESSION [$psid]-----------------------------------", $self->get_page_session() );
415 $self->log_dumper( "REF SESSION [$rsid]-----------------------------------", $self->get_page_session( 1 ) );
416 # $self->log_dumper( "USER SESSION-----------------------------------", $self->get_user_session() );
417 }
418  
419 # 9. render output action/page
420 if( $action_name )
421 {
422 $self->render( ACTION => $action_name );
423 }
424 else
425 {
426 $self->render( PAGE => $page_name );
427 }
428  
429 }
430  
431 sub __create_new_user_session
432 {
433 my $self = shift;
434  
435 my $user_sid;
436 my $user_shr;
437  
438 # FIXME: move to function
439 my $app_name = $self->{ 'ENV' }{ 'APP_NAME' } or $self->boom( "missing APP_NAME" );
440 my $cookie_name = lc( $self->{ 'ENV' }{ 'COOKIE_NAME' } || "$app_name\_cookie" );
441  
442 $user_sid = $self->sess_create( 'USER' );
443 $user_shr = { ':ID' => $user_sid };
444 $self->{ 'SESSIONS' }{ 'SID' }{ 'USER' } = $user_sid;
445 $self->{ 'SESSIONS' }{ 'DATA' }{ 'USER' }{ $user_sid } = $user_shr;
446  
447 my $secure_cookie = $self->{ 'ENV' }{ 'DISABLE_SECURE_COOKIES' } ? 0 : 1;
448 $self->set_cookie( $cookie_name, -value => $user_sid, -httponly => 1, -secure => $secure_cookie );
449 $self->log( "debug: creating new user session [$user_sid]" );
450  
451 my $user_session_expire = $self->{ 'ENV' }{ 'USER_SESSION_EXPIRE' } || 600; # 10 minutes
452  
453 $user_shr->{ ':CTIME' } = time();
454 $user_shr->{ ':CTIME_STR' } = scalar localtime();
455  
456 $self->set_user_session_expire_time_in( $user_session_expire );
457  
458 $user_shr->{ ":HTTP_CHECK_HR" } = { map { $_ => $ENV{ $_ } } @HTTP_VARS_CHECK };
459  
460 return ( $user_sid, $user_shr );
461 }
462  
463 ##############################################################################
464 #
465 # usual user visible api
466 #
467  
468 sub get_user_session
469 {
470 my $self = shift;
471  
472 my $user_sid = $self->{ 'SESSIONS' }{ 'SID' }{ 'USER' };
473 my $user_shr = $self->{ 'SESSIONS' }{ 'DATA' }{ 'USER' }{ $user_sid };
474  
475 return $user_shr;
476 }
477  
478 sub get_user_session_id
479 {
480 my $self = shift;
481  
482 my $user_sid = $self->{ 'SESSIONS' }{ 'SID' }{ 'USER' };
483  
484 return $user_sid;
485 }
486  
487 sub get_page_session
488 {
489 my $self = shift;
490 my $level = shift;
491  
492 my $page_sid = $self->{ 'SESSIONS' }{ 'SID' }{ 'PAGE' };
493 my $page_shr = $self->{ 'SESSIONS' }{ 'DATA' }{ 'PAGE' }{ $page_sid };
494  
495 while( $level-- )
496 {
497 $page_sid = $page_shr->{ ':REF_PAGE_SID' };
498 return undef unless $page_sid;
499 $page_shr = $self->{ 'SESSIONS' }{ 'DATA' }{ 'PAGE' }{ $page_sid };
500 if( ! $page_shr )
501 {
502 $page_shr = $self->sess_load( 'PAGE', $page_sid );
503 $self->{ 'SESSIONS' }{ 'DATA' }{ 'PAGE' }{ $page_sid } = $page_shr;
504 }
505 }
506  
507 return $page_shr;
508 }
509  
510 sub get_http_env
511 {
512 my $self = shift;
513  
514 my $user_shr = $self->get_user_session();
515  
516 boom "missing HTTP_ENV inside user session" unless exists $user_shr->{ ':HTTP_ENV_HR' };
517  
518 return $user_shr->{ ':HTTP_ENV_HR' };
519 }
520  
521 sub get_page_session_id
522 {
523 my $self = shift;
524 my $level = shift;
525  
526 my $shr = $self->get_page_session( $level ) || {};
527  
528 return $shr->{ ':ID' };
529 }
530  
531 sub get_ref_page_session_id
532 {
533 my $self = shift;
534 my $level = shift;
535  
536 my $shr = $self->get_page_session( $level ) || {};
537  
538 return $shr->{ ':REF_PAGE_SID' };
539 }
540  
541 sub get_safe_input
542 {
543 my $self = shift;
544  
545 my $input_safe_hr = $self->{ 'INPUT_SAFE_HR' };
546 return $input_safe_hr;
547 }
548  
549 sub get_user_input
550 {
551 my $self = shift;
552  
553 my $input_user_hr = $self->{ 'INPUT_USER_HR' };
554 return $input_user_hr;
555 }
556  
557 sub get_input_button
558 {
559 my $self = shift;
560  
561 my $input_user_hr = $self->get_user_input();
562 my $input_safe_hr = $self->get_safe_input();
563 return $input_safe_hr->{ 'BUTTON' } || $input_user_hr->{ 'BUTTON' };
564 }
565  
566 sub get_input_button_id
567 {
568 my $self = shift;
569  
570 my $input_user_hr = $self->get_user_input();
571 my $input_safe_hr = $self->get_safe_input();
572 return $input_safe_hr->{ 'BUTTON_ID' } || $input_user_hr->{ 'BUTTON_ID' };
573 }
574  
575 sub get_input_button_and_remove
576 {
577 my $self = shift;
578  
579 my $input_user_hr = $self->get_user_input();
580 my $input_safe_hr = $self->get_safe_input();
581 my $button = $input_safe_hr->{ 'BUTTON' } || $input_user_hr->{ 'BUTTON' };
582 delete $input_user_hr->{ 'BUTTON' };
583 delete $input_safe_hr->{ 'BUTTON' };
584 return $button;
585 }
586  
587 sub get_input_form_name
588 {
589 my $self = shift;
590  
591 my $input_safe_hr = $self->get_safe_input();
592 my $form_name = $input_safe_hr->{ 'FORM_NAME' }; # FIXME: replace with _FN
593  
594 return $form_name;
595 }
596  
597 sub get_page_frame
598 {
599 my $self = shift;
600  
601 my $page_shr = $self->get_page_session();
602  
603 return exists $page_shr->{ ':FRAME_NAME' } ? $page_shr->{ ':FRAME_NAME' } : undef;
604 }
605  
606 sub get_lang
607 {
608 my $self = shift;
609  
610 return $self->{ 'ENV' }{ 'LANG' };
611 }
612  
613 sub get_app_root
614 {
615 my $self = shift;
616  
617 return $self->{ 'ENV' }{ 'APP_ROOT' };
618 }
619  
620 sub args
621 {
622 my $self = shift;
623 my %args = @_;
624  
625 hash_uc_ipl( \%args );
626  
627 my $link_sid;
628 my $link_shr;
629  
630 if( ! $self->{ 'SESSIONS' }{ 'SID' }{ 'LINK' } )
631 {
632 $link_sid = $self->sess_create( 'LINK', 8 );
633 $link_shr = { ':ID' => $link_sid };
634 $self->{ 'SESSIONS' }{ 'DATA' }{ 'LINK' }{ $link_sid } = $link_shr;
635 $self->{ 'SESSIONS' }{ 'SID' }{ 'LINK' } = $link_sid;
636 }
637 else
638 {
639 $link_sid = $self->{ 'SESSIONS' }{ 'SID' }{ 'LINK' };
640 $link_shr = $self->{ 'SESSIONS' }{ 'DATA' }{ 'LINK' }{ $link_sid };
641 }
642  
643 my $link_key;
644 while(4)
645 {
646 $link_key = $self->{ 'REO_SESS' }->create_id( 8 ); # FIXME: length param env
647 last if ! exists $link_shr->{ $link_key };
648 }
649 $self->boom( "cannot create LINK key" ) unless $link_key;
650  
651 $link_shr->{ $link_key } = \%args;
652  
653 return $link_sid . '.' . $link_key;
654 }
655  
656 sub args_back
657 {
658 my $self = shift;
659 my %args = @_;
660  
661 $args{ '_P' } = $self->get_ref_page_session_id();
662 $args{ '_PN' } = 'main' unless $args{ '_P' }; # return to 'main' if no referer given
663  
664 return $self->args( %args );
665 }
666  
667 sub args_back_back
668 {
669 my $self = shift;
670 my %args = @_;
671  
672 $args{ '_P' } = $self->get_ref_page_session_id( 1 );
673 $args{ '_PN' } = 'main' unless $args{ '_P' }; # return to 'main' if no referer given
674  
675 return $self->args( %args );
676 }
677  
678 sub args_new
679 {
680 my $self = shift;
681 my %args = @_;
682  
683 $args{ '_R' } = $self->get_page_session_id();
684  
685 my $page_shr = $self->get_page_session();
686 if( exists $page_shr->{ ':FRAME_NAME' } )
687 {
688 $args{ '_FR' } = $page_shr->{ ':FRAME_NAME' };
689 }
690  
691 return $self->args( %args );
692 }
693  
694 sub args_here
695 {
696 my $self = shift;
697 my %args = @_;
698  
699 $args{ '_P' } = $self->get_page_session_id();
700  
701 return $self->args( %args );
702 }
703  
704 sub args_type
705 {
706 my $self = shift;
707  
708 my $type = lc shift;
709  
710 return $self->args_new( @_ ) if $type eq 'new';
711 return $self->args_here( @_ ) if $type eq 'here';
712 return $self->args_back( @_ ) if $type eq 'back';
713 return $self->args( @_ ) if $type eq 'none';
714 $self->boom( "unknown or not supported TYPE [$type]" );
715 }
716  
717 ##############################################################################
718  
719 sub get_cookie
720 {
721 my $self = shift;
722 my $name = shift;
723  
724 my $cookie = CGI::cookie( $name );
725 $self->log_debug( "get_cookie: name [$name] value [$cookie]" );
726 return $cookie;
727 }
728  
729 sub set_cookie
730 {
731 my $self = shift;
732 my $name = shift;
733 my %opt = @_;
734  
735 $self->log( "debug: creating new cookie [$name]" );
736 # FIXME: validate %opt Data::Validate::Struct
737  
738 $opt{ -name } = $name;
739  
740 $self->{ 'OUTPUT' }{ 'COOKIES' }{ $name } = new CGI::Cookie( %opt );
741 }
742  
743 ##############################################################################
744  
745 sub get_headers
746 {
747 my $self = shift;
748  
749 my %h = map { $_ => CGI::http( $_ ) } CGI::http();
750  
751 return \%h;
752 }
753  
754 sub set_headers
755 {
756 my $self = shift;
757 my %h = @_;
758  
759 hash_lc_ipl( \%h );
760  
761 $self->{ 'OUTPUT' }{ 'HEADERS' } ||= {};
762 $self->{ 'OUTPUT' }{ 'HEADERS' } = { %{ $self->{ 'OUTPUT' }{ 'HEADERS' } }, %h };
763 }
764  
765 sub __make_headers
766 {
767 my $self = shift;
768  
769 my $headers;
770  
771 $self->{ 'OUTPUT' }{ 'HEADERS' }{ 'content-type' } ||= 'text/html';
772  
773 # postprocess headers, custom logic, etc.
774 my %headers_out = %{ $self->{ 'OUTPUT' }{ 'HEADERS' } };
775  
776 if( $headers_out{ 'content-charset' } )
777 {
778 if( $headers_out{ 'content-type' } !~ /;\s*charset=/i )
779 {
780 $headers_out{ 'content-type' } .= '; charset=' . $headers_out{ 'content-charset' };
781 }
782 delete $headers_out{ 'content-charset' };
783 };
784  
785 while( my ( $k, $v ) = each %headers_out )
786 {
787 $headers .= "$k: $v\n";
788 }
789  
790 while( my ( $k, $v ) = each %{ $self->{ 'OUTPUT' }{ 'COOKIES' } } )
791 {
792 $k = 'set-cookie';
793 $headers .= "$k: $v\n";
794 }
795  
796 $headers .= "\n"; # just single newline separator
797  
798 $self->log_dumper( 'HEADERS----------------------------------------', $headers );
799  
800 return $headers;
801 }
802  
803 ##############################################################################
804  
805 sub save
806 {
807 my $self = shift;
808  
809 my $mod_cache = $self->{ 'CACHE' }{ 'SESSION_DATA_SHA1' } ||= {};
810  
811 for my $type ( qw( USER PAGE LINK ) )
812 {
813 while( my ( $sid, $shr ) = each %{ $self->{ 'SESSIONS' }{ 'DATA' }{ $type } } )
814 {
815 $self->boom( "SESSION:DATA:$type:$sid is not hashref" ) unless ref( $shr ) eq 'HASH';
816  
817 my $sha1 = sha1_hex( freeze( $shr ) );
818 my $cache1 = $mod_cache->{ $type }{ $sid };
819  
820 next if $sha1 eq $cache1;
821  
822 $self->log_debug( "saving session data [$type:$sid]" );
823  
824 $mod_cache->{ $type }{ $sid } = $sha1;
825  
826 $self->sess_save( $type, $sid, $shr );
827 }
828 }
829 }
830  
831 ##############################################################################
832 ##
833 ## CRYPTO api :)
834 ##
835  
836 ## FIXME: move most to Data::Tools or separate module
837  
838 sub __new_crypto_object
839 {
840 my $self = shift;
841  
842 # NOTE: RTFM says encryptor and decryptor must be different
843  
844 # FIXME: read key from config file only!
845 my $key = $self->{ 'ENV' }{ 'ENCRYPT_KEY' };
846 $self->boom( "missing ENV:ENCRYPT_KEY" ) unless $key =~ /\S/;
847  
848 my $ci = $self->{ 'ENV' }{ 'ENCRYPT_CIPHER' } || 'Twofish2'; # :)
849  
850 return new Crypt::CBC->new( -key => $key, -cipher => $ci );
851 }
852  
853 sub encrypt
854 {
855 my $self = shift;
856 my $data = shift;
857  
858 my $enc = $self->{ 'ENCRYPTOR' } ||= $self->__new_crypto_object();
859 return $enc->encrypt( $data );
860 }
861  
862 sub decrypt
863 {
864 my $self = shift;
865 my $data = shift;
866  
867 my $dec = $self->{ 'DECRYPTOR' } ||= $self->__new_crypto_object();
868 return $dec->decrypt( $data );
869 }
870  
871 sub encrypt_hex
872 {
873 my $self = shift;
874  
875 return str_hex( $self->encrypt( @_ ) );
876 }
877  
878 sub decrypt_hex
879 {
880 my $self = shift;
881  
882 return $self->decrypt( str_unhex( @_ ) );
883 }
884  
885 sub crypto_freeze_hex
886 {
887 my $self = shift;
888 my $data = shift; # reference to any data/scalar/hash/array
889  
890 return $self->encrypt_hex( freeze( $data ) );
891 }
892  
893 sub crypto_thaw_hex
894 {
895 my $self = shift;
896 my $data = shift; # hex encoded data
897  
898 return thaw( $self->decrypt_hex( $data ) );
899 }
900  
901 ##############################################################################
902  
903 sub set_debug
904 {
905 my $self = shift;
906 my $level = int(shift);
907  
908 if( $level > 0 )
909 {
910 $self->{ 'ENV' }{ 'DEBUG' } = $level > 0 ? $level : 0;
911 }
912 return $self->{ 'ENV' }{ 'DEBUG' };
913 }
914  
915 sub is_debug
916 {
917 my $self = shift;
918  
919 return $self->{ 'ENV' }{ 'DEBUG' };
920 }
921  
922 #-----------------------------------------------------------------------------
923  
924 sub log
925 {
926 my $self = shift;
927  
928 print STDERR @_, "\n";
929 }
930  
931 sub log_debug
932 {
933 my $self = shift;
934  
935 return unless $self->is_debug();
936 my @args = @_;
937 chomp( @args );
938 my $msg = join( "\n", @args );
939 $msg = "debug: $msg" unless $msg =~ /^debug:/i;
940 $self->log( $msg );
941 }
942  
943 sub log_stack
944 {
945 my $self = shift;
946  
947 $self->log_debug( @_, "\n", Exception::Sink::get_stack_trace() );
948 }
949  
950 sub log_dumper
951 {
952 my $self = shift;
953  
954 return unless $self->is_debug();
955 $self->log_debug( Dumper( @_ ) );
956 }
957  
958 ##############################################################################
959 ##
960 ## sanity policies
961 ## these are internal subs but are designed to be overriden if required
962 ##
963  
964 # fix/remove invalid parts of a CGI/input value
965 sub __input_cgi_make_safe_value
966 {
967 my $self = shift;
968 my $n = shift; # arg name
969 my $v = shift; # arg value
970  
971 $v =~ s/[\000]//go;
972  
973 return $v;
974 }
975  
976 # must return 1 for values which must be removed from input or 0 for ok
977 # this is called before __input_cgi_make_safe_value, default is pass all
978 sub __input_cgi_skip_invalid_value
979 {
980 my $self = shift;
981 # this is placeholder really
982 # my $n = shift; # arg name
983 # my $v = shift; # arg value
984 return 0;
985 }
986  
987 ##############################################################################
988  
989 sub html_content
990 {
991 my $self = shift;
992 my %hc = @_;
993  
994 hash_lc_ipl( \%hc );
995 $self->{ 'HTML_CONTENT' } ||= {};
996 %{ $self->{ 'HTML_CONTENT' } } = ( %{ $self->{ 'HTML_CONTENT' } }, %hc );
997  
998 return $self->{ 'HTML_CONTENT' };
999 }
1000  
1001 sub html_content_clear
1002 {
1003 my $self = shift;
1004  
1005 $self->{ 'HTML_CONTENT' } ||= {};
1006 }
1007  
1008 sub html_content_set
1009 {
1010 my $self = shift;
1011  
1012 $self->html_content_clear();
1013 return $self->html_content( @_ );
1014 }
1015  
1016 sub html_content_accumulator
1017 {
1018 my $self = shift;
1019 my $name = shift;
1020 my $text = shift;
1021  
1022 $self->{ 'HTML_CONTENT' } ||= {};
1023 $self->{ 'HTML_CONTENT' }{ $name }{ $text }++;
1024  
1025 $self->html_content_set( $name, join '', keys %{ $self->{ 'HTML_CONTENT' }{ $name } } );
1026 }
1027  
1028 sub html_content_accumulator_js
1029 {
1030 my $self = shift;
1031 my $text = shift;
1032  
1033 $text = "<script type='text/javascript' src='$text'></script>";
1034 $self->html_content_accumulator( "ACCUMULATOR_JS", $text );
1035 }
1036  
1037 sub html_content_accumulator_css
1038 {
1039 my $self = shift;
1040 my $css = shift;
1041  
1042 my $text = qq{ <link href="$css" rel="stylesheet" type="text/css"> };
1043 $self->html_content_accumulator( "ACCUMULATOR_HEAD", $text );
1044 }
1045  
1046 ##############################################################################
1047  
1048 sub render_data
1049 {
1050 my $self = shift;
1051  
1052 return $self->render( DATA => $self->portray( @_ ) );
1053 }
1054  
1055 sub render_action
1056 {
1057 my $self = shift;
1058 my $action = shift;
1059  
1060 return $self->render( ACTION => $action, @_ );
1061 }
1062  
1063 sub render_page
1064 {
1065 my $self = shift;
1066 my $page = shift;
1067  
1068 return $self->render( PAGE => $page, @_ );
1069 }
1070  
1071 sub render
1072 {
1073 my $self = shift;
1074 my %opt = @_;
1075  
1076 boom "too many nesting levels in rendering, probable bug in actions or pages" if (caller(512))[0] ne ''; # FIXME: config option for max level
1077  
1078 my $action = $opt{ 'ACTION' };
1079 my $page = $opt{ 'PAGE' };
1080 my $data = $opt{ 'DATA' };
1081  
1082 # FIXME: content vars handling set_content()/etc.
1083 my $ah = $self->args_here();
1084 $self->html_content( 'FORM_INPUT_SESSION_KEEPER' => "<input type=hidden name=_ value=$ah>" );
1085 $self->html_content( %opt );
1086  
1087 my $portray_data;
1088  
1089 if( ref( $data ) eq 'HASH' )
1090 {
1091 $portray_data = $data;
1092 $page = $action = undef;
1093 }
1094 elsif( $action )
1095 {
1096 # FIXME: handle content type also!
1097 $portray_data = $self->action_call( $action );
1098 $page = undef;
1099 }
1100 elsif( $page )
1101 {
1102 $portray_data = $self->prep_load_page( $page );
1103 $action = undef;
1104 }
1105 else
1106 {
1107 boom "render() needs PAGE or ACTION";
1108 }
1109  
1110 if( ref( $portray_data ) eq 'HASH' )
1111 {
1112 # nothing, ok
1113 }
1114 elsif( ref( $portray_data ) )
1115 {
1116 boom "expected portray data (i.e. HASHREF) but got different reference";
1117 }
1118 else
1119 {
1120 # default portray type is html
1121 $portray_data = $self->portray( $portray_data, 'text/html' );
1122 }
1123  
1124 #print STDERR Dumper( 'PORTRAY --- ' x 11, $page, $portray_data );
1125  
1126 my $page_data = $portray_data->{ 'DATA' };
1127 my $page_type = $portray_data->{ 'TYPE' };
1128 my $file_name = $portray_data->{ 'FILE_NAME' };
1129  
1130 if( lc $page_type =~ /^text\/html/ )
1131 {
1132 my $prep_opt1 = {};
1133 $page_data = $self->prep_process( $page, $page_data, $prep_opt1 );
1134  
1135 #print STDERR Dumper( 'OPT1 PREP --- ' x 11, $prep_opt1);
1136  
1137 my $prep_opt2 = {};
1138 $page_data = $self->prep_process( $page, $page_data, $prep_opt2 ) if $prep_opt1->{ 'SECOND_PASS_REQUIRED' };
1139  
1140 #print STDERR Dumper( 'PAGE DATA --- ' x 11, $page, $page_data );
1141  
1142 # FIXME: translation
1143 $self->load_trans();
1144 my $tr = $self->{ 'TRANS' }{ $self->{ 'ENV' }{ 'LANG' } } || {};
1145 $page_data =~ s/\<~([^\<\>]*)\>/$tr->{ $1 } || $1/ge;
1146 $page_data =~ s/\[~([^\[\]]*)\]/$tr->{ $1 } || $1/ge;
1147 }
1148  
1149 # FIXME: charset
1150 $self->set_headers( 'content-type' => $page_type );
1151 $self->set_headers( 'content-disposition' => "attachment; filename=$file_name" ) if $file_name;
1152  
1153 my $http_csp = $self->{ 'ENV' }{ 'HTTP_CSP' }; # || " default-src 'self' ";
1154 $self->set_headers( 'Content-Security-Policy' => $http_csp );
1155  
1156 my $app_charset = uc $self->{ 'ENV' }{ 'APP_CHARSET' } || 'UTF-8';
1157 $self->set_headers( 'content-charset' => $app_charset );
1158  
1159 my $page_headers = $self->__make_headers();
1160  
1161 print $page_headers;
1162 print $page_data;
1163  
1164 $self->log_debug( "debug: page response content: page, action, type, headers, data: " . Dumper( $page, $action, $page_type, $page_headers, $page_type =~ /^text\// ? $page_data : '*binary*' ) ) if $self->is_debug() > 2;
1165  
1166 if( $self->is_debug() > 1 and lc $page_type =~ /^text\/html/ )
1167 {
1168 my $psid = $self->get_page_session_id( 0 ) || 'empty';
1169 my $rsid = $self->get_page_session_id( 1 ) || 'empty';
1170 print "<hr><pre>[$rsid] << [$psid]</pre>";
1171 }
1172 if( $self->is_debug() > 2 and lc $page_type =~ /^text\/html/ )
1173 {
1174 local $Data::Dumper::Sortkeys = 1;
1175 local $Data::Dumper::Terse = 1;
1176 local $Data::Dumper::Indent = 3;
1177 print "<hr><pre>";
1178 print Dumper( 'USER INPUT:'.'_'x80, $self->{ 'INPUT_USER_HR' } );
1179 print Dumper( 'SAFE INPUT:'.'_'x80, $self->{ 'INPUT_SAFE_HR' } );
1180 print Dumper( 'PAGE SESSION:'.'_'x80, $self->{ 'SESSIONS' }{ 'DATA' }{ 'PAGE' }{ $self->{ 'SESSIONS' }{ 'SID' }{ 'PAGE' } } );
1181 print Dumper( 'USER SESSION:'.'_'x80, $self->{ 'SESSIONS' }{ 'DATA' }{ 'USER' }{ $self->{ 'SESSIONS' }{ 'SID' }{ 'USER' } } );
1182 # print "<hr>";
1183 # print Dumper( $self );
1184 print "</pre><hr>";
1185 }
1186  
1187 sink 'CONTENT';
1188 }
1189  
1190 my %SIMPLE_PORTRAY_TYPE_MAP = (
1191 html => 'text/html',
1192 text => 'text/plain',
1193 jpeg => 'image/jpeg',
1194 png => 'image/png',
1195 bin => 'application/octet-stream',
1196 );
1197  
1198 sub portray
1199 {
1200 my $self = shift;
1201 my $data = shift;
1202 my $type = lc shift; # mime type text/html
1203 my %opt = @_; # file name, charset, etc.
1204  
1205 $type = $SIMPLE_PORTRAY_TYPE_MAP{ $type } || $type;
1206  
1207 boom "portray needs mime type xxx/xxx as arg 2, got [$type]" unless $type =~ /^[a-z\-_0-9]+\/[a-z\-_0-9]+$/;
1208  
1209 return { DATA => $data, TYPE => $type, @_ };
1210 }
1211  
1212 ##############################################################################
1213  
1214 sub forward_url
1215 {
1216 my $self = shift;
1217 my $url = shift;
1218  
1219 # FIXME: use render+portray
1220 $self->set_headers( location => $url );
1221  
1222 my $page_headers = $self->__make_headers();
1223 print $page_headers;
1224  
1225 sink 'CONTENT';
1226 }
1227  
1228 sub forward
1229 {
1230 my $self = shift;
1231  
1232 boom "expected even number of arguments" unless @_ % 2 == 0;
1233  
1234 my $fw = $self->args( @_ );
1235 return $self->forward_url( "?_=$fw" );
1236 }
1237  
1238 sub forward_type
1239 {
1240 my $self = shift;
1241  
1242 boom "expected odd number of arguments" if @_ % 2 == 0;
1243  
1244 my $fw = $self->args_type( @_ );
1245 return $self->forward_url( "?_=$fw" );
1246 }
1247  
1248 sub forward_here
1249 {
1250 my $self = shift;
1251  
1252 boom "expected even number of arguments" unless @_ % 2 == 0;
1253  
1254 my $fw = $self->args_here( @_ );
1255 return $self->forward_url( "?_=$fw" );
1256 }
1257  
1258 sub forward_back
1259 {
1260 my $self = shift;
1261  
1262 boom "expected even number of arguments" unless @_ % 2 == 0;
1263  
1264 my $fw = $self->args_back( @_ );
1265 return $self->forward_url( "?_=$fw" );
1266 }
1267  
1268 sub forward_back_back
1269 {
1270 my $self = shift;
1271  
1272 boom "expected even number of arguments" unless @_ % 2 == 0;
1273  
1274 my $fw = $self->args_back_back( @_ );
1275 return $self->forward_url( "?_=$fw" );
1276 }
1277  
1278 sub forward_new
1279 {
1280 my $self = shift;
1281  
1282 boom "expected even number of arguments" unless @_ % 2 == 0;
1283  
1284 my $fw = $self->args_new( @_ );
1285 return $self->forward_url( "?_=$fw" );
1286 }
1287  
1288 sub forward_new_page
1289 {
1290 my $self = shift;
1291 my $page = shift;
1292  
1293 boom "expected page name + even number of arguments" unless @_ % 2 == 0;
1294  
1295 return $self->forward_new( _PN => $page, @_ );
1296 }
1297  
1298 sub forward_new_action
1299 {
1300 my $self = shift;
1301 my $actn = shift;
1302  
1303 boom "expected action name + even number of arguments" unless @_ % 2 == 0;
1304  
1305 return $self->forward_new( _AN => $actn, @_ );
1306 }
1307  
1308 ##############################################################################
1309 ##
1310 ## helpers
1311 ##
1312  
1313 sub __param
1314 {
1315 my $self = shift;
1316 my $safe = shift; # 1 safe_input, 0 user_input
1317  
1318 my $input_hr;
1319 my $save_key;
1320 if( $safe )
1321 {
1322 $input_hr = $self->get_safe_input();
1323 $save_key = 'SAVE_SAFE_INPUT';
1324 }
1325 else
1326 {
1327 $input_hr = $self->get_user_input();
1328 $save_key = 'SAVE_USER_INPUT';
1329 }
1330  
1331 my $ps = $self->get_page_session();
1332  
1333 $ps->{ $save_key } ||= {};
1334  
1335 my @res;
1336 while( @_ )
1337 {
1338 my $p = uc shift;
1339 if( exists $input_hr->{ $p } )
1340 {
1341 $ps->{ $save_key }{ $p } = $input_hr->{ $p };
1342 }
1343 push @res, $ps->{ $save_key }{ $p };
1344 }
1345  
1346 return wantarray ? @res : shift( @res );
1347 }
1348  
1349 sub param_unsafe
1350 {
1351 my $self = shift;
1352 return $self->__param( 0, @_ );
1353 }
1354  
1355 sub param
1356 {
1357 my $self = shift;
1358 return $self->__param( 1, @_ );
1359 }
1360  
1361 sub param_safe
1362 {
1363 my $self = shift;
1364 return $self->param( @_ );
1365 }
1366  
1367 sub param_clear_cache
1368 {
1369 my $self = shift;
1370  
1371 my $ps = $self->get_page_session();
1372  
1373 while( @_ )
1374 {
1375 my $p = uc shift;
1376 delete $ps->{ 'SAVE_SAFE_INPUT' }{ $p };
1377 delete $ps->{ 'SAVE_USER_INPUT' }{ $p };
1378 }
1379  
1380 return 1;
1381 }
1382  
1383  
1384 sub is_logged_in
1385 {
1386 my $self = shift;
1387  
1388 my $user_shr = $self->get_user_session();
1389 return $user_shr->{ ':LOGGED_IN' } ? 1 : 0;
1390 }
1391  
1392 sub login
1393 {
1394 my $self = shift;
1395  
1396 my $user_shr = $self->get_user_session();
1397 $user_shr->{ ':LOGGED_IN' } = 1;
1398 $user_shr->{ ':LTIME' } = time();
1399 $user_shr->{ ':LTIME_STR' } = scalar localtime();
1400 # FIXME: add more login info
1401 }
1402  
1403 sub logout
1404 {
1405 my $self = shift;
1406  
1407 my $user_shr = $self->get_user_session();
1408 $user_shr->{ ':LOGGED_IN' } = 0;
1409 $user_shr->{ ':CLOSED' } = 1;
1410 $user_shr->{ ':ETIME' } = time();
1411 $user_shr->{ ':ETIME_STR' } = scalar localtime();
1412 # FIXME: add more logout info
1413 my ( $user_sid, $user_shr ) = $self->__create_new_user_session();
1414 }
1415  
1416 # FIXME: s?
1417 sub need_login
1418 {
1419 my $self = shift;
1420  
1421 return if $self->is_logged_in();
1422  
1423 my $fw = $self->args_new( _PN => 'login' );
1424 return $self->forward_url( "?_=$fw" );
1425  
1426 # return $self->forward( _PN => 'login' );
1427 }
1428  
1429 sub set_user_session_expire_time
1430 {
1431 my $self = shift;
1432 my $xtime = shift;
1433  
1434 #use Exception::Sink;
1435 #my $xtt = localtime( $xtime );
1436 #print STDERR "set_user_session_expire_time($xtime)[$xtt]\n" . Exception::Sink::get_stack_trace();
1437  
1438 my $user_shr = $self->get_user_session();
1439 $user_shr->{ ':XTIME' } = $xtime; # FIXME: sanity?
1440 $user_shr->{ ':XTIME_STR' } = scalar localtime $user_shr->{ ':XTIME' };
1441 return exists $user_shr->{ ':XTIME' } ? $user_shr->{ ':XTIME' } : undef;
1442 }
1443  
1444 sub set_user_session_expire_time_in
1445 {
1446 my $self = shift;
1447 my $seconds = shift;
1448  
1449 #use Exception::Sink;
1450 #print STDERR "set_user_session_expire_time_in($seconds)\n" . Exception::Sink::get_stack_trace();
1451  
1452 # FIXME: support for more user friendly time periods 10m 60s
1453 return $self->set_user_session_expire_time( time() + $seconds );
1454 }
1455  
1456 # returns unix time at which user session will expire, undef if no expire time specified
1457 sub get_user_session_expire_time
1458 {
1459 my $self = shift;
1460  
1461 my $user_shr = $self->get_user_session();
1462 return exists $user_shr->{ ':XTIME' } ? $user_shr->{ ':XTIME' } : undef;
1463 }
1464  
1465 # returns time period in seconds, in which user session will expire, undef if no expire time specified
1466 sub get_user_session_expire_time_in
1467 {
1468 my $self = shift;
1469  
1470 my $xi = $self->get_user_session_expire_time() - time();
1471 return $xi > 0 ? $xi : undef;
1472 }
1473  
1474 sub need_post_method
1475 {
1476 my $self = shift;
1477  
1478 my $he = $self->get_http_env();
1479  
1480 return if $he->{ 'REQUEST_METHOD' } eq 'POST';
1481  
1482 $self->logout();
1483 $self->render( PAGE => 'epostrequired' );
1484 }
1485  
1486 sub get_user_session_agent
1487 {
1488 my $self = shift;
1489  
1490 my $user_session = $self->get_user_session();
1491 my $user_agent = $user_session->{ ':HTTP_ENV_HR' }{ 'HTTP_USER_AGENT' };
1492  
1493 return $user_agent || 'n/a';
1494 }
1495  
1496 ##############################################################################
1497  
1498 sub load_trans
1499 {
1500 my $self = shift;
1501  
1502 my $lang = lc $self->{ 'ENV' }{ 'LANG' };
1503  
1504 return 0 if $lang !~ /^[a-z][a-z]$/; # FIXME: move to init check! verofy hash etc. data::tools
1505  
1506 $self->{ 'TRANS' }{ 'LANG' } = $lang;
1507  
1508 return 1 if $self->{ 'TRANS' }{ $lang };
1509  
1510 my $tr = $self->{ 'TRANS' }{ $lang } = {};
1511  
1512 my $trans_dirs = $self->{ 'ENV' }{ 'TRANS_DIRS' };
1513  
1514 my @tf;
1515 for my $dir ( @$trans_dirs )
1516 {
1517 push @tf, glob( "$dir/$lang/*.tr" );
1518 push @tf, glob( "$dir/$lang/text/*.tr" );
1519 }
1520  
1521 for my $tf ( @tf )
1522 {
1523 my $hr = hash_load( $tf );
1524 # trim whitespace
1525 my @temp = %$hr;
1526 for( @temp )
1527 {
1528 s/^\s*//;
1529 s/\s*$//;
1530 }
1531 %$hr = @temp;
1532 @temp = ();
1533 @{ $tr }{ keys %$hr } = values %$hr;
1534 }
1535  
1536 return 1;
1537 }
1538  
1539 ##############################################################################
1540 ##
1541 ## REO proxies
1542 ##
1543  
1544 # FIXME: should actions have access to low-level session handling?
1545 sub sess_create { my $self = shift; $self->{ 'REO_SESS' }->create( @_ ) };
1546 sub sess_delete { my $self = shift; $self->{ 'REO_SESS' }->delete( @_ ) };
1547 sub sess_load { my $self = shift; $self->{ 'REO_SESS' }->load( @_ ) };
1548 sub sess_save { my $self = shift; $self->{ 'REO_SESS' }->save( @_ ) };
1549 sub sess_exists { my $self = shift; $self->{ 'REO_SESS' }->exists( @_ ) };
1550  
1551 #sub prep_render { my $self = shift; $self->{ 'REO_PREP' }->render( @_ ) };
1552 sub prep_load_page { my $self = shift; $self->{ 'REO_PREP' }->load_page( @_ ) };
1553 sub prep_load_file { my $self = shift; $self->{ 'REO_PREP' }->load_file( @_ ) };
1554 sub prep_process { my $self = shift; $self->{ 'REO_PREP' }->process( @_ ) };
1555  
1556 sub action_call { my $self = shift; $self->{ 'REO_ACTS' }->call( @_ ) };
1557  
1558 sub new_form
1559 {
1560 my $self = shift;
1561  
1562 my $form = new Web::Reactor::HTML::Form( @_, REO_REACTOR => $self );
1563  
1564 return $form;
1565 }
1566  
1567 ##############################################################################
1568  
1569 sub html_new_id
1570 {
1571 my $self = shift;
1572  
1573 my $psid = $self->get_page_session_id();
1574 $self->{ 'HTML_ID_COUNTER' }++;
1575 # FIXME: hash $psid once more to hide...
1576 return "REO_EID_$psid\_" . $self->{ 'HTML_ID_COUNTER' };
1577 }
1578  
1579 ##############################################################################
1580  
1581  
1582 =pod
1583  
1584 =head1 NAME
1585  
1586 Web::Reactor perl-based web application machinery.
1587  
1588 =head1 SYNOPSIS
1589  
1590 Startup CGI script example:
1591  
1592 #!/usr/bin/perl
1593 use strict;
1594 use lib '/opt/perl/reactor/lib'; # if Reactor is custom location installed
1595 use Web::Reactor;
1596  
1597 my %cfg = (
1598 'APP_NAME' => 'demo',
1599 'APP_ROOT' => '/opt/reactor/demo/',
1600 'LIB_DIRS' => [ '/opt/reactor/demo/lib/' ],
1601 'ACTIONS_SETS' => [ 'demo', 'Base', 'Core' ],
1602 'HTML_DIRS' => [ '/opt/reactor/demo/html/' ],
1603 'SESS_VAR_DIR' => '/opt/reactor/demo/var/sess/',
1604 'DEBUG' => 4,
1605 );
1606  
1607 eval { new Web::Reactor( %cfg )->run(); };
1608 if( $@ )
1609 {
1610 print STDERR "REACTOR CGI EXCEPTION: $@";
1611 print "content-type: text/html\n\nsystem is temporary unavailable";
1612 }
1613  
1614 =head1 INTRODUCTION
1615  
1616 Web::Reactor is a perl module which automates as much as possible of the all
1617 routine tasks when implementing web applications, interactive sites, etc.
1618 Main task is to handle all the repetative work and adding more comfortable
1619 functionality like:
1620  
1621 * setting and recognising web browser cookies (for sessions or other data)
1622 * handling user and page sessions (storage, cookie management, etc.)
1623 * hiding html link data and forms data to rise page-to-page transfer safety.
1624 * preprocessing of text/html, including hiding data, calling actions etc.
1625 * on-demand loading of 'actions', perl code modules to handle dynamic pages.
1626  
1627 Web::Reactor can be extended, though it was not supposed to. There are 4 main
1628 parts of it which can be extended. See section EXTENDING below for details.
1629  
1630 =head1 EXAMPLES
1631  
1632 HTML page file example:
1633  
1634 <#html_header>
1635  
1636 <$app_name>
1637  
1638 <#menu>
1639  
1640 testing page html file
1641  
1642 action test: <&test>
1643  
1644 <#html_footer>
1645  
1646 Action module example:
1647  
1648 package Reactor::Actions::demo::test;
1649 use strict;
1650 use Data::Dumper;
1651 use Web::Reactor::HTML::FormEngine;
1652  
1653 sub main
1654 {
1655 my $reo = shift; # Web::Reactor object. Provides all API and context.
1656  
1657 my $text; # result html text
1658  
1659 if( $reo->get_input_button() eq 'FORM_CANCEL' )
1660 {
1661 # if clicked form button is cancel,
1662 # return back to the calling/previous page/view with optional data
1663 return $reo->forward_back( ACTION_RETURN => 'IS_CANCEL' );
1664 }
1665  
1666 # add some html content
1667 $text .= "<p>Reactor::Actions::demo::test here!<p>";
1668  
1669 # create link and hide its data. only accessible from inside web app.
1670 my $grid_href = $reo->args_new( _PN => 'grid', TABLE => 'testtable', );
1671 $text .= "<a href=?_=$grid_href>go to grid</a><p>";
1672  
1673 # access page session. it will be auto-loaded on demand
1674 my $page_session_hr = $reo->get_page_session();
1675 my $fortune = $page_session_hr->{ 'FORTUNE' } ||= `/usr/games/fortune`;
1676  
1677 # access input (form) data. $i and $e are hashrefs
1678 my $i = $reo->get_user_input(); # get plain user input (hashref)
1679 my $e = $reo->get_safe_input(); # get safe data (never reach user browser)
1680  
1681 $text .= "<p><hr><p>$fortune<hr>";
1682  
1683 my $bc = $reo->args_here(); # session keeper, this is manual use
1684  
1685 $text .= "<form method=post>";
1686 $text .= "<input type=hidden name=_ value=$bc>";
1687 $text .= "input <input name=inp>";
1688 $text .= "<input type=submit name=button:form_ok>";
1689 $text .= "<input type=submit name=button:form_cancel>";
1690 $text .= "</form>";
1691  
1692 my $form = $reo->new_form();
1693  
1694 $text .= "<p><hr><p>";
1695  
1696 return $text;
1697 }
1698  
1699 1;
1700  
1701 =head1 PAGE NAMES, HTML FILE TEMPLATES, PAGE INSTANCES
1702  
1703 Web::Reactor has a notion of a "page" which represents visible output to the
1704 end user browser. It has (i.e. uses) the following attributes:
1705  
1706 * html file template (page name)
1707 * page session data
1708 * actions code (i.e. callbacks) used inside html text
1709  
1710 All of those represent "page instance" and produce end user html visible page.
1711  
1712 "Page names" are strictly limited to be alphanumeric and are mapped to file
1713 (or other storage) html content:
1714  
1715 page name: example
1716 html file template will be: page_example.html
1717  
1718 HTML content may include other files (also limited to be alphanumeric):
1719  
1720 include text: <#other_file>
1721 file included: other_file.html
1722 directories searched: 'HTML_DIRS' from Web::Reactor parameters.
1723  
1724 Page names may be requested from the end user side, but include html files may
1725 be used only from the pages already requested.
1726  
1727 =head1 ACTIONS/MODULES/CALLBACKS
1728  
1729 Actions are loaded and executed by package names. In the HTML source files they
1730 can be called this way:
1731  
1732 <&test_action arg1=val1 arg2=val2 flag1 flag2...>
1733 <&test_action>
1734  
1735 This will instruct Reactor action handler to look for this package name inside
1736 standard or user-added library directories:
1737  
1738 Web/Reactor/Actions/*/test_action.pm
1739  
1740 Asterisk will be replaced with the name of the used "action sets" give in config
1741 hash:
1742  
1743 'ACTIONS_SETS' => [ 'demo', 'Base', 'Core' ],
1744  
1745 So the result list in this example will be:
1746  
1747 Web/Reactor/Actions/demo/test_action.pm
1748 Web/Reactor/Actions/Base/test_action.pm
1749 Web/Reactor/Actions/Core/test_action.pm
1750  
1751 This is used to allow overriding of standard modules or modules you dont have
1752 write access to.
1753  
1754 Another way to call a module is directly from another module code with:
1755  
1756 $reo->action_call( 'test_action', @args );
1757  
1758 The package file will look like this:
1759  
1760 package Web/Reactor/Actions/demo/test_action;
1761 use strict;
1762  
1763 sub main
1764 {
1765 my $reo = shift; # Web::Reactor object/instance
1766 my %args = @_; # all args passed to the action
1767  
1768 my $html_args = $args{ 'HTML_ARGS' }; # all
1769 ...
1770 return $result_data; # usually html text
1771 }
1772  
1773 $html_args is hashref with all args give inside the html code if this action
1774 is called from a html text. If you look the example above:
1775  
1776 <&test_action arg1=val1 arg2=val2 flag1 flag2...>
1777  
1778 The $html_args will look like this:
1779  
1780 $html_args = {
1781 'arg1' => 'val1',
1782 'arg2' => 'val2',
1783 'flag1' => 1,
1784 'flag2' => 1,
1785 };
1786  
1787  
1788  
1789 =head1 HTTP PARAMETERS NAMES
1790  
1791 Web::Reactor uses underscore and one or two letters for its system http/html
1792 parameters. Some of the system params are:
1793  
1794 _PN -- html page name (points to file template, restricted to alphanumeric)
1795 _AN -- action name (points to action package name, restricted to alphanumeric)
1796 _P -- page session
1797 _R -- referer (caller) page session
1798  
1799 Usually those names should not be directly used or visible inside actions code.
1800 More details about how those params are used can be found below.
1801  
1802 =head1 USER SESSIONS
1803  
1804 WR creates unique session for each connected user. The session is kept by a cookie.
1805 Usually WR needs justthis cookie to handle all user/server interaction. Inside
1806 WR action code, user session is represented as a hash reference. It may hold
1807 arbitrary data. "System" or WR-specific data inside user session has colon as
1808 prefix:
1809  
1810 # $reo is Web::Reactor object (i.e. context) passed to the action/module code
1811 my $user_session = $reo->get_user_session();
1812 print STDERR $user_session->{ ':CTIME_STR' };
1813 # prints in http log the create time in human friendly form
1814  
1815 All data saved inside user session is automatically saved. When needed it can
1816 be explicitly with:
1817  
1818 $reo->save();
1819 # saves all modified context to disk or other storage
1820  
1821 =head1 PAGE SESSIONS
1822  
1823 Each page presented to the user has own session. It is very similar to the user
1824 session (it is hash reference, may hold any data, can be saved with $reo->save()).
1825 It is expected that page sessions hold all context data needed for any page to
1826 display properly. To preserve page session it is needed that it is included
1827 in any link to this page instance or in any html form used.
1828  
1829 When called for the first time, each page request needs page name (_PN). Afterwards
1830 a unique page session is created and page name is saved inside. At this moment
1831 this page instance can be accessed (i.e. given control to) only with a page
1832 session id (_P):
1833  
1834 $page_sid = ...; # taken from somewhere
1835 # to pass control to the page instance:
1836 $reo->forward( _P => $page_sid );
1837 # the page instance will pull data from its page session and display in
1838 # its last known state
1839  
1840 Not always page session are needed. For example, when forward to the caller is
1841 needed, you just need to:
1842  
1843 $reo->forward_back();
1844 # this is equivalent to
1845 my $ref_page_sid = $reo->get_ref_page_session_id();
1846 $reo->forward( _P => $ref_page_sid );
1847  
1848 Each page instance knows the caller page session and can give control back to.
1849 However it may pass more data when returning back to the caller:
1850  
1851 $reo->forward_back( MORE_DATA => 'is here', OPTIONS_LIST => \@list );
1852  
1853 When new page instance has to be called (created):
1854  
1855  
1856 $reo->forward_new( _PN => 'some_page_name' );
1857  
1858 =head1 CONFIG ENTRIES
1859  
1860 Upon creation, Web:Reactor instance gets hash with config entries/keys:
1861  
1862 * APP_NAME -- alphanumeric application name (plus underscore)
1863 * APP_ROOT -- application root dir, used for app components search
1864 * LIB_DIRS -- directories from which actions and other libs are loaded
1865 * ACTIONS_SETS -- list of action "sets", appended to ACTIONS_DIRS
1866 * HTML_DIRS -- html file inlude directories
1867 * SESS_VAR_DIR -- used by filesystem session handling to store sess data
1868 * DEBUG -- positive number, enables debugging with verbosity level
1869  
1870 Some entries may be omitted and default values are:
1871  
1872 * LIB_DIRS -- [ "$APP_ROOT/lib" ]
1873 * ACTIONS_SETS -- [ $APP_NAME, 'Base', 'Core' ]
1874 * HTML_DIRS -- [ "$APP_ROOT/html" ]
1875 * SESS_VAR_DIR -- [ "$APP_ROOT/var" ]
1876 * DEBUG -- 0
1877  
1878 =head1 API FUNCTIONS
1879  
1880 # TODO: input
1881 # TODO: sessions
1882 # TODO: arguments, constructing links
1883 # TODO: forwarding
1884 # TODO: html, forms, session keeping
1885  
1886 =head1 DEPLOYMENT, DIRECTORIES, FILESYSTEM STRUCTURE
1887  
1888 # TODO: install, cpan, manual, github, custom locations
1889 # TODO: sessions dir, custom storage/session handling
1890  
1891 =head1 EXTENDING
1892  
1893 Web::Reactor is designed to allow extending or replacing the 4 main parts:
1894  
1895 * Session storage (data store on filesystem, database, remote or vmem)
1896  
1897 base module: Web::Reactor::Sessions
1898 current in use: Web::Reactor::Sessions::Filesystem
1899  
1900 * HTML creation/expansion/preprocessing
1901  
1902 base module: Web::Reactor::Preprocessor
1903 current in use: Web::Reactor::Preprocessor::Native
1904  
1905 * Actions/modules execution (can be skipped if custom HTML prep used)
1906  
1907 base module: Web::Reactor::Actions
1908 current in use: Web::Reactor::Actions::Native
1909  
1910 * Main Web::Reactor modules, which controlls all the functionality.
1911  
1912 base module: Web::Reactor
1913 current in use: Web::Reactor
1914  
1915 Except main module (Web::Reactor) is is expected that base modules are
1916 subclassed for extension. Inside each of them there are notes on what must
1917 be extended and usage hints.
1918  
1919 Current implementations of the modules, shipped with Web::Reactor, can also
1920 be extended and/or modified. However it is suggested checking base modules
1921 first.
1922  
1923 Main module (Web::Reactor) handles all of the logic. It is not expected to
1924 be modified since it is designed to handle tightly all the parts. However,
1925 there are few things which can be modified but it is recommended to contact
1926 authors for an advice first. On the other hand, the main module instance is
1927 always passed as argument to all other modules/actions so it is good idea
1928 to add specific functionality which will be readily available everywhere.
1929  
1930 =head1 PROJECT STATUS
1931  
1932 At the moment Web::Reactor is in beta. API is mostly frozen but it is possible
1933 to be changed and/or extended. However drastic changes are not planned :)
1934  
1935 If you are interested in the project or have some notes etc, contact me at:
1936  
1937 Vladi Belperchinov-Shabanski "Cade"
1938 <cade@bis.bg>
1939 <cade@cpan.org>
1940 <shabanski@gmail.com>
1941  
1942 further contact info, mailing list and github repository is listed below.
1943  
1944 =head1 FIXME: TODO:
1945  
1946 * config examples
1947 * pages example
1948 * actions example
1949 * API description (input data, safe data, sessions, forwarding, actions, html)
1950 * ...
1951  
1952 =head1 REQUIRED ADDITIONAL MODULES
1953  
1954 Reactor uses mostly perl core modules but it needs few others:
1955  
1956 * CGI
1957 * Scalar::Util
1958 * Hash::Util
1959 * Data::Dumper (for debugging)
1960 * Exception::Sink
1961 * Data::Tools
1962  
1963 All modules are available with the perl package or from CPAN.
1964  
1965 Additionally, several are available and from github:
1966  
1967 * Exception::Sink
1968 https://github.com/cade-vs/perl-exception-sink
1969  
1970 * Data::Tools
1971 https://github.com/cade-vs/perl-data-tools
1972  
1973 =head1 DEMO APPLICATION
1974  
1975 Documentation will be improved. Meanwhile you can check 'demo'
1976 directory inside distribution tarball or inside the github repository. This is
1977 fully functional (however stupid :)) application. It shows how data is processed,
1978 calling pages/views, inspecting page (calling views) stack, html forms automation,
1979 forwarding.
1980  
1981 =head1 MAILING LIST
1982  
1983 web-reactor@googlegroups.com
1984  
1985 =head1 GITHUB REPOSITORY
1986  
1987 https://github.com/cade-vs/perl-web-reactor
1988  
1989 git clone git://github.com/cade-vs/perl-web-reactor.git
1990  
1991 =head1 AUTHOR
1992  
1993 Vladi Belperchinov-Shabanski "Cade"
1994  
1995 <cade@bis.bg> <cade@cpan.org> <shabanski@gmail.com>
1996  
1997 http://cade.datamax.bg
1998  
1999 https://github.com/cade-vs
2000  
2001 =head2 EOF
2002  
2003 =cut
2004  
2005  
2006 ##############################################################################
2007 1;
2008 ###EOF########################################################################