3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/App.pod
5 # Copyright 2007 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
10 use vars
qw($VERSION);
15 Time
::HiRes-
>import('time') if eval {require Time
::HiRes
};
16 eval {require Scalar
::Util
};
21 $msg = 'Something happened' if ! defined $msg;
22 die $msg if ref $msg || $msg =~ /\n\z/;
23 my ($pkg, $file, $line, $sub) = caller(1);
24 die "$msg in ${sub}() at $file line $line\n";
27 ###----------------------------------------------------------------###
30 my $class = shift || croak
"Usage: Package->new";
31 my $self = shift || {};
43 ###----------------------------------------------------------------###
46 my ($self, $args) = @_;
47 $self = $self->new($args) if ! ref $self;
49 $self->{'_time'} = time;
52 ### a chance to do things at the very beginning
53 return $self if ! $self->{'_no_pre_navigate'} && $self->pre_navigate;
57 local $self->{'_morph_lineage_start_index'} = $#{$self->{'_morph_lineage'} || []};
61 ### rethrow the error unless we long jumped out of recursive nav_loop calls
62 croak
$@ if $@ ne "Long Jump\n";
65 ### one chance to do things at the very end
66 $self->post_navigate if ! $self->{'_no_post_navigate'};
70 $self->handle_error($@) if $@; # catch any errors
72 $self->{'_time'} = time;
82 ### keep from an infinate nesting
83 local $self->{'_recurse'} = $self->{'_recurse'} || 0;
84 if ($self->{'_recurse'}++ >= $self->recurse_limit) {
85 my $err = "recurse_limit (".$self->recurse_limit.") reached";
86 $err .= " number of jumps (".$self->{'jumps'}.")" if ($self->{'jumps'} || 0) > 1;
90 my $path = $self->path;
92 ### allow for an early return
93 return if $self->pre_loop($path); # a true value means to abort the navigate
95 ### iterate on each step of the path
96 foreach ($self->{'path_i'} ||= 0;
97 $self->{'path_i'} <= $#$path;
98 $self->{'path_i'} ++) {
99 my $step = $path->[$self->{'path_i'}];
100 if ($step !~ /^([^\W0-9]\w*)$/) { # don't process the step if it contains odd characters
101 $self->stash->{'forbidden_step'} = $step;
102 $self->replace_path($self->forbidden_step);
105 $step = $1; # untaint
107 ### allow for per-step authentication
108 if (! $self->is_authed) {
109 my $req = $self->run_hook('require_auth', $step, 1);
110 if (ref($req) ? $req->{$step} : $req) { # in the hash - or true
111 return if ! $self->get_valid_auth;
115 ### allow for becoming another package (allows for some steps in external files)
118 ### allow for mapping path_info pieces to form elements
119 if (my $info = $self->path_info) {
120 my $maps = $self->run_hook('path_info_map', $step) || [];
121 croak
'Usage: sub path_info_map { [[qr{/path_info/(\w+)}, "keyname"]] }'
122 if ! UNIVERSAL
::isa
($maps, 'ARRAY') || (@$maps && ! UNIVERSAL
::isa
($maps->[0], 'ARRAY'));
123 foreach my $map (@$maps) {
124 my @match = $info =~ $map->[0];
126 $self->form->{$map->[$_]} = $match[$_ - 1] foreach grep {! defined $self->form->{$map->[$_]}} 1 .. $#$map;
131 ### run the guts of the step
132 my $handled = $self->run_hook('run_step', $step);
134 ### Allow for the run_step to intercept.
135 ### A true status means the run_step took over navigation.
137 $self->unmorph($step);
141 ### if there are no future steps - allow for this step to designate one to follow
142 my $is_at_end = $self->{'path_i'} >= $#$path ? 1 : 0;
143 $self->run_hook('refine_path', $step, $is_at_end);
145 $self->unmorph($step);
148 ### allow for one exit point after the loop
149 return if $self->post_loop($path); # a true value means to abort the navigate
151 ### run the default step as a last resort
152 $self->insert_path($self->default_step);
153 $self->nav_loop; # go recursive
158 sub pre_navigate
{ 0 } # true means to not enter nav_loop
162 sub pre_loop
{ 0 } # true value means to abort the nav_loop routine
164 sub post_loop
{ 0 } # true value means to abort the nav_loop - don't recurse
166 sub recurse_limit
{ shift-
>{'recurse_limit'} || 15 }
168 ### default die handler - show what happened and die (so its in the error logs)
173 die $err if $self->{'_handling_error'};
174 local $self->{'_handling_error'} = 1;
175 local $self->{'_recurse'} = 0; # allow for this next step - even if we hit a recurse error
177 $self->stash->{'error_step'} = $self->current_step;
178 $self->stash->{'error'} = $err;
179 $self->replace_path($self->error_step);
180 $self->jump; # exits nav loop when finished
183 ###----------------------------------------------------------------###
185 sub default_step
{ shift-
>{'default_step'} || 'main' }
186 sub js_step
{ shift-
>{'js_step'} || 'js' }
187 sub login_step
{ shift-
>{'login_step'} || '__login' }
188 sub error_step
{ shift-
>{'error_step'} || '__error' }
189 sub forbidden_step
{ shift-
>{'forbidden_step'} || '__forbidden' }
191 sub step_key
{ shift-
>{'step_key'} || 'step' }
195 if (! $self->{'path'}) {
196 my $path = $self->{'path'} = []; # empty path
198 ### add initial items to the form hash from path_info5B
199 if (my $info = $self->path_info) {
200 my $maps = $self->path_info_map_base || [];
201 croak
'Usage: sub path_info_map_base { [[qr{/path_info/(\w+)}, "keyname"]] }'
202 if ! UNIVERSAL
::isa
($maps, 'ARRAY') || (@$maps && ! UNIVERSAL
::isa
($maps->[0], 'ARRAY'));
203 foreach my $map (@$maps) {
204 my @match = $info =~ $map->[0];
206 $self->form->{$map->[$_]} = $match[$_ - 1] foreach grep {! defined $self->form->{$map->[$_]}} 1 .. $#$map;
211 ### make sure the step is valid
212 my $step = $self->form->{$self->step_key};
214 if ($step =~ /^_/) { # can't begin with _
215 $self->stash->{'forbidden_step'} = $step;
216 push @$path, $self->forbidden_step;
217 } elsif ($self->valid_steps # must be in valid_steps if defined
218 && ! $self->valid_steps->{$step}
219 && $step ne $self->default_step
220 && $step ne $self->js_step) {
221 $self->stash->{'forbidden_step'} = $step;
222 push @$path, $self->forbidden_step;
229 return $self->{'path'};
232 sub path_info_map_base
{
234 return [[qr{/(\w+)}, $self->step_key]];
239 my $path = $self->{'path'} ||= [];
240 croak
"Cannot call set_path after the navigation loop has begun" if $self->{'path_i'};
241 splice @$path, 0, $#$path + 1, @_; # change entries in the ref (which updates other copies of the ref)
244 ### legacy - same as append_path
247 push @{ $self->path }, @_;
252 push @{ $self->path }, @_;
257 my $ref = $self->path;
258 my $i = $self->{'path_i'} || 0;
259 if ($i + 1 > $#$ref) {
262 splice(@$ref, $i + 1, $#$ref - $i, @_); # replace remaining entries
268 my $ref = $self->path;
269 my $i = $self->{'path_i'} || 0;
270 if ($i + 1 > $#$ref) {
273 splice(@$ref, $i + 1, 0, @_); # insert a path at the current location
277 ### a hash of paths that are allowed, default undef is all are allowed
280 ###----------------------------------------------------------------###
281 ### allow for checking where we are in the path and for jumping around
287 if (my $ref = $self->{'_morph_lineage'}) {
288 ### use the saved index - this allows for early "morphers" to only get rolled back so far
289 my $index = $self->{'_morph_lineage_start_index'};
290 $index = -1 if ! defined $index;
291 $self->unmorph while $#$ref != $index;
300 my $i = @_ == 1 ? shift : 1;
301 my $path = $self->path;
302 my $path_i = $self->{'path_i'};
303 croak
"Can't jump if nav_loop not started" if ! defined $path_i;
305 ### validate where we are jumping to
309 } elsif ($i eq 'LAST') {
310 $i = $#$path - $path_i;
311 } elsif ($i eq 'NEXT') {
313 } elsif ($i eq 'CURRENT') {
315 } elsif ($i eq 'PREVIOUS') {
317 } else { # look for a step by that name
318 for (my $j = $#$path; $j >= 0; $j --) {
319 if ($path->[$j] eq $i) {
326 if ($i !~ /^-?\d+$/) {
328 Carp
::croak
("Invalid jump index ($i)");
331 ### manipulate the path to contain the new jump location
333 my $cut_i = $path_i + $i;
334 if ($cut_i > $#$path) {
335 push @replace, $self->default_step;
336 } elsif ($cut_i < 0) {
337 push @replace, @$path;
339 push @replace, @$path[$cut_i .. $#$path];
341 $self->replace_path(@replace);
343 ### record the number of jumps
344 $self->{'jumps'} ||= 0;
347 ### run the newly fixed up path (recursively)
348 $self->{'path_i'} ++; # move along now that the path is updated
350 $self->exit_nav_loop;
353 sub step_by_path_index
{
356 my $ref = $self->path;
358 return $self->default_step if $i > $#$ref;
364 return $self->step_by_path_index( ($self->{'path_i'} || 0) - 1 );
369 return $self->step_by_path_index( ($self->{'path_i'} || 0) );
372 sub next_step
{ # method and hook
374 return $self->step_by_path_index( ($self->{'path_i'} || 0) + 1 );
379 return $self->step_by_path_index( $#{ $self->path } );
384 return $self->step_by_path_index( 0 );
387 ###----------------------------------------------------------------###
388 ### hooks and history
392 my $hook = shift || do { require Carp
; Carp
::confess
("Missing hook name") };
393 my $step = shift || '';
395 if ($step && ($code = $self->can("${step}_${hook}"))) {
396 return [$code, "${step}_${hook}"],
398 } elsif ($code = $self->can($hook)) {
399 return [$code, $hook];
412 my ($code, $found) = @{ $self->find_hook($hook, $step) };
414 croak
"Could not find a method named ${step}_${hook} or ${hook}";
415 } elsif (! UNIVERSAL
::isa
($code, 'CODE')) {
416 croak
"Value for $hook ($found) is not a code ref ($code)";
427 push @{ $self->history }, $hist;
429 $hist->{'level'} = $self->{'_level'};
430 local $self->{'_level'} = 1 + ($self->{'_level'} || 0);
432 $hist->{'elapsed'} = time - $hist->{'time'};
434 my $resp = $self->$code($step, @_);
436 $hist->{'elapsed'} = time - $hist->{'time'};
437 $hist->{'response'} = $resp;
443 return shift-
>{'history'} ||= [];
448 my $all = shift || 0;
449 my $hist = $self->history;
451 push @$dump, sprintf("Elapsed: %.5f", time - $self->{'_time'});
453 ### show terse - yet informative info
454 foreach my $row (@$hist) {
456 || ref($row) ne 'HASH'
457 || ! exists $row->{'elapsed'}) {
460 my $note = (' ' x
($row->{'level'} || 0))
461 . join(' - ', $row->{'step'}, $row->{'meth'}, $row->{'found'}, sprintf('%.5f', $row->{'elapsed'}));
462 my $resp = $row->{'response'};
463 if (ref($resp) eq 'HASH' && ! scalar keys %$resp) {
465 } elsif (ref($resp) eq 'ARRAY' && ! @$resp) {
467 } elsif (! defined $resp) {
469 } elsif (! ref $resp || ! $all) {
470 my $max = $self->{'history_max'} || 30;
471 if (length($resp) > $max) {
472 $resp = substr($resp, 0, $max);
478 $note = [$note, $resp];
488 ###----------------------------------------------------------------###
489 ### utility methods to allow for storing separate steps in other modules
493 return $self->{'allow_morph'} ? 1 : 0;
496 sub allow_nested_morph
{
498 return $self->{'allow_nested_morph'} ? 1 : 0;
503 my $step = shift || return;
504 my $allow = $self->allow_morph($step) || return;
506 ### place to store the lineage
507 my $lin = $self->{'_morph_lineage'} ||= [];
508 my $cur = ref $self; # what are we currently
509 push @$lin, $cur; # store so subsequent unmorph calls can do the right thing
519 push @{ $self->history }, $hist;
521 if (ref($allow) && ! $allow->{$step}) { # hash - but no step - record for unbless
522 $hist->{'found'} .= " (not allowed to morph to that step)";
526 ### make sure we haven't already been reblessed
527 if ($#$lin != 0 # is this the second morph call
528 && (! ($allow = $self->allow_nested_morph($step)) # not true
529 || (ref($allow) && ! $allow->{$step}) # hash - but no step
531 $hist->{'found'} .= $allow ? " (not allowed to nested_morph to that step)" : " (nested_morph disabled)";
532 return 0; # just return - don't die so that we can morph early
535 ### if we are not already that package - bless us there
536 my $new = $self->run_hook('morph_package', $step);
538 my $file = $new .'.pm';
540 if (UNIVERSAL
::can
($new, 'can') # check if the package space exists
541 || eval { require $file }) { # check for a file that holds this package
542 ### become that package
544 $hist->{'found'} .= " (changed $cur to $new)";
545 $self->fixup_after_morph($step);
548 if ($@ =~ /^\s*(Can\'t locate \S+ in \@INC)/) { # let us know what happened
549 $hist->{'found'} .= " (failed from $cur to $new: $1)";
551 $hist->{'found'} .= " (failed from $cur to $new: $@)";
552 my $err = "Trouble while morphing to $file: $@";
559 $hist->{'response'} = 1;
565 my $step = shift || '_no_step';
566 my $lin = $self->{'_morph_lineage'} || return;
569 my $prev = pop(@$lin) || croak
"unmorph called more times than morph - current ($cur)";
570 delete $self->{'_morph_lineage'} if ! @$lin;
572 ### if we are not already that package - bless us there
581 push @{ $self->history }, $hist;
584 $self->fixup_before_unmorph($step);
586 $hist->{'found'} .= " (changed from $cur to $prev)";
588 $hist->{'found'} .= " (already isa $cur)";
591 $hist->{'response'} = 1;
595 sub fixup_after_morph
{}
597 sub fixup_before_unmorph
{}
599 ###----------------------------------------------------------------###
600 ### allow for authentication
602 sub navigate_authenticated
{
603 my ($self, $args) = @_;
604 $self = $self->new($args) if ! ref $self;
606 if ($self->can('require_auth') != \
&CGI
::Ex
::App
::require_auth
) {
608 Carp
::croak
("The default navigate_authenticated method was called but the default require_auth method has been overwritten - aborting");
610 $self->require_auth(1);
612 return $self->navigate;
617 $self->{'require_auth'} = shift if @_ == 1 && (! defined($_[0]) || ref($_[0]) || $_[0] =~ /^[01]$/);
618 return $self->{'require_auth'} || 0;
621 sub is_authed
{ shift-
>auth_data }
625 $self->{'auth_data'} = shift if @_ == 1;
626 return $self->{'auth_data'};
631 return 1 if $self->is_authed;
633 my $args = $self->auth_args;
635 ### allow passed in args
636 if (my $extra = shift) {
637 $args = {%$args, %$extra};
640 ### augment the args with sensible defaults
641 $args->{'script_name'} ||= $self->script_name;
642 $args->{'path_info'} ||= $self->path_info;
643 $args->{'cgix'} ||= $self->cgix;
644 $args->{'form'} ||= $self->form;
645 $args->{'cookies'} ||= $self->cookies;
646 $args->{'js_uri_path'} ||= $self->js_uri_path;
647 $args->{'get_pass_by_user'} ||= sub { my ($auth, $user) = @_; $self->get_pass_by_user($user, $auth) };
648 $args->{'verify_user'} ||= sub { my ($auth, $user) = @_; $self->verify_user( $user, $auth) };
649 $args->{'cleanup_user'} ||= sub { my ($auth, $user) = @_; $self->cleanup_user( $user, $auth) };
650 $args->{'login_print'} ||= sub {
651 my ($auth, $template, $hash) = @_;
652 my $step = $self->login_step;
653 my $hash_base = $self->run_hook('hash_base', $step) || {};
654 my $hash_comm = $self->run_hook('hash_common', $step) || {};
655 my $hash_swap = $self->run_hook('hash_swap', $step) || {};
656 my $swap = {%$hash_base, %$hash_comm, %$hash_swap, %$hash};
658 my $out = $self->run_hook('swap_template', $step, $template, $swap);
659 $self->run_hook('fill_template', $step, \
$out, $hash);
660 $self->run_hook('print_out', $step, \
$out);
663 require CGI
::Ex
::Auth
;
664 my $obj = CGI
::Ex
::Auth-
>new($args);
665 my $resp = $obj->get_valid_auth;
667 my $data = $obj->last_auth_data;
668 delete $data->{'real_pass'} if defined $data; # data may be defined but false
669 $self->auth_data($data); # failed authentication may still have auth_data
671 return ($resp && $data) ? 1 : 0;
676 sub get_pass_by_user
{ die "get_pass_by_user is a virtual method and needs to be overridden for authentication to work" }
677 sub cleanup_user
{ my ($self, $user) = @_; $user }
678 sub verify_user
{ 1 }
680 ###----------------------------------------------------------------###
681 ### a few standard base accessors
683 sub script_name
{ shift-
>{'script_name'} || $ENV{'SCRIPT_NAME'} || $0 }
685 sub path_info
{ shift-
>{'path_info'} || $ENV{'PATH_INFO'} || '' }
689 $self->{'cgix'} = shift if @_ == 1;
690 return $self->{'cgix'} ||= do {
692 CGI
::Ex-
>new; # return of the do
698 $self->{'form'} = shift if @_ == 1;
699 return $self->{'form'} ||= $self->cgix->get_form;
704 $self->{'cookies'} = shift if @_ == 1;
705 return $self->{'cookies'} ||= $self->cgix->get_cookies;
710 $self->{'vob'} = shift if @_ == 1;
711 return $self->{'vob'} ||= do {
712 require CGI
::Ex
::Validate
;
713 CGI
::Ex
::Validate-
>new($self->vob_args); # return of the do
724 ### provide a place for placing variables
727 return $self->{'stash'} ||= {};
733 delete @{ $self }{qw(
742 _morph_lineage_start_index
753 ###----------------------------------------------------------------###
754 ### default hook implementations
756 sub path_info_map
{ }
762 ### if the pre_step exists and returns true, exit the nav_loop
763 return 1 if $self->run_hook('pre_step', $step);
765 ### allow for skipping this step (but stay in the nav_loop)
766 return 0 if $self->run_hook('skip', $step);
768 ### see if we have complete valid information for this step
769 ### if so, do the next step
770 ### if not, get necessary info and print it out
771 if ( ! $self->run_hook('prepare', $step)
772 || ! $self->run_hook('info_complete', $step)
773 || ! $self->run_hook('finalize', $step)) {
775 ### show the page requesting the information
776 $self->run_hook('prepared_print', $step);
778 ### a hook after the printing process
779 $self->run_hook('post_print', $step);
784 ### a hook before end of loop
785 ### if the post_step exists and returns true, exit the nav_loop
786 return 1 if $self->run_hook('post_step', $step);
788 ### let the nav_loop continue searching the path
793 my ($self, $step, $is_at_end) = @_;
794 return 0 if ! $is_at_end; # if we aren't at the end of the path, don't do anything
796 my $next_step = $self->run_hook('next_step', $step) || return 0;
797 $self->run_hook('set_ready_validate', $step, 0);
798 $self->append_path($next_step);
806 my $hash_base = $self->run_hook('hash_base', $step) || {};
807 my $hash_comm = $self->run_hook('hash_common', $step) || {};
808 my $hash_form = $self->run_hook('hash_form', $step) || {};
809 my $hash_fill = $self->run_hook('hash_fill', $step) || {};
810 my $hash_swap = $self->run_hook('hash_swap', $step) || {};
811 my $hash_errs = $self->run_hook('hash_errors', $step) || {};
814 $hash_errs->{$_} = $self->format_error($hash_errs->{$_})
815 foreach keys %$hash_errs;
816 $hash_errs->{'has_errors'} = 1 if scalar keys %$hash_errs;
818 ### layer hashes together
819 my $fill = {%$hash_form, %$hash_base, %$hash_comm, %$hash_fill};
820 my $swap = {%$hash_form, %$hash_base, %$hash_comm, %$hash_swap, %$hash_errs};
822 ### run the print hook - passing it the form and fill info
823 $self->run_hook('print', $step, $swap, $fill);
827 my ($self, $step, $swap, $fill) = @_;
828 my $file = $self->run_hook('file_print', $step); # get a filename relative to base_dir_abs
829 my $out = $self->run_hook('swap_template', $step, $file, $swap);
830 $self->run_hook('fill_template', $step, \
$out, $fill);
831 $self->run_hook('print_out', $step, \
$out);
835 my ($self, $step, $out) = @_;
837 $self->cgix->print_content_type;
838 print ref($out) eq 'SCALAR' ? $$out : $out;
842 my ($self, $step, $file, $swap) = @_;
844 my $args = $self->run_hook('template_args', $step);
845 $args->{'INCLUDE_PATH'} ||= $self->base_dir_abs;
847 my $t = $self->template_obj($args);
849 $t->process($file, $swap, \
$out) || die $t->error;
854 sub template_args
{ {} }
857 my ($self, $args) = @_;
859 require CGI
::Ex
::Template
;
860 my $t = CGI
::Ex
::Template-
>new($args);
864 my ($self, $step, $outref, $fill) = @_;
868 my $args = $self->run_hook('fill_args', $step);
869 local $args->{'text'} = $outref;
870 local $args->{'form'} = $fill;
872 require CGI
::Ex
::Fill
;
873 CGI
::Ex
::Fill
::fill
($args);
878 sub pre_step
{ 0 } # success indicates we handled step (don't continue step or loop)
879 sub skip
{ 0 } # success indicates to skip the step (and continue loop)
880 sub prepare
{ 1 } # failure means show step
881 sub finalize
{ 1 } # failure means show step
883 sub post_step
{ 0 } # success indicates we handled step (don't continue step or loop)
887 my $step = shift || '';
888 my $cur = ref $self; # default to using self as the base for morphed modules
889 my $new = $cur .'::'. $step;
890 $new =~ s/(\b|_+)(\w)/\u$2/g; # turn Foo::my_step_name into Foo::MyStepName
896 my $step = shift || '';
898 return $self->{'name_module'} ||= do {
899 # allow for cgi-bin/foo or cgi-bin/foo.pl to resolve to "foo"
900 my $script = $self->script_name;
901 $script =~ m/ (\w+) (?:\.\w+)? $/x || die "Couldn't determine module name from \"name_module\" lookup ($step)";
902 $1; # return of the do
907 my ($self, $step) = @_;
915 my $base_dir = $self->base_dir_rel;
916 my $module = $self->run_hook('name_module', $step);
917 my $_step = $self->run_hook('name_step', $step) || die "Missing name_step";
918 $_step .= '.'. $self->ext_print if $_step !~ /\.\w+$/;
920 foreach ($base_dir, $module) { $_ .= '/' if length($_) && ! m
|/$| }
922 return $base_dir . $module . $_step;
929 ### determine the path to begin looking for files - allow for an arrayref
930 my $abs = $self->base_dir_abs || [];
931 $abs = $abs->() if UNIVERSAL
::isa
($abs, 'CODE');
932 $abs = [$abs] if ! UNIVERSAL
::isa
($abs, 'ARRAY');
933 return {} if @$abs == 0;
935 my $base_dir = $self->base_dir_rel;
936 my $module = $self->run_hook('name_module', $step);
937 my $_step = $self->run_hook('name_step', $step) || die "Missing name_step";
938 $_step .= '.'. $self->ext_val if $_step !~ /\.\w+$/;
940 foreach (@$abs, $base_dir, $module) { $_ .= '/' if length($_) && ! m
|/$| }
943 foreach my $_abs (@$abs) {
944 my $path = $_abs . $base_dir . $module . $_step;
945 return $path if -e
$path;
949 return $abs->[0] . $base_dir . $module . $_step;
953 my ($self, $step) = @_;
954 return 0 if ! $self->run_hook('ready_validate', $step);
955 return 0 if ! $self->run_hook('validate', $step, $self->form);
960 my ($self, $step) = @_;
961 return ($ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq 'POST') ? 1 : 0;
964 sub set_ready_validate
{ # hook and method
966 my ($step, $is_ready) = (@_ == 2) ? @_ : (undef, shift);
967 $ENV{'REQUEST_METHOD'} = ($is_ready) ? 'POST' : 'GET';
972 my ($self, $step, $form) = @_;
974 my $hash = $self->run_hook('hash_validation', $step);
975 my $what_was_validated = [];
977 my $err_obj = eval { $self->vob->validate($form, $hash, $what_was_validated) };
978 die "Step $step: $@" if $@ && ! $err_obj;
980 ### had an error - store the errors and return false
982 $self->add_errors($err_obj->as_hash({
983 as_hash_join
=> "<br>\n",
984 as_hash_suffix
=> '_error',
989 ### allow for the validation to give us some redirection
990 foreach my $ref (@$what_was_validated) {
991 foreach my $method (qw(append_path replace_path insert_path)) {
992 next if ! (my $val = $ref->{$method});
993 $self->$method(ref $val ? @$val : $val);
1000 ### creates javascript suitable for validating the form
1004 return '' if $self->ext_val =~ /^html?$/; # let htm validation do it itself
1006 my $form_name = shift || $self->run_hook('form_name', $step);
1007 my $hash_val = shift || $self->run_hook('hash_validation', $step);
1008 my $js_uri = $self->js_uri_path;
1009 return '' if UNIVERSAL
::isa
($hash_val, 'HASH') && ! scalar keys %$hash_val
1010 || UNIVERSAL
::isa
($hash_val, 'ARRAY') && ! @$hash_val;
1012 return $self->vob->generate_js($hash_val, $form_name, $js_uri);
1015 sub form_name
{ 'theform' }
1017 sub hash_validation
{
1018 my ($self, $step) = @_;
1020 return $self->{'hash_validation'}->{$step} ||= do {
1022 my $file = $self->run_hook('file_val', $step);
1024 ### allow for returning the validation hash in the filename
1025 ### a scalar ref means it is a yaml document to be read by get_validation
1026 if (ref($file) && ! UNIVERSAL
::isa
($file, 'SCALAR')) {
1029 ### read the file - if it is not found, errors will be in the webserver logs (all else dies)
1031 $hash = $self->vob->get_validation($file) || {};
1037 $hash; # return of the do
1042 my ($self, $step) = @_;
1044 return $self->{'hash_base'} ||= do {
1045 ### create a weak copy of self to use in closures
1047 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($copy)};
1049 script_name
=> $copy->script_name,
1050 path_info
=> $copy->path_info,
1051 js_validation
=> sub { $copy->run_hook('js_validation', $step, shift) },
1052 form_name
=> sub { $copy->run_hook('form_name', $step) },
1053 $self->step_key => $step,
1054 }; # return of the do
1058 sub hash_common
{ shift-
>{'hash_common'} ||= {} }
1059 sub hash_form
{ shift-
>form }
1060 sub hash_fill
{ shift-
>{'hash_fill'} ||= {} }
1061 sub hash_swap
{ shift-
>{'hash_swap'} ||= {} }
1062 sub hash_errors
{ shift-
>{'hash_errors'} ||= {} }
1064 ###----------------------------------------------------------------###
1065 ### routines to support the base hooks
1069 my $hash = $self->hash_errors;
1070 my $args = ref($_[0]) ? shift : {@_};
1071 foreach my $key (keys %$args) {
1072 my $_key = ($key =~ /error$/) ? $key : "${key}_error";
1073 if ($hash->{$_key}) {
1074 $hash->{$_key} .= '<br>' . $args->{$key};
1076 $hash->{$_key} = $args->{$key};
1079 $hash->{'has_errors'} = 1;
1082 sub has_errors
{ scalar keys %{ shift-
>hash_errors } }
1085 my ($self, $error) = @_;
1089 sub add_to_errors
{ shift-
>add_errors(@_) }
1090 sub add_to_swap
{ my $self = shift; $self->add_to_hash($self->hash_swap, @_) }
1091 sub add_to_fill
{ my $self = shift; $self->add_to_hash($self->hash_fill, @_) }
1092 sub add_to_form
{ my $self = shift; $self->add_to_hash($self->hash_form, @_) }
1093 sub add_to_common
{ my $self = shift; $self->add_to_hash($self->hash_common, @_) }
1094 sub add_to_base
{ my $self = shift; $self->add_to_hash($self->hash_base, @_) }
1100 $new = {$new, @_} if ! ref $new; # non-hashref
1101 $old->{$_} = $new->{$_} foreach keys %$new;
1107 $self->{'base_dir_rel'} = shift if @_ == 1;
1108 return $self->{'base_dir_rel'} || '';
1113 $self->{'base_dir_abs'} = shift if @_ == 1;
1114 return $self->{'base_dir_abs'} || ['.']; # default to the current directory
1119 $self->{'ext_print'} = shift if @_ == 1;
1120 return $self->{'ext_print'} || 'html';
1125 $self->{'ext_val'} = shift if @_ == 1;
1126 return $self->{'ext_val'} || 'val';
1129 ### where to find the javascript files
1130 ### default to using this script as a handler
1133 my $script = $self->script_name;
1134 my $js_step = $self->js_step;
1135 return ($self->can('path') == \
&CGI
::Ex
::App
::path
)
1136 ? $script .'/'. $js_step # try to use a cache friendly URI (if path is our own)
1137 : $script . '?'.$self->step_key.'='.$js_step.'&js='; # use one that works with more paths
1140 ###----------------------------------------------------------------###
1141 ### a simple step that allows for printing javascript libraries that
1142 ### are stored in perls @INC. Which ever step is in js_step should do something similar.
1147 ### make sure path info looks like /js/CGI/Ex/foo.js
1148 my $file = $self->form->{'js'} || $self->path_info;
1149 $file = ($file =~ m!^(?:/js/|/)?(\w+(?:/\w+)*\.js)$!) ? $1 : '';
1151 $self->cgix->print_js($file);
1152 $self->{'_no_post_navigate'} = 1;
1156 ###----------------------------------------------------------------###
1157 ### a step that will be used if a valid_steps is defined
1158 ### and the current step of the path is not in valid_steps
1159 ### or if the step is a "hidden" step that begins with _
1160 ### or if the step name contains \W
1162 sub __forbidden_info_complete
{ 0 }
1164 sub __forbidden_hash_swap
{ shift-
>stash }
1166 sub __forbidden_file_print
{ \
"<h1>Denied</h1>You do not have access to the step <b>\"[% forbidden_step %]\"</b>" }
1168 ###----------------------------------------------------------------###
1169 ### a step that is used by the default handle_error
1171 sub __error_info_complete
{ 0 }
1173 sub __error_hash_swap
{ shift-
>stash }
1175 sub __error_file_print
{ \
"<h1>An a fatal error occurred</h1>Step: <b>\"[% error_step %]\"</b><br>[% TRY; CONFIG DUMP => {header => 0}; DUMP error; END %]" }
1177 ###----------------------------------------------------------------###
1181 ### See the perldoc in CGI/Ex/App.pod