Reactor.pm untested

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