blib/lib/CGI/FormBuilder.pm untested

filter: Statementstmt 0.0% 0 / 852 Branchbran 0.0% 0 / 438 Conditioncond 0.0% 0 / 205 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 72 Podpod 0.0% 0 / 60 totaltotal 0.0% 0 / 1627 SCAR 107.9
CC
220
Cov
0%
new
1122.0
field
156.0
render
132.0
CRAP 48620.0
1  
2 ###########################################################################
3 # Copyright (c) Nate Wiger http://nateware.com. All Rights Reserved.
4 # Please visit http://formbuilder.org for tutorials, support, and examples.
5 ###########################################################################
6  
7 # Note: Documentation has grown so massive it is now in FormBuilder.pod
8  
9 package CGI::FormBuilder;
10  
11 use Carp;
12 use strict;
13 use warnings;
14 no warnings 'uninitialized';
15 use Scalar::Util qw(weaken);
16  
17 use CGI::FormBuilder::Util;
18 use CGI::FormBuilder::Field;
19 use CGI::FormBuilder::Messages;
20  
21 our $VERSION = '3.10';
22  
23 our $AUTOLOAD;
24  
25 # Default options for FormBuilder
26 our %DEFAULT = (
27 sticky => 1,
28 method => 'get',
29 submit => 1,
30 reset => 0,
31 header => 0,
32 body => { },
33 text => '',
34 table => { },
35 tr => { },
36 th => { },
37 td => { },
38 div => { },
39 jsname => 'validate',
40 jsprefix => 'fb_', # prefix for JS tags
41 sessionidname => '_sessionid',
42 submittedname => '_submitted',
43 pagename => '_page',
44 template => '', # default template
45 debug => 0, # can be 1 or 2
46 javascript => 'auto', # 0, 1, or 'auto'
47 cookies => 1,
48 cleanopts => 1,
49 render => 'render', # render sub name
50 smartness => 1, # can be 1 or 2
51 selectname => 1, # include -select-?
52 selectnum => 5,
53 stylesheet => 0, # use stylesheet stuff?
54 styleclass => 'fb', # style class to use
55 # For translating tag names (experimental)
56 tagnames => { },
57 # I don't see any reason why these are variables
58 formname => '_form',
59 submitname => '_submit',
60 resetname => '_reset',
61 bodyname => '_body',
62 tabname => '_tab',
63 rowname => '_row',
64 labelname => '_label',
65 fieldname => '_field', # equiv of <tmpl_var field-tag>
66 buttonname => '_button',
67 errorname => '_error',
68 othername => '_other',
69 growname => '_grow',
70 statename => '_state',
71 extraname => '_extra',
72 dtd => <<'EOD', # modified from CGI.pm
73 <?xml version="1.0" encoding="{charset}"?>
74 <!DOCTYPE html
75 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
76 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
77 <html xmlns="http://www.w3.org/1999/xhtml" lang="{lang}" xml:lang="{lang}">
78 EOD
79 );
80  
81 # Which options to rearrange from new() into field()
82 our %REARRANGE = qw(
83 options options
84 optgroups optgroups
85 labels label
86 validate validate
87 required required
88 selectname selectname
89 selectnum selectnum
90 sortopts sortopts
91 nameopts nameopts
92 cleanopts cleanopts
93 sticky sticky
94 disabled disabled
95 columns columns
96 );
97  
98 *redo = \&new;
99 sub new {
100 local $^W = 0; # -w sucks
101 my $self = shift;
102  
103 # A single arg is a source; others are opt => val pairs
104 my %opt;
105 if (@_ == 1) {
106 %opt = UNIVERSAL::isa($_[0], 'HASH')
107 ? %{ $_[0] }
108 : ( source => shift() );
109 } else {
110 %opt = arghash(@_);
111 }
112  
113 # Pre-check for an external source
114 if (my $src = delete $opt{source}) {
115  
116 # check for engine type
117 my $mod;
118 my $sopt; # opts returned from parsing
119 my $ref = ref $src;
120 unless ($ref) {
121 # string filename; redo format (ala $self->{template})
122 $src = {
123 type => 'File',
124 source => $src,
125 # pass catalyst class for \&validate refs
126 ($opt{c} && $opt{c}->action)
127 ? (caller => $opt{c}->action->class) : ()
128 };
129 $ref = 'HASH'; # tricky
130 debug 2, "rewrote 'source' option since found filename";
131 }
132 debug 1, "creating form from source ", $ref || $src;
133  
134 if ($ref eq 'HASH') {
135 # grab module
136 $mod = delete $src->{type} || 'File';
137  
138 # user can give 'Their::Complete::Module' or an 'IncludedTemplate'
139 $mod = join '::', __PACKAGE__, 'Source', $mod unless $mod =~ /::/;
140 debug 1, "loading $mod for 'source' option";
141  
142 eval "require $mod";
143 puke "Bad source module $mod: $@" if $@;
144  
145 my $sob = $mod->new(%$src);
146 $sopt = $sob->parse;
147 } elsif ($ref eq 'CODE') {
148 # subroutine wrapper
149 $sopt = &{$src->{source}}($self);
150 } elsif (UNIVERSAL::can($src->{source}, 'parse')) {
151 # instantiated object
152 $sopt = $src->{source}->parse($self);
153 } elsif ($ref) {
154 puke "Unsupported operand to 'template' option - must be \\%hash, \\&sub, or \$object w/ parse()";
155 }
156  
157 # per-instance variables win
158 while (my($k,$v) = each %$sopt) {
159 $opt{$k} = $v unless exists $opt{$k};
160 }
161 }
162  
163 if (ref $self) {
164 # cloned/original object
165 debug 1, "rewriting existing FormBuilder object";
166 while (my($k,$v) = each %opt) {
167 $self->{$k} = $v;
168 }
169 } else {
170 debug 1, "constructing new FormBuilder object";
171 # damn deep copy this is SO damn annoying
172 while (my($k,$v) = each %DEFAULT) {
173 next if exists $opt{$k};
174 if (ref $v eq 'HASH') {
175 $opt{$k} = { %$v };
176 } elsif (ref $v eq 'ARRAY') {
177 $opt{$k} = [ @$v ];
178 } else {
179 $opt{$k} = $v;
180 }
181 }
182 $self = bless \%opt, $self;
183 }
184  
185 # Create our CGI object if not present
186 unless (ref $self->{params}) {
187 require CGI;
188 $CGI::USE_PARAM_SEMICOLONS = 0; # fuck ; in urls
189 $self->{params} = CGI->new($self->{params});
190 }
191  
192 # XXX not mod_perl safe
193 $CGI::FormBuilder::Util::DEBUG = $ENV{FORMBUILDER_DEBUG} || $self->{debug};
194  
195 # And a messages delegate if not existent
196 # Handle 'auto' mode by trying to detect from request
197 # Can't do this in ::Messages because it has no CGI knowledge
198 if (lc($self->{messages}) eq 'auto') {
199 my $lang = $self->{messages};
200 # figure out the messages from our params object
201 if (UNIVERSAL::isa($self->{params}, 'CGI')) {
202 $lang = $self->{params}->http('Accept-Language');
203 } elsif (UNIVERSAL::isa($self->{params}, 'Apache')) {
204 $lang = $self->{params}->headers_in->get('Accept-Language');
205 } elsif (UNIVERSAL::isa($self->{params}, 'Catalyst::Request')) {
206 $lang = $self->{params}->headers->header('Accept-Language');
207 } else {
208 # last-ditch effort
209 $lang = $ENV{HTTP_ACCEPT_LANGUAGE}
210 || $ENV{LC_MESSAGES} || $ENV{LC_ALL} || $ENV{LANG};
211 }
212 $lang ||= 'default';
213 $self->{messages} = CGI::FormBuilder::Messages->new(":$lang");
214 } else {
215 # ref or filename (::Messages will decode)
216 $self->{messages} = CGI::FormBuilder::Messages->new($self->{messages});
217 }
218  
219 # Initialize form fields (probably a good idea)
220 if ($self->{fields}) {
221 debug 1, "creating fields list";
222  
223 # check to see if 'fields' is a hash or array ref
224 my $ref = ref $self->{fields};
225 if ($ref && $ref eq 'HASH') {
226 # with a hash ref, we setup keys/values
227 debug 2, "got fields list from HASH";
228 while(my($k,$v) = each %{$self->{fields}}) {
229 $k = lc $k; # must lc to ignore case
230 $self->{values}{$k} = [ autodata $v ];
231 }
232 # reset main fields to field names
233 $self->{fields} = [ sort keys %{$self->{fields}} ];
234 } else {
235 # rewrite fields to ensure format
236 debug 2, "assuming fields list from ARRAY";
237 $self->{fields} = [ autodata $self->{fields} ];
238 }
239 }
240  
241 if (UNIVERSAL::isa($self->{validate}, 'Data::FormValidator')) {
242 debug 2, "got a Data::FormValidator for validate";
243 # we're being a bit naughty and peeking inside the DFV object
244 $self->{required} = $self->{validate}{profiles}{fb}{required};
245 } else {
246 # Catch the intersection of required and validate
247 if (ref $self->{required}) {
248 # ok, will handle itself automatically below
249 } elsif ($self->{required}) {
250 # catches for required => 'ALL'|'NONE'
251 if ($self->{required} eq 'NONE') {
252 delete $self->{required}; # that's it
253 }
254 elsif ($self->{required} eq 'ALL') {
255 $self->{required} = [ @{$self->{fields}} ];
256 }
257 elsif ($self->{required}) {
258 # required => 'single_field' catch
259 $self->{required} = { $self->{required} => 1 };
260 }
261 } elsif ($self->{validate}) {
262 # construct a required list of all validated fields
263 $self->{required} = [ keys %{$self->{validate}} ];
264 }
265 }
266  
267 # Now, new for the 3.x series, we cycle thru the fields list and
268 # replace it with a list of objects, which stringify to field names
269 my @ftmp = ();
270 for (@{$self->{fields}}) {
271 my %fprop = %{$self->{fieldopts}{$_} || {}}; # field properties
272  
273 if (ref $_ =~ /^CGI::FormBuilder::Field/i) {
274 # is an existing Field object, so update its properties
275 $_->field(%fprop);
276 } else {
277 # init a new one
278 $fprop{name} = "$_";
279 $_ = $self->new_field(%fprop);
280 weaken($_->{_form});
281 }
282 debug 2, "push \@(@ftmp), $_";
283 weaken($self->{fieldrefs}{"$_"} = $_);
284 push @ftmp, $_;
285 }
286  
287 # stringifiable objects (overwrite previous container)
288 $self->{fields} = \@ftmp;
289  
290 # setup values
291 $self->values($self->{values}) if $self->{values};
292  
293 debug 1, "field creation done, list = (@ftmp)";
294  
295 return $self;
296 }
297  
298 *param = \&field;
299 *params = \&field;
300 *fields = \&field;
301 sub field {
302 local $^W = 0; # -w sucks
303 my $self = shift;
304 debug 2, "called \$form->field(@_)";
305  
306 # Handle any of:
307 #
308 # $form->field($name)
309 # $form->field(name => $name, arg => 'val')
310 # $form->field(\@newlist);
311 #
312  
313 return $self->new(fields => $_[0])
314 if ref $_[0] eq 'ARRAY' && @_ == 1;
315  
316 my $name = (@_ % 2 == 0) ? '' : shift();
317 my $args = arghash(@_);
318 $args->{name} ||= $name;
319  
320 # no name - return ala $cgi->param
321 unless ($args->{name}) {
322 # sub fields
323 # return an array of the names in list context, and a
324 # hashref of name/value pairs in a scalar context
325 if (wantarray) {
326 # pre-scan for any "order" arguments, reorder, delete
327 for my $redo (grep { $_->order } @{$self->{fields}}) {
328 next if $redo->order eq 'auto'; # like javascript
329 # kill existing order
330 for (my $i=0; $i < @{$self->{fields}}; $i++) {
331 if ($self->{fields}[$i] eq $redo) {
332 debug 2, "reorder: removed $redo from \$fields->[$i]";
333 splice(@{$self->{fields}}, $i, 1);
334 }
335 }
336 # put it in its new place
337 debug 2, "reorder: moving $redo to $redo->{order}";
338 if ($redo->order <= 1) {
339 # start
340 unshift @{$self->{fields}}, $redo;
341 } elsif ($redo->order >= @{$self->{fields}}) {
342 # end
343 push @{$self->{fields}}, $redo;
344 } else {
345 # middle
346 splice(@{$self->{fields}}, $redo->order - 1, 0, $redo);
347 }
348 # kill subsequent reorders (unnecessary)
349 delete $redo->{order};
350 }
351  
352 # list of all field objects
353 debug 2, "return (@{$self->{fields}})";
354 return @{$self->{fields}};
355 } else {
356 # this only returns a single scalar value for each field
357 return { map { $_ => scalar($_->value) } @{$self->{fields}} };
358 }
359 }
360  
361 # have name, so redispatch to field member
362 debug 2, "searching fields for '$args->{name}'";
363 if ($args->{delete}) {
364 # blow the thing away
365 delete $self->{fieldrefs}{$args->{name}};
366 my @tf = grep { $_->name ne $args->{name} } @{$self->{fields}};
367 $self->{fields} = \@tf;
368 return;
369 } elsif (my $f = $self->{fieldrefs}{$args->{name}}) {
370 delete $args->{name}; # segfault??
371 return $f->field(%$args); # set args, get value back
372 }
373  
374 # non-existent field, and no args, so assume we're checking for it
375 return unless keys %$args > 1;
376  
377 # if we're still in here, we need to init a new field
378 # push it onto our mail fields array, just like initfields()
379 my $f = $self->new_field(%$args);
380 weaken($self->{fieldrefs}{"$f"} = $f);
381 weaken($f->{_form});
382 weaken($f->{fieldrefs}{"$f"});
383 push @{$self->{fields}}, $f;
384
385 return $f->value;
386 }
387  
388 sub new_field {
389 my $self = shift;
390 my $args = arghash(@_);
391 puke "Need a name for \$form->new_field()" unless exists $args->{name};
392 debug 1, "called \$form->new_field($args->{name})";
393  
394 # extract our per-field options from rearrange
395 while (my($from,$to) = each %REARRANGE) {
396 next unless exists $self->{$from};
397 next if defined $args->{$to}; # manually set
398 my $tval = rearrange($self->{$from}, $args->{name});
399 debug 2, "rearrange: \$args->{$to} = $tval;";
400 $args->{$to} = $tval;
401 }
402  
403 $args->{type} = lc $self->{fieldtype}
404 if $self->{fieldtype} && ! exists $args->{type};
405 if ($self->{fieldattr}) { # legacy
406 while (my($k,$v) = each %{$self->{fieldattr}}) {
407 next if exists $args->{$k};
408 $args->{$k} = $v;
409 }
410 }
411
412 my $f = CGI::FormBuilder::Field->new($self, $args);
413 debug 1, "created field $f";
414 return $f; # already set args above ^^^
415 }
416  
417 *fieldset = \&fieldsets;
418 sub fieldsets {
419 my $self = shift;
420 if (@_) {
421 if (ref($_[0]) eq 'ARRAY') {
422 $self->{fieldsets} = shift;
423 } elsif (@_ % 2) {
424 # search for fieldset and update it, or add it
425 # can't use optalign because must change in-place
426 while (@_) {
427 my($k,$v) = (shift,shift);
428 for (@{$self->{fieldsets}||=[]}) {
429 if ($k eq $_->[0]) {
430 $_->[1] = $v;
431 undef $k; # catch below
432 }
433 }
434 # not found, so append
435 if ($k) {
436 push @{$self->{fieldsets}}, [$k,$v];
437 }
438 }
439 } else {
440 puke "Invalid usage of \$form->fieldsets(name => 'Label')"
441 }
442 }
443  
444 # We look for all the fieldset definitions, checking the main
445 # form for a "proper" legend ala our other settings. We then
446 # divide up all the fields and group them in fieldsets.
447 my(%legends, @sets);
448 for (optalign($self->{fieldsets})) {
449 my($o,$n) = optval($_);
450 next if exists $legends{$o};
451 push @sets, $o;
452 debug 2, "added fieldset $o (legend=$n) to \@sets";
453 $legends{$o} = $n;
454 }
455  
456 # find *all* our fieldsets, even hidden in fields w/o Human Tags
457 for ($self->field) {
458 next unless my $o = $_->fieldset;
459 next if exists $legends{$o};
460 push @sets, $o;
461 debug 2, "added fieldset $o (legend=undef) to \@sets";
462 $legends{$o} = $o; # use fieldset as <legend>
463 }
464 return wantarray ? @sets : \%legends;
465 }
466  
467 sub fieldlist {
468 my $self = shift;
469 my @fields = @_ ? @_ : $self->field;
470 my(%saw, @ret);
471 for my $set ($self->fieldsets) {
472 # reorder fields
473 for (@fields) {
474 next if $saw{$_};
475 if ($_->fieldset && $_->fieldset eq $set) {
476 # if this field is in this fieldset, regroup
477 push @ret, $_;
478 debug 2, "added field $_ to field order (fieldset=$set)";
479 $saw{$_} = 1;
480 }
481 }
482 }
483  
484 # keep non-fieldset fields in order relative
485 # to one another, appending them to the end
486 # of the form
487 for (@fields) {
488 debug 2, "appended non-fieldset field $_ to form";
489 push @ret, $_ unless $saw{$_};
490 }
491  
492 return wantarray ? @ret : \@ret;
493 }
494  
495 sub header {
496 my $self = shift;
497 $self->{header} = shift if @_;
498 return unless $self->{header};
499 my %head;
500 if ($self->{cookies} && defined(my $sid = $self->sessionid)) {
501 require CGI::Cookie;
502 $head{'-cookie'} = CGI::Cookie->new(-name => $self->{sessionidname},
503 -value => $sid);
504 }
505 # Set the charset for i18n
506 $head{'-charset'} = $self->charset;
507  
508 # Forcibly require - no extra time in normal case, and if
509 # using Apache::Request this needs to be loaded anyways.
510 return "Content-type: text/html\n\n" if $::TESTING;
511 require CGI;
512 return CGI::header(%head); # CGI.pm MOD_PERL fanciness
513 }
514  
515 sub charset {
516 my $self = shift;
517 $self->{charset} = shift if @_;
518 return $self->{charset} || $self->{messages}->charset || 'iso8859-1';
519 }
520  
521 sub lang {
522 my $self = shift;
523 $self->{lang} = shift if @_;
524 return $self->{lang} || $self->{messages}->lang || 'en_US';
525 }
526  
527 sub dtd {
528 my $self = shift;
529 $self->{dtd} = shift if @_;
530 return '<html>' if $::TESTING;
531  
532 # replace special chars in dtd by exec'ing subs
533 my $dtd = $self->{dtd};
534 $dtd =~ s/\{(\w+)\}/$self->$1/ge;
535 return $dtd;
536 }
537  
538 sub title {
539 my $self = shift;
540 $self->{title} = shift if @_;
541 return $self->{title} if exists $self->{title};
542 return toname(basename);
543 }
544  
545 *script_name = \&action;
546 sub action {
547 local $^W = 0; # -w sucks (still)
548 my $self = shift;
549 $self->{action} = shift if @_;
550 return $self->{action} if exists $self->{action};
551 return basename . $ENV{PATH_INFO};
552 }
553  
554 sub font {
555 my $self = shift;
556 $self->{font} = shift if @_;
557 return '' unless $self->{font};
558 return '' if $self->{stylesheet}; # kill fonts for style
559  
560 # Catch for allowable hashref or string
561 my $ret;
562 my $ref = ref $self->{font} || '';
563 if (! $ref) {
564 # string "arial,helvetica"
565 $ret = { face => $self->{font} };
566 } elsif ($ref eq 'ARRAY') {
567 # hack for array [arial,helvetica] from conf
568 $ret = { face => join ',', @{$self->{font}} };
569 } else {
570 $ret = $self->{font};
571 }
572 return wantarray ? %$ret : htmltag('font', %$ret);
573 }
574  
575 *tag = \&start;
576 sub start {
577 my $self = shift;
578 my %attr = htmlattr('form', %$self);
579  
580 $attr{action} ||= $self->action;
581 $attr{method} ||= $self->method;
582 $attr{method} = lc($attr{method}); # xhtml
583 $self->disabled ? $attr{disabled} = 'disabled' : delete $attr{disabled};
584 $attr{class} ||= $self->class($self->formname);
585  
586 # Bleech, there's no better way to do this...?
587 belch "You should really call \$form->script BEFORE \$form->start"
588 unless $self->{_didscript};
589  
590 # A catch for lowercase actions
591 belch "Old-style 'onSubmit' action found - should be 'onsubmit'"
592 if $attr{onSubmit};
593  
594 return $self->version . htmltag('form', %attr);
595 }
596  
597 sub end {
598 return '</form>';
599 }
600  
601 # Need to wrap this or else AUTOLOAD whines (OURATTR missing)
602 sub disabled {
603 my $self = shift;
604 $self->{disabled} = shift if @_;
605 return $self->{disabled} ? 'disabled' : undef;
606 }
607
608 sub body {
609 my $self = shift;
610 $self->{body} = shift if @_;
611 $self->{body}{bgcolor} ||= 'white' unless $self->{stylesheet};
612 return htmltag('body', $self->{body});
613 }
614  
615 sub class {
616 my $self = shift;
617 return undef unless $self->{stylesheet};
618 return join '', $self->{styleclass}, @_; # remainder is optional tag
619 }
620  
621 sub idname {
622 my $self = shift;
623 $self->{id} = $self->{name}
624 unless defined $self->{id};
625 return undef unless $self->{id};
626 return join '', $self->{id}, @_; # remainder is optional tag
627 }
628  
629 sub table {
630 my $self = shift;
631  
632 # single hashref kills everything; a list is temporary
633 $self->{table} = shift if @_ == 1;
634 return unless $self->{table};
635  
636 # set defaults for numeric table => 1
637 $self->{table} = $DEFAULT{table} if $self->{table} == 1;
638  
639 my $attr = $self->{table};
640 if (@_) {
641 # if still have args, create a temp hash
642 my %temp = %$attr;
643 while (my $k = shift) {
644 $temp{$k} = shift;
645 }
646 $attr = \%temp;
647 }
648  
649 return unless $self->{table}; # 0 or unset via table(0)
650 $attr->{class} ||= $self->class;
651 return htmltag('table', $attr);
652 }
653  
654 sub tr {
655 my $self = shift;
656  
657 # single hashref kills everything; a list is temporary
658 $self->{tr} = shift if @_ == 1 && UNIVERSAL::isa($_[0], 'HASH');
659  
660 my $attr = $self->{tr};
661 if (@_) {
662 # if still have args, create a temp hash
663 my %temp = %$attr;
664 while (my $k = shift) {
665 $temp{$k} = shift;
666 }
667 $attr = \%temp;
668 }
669  
670 # reduced formatting
671 if ($self->{stylesheet}) {
672 # extraneous - inherits from <table>
673 #$attr->{class} ||= $self->class($self->{rowname});
674 } else {
675 $attr->{valign} ||= 'top';
676 }
677  
678 return htmltag('tr', $attr);
679 }
680  
681 sub th {
682 my $self = shift;
683  
684 # single hashref kills everything; a list is temporary
685 $self->{th} = shift if @_ == 1 && UNIVERSAL::isa($_[0], 'HASH');
686  
687 my $attr = $self->{th};
688 if (@_) {
689 # if still have args, create a temp hash
690 my %temp = %$attr;
691 while (my $k = shift) {
692 $temp{$k} = shift;
693 }
694 $attr = \%temp;
695 }
696  
697 # reduced formatting
698 if ($self->{stylesheet}) {
699 # extraneous - inherits from <table>
700 #$attr->{class} ||= $self->class($self->{labelname});
701 } else {
702 $attr->{align} ||= $self->{lalign} || 'left';
703 }
704  
705 return htmltag('th', $attr);
706 }
707  
708 sub td {
709 my $self = shift;
710  
711 # single hashref kills everything; a list is temporary
712 $self->{td} = shift if @_ == 1 && UNIVERSAL::isa($_[0], 'HASH');
713  
714 my $attr = $self->{td};
715 if (@_) {
716 # if still have args, create a temp hash
717 my %temp = %$attr;
718 while (my $k = shift) {
719 $temp{$k} = shift;
720 }
721 $attr = \%temp;
722 }
723  
724 # extraneous - inherits from <table>
725 #$attr->{class} ||= $self->class($self->{fieldname});
726  
727 return htmltag('td', $attr);
728 }
729  
730 sub div {
731 my $self = shift;
732  
733 # single hashref kills everything; a list is temporary
734 $self->{div} = shift if @_ == 1 && UNIVERSAL::isa($_[0], 'HASH');
735  
736 my $attr = $self->{div};
737 if (@_) {
738 # if still have args, create a temp hash
739 my %temp = %$attr;
740 while (my $k = shift) {
741 $temp{$k} = shift;
742 }
743 $attr = \%temp;
744 }
745  
746 return htmltag('div', $attr);
747 }
748  
749 sub submitted {
750 my $self = shift;
751 my $smnam = shift || $self->submittedname; # temp smnam
752 my $smtag = $self->{name} ? "${smnam}_$self->{name}" : $smnam;
753  
754 if ($self->{params}->param($smtag)) {
755 # If we've been submitted, then we return the value of
756 # the submit tag (which allows multiple submission buttons).
757 # Must use an "|| 0E0" or else hitting "Enter" won't cause
758 # $form->submitted to be true (as the button is only sent
759 # across CGI when clicked).
760 my $sr = $self->{params}->param($self->submitname) || '0E0';
761 debug 2, "\$form->submitted() is true, returning $sr";
762 return $sr;
763 }
764 return 0;
765 }
766  
767 # This creates a modified self_url, just including fields (no sessionid, etc)
768 sub query_string {
769 my $self = shift;
770 my @qstr = ();
771 for my $f ($self->fields, $self->keepextras) {
772 # get all values, but ONLY from CGI
773 push @qstr, join('=', escapeurl($f), escapeurl($_)) for $self->cgi_param($f);
774 }
775 return join '&', @qstr;
776 }
777  
778 sub self_url {
779 my $self = shift;
780 return join '?', $self->action, $self->query_string;
781 }
782  
783 # must forcibly return scalar undef for CGI::Session easiness
784 sub sessionid {
785 my $self = shift;
786 $self->{sessionid} = shift if @_;
787 return $self->{sessionid} if $self->{sessionid};
788 return undef unless $self->{sessionidname};
789 my %cookies;
790 if ($self->{cookies}) {
791 require CGI::Cookie;
792 %cookies = CGI::Cookie->fetch;
793 }
794 if (my $cook = $cookies{"$self->{sessionidname}"}) {
795 return $cook->value;
796 } else {
797 return $self->{params}->param($self->{sessionidname}) || undef;
798 }
799 }
800  
801 sub statetags {
802 my $self = shift;
803 my @html = ();
804  
805 # get _submitted
806 my $smnam = $self->submittedname;
807 my $smtag = $self->{name} ? "${smnam}_$self->{name}" : $smnam;
808 my $smval = $self->{params}->param($smnam) + 1;
809 push @html, htmltag('input', name => $smtag, value => $smval, type => 'hidden');
810  
811 # and how about _sessionid
812 if (defined(my $sid = $self->sessionid)) {
813 push @html, htmltag('input', name => $self->{sessionidname},
814 type => 'hidden', value => $sid);
815 }
816  
817 # and what page (hooks for ::Multi)
818 if (defined $self->{page}) {
819 push @html, htmltag('input', name => $self->pagename,
820 type => 'hidden', value => $self->{page});
821 }
822  
823 return wantarray ? @html : join "\n", @html;
824 }
825  
826 *keepextra = \&keepextras;
827 sub keepextras {
828 local $^W = 0; # -w sucks
829 my $self = shift;
830 my @keep = ();
831 my @html = ();
832  
833 # which ones do they want?
834 $self->{keepextras} = shift if @_;
835 return '' unless $self->{keepextras};
836  
837 # If we set keepextras, then this means that any extra fields that
838 # we've set that are *not* in our fields() will be added to the form
839 my $ref = ref $self->{keepextras} || '';
840 if ($ref eq 'ARRAY') {
841 @keep = @{$self->{keepextras}};
842 } elsif ($ref) {
843 puke "Unsupported data structure type '$ref' passed to 'keepextras' option";
844 } else {
845 # Set to "1", so must go thru all params, skipping
846 # leading underscore fields and form fields
847 for my $p ($self->{params}->param()) {
848 next if $p =~ /^_/ || $self->{fieldrefs}{$p};
849 push @keep, $p;
850 }
851 }
852  
853 # In array context, we just return names we've resolved
854 return @keep if wantarray;
855  
856 # Make sure to get all values
857 for my $p (@keep) {
858 my @values = $self->{params}->can('multi_param') ? $self->{params}->multi_param($p) : $self->{params}->param($p);
859 for my $v (@values) {
860 debug 1, "keepextras: saving hidden param $p = $v";
861 push @html, htmltag('input', name => $p, type => 'hidden', value => $v);
862 }
863 }
864 return join "\n", @html; # wantarray above
865 }
866  
867 sub javascript {
868 my $self = shift;
869 $self->{javascript} = shift if @_;
870  
871 # auto-determine javascript setting based on user agent
872 if (lc($self->{javascript}) eq 'auto') {
873 if (exists $ENV{HTTP_USER_AGENT}
874 && $ENV{HTTP_USER_AGENT} =~ /lynx|mosaic/i)
875 {
876 # Turn off for old/non-graphical browsers
877 return 0;
878 }
879 return 1;
880 }
881 return $self->{javascript} if exists $self->{javascript};
882  
883 # Turn on for all other browsers by default.
884 # I suspect this process should be reversed, only
885 # showing JavaScript on those browsers we know accept
886 # it, but maintaining a full list will result in this
887 # module going out of date and having to be updated.
888 return 1;
889 }
890  
891 sub jsname {
892 my $self = shift;
893 return $self->{name}
894 ? (join '_', $self->{jsname}, tovar($self->{name}))
895 : $self->{jsname};
896 }
897  
898 sub script {
899 my $self = shift;
900  
901 # get validate() function name
902 my $jsname = $self->jsname || puke "Must have 'jsname' if 'javascript' is on";
903 my $jspre = $self->jsprefix || '';
904  
905 # "counter"
906 $self->{_didscript} = 1;
907 return '' unless $self->javascript;
908  
909 # code for misc non-validate functions
910 my $jsmisc = $self->script_growable # code to grow growable fields, if any
911 . $self->script_otherbox; # code to enable/disable the "other" box
912  
913 # custom user jsfunc option for w/i validate()
914 my $jsfunc = $self->jsfunc || '';
915 my $jshead = $self->jshead || '';
916  
917 # expand per-field validation functions, but
918 # only if we are not using Data::FormValidator
919 unless (UNIVERSAL::isa($self->{validate}, 'Data::FormValidator')) {
920 for ($self->field) {
921 $jsfunc .= $_->script;
922 }
923 }
924
925 # skip out if we have nothing useful
926 return '' unless $jsfunc || $jsmisc || $jshead;
927  
928 # prefix with opening code
929 if ($jsfunc) {
930 $jsfunc = <<EOJ1 . $jsfunc . <<EOJ2;
931 function $jsname (form) {
932 var alertstr = '';
933 var invalid = 0;
934 var invalid_fields = new Array();
935  
936 EOJ1
937 if (invalid > 0 || alertstr != '') {
938 EOJ2
939  
940 # Check to see if we have our own jserror callback on form failure
941 # if not, then use the builtin one. Aka jsalert
942 if (my $jse = $self->jserror) {
943 $jsfunc .= " return $jse(form, invalid, alertstr, invalid_fields);\n";
944 } else {
945 # Finally, close our JavaScript if it was opened, wrapping in <script> tags
946 # We do a regex trick to turn "%s" into "+invalid+"
947 (my $alertstart = $self->{messages}->js_invalid_start) =~ s/%s/'+invalid+'/g;
948 (my $alertend = $self->{messages}->js_invalid_end) =~ s/%s/'+invalid+'/g;
949  
950 $jsfunc .= <<EOJS;
951 if (! invalid) invalid = 'The following'; // catch for programmer error
952 alert('$alertstart'+'\\n\\n'
953 +alertstr+'\\n'+'$alertend');
954 return false;
955 EOJS
956 }
957  
958 # Close the function
959 if (my $jss = $self->jsvalid) {
960 $jsfunc .= " }\n return $jss(form);\n}\n";
961 } else {
962 $jsfunc .= " }\n return true; // all checked ok\n}\n";
963 }
964  
965 # Must set our onsubmit to call validate()
966 # Unfortunately, this introduces the requirement that script()
967 # must be generated/called before start() in our template engines.
968 # Fortunately, that usually happens anyways. Still sucks.
969 $self->{onsubmit} ||= "return $jsname(this);";
970 }
971  
972 # set <script> now to the expanded javascript
973 return '<script type="text/javascript">'
974 . "<!-- hide from old browsers\n"
975 #. "<![CDATA[\n" # fucking web "standards"
976 . $jshead . $jsmisc . $jsfunc
977 #. "\n]]>"
978 . "//-->\n</script>";
979 }
980  
981 sub script_growable {
982 my $self = shift;
983 return '' unless my @growable = grep { $_->growable } $self->field;
984  
985 my $jspre = $self->jsprefix || '';
986 my $jsmisc = '';
987  
988 my $grow = $self->growname;
989 $jsmisc .= <<EOJS;
990 var ${jspre}counter = new Object; // for assigning unique ids; keyed by field name
991 var ${jspre}limit = new Object; // for limiting the size of growable fields
992 function ${jspre}grow (baseID) {
993 // inititalize the counter for this ID
994 if (isNaN(${jspre}counter[baseID])) ${jspre}counter[baseID] = 1;
995  
996 // don't go past the growth limit for this field
997 if (${jspre}counter[baseID] >= ${jspre}limit[baseID]) return;
998  
999 var base = document.getElementById(baseID + '_' + (${jspre}counter[baseID] - 1));
1000  
1001 // we are inserting after the last field
1002 insertPoint = base.nextSibling;
1003  
1004 // line break
1005 base.parentNode.insertBefore(document.createElement('br'), insertPoint);
1006  
1007 var dup = base.cloneNode(true);
1008  
1009 dup.setAttribute('id', baseID + '_' + ${jspre}counter[baseID]);
1010 base.parentNode.insertBefore(dup, insertPoint);
1011  
1012 // add some padding space between the field and the "add field" button
1013 base.parentNode.insertBefore(document.createTextNode(' '), insertPoint);
1014  
1015 ${jspre}counter[baseID]++;
1016  
1017 // disable the "add field" button if we are at the limit
1018 if (${jspre}counter[baseID] >= ${jspre}limit[baseID]) {
1019 var addButton = document.getElementById('$grow' + '_' + baseID);
1020 addButton.setAttribute('disabled', 'disabled');
1021 }
1022 }
1023  
1024 EOJS
1025  
1026 # initialize growable counters
1027 for (@growable) {
1028 my $count = scalar(my @v = $_->values);
1029 $jsmisc .= "${jspre}counter['$_'] = $count;\n" if $count > 0;
1030 # assume that values of growable > 1 provide limits
1031 my $limit = $_->growable;
1032 if ($limit && $limit ne 1) {
1033 $jsmisc .= "${jspre}limit['$_'] = $limit;\n";
1034 }
1035 }
1036 return $jsmisc;
1037 }
1038  
1039 sub script_otherbox {
1040 my $self = shift;
1041 return '' unless my @otherable = grep { $_->other } $self->field;
1042  
1043 my $jspre = $self->jsprefix || '';
1044 my $jsmisc = '';
1045
1046 $jsmisc .= <<EOJS;
1047 // turn on/off any "other"fields
1048 function ${jspre}other_on (othername) {
1049 var box = document.getElementById(othername);
1050 box.removeAttribute('disabled');
1051 }
1052  
1053 function ${jspre}other_off (othername) {
1054 var box = document.getElementById(othername);
1055 box.setAttribute('disabled', 'disabled');
1056 }
1057  
1058 EOJS
1059  
1060 return $jsmisc;
1061 }
1062  
1063 sub noscript {
1064 my $self = shift;
1065 # no state is kept and no args are allowed
1066 puke "No args allowed for \$form->noscript" if @_;
1067 return '' unless $self->javascript;
1068 return '<noscript>' . $self->invalid_tag($self->{messages}->js_noscript) . '</noscript>';
1069 }
1070  
1071 sub submits {
1072 local $^W = 0; # -w sucks
1073 my $self = shift;
1074  
1075 # handle the submit button(s)
1076 # logic is a little complicated - if set but to a false value,
1077 # then leave off. otherwise use as the value for the tags.
1078 my @submit = ();
1079 my $sn = $self->{submitname};
1080 my $sc = $self->class($self->{buttonname});
1081 if (ref $self->{submit} eq 'ARRAY') {
1082 # multiple buttons + JavaScript - dynamically set the _submit value
1083 my @oncl = $self->javascript
1084 ? (onclick => "this.form.$sn.value = this.value;") : ();
1085 my $i=1;
1086 for my $subval (autodata $self->{submit}) {
1087 my $si = $i > 1 ? "_$i" : ''; # number with second one
1088 push @submit, { type => 'submit',
1089 id => "$self->{name}$sn$si",
1090 class => $sc,
1091 name => $sn,
1092 value => $subval, @oncl };
1093 $i++;
1094 }
1095 } else {
1096 # show the text on the button
1097 my $subval = $self->{submit} eq 1 ? $self->{messages}->form_submit_default
1098 : $self->{submit};
1099 push @submit, { type => 'submit',
1100 id => "$self->{name}$sn",
1101 class => $sc,
1102 name => $sn,
1103 value => $subval };
1104 }
1105 return wantarray ? @submit : [ map { htmltag('input', $_) } @submit ];
1106 }
1107  
1108 sub submit {
1109 my $self = shift;
1110 $self->{submit} = shift if @_;
1111 return '' if ! $self->{submit} || $self->static || $self->disabled;
1112  
1113 # no newline on buttons regardless of setting
1114 return join '', map { htmltag('input', $_) } $self->submits(@_);
1115 }
1116  
1117 sub reset {
1118 local $^W = 0; # -w sucks
1119 my $self = shift;
1120 $self->{reset} = shift if @_;
1121 return '' if ! $self->{reset} || $self->static || $self->disabled;
1122 my $sc = $self->class($self->{buttonname});
1123  
1124 # similar to submit(), but a little simpler ;-)
1125 my $reset = $self->{reset} eq 1 ? $self->{messages}->form_reset_default
1126 : $self->{reset};
1127 my $rn = $self->resetname;
1128 return htmltag('input', type => 'reset',
1129 id => "$self->{name}$rn",
1130 class => $sc,
1131 name => $rn,
1132 value => $reset);
1133 }
1134  
1135 sub text {
1136 my $self = shift;
1137 $self->{text} = shift if @_;
1138
1139 # having any required fields changes the leading text
1140 my $req = 0;
1141 my $inv = 0;
1142 for ($self->fields) {
1143 $req++ if $_->required;
1144 $inv++ if $_->invalid; # failed validate()
1145 }
1146  
1147 unless ($self->static || $self->disabled) {
1148 # only show either invalid or required text
1149 return $self->{text} .'<p>'. sprintf($self->{messages}->form_invalid_text,
1150 $inv,
1151 $self->invalid_tag).'</p>' if $inv;
1152  
1153 return $self->{text} .'<p>'. sprintf($self->{messages}->form_required_text,
1154 $self->required_tag).'</p>' if $req;
1155 }
1156 return $self->{text};
1157 }
1158  
1159 sub invalid_tag {
1160 my $self = shift;
1161 my $label = shift || '';
1162 my @tags = $self->{stylesheet}
1163 ? (qq(<span class="$self->{styleclass}_invalid">), '</span>')
1164 : ('<font color="#cc0000"><b>', '</b></font>');
1165 return wantarray ? @tags : join $label, @tags;
1166 }
1167  
1168 sub required_tag {
1169 my $self = shift;
1170 my $label = shift || '';
1171 my @tags = $self->{stylesheet}
1172 ? (qq(<span class="$self->{styleclass}_required">), '</span>')
1173 : ('<b>', '</b>');
1174 return wantarray ? @tags : join $label, @tags;
1175 }
1176  
1177 sub cgi_param {
1178 my $self = shift;
1179 $self->{params}->param(@_);
1180 }
1181  
1182 sub tmpl_param {
1183 my $self = shift;
1184 if (my $key = shift) {
1185 return @_ ? $self->{tmplvar}{$key} = shift
1186 : $self->{tmplvar}{$key};
1187 } else {
1188 # return hash or key/value pairs
1189 my $hr = $self->{tmplvar} || {};
1190 return wantarray ? %$hr : $hr;
1191 }
1192 }
1193  
1194 sub version {
1195 # Hidden trailer. If you perceive this as annoying, let me know and I
1196 # may remove it. It's supposed to help.
1197 return '' if $::TESTING;
1198 if (ref $_[0]) {
1199 return "\n<!-- Generated by CGI::FormBuilder v$VERSION available from www.formbuilder.org -->\n";
1200 } else {
1201 return "CGI::FormBuilder v$VERSION by Nate Wiger. All Rights Reserved.\n";
1202 }
1203 }
1204  
1205 sub values {
1206 my $self = shift;
1207  
1208 if (@_) {
1209 $self->{values} = arghash(@_);
1210 my %val = ();
1211 my @val = ();
1212  
1213 # We currently make two passes, first getting the values
1214 # and storing them into a temp hash, and then going thru
1215 # the fields and picking up the values and attributes.
1216 local $" = ',';
1217 debug 1, "\$form->{values} = ($self->{values})";
1218  
1219 # Using isa() allows objects to transparently fit in here
1220 if (UNIVERSAL::isa($self->{values}, 'CODE')) {
1221 # it's a sub; lookup each value in turn
1222 for my $key (&{$self->{values}}) {
1223 # always assume an arrayref of values...
1224 $val{$key} = [ &{$self->{values}}($key) ];
1225 debug 2, "setting values from \\&code(): $key = (@{$val{$key}})";
1226 }
1227 } elsif (UNIVERSAL::isa($self->{values}, 'HASH')) {
1228 # must lc all the keys since we're case-insensitive, then
1229 # we turn our values hashref into an arrayref on the fly
1230 my @v = autodata $self->{values};
1231 while (@v) {
1232 my $key = lc shift @v;
1233 $val{$key} = [ autodata shift @v ];
1234 debug 2, "setting values from HASH: $key = (@{$val{$key}})";
1235 }
1236 } elsif (UNIVERSAL::isa($self->{values}, 'ARRAY')) {
1237 # also accept an arrayref which is walked sequentially below
1238 debug 2, "setting values from ARRAY: (walked below)";
1239 @val = autodata $self->{values};
1240 } else {
1241 puke "Unsupported operand to 'values' option - must be \\%hash, \\&sub, or \$object";
1242 }
1243  
1244 # redistribute values across all existing fields
1245 for ($self->fields) {
1246 my $v = $val{lc($_)} || shift @val; # use array if no value
1247 $_->field(value => $v) if defined $v;
1248 }
1249 }
1250  
1251 }
1252  
1253 sub name {
1254 my $self = shift;
1255 @_ ? $self->{name} = shift : $self->{name};
1256 }
1257  
1258 sub nameopts {
1259 my $self = shift;
1260 if (@_) {
1261 $self->{nameopts} = shift;
1262 for ($self->fields) {
1263 $_->field(nameopts => $self->{nameopts});
1264 }
1265 }
1266 return $self->{nameopts};
1267 }
1268  
1269 sub sortopts {
1270 my $self = shift;
1271 if (@_) {
1272 $self->{sortopts} = shift;
1273 for ($self->fields) {
1274 $_->field(sortopts => $self->{sortopts});
1275 }
1276 }
1277 return $self->{sortopts};
1278 }
1279  
1280 sub selectnum {
1281 my $self = shift;
1282 if (@_) {
1283 $self->{selectnum} = shift;
1284 for ($self->fields) {
1285 $_->field(selectnum => $self->{selectnum});
1286 }
1287 }
1288 return $self->{selectnum};
1289 }
1290  
1291 sub options {
1292 my $self = shift;
1293 if (@_) {
1294 $self->{options} = arghash(@_);
1295 my %val = ();
1296  
1297 # same case-insensitization as $form->values
1298 my @v = autodata $self->{options};
1299 while (@v) {
1300 my $key = lc shift @v;
1301 $val{$key} = [ autodata shift @v ];
1302 }
1303  
1304 for ($self->fields) {
1305 my $v = $val{lc($_)};
1306 $_->field(options => $v) if defined $v;
1307 }
1308 }
1309 return $self->{options};
1310 }
1311  
1312 sub labels {
1313 my $self = shift;
1314 if (@_) {
1315 $self->{labels} = arghash(@_);
1316 my %val = ();
1317  
1318 # same case-insensitization as $form->values
1319 my @v = autodata $self->{labels};
1320 while (@v) {
1321 my $key = lc shift @v;
1322 $val{$key} = [ autodata shift @v ];
1323 }
1324  
1325 for ($self->fields) {
1326 my $v = $val{lc($_)};
1327 $_->field(label => $v) if defined $v;
1328 }
1329 }
1330 return $self->{labels};
1331 }
1332  
1333 # Note that validate does not work like a true accessor
1334 sub validate {
1335 my $self = shift;
1336
1337 if (@_) {
1338 if (ref $_[0]) {
1339 # this'll either be a hashref or a DFV object
1340 $self->{validate} = shift;
1341 } elsif (@_ % 2 == 0) {
1342 # someone passed a hash-as-list
1343 $self->{validate} = { @_ };
1344 } elsif (@_ > 1) {
1345 # just one argument we'll interpret as a DFV profile name;
1346 # an odd number > 1 is probably a typo...
1347 puke "Odd number of elements passed to validate";
1348 }
1349 }
1350  
1351 my $ok = 1;
1352  
1353 if (UNIVERSAL::isa($self->{validate}, 'Data::FormValidator')) {
1354 my $profile_name = shift || 'fb';
1355 debug 1, "validating fields via the '$profile_name' profile";
1356 # hang on to the DFV results, for things like DBIx::Class::WebForm
1357 $self->{dfv_results} = $self->{validate}->check($self, $profile_name);
1358  
1359 # mark the invalid fields
1360 my @invalid_fields = (
1361 $self->{dfv_results}->invalid,
1362 $self->{dfv_results}->missing,
1363 );
1364 for my $field_name (@invalid_fields) {
1365 $self->field(
1366 name => $field_name,
1367 invalid => 1,
1368 );
1369 }
1370 # validation failed
1371 $ok = 0 if @invalid_fields > 0;
1372 } else {
1373 debug 1, "validating all fields via \$form->validate";
1374 for ($self->fields) {
1375 $ok = 0 unless $_->validate;
1376 }
1377 }
1378 debug 1, "validation done, ok = $ok (should be 1)";
1379 return $ok;
1380 }
1381  
1382 sub confirm {
1383 # This is nothing more than a special wrapper around render()
1384 my $self = shift;
1385 my $date = $::TESTING ? 'LOCALTIME' : localtime();
1386 $self->{text} ||= sprintf $self->{messages}->form_confirm_text, $date;
1387 $self->{static} = 1;
1388 return $self->render(@_);
1389 }
1390  
1391 # Prepare a template
1392 sub prepare {
1393 my $self = shift;
1394 debug 1, "Calling \$form->prepare(@_)";
1395  
1396 # Build a big hashref of data that can be used by the template
1397 # engine. Templates then have the ability to expand this however
1398 # they see fit.
1399 my %tmplvar = $self->tmpl_param;
1400  
1401 # This is based on the original Template Toolkit render()
1402 for my $field ($self->field) {
1403  
1404 # Extract value since used often
1405 my @value = $field->tag_value;
1406  
1407 # Create a struct for each field
1408 $tmplvar{field}{"$field"} = {
1409 %$field, # gets invalid/missing/required
1410 field => $field->tag,
1411 value => $value[0],
1412 values => \@value,
1413 options => [$field->options],
1414 label => $field->label,
1415 type => $field->type,
1416 comment => $field->comment,
1417 nameopts => $field->nameopts,
1418 cleanopts => $field->cleanopts,
1419 };
1420 # Force-stringify "$field" to get name() under buggy Perls
1421 $tmplvar{field}{"$field"}{error} = $field->error;
1422 }
1423  
1424 # Must generate JS first because it affects the others.
1425 # This is a bit action-at-a-distance, but I just can't
1426 # figure out a way around it.
1427 debug 2, "\$tmplvar{jshead} = \$self->script";
1428 $tmplvar{jshead} = $self->script;
1429 debug 2, "\$tmplvar{title} = \$self->title";
1430 $tmplvar{title} = $self->title;
1431 debug 2, "\$tmplvar{start} = \$self->start . \$self->statetags . \$self->keepextras";
1432 $tmplvar{start} = $self->start . $self->statetags . $self->keepextras;
1433 debug 2, "\$tmplvar{submit} = \$self->submit";
1434 $tmplvar{submit} = $self->submit;
1435 debug 2, "\$tmplvar{reset} = \$self->reset";
1436 $tmplvar{reset} = $self->reset;
1437 debug 2, "\$tmplvar{end} = \$self->end";
1438 $tmplvar{end} = $self->end;
1439 debug 2, "\$tmplvar{invalid} = \$self->invalid";
1440 $tmplvar{invalid} = $self->invalid;
1441 debug 2, "\$tmplvar{required} = \$self->required";
1442 $tmplvar{required} = $self->required;
1443  
1444 my $fieldsets = $self->fieldsets;
1445 for my $key (keys %$fieldsets) {
1446 $tmplvar{fieldset}{$key} = {
1447 name => $key,
1448 label => $fieldsets->{$key},
1449 }
1450 }
1451 $tmplvar{fieldsets} = [ map $tmplvar{fieldset}{$_}, $self->fieldsets ];
1452  
1453 debug 2, "\$tmplvar{fields} = [ map \$tmplvar{field}{\$_}, \$self->field ]";
1454 $tmplvar{fields} = [ map $tmplvar{field}{$_}, $self->field ];
1455  
1456 return wantarray ? %tmplvar : \%tmplvar;
1457 }
1458  
1459 sub render {
1460 local $^W = 0; # -w sucks
1461 my $self = shift;
1462 debug 1, "starting \$form->render(@_)";
1463  
1464 # any arguments are used to make permanent changes to the $form
1465 if (@_) {
1466 puke "Odd number of arguments passed into \$form->render()"
1467 unless @_ % 2 == 0;
1468 while (@_) {
1469 my $k = shift;
1470 $self->$k(shift);
1471 }
1472 }
1473  
1474 # check for engine type
1475 my $mod;
1476 my $ref = ref $self->{template};
1477 if (! $ref && $self->{template}) {
1478 # "legacy" string filename for HTML::Template; redo format
1479 # modifying $self object is ok because it's compatible
1480 $self->{template} = {
1481 type => 'HTML',
1482 filename => $self->{template},
1483 };
1484 $ref = 'HASH'; # tricky
1485 debug 2, "rewrote 'template' option since found filename";
1486 }
1487 # Get ourselves ready
1488 $self->{prepare} = $self->prepare;
1489 # weaken($self->{prepare});
1490
1491 my $opt;
1492 if ($ref eq 'HASH') {
1493 # must copy to avoid destroying
1494 $opt = { %{ $self->{template} } };
1495 $mod = ucfirst(delete $opt->{type} || 'HTML');
1496 } elsif ($ref eq 'CODE') {
1497 # subroutine wrapper
1498 return &{$self->{template}}($self);
1499 } elsif (UNIVERSAL::can($self->{template}, 'render')) {
1500 # instantiated object
1501 return $self->{template}->render($self);
1502 } elsif ($ref) {
1503 puke "Unsupported operand to 'template' option - must be \\%hash, \\&sub, or \$object w/ render()";
1504 }
1505  
1506 # load user-specified rendering module, or builtin rendering
1507 $mod ||= 'Builtin';
1508  
1509 # user can give 'Their::Complete::Module' or an 'IncludedAdapter'
1510 $mod = join '::', __PACKAGE__, 'Template', $mod unless $mod =~ /::/;
1511 debug 1, "loading $mod for 'template' option";
1512  
1513 # load module
1514 eval "require $mod";
1515 puke "Bad template engine $mod: $@" if $@;
1516  
1517 # create new object
1518 #CGI::FormBuilder::Template::Builtin
1519
1520 my $tmpl = $mod->new($opt);
1521 # Experiemental: Alter tag names as we're rendering, to support
1522 # Ajaxian markup schemes that use their own tags (Backbase, Dojo, etc)
1523 local %CGI::FormBuilder::Util::TAGNAMES;
1524 while (my($k,$v) = each %{$self->{tagnames}}) {
1525 $CGI::FormBuilder::Util::TAGNAMES{$k} = $v;
1526 }
1527  
1528  
1529 # Call the engine's prepare too, if it exists
1530 # Give it the form object so it can do what it wants
1531 # This will have all of the prepared data in {prepare} anyways
1532 if ($tmpl && UNIVERSAL::can($tmpl, 'prepare')) {
1533 $tmpl->prepare($self);
1534 }
1535
1536  
1537  
1538 # dispatch to engine, prepend header
1539 debug 1, "returning $tmpl->render($self->{prepare})";
1540  
1541 my $ret = $self->header . $tmpl->render($self->{prepare});
1542
1543 #we have a circular reference but we need to kill it after setting up return
1544 weaken($self->{prepare});
1545 return $ret;
1546 }
1547  
1548 # These routines should be moved to ::Mail or something since they're rarely used
1549 sub mail () {
1550 # This is a very generic mail handler
1551 my $self = shift;
1552 my $args = arghash(@_);
1553  
1554 # Where does the mailer live? Must be sendmail-compatible
1555 my $mailer = undef;
1556 unless ($mailer = $args->{mailer} && -x $mailer) {
1557 for my $sendmail (qw(/usr/lib/sendmail /usr/sbin/sendmail /usr/bin/sendmail)) {
1558 if (-x $sendmail) {
1559 $mailer = "$sendmail -t";
1560 last;
1561 }
1562 }
1563 }
1564 unless ($mailer) {
1565 belch "Cannot find a sendmail-compatible mailer; use mailer => '/path/to/mailer'";
1566 return;
1567 }
1568 unless ($args->{to}) {
1569 belch "Missing required 'to' argument; cannot continue without recipient";
1570 return;
1571 }
1572 if ($args->{from}) {
1573 (my $from = $args->{from}) =~ s/"/\\"/g;
1574 $mailer .= qq( -f "$from");
1575 }
1576  
1577 debug 1, "opening new mail to $args->{to}";
1578  
1579 # untaint
1580 my $oldpath = $ENV{PATH};
1581 $ENV{PATH} = '/usr/bin:/usr/sbin';
1582  
1583 open(MAIL, "|$mailer >/dev/null 2>&1") || next;
1584 print MAIL "From: $args->{from}\n";
1585 print MAIL "To: $args->{to}\n";
1586 print MAIL "Cc: $args->{cc}\n" if $args->{cc};
1587 print MAIL "Content-Type: text/plain; charset=\""
1588 . $self->charset . "\"\n" if $self->charset;
1589 print MAIL "Subject: $args->{subject}\n\n";
1590 print MAIL "$args->{text}\n";
1591  
1592 # retaint
1593 $ENV{PATH} = $oldpath;
1594  
1595 return close(MAIL);
1596 }
1597  
1598 sub mailconfirm () {
1599  
1600 # This prints out a very generic message. This should probably
1601 # be much better, but I suspect very few if any people will use
1602 # this method. If you do, let me know and maybe I'll work on it.
1603  
1604 my $self = shift;
1605 my $to = shift unless (@_ > 1);
1606 my $args = arghash(@_);
1607  
1608 # must have a "to"
1609 return unless $args->{to} ||= $to;
1610  
1611 # defaults
1612 $args->{from} ||= 'auto-reply';
1613 $args->{subject} ||= sprintf $self->{messages}->mail_confirm_subject, $self->title;
1614 $args->{text} ||= sprintf $self->{messages}->mail_confirm_text, scalar localtime();
1615  
1616 debug 1, "mailconfirm() called, subject = '$args->{subject}'";
1617  
1618 $self->mail($args);
1619 }
1620  
1621 sub mailresults () {
1622 # This is a wrapper around mail() that sends the form results
1623 my $self = shift;
1624 my $args = arghash(@_);
1625  
1626 if (exists $args->{plugin}) {
1627 my $lib = "CGI::FormBuilder::Mail::$args->{plugin}";
1628 eval "use $lib";
1629 puke "Cannot use mailresults() plugin '$lib': $@" if $@;
1630 eval {
1631 my $plugin = $lib->new( form => $self, %$args );
1632 $plugin->mailresults();
1633 };
1634 puke "Could not mailresults() with plugin '$lib': $@" if $@;
1635 return;
1636 }
1637  
1638 # Get the field separator to use
1639 my $delim = $args->{delimiter} || ': ';
1640 my $join = $args->{joiner} || $";
1641 my $sep = $args->{separator} || "\n";
1642  
1643 # subject default
1644 $args->{subject} ||= sprintf $self->{messages}->mail_results_subject, $self->title;
1645 debug 1, "mailresults() called, subject = '$args->{subject}'";
1646  
1647 if ($args->{skip}) {
1648 if ($args->{skip} =~ m#^m?(\S)(.*)\1$#) {
1649 ($args->{skip} = $2) =~ s/\\\//\//g;
1650 $args->{skip} =~ s/\//\\\//g;
1651 }
1652 }
1653  
1654 my @form = ();
1655 for my $field ($self->fields) {
1656 if ($args->{skip} && $field =~ /$args->{skip}/) {
1657 next;
1658 }
1659 my $v = join $join, $field->value;
1660 $field = $field->label if $args->{labels};
1661 push @form, "$field$delim$v";
1662 }
1663 my $text = join $sep, @form;
1664  
1665 $self->mail(%$args, text => $text);
1666 }
1667  
1668 sub DESTROY { 1 }
1669  
1670 # This is used to access all options after new(), by name
1671 sub AUTOLOAD {
1672 # This allows direct addressing by name
1673 local $^W = 0;
1674 my $self = shift;
1675 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1676  
1677 # If fieldsubs => 1 set, then allow grabbing fields directly
1678 if ($self->{fieldsubs} && $self->{fieldrefs}{$name}) {
1679 return $self->field(name => $name, @_);
1680 }
1681  
1682 debug 3, "-> dispatch to \$form->{$name} = @_";
1683 if (@_ % 2 == 1) {
1684 $self->{$name} = shift;
1685  
1686 if ($REARRANGE{$name}) {
1687 # needs to be splatted into every field
1688 for ($self->fields) {
1689 my $tval = rearrange($self->{$name}, "$_");
1690 $_->$name($tval);
1691 }
1692 }
1693 }
1694  
1695 # Try to catch $form->$fieldname usage
1696 if ((! exists($self->{$name}) || @_) && ! $CGI::FormBuilder::Util::OURATTR{$name}) {
1697 if ($self->{fieldsubs}) {
1698 return $self->field(name => $name, @_);
1699 } else {
1700 belch "Possible field access via \$form->$name() - see 'fieldsubs' option"
1701 }
1702 }
1703  
1704 return $self->{$name};
1705 }
1706  
1707 1;
1708 __END__