]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/App.pm
CGI::Ex 2.06
[chaz/p5-CGI-Ex] / lib / CGI / Ex / App.pm
1 package CGI::Ex::App;
2
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/App.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
8
9 use strict;
10 use vars qw($VERSION);
11
12 BEGIN {
13 $VERSION = '2.06';
14
15 Time::HiRes->import('time') if eval {require Time::HiRes};
16 eval {require Scalar::Util};
17 }
18
19 sub croak {
20 my $msg = shift;
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";
25 }
26
27 ###----------------------------------------------------------------###
28
29 sub new {
30 my $class = shift || croak "Usage: Package->new";
31 my $self = shift || {};
32 bless $self, $class;
33
34 $self->init;
35
36 return $self;
37 }
38
39 sub init {}
40
41 sub destroy {}
42
43 ###----------------------------------------------------------------###
44
45 sub navigate {
46 my ($self, $args) = @_;
47 $self = $self->new($args) if ! ref $self;
48
49 $self->{'_time'} = time;
50
51 eval {
52 ### allow for authentication
53 my $ref = $self->require_auth;
54 if ($ref && ! ref $ref) {
55 return $self if ! $self->get_valid_auth;
56 }
57
58 ### a chance to do things at the very beginning
59 return $self if ! $self->{'_no_pre_navigate'} && $self->pre_navigate;
60
61 ### run the step loop
62 eval {
63 local $self->{'__morph_lineage_start_index'} = $#{$self->{'__morph_lineage'} || []};
64 $self->nav_loop;
65 };
66 if ($@) {
67 ### rethrow the error unless we long jumped out of recursive nav_loop calls
68 croak $@ if $@ ne "Long Jump\n";
69 }
70
71 ### one chance to do things at the very end
72 $self->post_navigate if ! $self->{'_no_post_navigate'};
73
74
75 };
76 $self->handle_error($@) if $@; # catch any errors
77
78 $self->{'_time'} = time;
79
80 $self->destroy;
81
82 return $self;
83 }
84
85 sub nav_loop {
86 my $self = shift;
87
88 ### keep from an infinate nesting
89 local $self->{'recurse'} = $self->{'recurse'} || 0;
90 if ($self->{'recurse'} ++ >= $self->recurse_limit) {
91 my $err = "recurse_limit (".$self->recurse_limit.") reached";
92 $err .= " number of jumps (".$self->{'jumps'}.")" if ($self->{'jumps'} || 0) > 1;
93 croak $err;
94 }
95
96 my $path = $self->path;
97
98 ### allow for an early return
99 return if $self->pre_loop($path); # a true value means to abort the navigate
100
101 my $req_auth = ref($self->require_auth) ? $self->require_auth : undef;
102
103 ### iterate on each step of the path
104 foreach ($self->{'path_i'} ||= 0;
105 $self->{'path_i'} <= $#$path;
106 $self->{'path_i'} ++) {
107 my $step = $path->[$self->{'path_i'}];
108 if ($step !~ /^([^\W0-9]\w*)$/) { # don't process the step if it contains odd characters
109 $self->stash->{'forbidden_step'} = $step;
110 $self->replace_path($self->forbidden_step);
111 next;
112 }
113 $step = $1; # untaint
114
115 ### allow for per-step authentication
116 if ($req_auth
117 && $req_auth->{$step}
118 && ! $self->get_valid_auth) {
119 return;
120 }
121
122 ### allow for becoming another package (allows for some steps in external files)
123 $self->morph($step);
124
125 ### run the guts of the step
126 my $handled = $self->run_hook('run_step', $step);
127
128 ### Allow for the run_step to intercept.
129 ### A true status means the run_step took over navigation.
130 if ($handled) {
131 $self->unmorph($step);
132 return;
133 }
134
135 ### if there are no future steps - allow for this step to designate one to follow
136 my $is_at_end = $self->{'path_i'} >= $#$path ? 1 : 0;
137 $self->run_hook('refine_path', $step, $is_at_end);
138
139 $self->unmorph($step);
140 }
141
142 ### allow for one exit point after the loop
143 return if $self->post_loop($path); # a true value means to abort the navigate
144
145 ### run the default step as a last resort
146 $self->insert_path($self->default_step);
147 $self->nav_loop; # go recursive
148
149 return;
150 }
151
152 sub pre_navigate { 0 } # true means to not enter nav_loop
153
154 sub post_navigate {}
155
156 sub pre_loop { 0 } # true value means to abort the nav_loop routine
157
158 sub post_loop { 0 } # true value means to abort the nav_loop - don't recurse
159
160 sub recurse_limit { shift->{'recurse_limit'} || 15 }
161
162 ### default die handler - show what happened and die (so its in the error logs)
163 sub handle_error {
164 my $self = shift;
165 my $err = shift;
166
167 die $err;
168 }
169
170 ###----------------------------------------------------------------###
171
172 sub default_step { shift->{'default_step'} || 'main' }
173
174 sub js_step { shift->{'js_step'} || 'js' }
175
176 sub forbidden_step { shift->{'forbidden_step'} || '__forbidden' }
177
178 sub step_key { shift->{'step_key'} || 'step' }
179
180 sub path {
181 my $self = shift;
182 if (! $self->{'path'}) {
183 my $path = $self->{'path'} = []; # empty path
184
185 my $step = $self->form->{ $self->step_key };
186 $step = lc($1) if ! $step && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} =~ m|^/(\w+)|;
187
188 ### make sure the step is valid
189 if (defined $step) {
190 if ($step =~ /^_/) { # can't begin with _
191 $self->stash->{'forbidden_step'} = $step;
192 push @$path, $self->forbidden_step;
193 } elsif ($self->valid_steps # must be in valid_steps if defined
194 && ! $self->valid_steps->{$step}
195 && $step ne $self->default_step
196 && $step ne $self->js_step) {
197 $self->stash->{'forbidden_step'} = $step;
198 push @$path, $self->forbidden_step;
199 } else {
200 push @$path, $step;
201 }
202 }
203 }
204
205 return $self->{'path'};
206 }
207
208 sub set_path {
209 my $self = shift;
210 my $path = $self->{'path'} ||= [];
211 croak "Cannot call set_path after the navigation loop has begun" if $self->{'path_i'};
212 splice @$path, 0, $#$path + 1, @_; # change entries in the ref (which updates other copies of the ref)
213 }
214
215 ### legacy - same as append_path
216 sub add_to_path {
217 my $self = shift;
218 push @{ $self->path }, @_;
219 }
220
221 sub append_path {
222 my $self = shift;
223 push @{ $self->path }, @_;
224 }
225
226 sub replace_path {
227 my $self = shift;
228 my $ref = $self->path;
229 my $i = $self->{'path_i'} || 0;
230 if ($i + 1 > $#$ref) {
231 push @$ref, @_;
232 } else {
233 splice(@$ref, $i + 1, $#$ref - $i, @_); # replace remaining entries
234 }
235 }
236
237 sub insert_path {
238 my $self = shift;
239 my $ref = $self->path;
240 my $i = $self->{'path_i'} || 0;
241 if ($i + 1 > $#$ref) {
242 push @$ref, @_;
243 } else {
244 splice(@$ref, $i + 1, 0, @_); # insert a path at the current location
245 }
246 }
247
248 ### a hash of paths that are allowed, default undef is all are allowed
249 sub valid_steps {}
250
251 ###----------------------------------------------------------------###
252 ### allow for checking where we are in the path and for jumping around
253
254 sub exit_nav_loop {
255 my $self = shift;
256
257 ### undo morphs
258 if (my $ref = $self->{'__morph_lineage'}) {
259 ### use the saved index - this allows for early "morphers" to only get rolled back so far
260 my $index = $self->{'__morph_lineage_start_index'};
261 $index = -1 if ! defined $index;
262 $self->unmorph while $#$ref != $index;
263 }
264
265 ### long jump back
266 die "Long Jump\n";
267 }
268
269 sub jump {
270 my $self = shift;
271 my $i = @_ == 1 ? shift : 1;
272 my $path = $self->path;
273 my $path_i = $self->{'path_i'};
274 croak "Can't jump if nav_loop not started" if ! defined $path_i;
275
276 ### validate where we are jumping to
277 if ($i =~ /^\w+$/) {
278 if ($i eq 'FIRST') {
279 $i = - $path_i - 1;
280 } elsif ($i eq 'LAST') {
281 $i = $#$path - $path_i;
282 } elsif ($i eq 'NEXT') {
283 $i = 1;
284 } elsif ($i eq 'CURRENT') {
285 $i = 0;
286 } elsif ($i eq 'PREVIOUS') {
287 $i = -1;
288 } else { # look for a step by that name
289 for (my $j = $#$path; $j >= 0; $j --) {
290 if ($path->[$j] eq $i) {
291 $i = $j - $path_i;
292 last;
293 }
294 }
295 }
296 }
297 if ($i !~ /^-?\d+$/) {
298 require Carp;
299 Carp::croak("Invalid jump index ($i)");
300 }
301
302 ### manipulate the path to contain the new jump location
303 my @replace;
304 my $cut_i = $path_i + $i;
305 if ($cut_i > $#$path) {
306 push @replace, $self->default_step;
307 } elsif ($cut_i < 0) {
308 push @replace, @$path;
309 } else {
310 push @replace, @$path[$cut_i .. $#$path];
311 }
312 $self->replace_path(@replace);
313
314 ### record the number of jumps
315 $self->{'jumps'} ||= 0;
316 $self->{'jumps'} ++;
317
318 ### run the newly fixed up path (recursively)
319 $self->{'path_i'} ++; # move along now that the path is updated
320 $self->nav_loop;
321 $self->exit_nav_loop;
322 }
323
324 sub step_by_path_index {
325 my $self = shift;
326 my $i = shift || 0;
327 my $ref = $self->path;
328 return '' if $i < 0;
329 return $self->default_step if $i > $#$ref;
330 return $ref->[$i];
331 }
332
333 sub previous_step {
334 my $self = shift;
335 return $self->step_by_path_index( ($self->{'path_i'} || 0) - 1 );
336 }
337
338 sub current_step {
339 my $self = shift;
340 return $self->step_by_path_index( ($self->{'path_i'} || 0) );
341 }
342
343 sub next_step { # method and hook
344 my $self = shift;
345 return $self->step_by_path_index( ($self->{'path_i'} || 0) + 1 );
346 }
347
348 sub last_step {
349 my $self = shift;
350 return $self->step_by_path_index( $#{ $self->path } );
351 }
352
353 sub first_step {
354 my $self = shift;
355 return $self->step_by_path_index( 0 );
356 }
357
358 ###----------------------------------------------------------------###
359 ### hooks and history
360
361 sub find_hook {
362 my $self = shift;
363 my $hook = shift || do { require Carp; Carp::confess("Missing hook name") };
364 my $step = shift || '';
365 my $code;
366 if ($step && ($code = $self->can("${step}_${hook}"))) {
367 return [$code, "${step}_${hook}"],
368
369 } elsif ($code = $self->can($hook)) {
370 return [$code, $hook];
371
372 } else {
373 return [];
374
375 }
376 }
377
378 sub run_hook {
379 my $self = shift;
380 my $hook = shift;
381 my $step = shift;
382
383 my ($code, $found) = @{ $self->find_hook($hook, $step) };
384 if (! $code) {
385 croak "Could not find a method named ${step}_${hook} or ${hook}";
386 } elsif (! UNIVERSAL::isa($code, 'CODE')) {
387 croak "Value for $hook ($found) is not a code ref ($code)";
388 }
389
390 ### record history
391 my $hist = {
392 step => $step,
393 meth => $hook,
394 found => $found,
395 time => time,
396 };
397
398 push @{ $self->history }, $hist;
399
400 $hist->{'level'} = $self->{'_level'};
401 local $self->{'_level'} = 1 + ($self->{'_level'} || 0);
402
403 $hist->{'elapsed'} = time - $hist->{'time'};
404
405 my $resp = $self->$code($step, @_);
406
407 $hist->{'elapsed'} = time - $hist->{'time'};
408 $hist->{'response'} = $resp;
409
410 return $resp;
411 }
412
413 sub history {
414 return shift->{'history'} ||= [];
415 }
416
417 sub dump_history {
418 my $self = shift;
419 my $all = shift || 0;
420 my $hist = $self->history;
421 my $dump = [];
422 push @$dump, sprintf("Elapsed: %.5f", time - $self->{'_time'});
423
424 ### show terse - yet informative info
425 foreach my $row (@$hist) {
426 if (! ref($row)
427 || ref($row) ne 'HASH'
428 || ! exists $row->{'elapsed'}) {
429 push @$dump, $row;
430 } else {
431 my $note = (' ' x ($row->{'level'} || 0))
432 . join(' - ', $row->{'step'}, $row->{'meth'}, $row->{'found'}, sprintf('%.5f', $row->{'elapsed'}));
433 my $resp = $row->{'response'};
434 if (ref($resp) eq 'HASH' && ! scalar keys %$resp) {
435 $note .= ' - {}';
436 } elsif (ref($resp) eq 'ARRAY' && ! @$resp) {
437 $note .= ' - []';
438 } elsif (! ref $resp || ! $all) {
439 my $max = $self->{'history_max'} || 30;
440 if (length($resp) > $max) {
441 $resp = substr($resp, 0, $max);
442 $resp =~ s/\n.+//s;
443 $resp = "$resp ...";
444 }
445 $note .= " - $resp";
446 } else {
447 $note = [$note, $resp];
448 }
449
450 push @$dump, $note;
451 }
452 }
453
454 return $dump;
455 }
456
457 ###----------------------------------------------------------------###
458 ### utility methods to allow for storing separate steps in other modules
459
460 sub allow_morph {
461 my $self = shift;
462 return $self->{'allow_morph'} ? 1 : 0;
463 }
464
465 sub allow_nested_morph {
466 my $self = shift;
467 return $self->{'allow_nested_morph'} ? 1 : 0;
468 }
469
470 sub morph {
471 my $self = shift;
472 my $step = shift || return;
473 my $allow = $self->allow_morph($step) || return;
474
475 ### place to store the lineage
476 my $lin = $self->{'__morph_lineage'} ||= [];
477 my $cur = ref $self; # what are we currently
478 push @$lin, $cur; # store so subsequent unmorph calls can do the right thing
479
480 my $hist = {
481 step => $step,
482 meth => 'morph',
483 found => 'morph',
484 time => time,
485 elapsed => 0,
486 response => 0
487 };
488 push @{ $self->history }, $hist;
489
490 if (ref($allow) && ! $allow->{$step}) { # hash - but no step - record for unbless
491 $hist->{'found'} .= " (not allowed to morph to that step)";
492 return 0;
493 }
494
495 ### make sure we haven't already been reblessed
496 if ($#$lin != 0 # is this the second morph call
497 && (! ($allow = $self->allow_nested_morph($step)) # not true
498 || (ref($allow) && ! $allow->{$step}) # hash - but no step
499 )) {
500 $hist->{'found'} .= $allow ? " (not allowed to nested_morph to that step)" : " (nested_morph disabled)";
501 return 0; # just return - don't die so that we can morph early
502 }
503
504 ### if we are not already that package - bless us there
505 my $new = $self->run_hook('morph_package', $step);
506 if ($cur ne $new) {
507 my $file = $new .'.pm';
508 $file =~ s|::|/|g;
509 if (UNIVERSAL::can($new, 'can') # check if the package space exists
510 || eval { require $file }) { # check for a file that holds this package
511 ### become that package
512 bless $self, $new;
513 $hist->{'found'} .= " (changed $cur to $new)";
514 $self->fixup_after_morph($step);
515 } else {
516 if ($@) {
517 if ($@ =~ /^\s*(Can\'t locate \S+ in \@INC)/) { # let us know what happened
518 $hist->{'found'} .= " (failed from $cur to $new: $1)";
519 } else {
520 $hist->{'found'} .= " (failed from $cur to $new: $@)";
521 my $err = "Trouble while morphing to $file: $@";
522 warn $err;
523 }
524 }
525 }
526 }
527
528 $hist->{'response'} = 1;
529 return 1;
530 }
531
532 sub unmorph {
533 my $self = shift;
534 my $step = shift || '__no_step';
535 my $lin = $self->{'__morph_lineage'} || return;
536 my $cur = ref $self;
537
538 my $prev = pop(@$lin) || croak "unmorph called more times than morph - current ($cur)";
539 delete $self->{'__morph_lineage'} if ! @$lin;
540
541 ### if we are not already that package - bless us there
542 my $hist = {
543 step => $step,
544 meth => 'unmorph',
545 found => 'unmorph',
546 time => time,
547 elapsed => 0,
548 response => 0,
549 };
550 push @{ $self->history }, $hist;
551
552 if ($cur ne $prev) {
553 $self->fixup_before_unmorph($step);
554 bless $self, $prev;
555 $hist->{'found'} .= " (changed from $cur to $prev)";
556 } else {
557 $hist->{'found'} .= " (already isa $cur)";
558 }
559
560 $hist->{'response'} = 1;
561 return $self;
562 }
563
564 sub fixup_after_morph {}
565
566 sub fixup_before_unmorph {}
567
568 ###----------------------------------------------------------------###
569 ### allow for authentication
570
571 sub navigate_authenticated {
572 my ($self, $args) = @_;
573 $self = $self->new($args) if ! ref $self;
574
575 $self->require_auth(1);
576
577 return $self->navigate;
578 }
579
580 sub require_auth {
581 my $self = shift;
582 $self->{'require_auth'} = shift if @_ == 1;
583 return $self->{'require_auth'};
584 }
585
586 sub is_authed { shift->auth_data }
587
588 sub auth_data {
589 my $self = shift;
590 $self->{'auth_data'} = shift if @_ == 1;
591 return $self->{'auth_data'};
592 }
593
594 sub get_valid_auth {
595 my $self = shift;
596 return 1 if $self->is_authed;
597
598 ### augment the args with sensible defaults
599 my $args = $self->auth_args;
600 $args->{'cgix'} ||= $self->cgix;
601 $args->{'form'} ||= $self->form;
602 $args->{'cookies'} ||= $self->cookies;
603 $args->{'js_uri_path'} ||= $self->js_uri_path;
604 $args->{'get_pass_by_user'} ||= sub { my ($auth, $user) = @_; $self->get_pass_by_user($user, $auth) };
605 $args->{'verify_user'} ||= sub { my ($auth, $user) = @_; $self->verify_user( $user, $auth) };
606 $args->{'cleanup_user'} ||= sub { my ($auth, $user) = @_; $self->cleanup_user( $user, $auth) };
607 $args->{'login_print'} ||= sub {
608 my ($auth, $template, $hash) = @_;
609 my $out = $self->run_hook('swap_template', '__login', $template, $hash);
610 $self->run_hook('fill_template', '__login', \$out, $hash);
611 $self->run_hook('print_out', '__login', $out);
612 };
613
614 require CGI::Ex::Auth;
615 my $obj = CGI::Ex::Auth->new($args);
616 my $resp = $obj->get_valid_auth;
617
618 my $data = $obj->last_auth_data;
619 delete $data->{'real_pass'} if defined $data; # data may be defined but false
620 $self->auth_data($data); # failed authentication may still have auth_data
621
622 return ($resp && $data) ? 1 : 0;
623 }
624
625 sub auth_args { {} }
626
627 sub get_pass_by_user { die "get_pass_by_user is a virtual method and needs to be overridden for authentication to work" }
628 sub cleanup_user { my ($self, $user) = @_; $user }
629 sub verify_user { 1 }
630
631 ###----------------------------------------------------------------###
632 ### a few standard base accessors
633
634 sub form {
635 my $self = shift;
636 $self->{'form'} = shift if @_ == 1;
637 return $self->{'form'} ||= $self->cgix->get_form;
638 }
639
640 sub cookies {
641 my $self = shift;
642 $self->{'cookies'} = shift if @_ == 1;
643 return $self->{'cookies'} ||= $self->cgix->get_cookies;
644 }
645
646 sub cgix {
647 my $self = shift;
648 $self->{'cgix'} = shift if @_ == 1;
649 return $self->{'cgix'} ||= do {
650 require CGI::Ex;
651 CGI::Ex->new; # return of the do
652 };
653 }
654
655 sub vob {
656 my $self = shift;
657 $self->{'vob'} = shift if @_ == 1;
658 return $self->{'vob'} ||= do {
659 require CGI::Ex::Validate;
660 CGI::Ex::Validate->new($self->vob_args); # return of the do
661 };
662 }
663
664 sub vob_args {
665 my $self = shift;
666 return {
667 cgix => $self->cgix,
668 };
669 }
670
671 ### provide a place for placing variables
672 sub stash {
673 my $self = shift;
674 return $self->{'stash'} ||= {};
675 }
676
677 ###----------------------------------------------------------------###
678 ### default hook implementations
679
680 sub run_step {
681 my $self = shift;
682 my $step = shift;
683
684 ### if the pre_step exists and returns true, exit the nav_loop
685 return 1 if $self->run_hook('pre_step', $step);
686
687 ### allow for skipping this step (but stay in the nav_loop)
688 return 0 if $self->run_hook('skip', $step);
689
690 ### see if we have complete valid information for this step
691 ### if so, do the next step
692 ### if not, get necessary info and print it out
693 if ( ! $self->run_hook('prepare', $step)
694 || ! $self->run_hook('info_complete', $step)
695 || ! $self->run_hook('finalize', $step)) {
696
697 ### show the page requesting the information
698 $self->run_hook('prepared_print', $step);
699
700 ### a hook after the printing process
701 $self->run_hook('post_print', $step);
702
703 return 1;
704 }
705
706 ### a hook before end of loop
707 ### if the post_step exists and returns true, exit the nav_loop
708 return 1 if $self->run_hook('post_step', $step);
709
710 ### let the nav_loop continue searching the path
711 return 0;
712 }
713
714 sub refine_path {
715 my ($self, $step, $is_at_end) = @_;
716 return 0 if ! $is_at_end; # if we aren't at the end of the path, don't do anything
717
718 my $next_step = $self->run_hook('next_step', $step) || return 0;
719 $self->run_hook('set_ready_validate', $step, 0);
720 $self->append_path($next_step);
721 return 1;
722 }
723
724 sub prepared_print {
725 my $self = shift;
726 my $step = shift;
727
728 my $hash_base = $self->run_hook('hash_base', $step) || {};
729 my $hash_comm = $self->run_hook('hash_common', $step) || {};
730 my $hash_form = $self->run_hook('hash_form', $step) || {};
731 my $hash_fill = $self->run_hook('hash_fill', $step) || {};
732 my $hash_swap = $self->run_hook('hash_swap', $step) || {};
733 my $hash_errs = $self->run_hook('hash_errors', $step) || {};
734
735 ### fix up errors
736 $hash_errs->{$_} = $self->format_error($hash_errs->{$_})
737 foreach keys %$hash_errs;
738 $hash_errs->{'has_errors'} = 1 if scalar keys %$hash_errs;
739
740 ### layer hashes together
741 my $fill = {%$hash_form, %$hash_base, %$hash_comm, %$hash_fill};
742 my $swap = {%$hash_form, %$hash_base, %$hash_comm, %$hash_swap, %$hash_errs};
743
744 ### run the print hook - passing it the form and fill info
745 $self->run_hook('print', $step, $swap, $fill);
746 }
747
748 sub print {
749 my ($self, $step, $swap, $fill) = @_;
750
751 my $file = $self->run_hook('file_print', $step); # get a filename relative to base_dir_abs
752
753 my $out = $self->run_hook('swap_template', $step, $file, $swap);
754
755 $self->run_hook('fill_template', $step, \$out, $fill);
756
757 $self->run_hook('print_out', $step, $out);
758 }
759
760 sub print_out {
761 my ($self, $step, $out) = @_;
762
763 $self->cgix->print_content_type;
764 print $out;
765 }
766
767 sub swap_template {
768 my ($self, $step, $file, $swap) = @_;
769
770 my $args = $self->run_hook('template_args', $step);
771 my $copy = $self;
772 eval {require Scalar::Util; Scalar::Util::weaken($copy)};
773 $args->{'INCLUDE_PATH'} ||= sub { $copy->base_dir_abs || die "Could not find base_dir_abs while looking for template INCLUDE_PATH on step \"$step\"" };
774
775 require CGI::Ex::Template;
776 my $t = CGI::Ex::Template->new($args);
777
778 my $out = '';
779 $t->process($file, $swap, \$out) || die $t->error;
780
781 return $out;
782 }
783
784 sub template_args { {} }
785
786 sub fill_template {
787 my ($self, $step, $outref, $fill) = @_;
788
789 return if ! $fill;
790
791 my $args = $self->run_hook('fill_args', $step);
792 local $args->{'text'} = $outref;
793 local $args->{'form'} = $fill;
794
795 require CGI::Ex::Fill;
796 CGI::Ex::Fill::fill($args);
797 }
798
799 sub fill_args { {} }
800
801 sub pre_step { 0 } # success indicates we handled step (don't continue step or loop)
802 sub skip { 0 } # success indicates to skip the step (and continue loop)
803 sub prepare { 1 } # failure means show step
804 sub finalize { 1 } # failure means show step
805 sub post_print { 0 } # success indicates we handled step (don't continue loop)
806 sub post_step { 0 } # success indicates we handled step (don't continue step or loop)
807
808 sub name_step {
809 my ($self, $step) = @_;
810 return $step;
811 }
812
813 sub morph_package {
814 my $self = shift;
815 my $step = shift || '';
816 my $cur = ref $self; # default to using self as the base for morphed modules
817 my $new = $cur .'::'. $step;
818 $new =~ s/(\b|_+)(\w)/\u$2/g; # turn Foo::my_step_name into Foo::MyStepName
819 return $new;
820 }
821
822 sub name_module {
823 my $self = shift;
824 my $step = shift || '';
825
826 return $self->{'name_module'} ||= do {
827 # allow for cgi-bin/foo or cgi-bin/foo.pl to resolve to "foo"
828 my $script = $ENV{'SCRIPT_NAME'} || $0;
829 $script =~ m/ (\w+) (?:\.\w+)? $/x || die "Couldn't determine module name from \"name_module\" lookup ($step)";
830 $1; # return of the do
831 };
832 }
833
834 sub file_print {
835 my $self = shift;
836 my $step = shift;
837
838 my $base_dir = $self->base_dir_rel;
839 my $module = $self->run_hook('name_module', $step);
840 my $_step = $self->run_hook('name_step', $step) || die "Missing name_step";
841 $_step .= '.'. $self->ext_print if $_step !~ /\.\w+$/;
842
843 foreach ($base_dir, $module) { $_ .= '/' if length($_) && ! m|/$| }
844
845 return $base_dir . $module . $_step;
846 }
847
848 sub file_val {
849 my $self = shift;
850 my $step = shift;
851
852 my $abs = $self->base_dir_abs || return {};
853 my $base_dir = $self->base_dir_rel;
854 my $module = $self->run_hook('name_module', $step);
855 my $_step = $self->run_hook('name_step', $step);
856 $_step .= '.'. $self->ext_val if $_step !~ /\.\w+$/;
857
858 foreach ($abs, $base_dir, $module) { $_ .= '/' if length($_) && ! m|/$| }
859
860 return $abs . $base_dir . $module . $_step;
861 }
862
863 sub info_complete {
864 my ($self, $step) = @_;
865 return 0 if ! $self->run_hook('ready_validate', $step);
866 return 0 if ! $self->run_hook('validate', $step, $self->form);
867 return 1;
868 }
869
870 sub ready_validate {
871 my ($self, $step) = @_;
872 return ($ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq 'POST') ? 1 : 0;
873 }
874
875 sub set_ready_validate { # hook and method
876 my $self = shift;
877 my ($step, $is_ready) = (@_ == 2) ? @_ : (undef, shift);
878 $ENV{'REQUEST_METHOD'} = ($is_ready) ? 'POST' : 'GET';
879 return $is_ready;
880 }
881
882 sub validate {
883 my ($self, $step, $form) = @_;
884
885 my $hash = $self->run_hook('hash_validation', $step);
886 my $what_was_validated = [];
887
888 my $err_obj = eval { $self->vob->validate($form, $hash, $what_was_validated) };
889 die "Step $step: $@" if $@ && ! $err_obj;
890
891 ### had an error - store the errors and return false
892 if ($err_obj) {
893 $self->add_errors($err_obj->as_hash({
894 as_hash_join => "<br>\n",
895 as_hash_suffix => '_error',
896 }));
897 return 0;
898 }
899
900 ### allow for the validation to give us some redirection
901 foreach my $ref (@$what_was_validated) {
902 foreach my $method (qw(append_path replace_path insert_path)) {
903 next if ! (my $val = $ref->{$method});
904 $self->$method(ref $val ? @$val : $val);
905 }
906 }
907
908 return 1;
909 }
910
911 ### creates javascript suitable for validating the form
912 sub js_validation {
913 my $self = shift;
914 my $step = shift;
915 return '' if $self->ext_val =~ /^html?$/; # let htm validation do it itself
916
917 my $form_name = shift || $self->run_hook('form_name', $step);
918 my $hash_val = shift || $self->run_hook('hash_validation', $step);
919 my $js_uri = $self->js_uri_path;
920 return '' if UNIVERSAL::isa($hash_val, 'HASH') && ! scalar keys %$hash_val
921 || UNIVERSAL::isa($hash_val, 'ARRAY') && ! @$hash_val;
922
923 return $self->vob->generate_js($hash_val, $form_name, $js_uri);
924 }
925
926 sub form_name { 'theform' }
927
928 sub hash_validation {
929 my ($self, $step) = @_;
930
931 return $self->{'hash_validation'}->{$step} ||= do {
932 my $hash;
933 my $file = $self->run_hook('file_val', $step);
934
935 ### allow for returning the validation hash in the filename
936 ### a scalar ref means it is a yaml document to be read by get_validation
937 if (ref($file) && ! UNIVERSAL::isa($file, 'SCALAR')) {
938 $hash = $file;
939
940 ### read the file - if it is not found, errors will be in the webserver logs (all else dies)
941 } elsif ($file) {
942 $hash = $self->vob->get_validation($file) || {};
943
944 } else {
945 $hash = {};
946 }
947
948 $hash; # return of the do
949 };
950 }
951
952 sub hash_base {
953 my ($self, $step) = @_;
954
955 return $self->{'hash_base'} ||= do {
956 ### create a weak copy of self to use in closures
957 my $copy = $self;
958 eval {require Scalar::Util; Scalar::Util::weaken($copy)};
959 my $hash = {
960 script_name => $ENV{'SCRIPT_NAME'} || $0,
961 path_info => $ENV{'PATH_INFO'} || '',
962 js_validation => sub { $copy->run_hook('js_validation', $step, shift) },
963 form_name => sub { $copy->run_hook('form_name', $step) },
964 $self->step_key => $step,
965 }; # return of the do
966 };
967 }
968
969 sub hash_common { shift->{'hash_common'} ||= {} }
970 sub hash_form { shift->form }
971 sub hash_fill { shift->{'hash_fill'} ||= {} }
972 sub hash_swap { shift->{'hash_swap'} ||= {} }
973 sub hash_errors { shift->{'hash_errors'} ||= {} }
974
975 ###----------------------------------------------------------------###
976 ### routines to support the base hooks
977
978 sub add_errors {
979 my $self = shift;
980 my $hash = $self->hash_errors;
981 my $args = ref($_[0]) ? shift : {@_};
982 foreach my $key (keys %$args) {
983 my $_key = ($key =~ /error$/) ? $key : "${key}_error";
984 if ($hash->{$_key}) {
985 $hash->{$_key} .= '<br>' . $args->{$key};
986 } else {
987 $hash->{$_key} = $args->{$key};
988 }
989 }
990 $hash->{'has_errors'} = 1;
991 }
992
993 sub has_errors { scalar keys %{ shift->hash_errors } }
994
995 sub format_error {
996 my ($self, $error) = @_;
997 return $error;
998 }
999
1000 sub add_to_errors { shift->add_errors(@_) }
1001 sub add_to_swap { my $self = shift; $self->add_to_hash($self->hash_swap, @_) }
1002 sub add_to_fill { my $self = shift; $self->add_to_hash($self->hash_fill, @_) }
1003 sub add_to_form { my $self = shift; $self->add_to_hash($self->hash_form, @_) }
1004 sub add_to_common { my $self = shift; $self->add_to_hash($self->hash_common, @_) }
1005 sub add_to_base { my $self = shift; $self->add_to_hash($self->hash_base, @_) }
1006
1007 sub add_to_hash {
1008 my $self = shift;
1009 my $old = shift;
1010 my $new = shift;
1011 $new = {$new, @_} if ! ref $new; # non-hashref
1012 $old->{$_} = $new->{$_} foreach keys %$new;
1013 }
1014
1015
1016 sub base_dir_rel {
1017 my $self = shift;
1018 $self->{'base_dir_rel'} = shift if $#_ != -1;
1019 return $self->{'base_dir_rel'} || '';
1020 }
1021
1022 sub base_dir_abs {
1023 my $self = shift;
1024 $self->{'base_dir_abs'} = shift if $#_ != -1;
1025 return $self->{'base_dir_abs'} || '';
1026 }
1027
1028 sub ext_val {
1029 my $self = shift;
1030 $self->{'ext_val'} = shift if $#_ != -1;
1031 return $self->{'ext_val'} || 'val';
1032 }
1033
1034 sub ext_print {
1035 my $self = shift;
1036 $self->{'ext_print'} = shift if $#_ != -1;
1037 return $self->{'ext_print'} || 'html';
1038 }
1039
1040 ### where to find the javascript files
1041 ### default to using this script as a handler
1042 sub js_uri_path {
1043 my $self = shift;
1044 my $script = $ENV{'SCRIPT_NAME'} || return '';
1045 my $js_step = $self->js_step;
1046 return ($self->can('path') == \&CGI::Ex::App::path)
1047 ? $script .'/'. $js_step # try to use a cache friendly URI (if path is our own)
1048 : $script . '?'.$self->step_key.'='.$js_step.'&js='; # use one that works with more paths
1049 }
1050
1051 ###----------------------------------------------------------------###
1052 ### a simple step that allows for printing javascript libraries that
1053 ### are stored in perls @INC. Which ever step is in js_step should do something similar.
1054
1055 sub js_run_step {
1056 my $self = shift;
1057
1058 ### make sure path info looks like /js/CGI/Ex/foo.js
1059 my $file = $self->form->{'js'} || $ENV{'PATH_INFO'} || '';
1060 $file = ($file =~ m!^(?:/js/|/)?(\w+(?:/\w+)*\.js)$!) ? $1 : '';
1061
1062 $self->cgix->print_js($file);
1063 $self->{'_no_post_navigate'} = 1;
1064 return 1;
1065 }
1066
1067 ###----------------------------------------------------------------###
1068 ### a step that will be used if a valid_steps is defined
1069 ### and the current step of the path is not in valid_steps
1070 ### or if the step is a "hidden" step that begins with _
1071 ### or if the step name contains \W
1072
1073 sub __forbidden_info_complete { 0 }
1074
1075 sub __forbidden_hash_swap { {forbidden_step => shift->stash->{'forbidden_step'}} }
1076
1077 sub __forbidden_file_print { \ "<h1>Denied</h1>You do not have access to the step <b>\"[% forbidden_step %]\"</b>" }
1078
1079 ###----------------------------------------------------------------###
1080
1081 1;
1082
1083 ### See the perldoc in CGI/Ex/App.pod
This page took 0.122727 seconds and 4 git commands to generate.