FormMagick.pm untested

filter: Statementstmt 0.0% 0 / 201 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 330 CC 31 SCAR 27.5
CC
31
Cov
0%
display
56.0
AUTOLOAD
20.0
wherenext
20.0
CRAP 15.6
1 #!/usr/bin/perl -w
2 #
3 # FormMagick (c) 2000-2001 Kirrily Robert <skud@cpan.org>
4 # Copyright (c) 2000-2002 Mitel Networks Corporation
5 # This software is distributed under the same licenses as Perl itself;
6 # see the file COPYING for details.
7 #
8 # $Id: FormMagick.pm,v 1.129 2003/02/05 20:16:36 segfault- Exp $
9 #
10  
11 package CGI::FormMagick;
12  
13 my $VERSION = $VERSION = "0.89";
14  
15 use XML::Parser;
16 use Text::Template;
17 use CGI::Persistent;
18 use CGI::FormMagick::TagMaker;
19 use CGI::FormMagick::Validator;
20 use CGI::FormMagick::L10N;
21 use CGI::FormMagick::HTML;
22 use CGI::FormMagick::Setup;
23 use CGI::FormMagick::Events;
24 use CGI::FormMagick::Utils;
25 use CGI::FormMagick::Sub;
26  
27 use strict;
28 use Carp;
29  
30 use constant 'FIRST_PAGENUM' => 0;
31  
32 use vars qw( $AUTOLOAD @ISA @EXPORT);
33  
34 @ISA = qw( Exporter );
35 @EXPORT = qw(
36 wherenext
37 go_to_finish
38 );
39  
40 =pod
41  
42 =head1 NAME
43  
44 CGI::FormMagick - easily create CGI form-based applications
45  
46 =head1 SYNOPSIS
47  
48 use CGI::FormMagick;
49  
50 my $f = new CGI::FormMagick();
51  
52 # all options available to new()
53 my $f = new CGI::FormMagick(
54 type => file,
55 source => $myxmlfile,
56 );
57  
58 # other types available
59 my $f = new CGI::FormMagick(type => string, source => $data );
60  
61 $f->display();
62  
63 =head1 DESCRIPTION
64  
65 FormMagick is a toolkit for easily building fairly complex form-based
66 web applications. It allows the developer to specify the structure of a
67 multi-page "wizard" style form using XML, then display that form using
68 only a few lines of Perl.
69  
70 =head2 How it works:
71  
72 You (the developer) provide at least:
73  
74 =over 4
75  
76 =item *
77  
78 An XML form description
79  
80 =item *
81  
82 HTML templates for the page headers and footers
83  
84 =back
85  
86 And may optionally provide:
87  
88 =over 4
89  
90 =item *
91  
92 Translations of strings used in your application, for localisation
93  
94 =item *
95  
96 Validation routines for user input data
97  
98 =item *
99  
100 Routines to run before or after a page of the form is displayed
101  
102 =back
103  
104 FormMagick brings them all together to create a full application.
105  
106 =head1 METHODS
107  
108 =head2 new()
109  
110 The C<new()> method requires no arguments, but may take the following
111 optional arguments (as a hash):
112  
113 =over 4
114  
115 =item type
116  
117 Defaults to "file". "string" is also available, in which case you must
118 specify a source which is either a literal string or a scalar variable.
119  
120 =item source
121  
122 Defaults to a filename matching that of your script, only with an
123 extension of .xml (we got this idea from XML::Simple).
124  
125 =item charset
126  
127 Tell FormMagick that the XML input uses the specified character set encoding.
128 Defaults to 'none' which is good enough for English text and US ASCII. Any
129 other characters may cause parse errors. Valid charsets are "ISO-8859-1",
130 "UTF-8", "UTF-16", or "US-ASCII". This option is case sensitive.
131  
132 =back
133  
134 =begin testing
135 BEGIN: {
136 use_ok('CGI::FormMagick');
137 use vars qw($fm);
138 use lib "lib/";
139 }
140  
141 ok(CGI::FormMagick->can('new'), "We can call new");
142 ok($fm = CGI::FormMagick->new(type => 'file', source => "t/simple.xml"), "create fm object");
143 ok($fm2 = CGI::FormMagick->new(type => 'string', source => '<form></form>',
144 charset => 'US-ASCII'), 'We can pass charset');
145 isa_ok($fm, 'CGI::FormMagick');
146 isa_ok($fm2, 'CGI::FormMagick');
147 $fm->parse_xml();
148  
149 =end testing
150  
151 =cut
152  
153 sub new {
154 my $self = shift;
155 my $class = ref($self) || $self;
156 $self = bless {}, $class;
157  
158 my %args = @_;
159  
160  
161 $self->{debug} = $args{DEBUG} || 0;
162 # $self->{inputtype} = uc($args{type}) || "file";
163 $self->{inputtype} = $args{type} || "file";
164 $self->{source} = $args{source};
165 $self->{charset} = $args{charset} || undef;
166  
167 foreach (qw(PREVIOUSBUTTON RESETBUTTON STARTOVERLINK NEXTBUTTON)) {
168 if (exists $args{$_}) {
169 warn("$_ as arg to new() is deprecated -- use accessor method instead\n");
170 $self->{lc($_)} = $args{$_};
171 } else {
172 $self->{lc($_)} = 1;
173 }
174 }
175  
176 #$self->{sessiondir} = initialise_sessiondir($args{SESSIONDIR});
177 $self->{calling_package} = (caller)[0];
178 $self->{fallback_language} = undef;
179
180 return $self;
181 }
182  
183 =pod
184  
185 =head2 previousbutton()
186  
187 With no arguments, tells you whether the previousbutton will be
188 displayed or not. If you give it a true argument (eg 1) it will set the
189 previous button to be displayed. A false value (eg 0) will set it to
190 not be displayed.
191  
192 =head2 nextbutton()
193  
194 As for previousbutton, but affects the "Next" button.
195  
196 =head2 finishbutton()
197  
198 Ditto.
199  
200 =head2 resetbutton()
201  
202 Ditto.
203  
204 =head2 startoverlink()
205  
206 Ditto.
207  
208 =head2 debug()
209  
210 Turns debugging on/off.
211  
212 =begin testing
213  
214 is($fm->previousbutton, 1, "Previous button set on to begin with");
215 $fm->previousbutton(0);
216 is($fm->previousbutton, 0, "Previous button turned off");
217 $fm->previousbutton(1);
218 is($fm->previousbutton, 1, "Previous button turned on again");
219 $fm->previousbutton("");
220 is($fm->previousbutton, 0, "Previous button turned off with empty string");
221 $fm->previousbutton("a");
222 is($fm->previousbutton, 1, "Previous button turned on with true string");
223  
224 is($fm->debug, 0, "Debug set off to begin with");
225 $fm->debug(1);
226 is($fm->debug, 1, "Debug turned on");
227 $fm->debug(0);
228  
229 =end testing
230  
231 =cut
232  
233 sub AUTOLOAD {
234 my ($self, $onoff) = @_;
235 my ($called_sub_name) = ($AUTOLOAD =~ m/([^:]*)$/);
236 $called_sub_name = lc($called_sub_name);
237 my @flags = qw(
238 previousbutton
239 nextbutton
240 finishbutton
241 resetbutton
242 startoverlink
243 debug
244 );
245 if (grep /^$called_sub_name$/, @flags) {
246 if ($onoff) {
247 $self->{$called_sub_name} = 1;
248 } elsif (defined $onoff) {
249 $self->{$called_sub_name} = 0;
250 } else {
251 return $self->{$called_sub_name};
252 }
253 }
254 }
255  
256 =pod
257  
258 =head2 sessiondir()
259  
260 With no arguments, tells you the directory in which session tokens are
261 kept.
262  
263 With a true value, set the session directory, in which session tokens are kept. Defaults
264 to C<session-tokens> under the directory in which your CGI script is
265 kept, but you probably want to set it to something outside the web tree.
266  
267 With a false (but defined) value, resets the session dir to its default
268 value.
269  
270 =begin testing
271  
272 is($fm->sessiondir, undef, "Session dir undefined to begin with");
273 $fm->sessiondir("/tmp");
274 is($fm->sessiondir, "/tmp", "Session dir changed");
275 $fm->sessiondir(0);
276 like($fm->sessiondir, qr(/session-tokens/), "Session dir returned to default");
277  
278 =end testing
279  
280 =cut
281  
282 sub sessiondir {
283 my ($self, $sd) = @_;
284 if ($sd) {
285 $self->{sessiondir} = $sd;
286 } elsif (defined $sd) {
287 $self->{sessiondir} = "./session-tokens/";
288 } else {
289 return $self->{sessiondir};
290 }
291 }
292  
293 =head2 fallback_language($language)
294  
295 Given a 2-letter ISO language code, makes that language the fallback
296 language for localisation. Not necessary unless you want it to be
297 something other than the base language in which your application is
298 written. Set it to a false (but defined) value to turn off the fallback
299 language feature.
300  
301 With no arguments, tells you what the current fallback language is.
302  
303 =begin testing
304  
305 is($fm->fallback_language(), undef, "Fallback language undefined to begin with");
306 $fm->fallback_language("fr");
307 is($fm->fallback_language(), "fr", "Set fallback language to French");
308 $fm->fallback_language("");
309 is($fm->fallback_language(), undef, "Turn fallback language off again");
310  
311 =end testing
312  
313 =cut
314  
315 sub fallback_language {
316 my ($self, $fl) = @_;
317 if ($fl) {
318 $self->{fallback_language} = $fl;
319 } elsif (defined $fl) {
320 $self->{fallback_language} = undef;
321 } else {
322 return $self->{fallback_language};
323 }
324 }
325  
326 =pod
327  
328 =head2 display()
329  
330 The display method displays your form. It takes no arguments.
331  
332 =for testing
333 SKIP: {
334 skip "Problems with CGI::Persistent", 1 unless 0;
335 ok($fm->display(), "Display");
336 }
337  
338 =cut
339  
340 sub display {
341 my $self = shift;
342  
343 $self->parse_xml();
344  
345 {
346 local $^W = 0;
347 # create a session-handling CGI object
348 $self->{cgi} = new CGI::Persistent $self->{sessiondir};
349 }
350  
351 print $self->{cgi}->header;
352 # debug thingy, to check L10N lexicons, only if you need it
353 $self->check_l10n() if $self->{cgi}->param('checkl10n');
354  
355 # pick up page number from CGI, else default to 1
356 $self->{page_number} = $self->{cgi}->param("page") || FIRST_PAGENUM;
357 $self->debug_msg("The page number started out as $self->{page_number}");
358  
359 if (defined $self->{cgi}->param("page_stack")) {
360 $self->{page_stack} = $self->{cgi}->param("page_stack")
361 } else {
362 $self->{page_stack} = "";
363 }
364  
365 $self->debug_msg("The page stack started out as $self->{page_stack}");
366  
367 unless ($self->just_starting) {
368 $self->cleanup_checkboxes();
369 }
370  
371 # Check whether they clicked "Previous" or something else
372 # If they clicked previous, we avoid validation etc. See
373 # doc/pageflow.dia for details
374  
375 if ($self->{cgi}->param("Previous")) {
376 $self->{page_number} = $self->pop_page_stack();
377 $self->debug_msg("Going to previous page, the page number is now
378 $self->{page_number} and the stack is $self->{page_stack}");
379 } elsif ($self->just_starting) {
380 $self->form_pre_event();
381 } else {
382 $self->prepare_for_next_page();
383 }
384  
385 $self->print_form_header();
386  
387 if ($self->finished()) {
388 $self->validate_all();
389 $self->form_post_event();
390 } else {
391 $self->page_pre_event();
392 $self->print_page();
393 }
394 $self->print_form_footer();
395 $self->clear_navigation_params();
396
397 }
398  
399 =head1 RANDOM USEFUL METHODS
400  
401 =head2 $fm->cgi()
402  
403 Returns the CGI object that FormMagick is using.
404  
405 =for testing
406 local $fm->{cgi} = CGI->new("");
407 isa_ok($fm->cgi(), 'CGI');
408  
409 =cut
410  
411 sub cgi {
412 my $self = shift;
413 return $self->{cgi};
414 }
415  
416 =head2 $fm->wherenext($pagename);
417  
418 Set the magic "wherenext" CGI parameter, which tells FormMagick which
419 page to display next. Particularly useful when used in a page's
420 post-event routine, to (for instance) go to a different next page
421 depending on what the user entered on the last page.
422  
423 This method is also exported so you can use it in the form itself, for
424 instance:
425  
426 <page post-event="wherenext('SomePage')">
427  
428 With no args, returns the value of the "wherenext" parameter.
429  
430 =for testing
431 local $fm->{cgi} = CGI->new("");
432 can_ok('main', 'wherenext');
433 is($fm->wherenext(), undef, "wherenext starts out undef");
434 $fm->wherenext("Foo");
435 is($fm->wherenext(), "Foo", "Set wherenext");
436 $fm->wherenext(undef);
437 is($fm->wherenext(), undef, "wherenext returns to undef");
438  
439 =cut
440  
441 sub wherenext {
442 my ($self, $where) = @_;
443 return undef unless $self->cgi()->isa('CGI');
444 if (@_ > 1) {
445 if (defined $where) {
446 $self->cgi->param(-name => 'wherenext', -value => $where);
447 } else {
448 $self->cgi->delete('wherenext');
449 }
450 }
451 return $self->cgi->param('wherenext');
452 }
453  
454 =head2 $fm->go_to_finish()
455  
456 Like wherenext(), except that it says to go to the finish and perform
457 the form post-event and do all the things that would ordinarily be done
458 when a user clicks the "Finish" button. Can be used as a method or as
459 an exported function, so you can do things like:
460  
461 <page post-event="go_to_finish()">
462  
463 =for testing
464 local $fm->{cgi} = CGI->new("");
465 can_ok('main', 'go_to_finish');
466 is($fm->cgi->param('Finish'), undef, "Finish starts out undef");
467 $fm->go_to_finish();
468 is($fm->cgi->param('Finish'), 1, "Finish is set");
469  
470 =cut
471  
472 sub go_to_finish {
473 my ($self) = @_;
474 $self->cgi->param(-name => 'Finish', -value => 1);
475 }
476  
477 =begin blah
478  
479 =head2 $fm->go_to_start()
480  
481 Like wherenext(), except that it says to go to the finish and perform
482 the form post-event and do all the things that would ordinarily be done
483 when a user clicks the "Finish" button.
484  
485 =end blah
486  
487 =cut
488  
489 sub go_to_start {
490 }
491  
492 =head1 FORMMAGICK XML TUTORIAL
493  
494 =head2 Form descriptions
495  
496 The main thing you need to know to use FormMagick is the structure
497 and syntax of FormMagick forms. FormMagick is based on a "wizard" sort
498 of interface, in which one form has many pages, and each page has many
499 fields. This is expressed as a nested hierarchy of XML elements.
500  
501 For examples of FormMagick XML, see the C<examples/> directory included
502 in the FormMagick distribution.
503  
504 The XML must comply with the FormMagick DTD (included in the
505 distribution as FormMagick.dtd). A command-line tool to test compliance
506 is planned for a future release.
507  
508 Here is an explanation of the nesting of elements and the attributes
509 supported by each element.
510  
511 =head1 FORMS
512  
513 =head2 Form sub-elements
514  
515 A form may contain the following elements:
516  
517 =over 4
518  
519 =item *
520  
521 page
522  
523 =back
524  
525 =head2 Form attributes
526  
527 The following attributes are supported for forms:
528  
529 =over 4
530  
531 =item *
532  
533 pre-event (a subroutine to run before the form is displayed)
534  
535 =item *
536  
537 post-event (a subroutine to run after the form is completed)
538  
539 =back
540  
541 =head2 Example
542  
543 <form pre-event="setup()" post-event="submit()>
544 <page> ... </page>
545 <page> ... </page>
546 <page> ... </page>
547 </form>
548  
549 =head1 PAGES
550  
551 =head2 Page sub-elements
552  
553 A page may contain the following sub-elements:
554  
555 =over 4
556  
557 =item *
558  
559 description
560  
561 =item *
562  
563 field
564  
565 =back
566  
567  
568 =head2 Page attributes
569  
570 The following attributes are supported for pages:
571  
572 =over 4
573  
574 =item *
575  
576 name (required)
577  
578 =back
579  
580 =head2 Example
581  
582 <page name="RoomType" post-event="check_availability">
583 <description>
584 Please provide us with details of your preferred room.
585 </description>
586 <field> ... </field>
587 <field> ... </field>
588 <field> ... </field>
589 </page>
590  
591  
592 =head1 FIELDS
593  
594 Fields are the most important part of the form definition. Several
595 types of HTML fields are supported, and each one has various attributes
596 associated with it.
597  
598 =head2 Field types
599  
600 You can specify the type of HTML field to be generated using the type
601 attribute:
602  
603 <field type="...">
604  
605 The following field types are supported:
606  
607 =over 4
608  
609 =item text
610  
611 A plain text field. You may optionally use the size attribute to modify
612 the size of the field displayed. To restrict the length of data entered
613 by the user, use the maxlength() validation routine.
614  
615 =item select
616  
617 A dropdown list. You must provide the options attribute to specify the
618 contents of the list (see below for the format of this attribute). If
619 you set the multiple attribute to 1, multiple selections will be
620 enabled. The optional size attribute sets the number of items displayed
621 at once.
622  
623 =item radio
624  
625 Radio buttons allow users to choose one item from a group. This field
626 type requires the options attribute (as for select, above).
627  
628 =item checkbox
629  
630 This field type provides a simple check box for yes/no questions. The
631 checked attribute is optional, but if set to 1 will make the checkbox
632 checked by default.
633  
634 =item password
635  
636 The password field type is like a text field, but obscures the data
637 typed in by the user.
638  
639 =item file
640  
641 This field type allows the upload of a file by the user.
642  
643 =item textarea
644  
645 A multi-line text field allowing the input of blocks of text. Defaults
646 to 5 rows and 60 columns, but you can specify "rows" and "cols" arguments
647 to change that.
648  
649 =item literal
650  
651 A field that is just printed literally. Useful if you want to just print out a
652 non-editable bit of text in the same sort of layout as the other fields in the form.
653  
654 =back
655  
656 =head2 Field sub-elements
657  
658 The following elements may be nested within a field:
659  
660 =over 4
661  
662 =item *
663  
664 label (a short description; required)
665  
666 =item *
667  
668 description (a more verbose description; optional)
669  
670 =back
671  
672  
673 =head2 Other field attributes
674  
675 Fields must ALWAYS have a type (described in the previous section) and
676 an id attribute, which is a unique name for
677 the field. Each type of field may have additional required attributes,
678 and may support other optional attributes.
679  
680 Here is a list of optional attributes for fields:
681  
682 =over 4
683  
684 =item value
685  
686 A default value to fill in; see below for more information on the format
687 of this field.
688  
689 =item validation
690  
691 a list of validation functions; see L<CGI::FormMagick::Validator> for more
692 information on this subject.
693  
694 =item validation-error-message
695  
696 an error message to present to the user if validation fails.
697 CGI::FormMagick::Validator provides one by default, but you may prefer
698 to override it.
699  
700 =item options
701  
702 A list of options required for a select list or radio buttons; see below for
703 more information on the format of this attribute.
704  
705 =item checked
706  
707 For checkbox fields, used to make the box checked by default. Defaults
708 to 0.
709  
710 =item multiple
711  
712 For select fields, used to allow the user to select more than one value.
713  
714 =item size
715  
716 For select fields, height; for text and textarea fields, length.
717  
718 =back
719  
720 =head2 Notes on parsing of value attribute
721  
722 If your value attribute ends in parens, it'll be taken as a subroutine
723 to run. Otherwise, it'll just be taken as a literal.
724  
725 This will be literal:
726  
727 value="username"
728  
729 This will run a subroutine:
730  
731 value="get_username()"
732  
733 The subroutine will be passed the CGI object as an argument, so you can
734 use the CGI params to help you generate the value you need.
735  
736 Your subroutine should return a string containing the value you want.
737  
738 =head2 Notes on parsing of options attribute
739  
740 The options attribute has automagical Do What I Mean (DWIM) abilities.
741 You can give it a value which looks like a Perl list, a Perl hash, or a
742 subroutine name. For instance:
743  
744 options="'red', 'green', 'blue'"
745  
746 options="'ff0000' => 'red', '00ff00' => 'green', '0000ff' => 'blue'"
747  
748 options="get_colors()"
749  
750 How it works is that FormMagick looks for the => operator, and if it
751 finds it it evals the options string and assigns the result to a hash.
752 If it finds a comma (but no little => arrows) it figures it's a list,
753 and evals it and assigns the results to an array. Otherwise, it tries
754 to interpret what's there as the name of a subroutine in the scope of
755 the script that called FormMagick, expecting to get back a value which
756 is either an arrayref or a hashref, which it will deal with appropriately
757 in either case.
758  
759 A few gotchas to look out for:
760  
761 =over 4
762  
763 =item *
764  
765 Make sure you quote strings in lists and hashes. "red,blue,green" will
766 fail (silently) because of the barewords.
767  
768 =item *
769  
770 Single-element lists ("red") will fail because the DWIM parsing doesn't
771 find a comma there and treats it as the name of a subroutine. But then,
772 a single-element radio button group or select dropdown is pretty
773 meaningless anyway, so why would you do that?
774  
775 =item *
776  
777 Arrays will result in options being sorted in the same order they were
778 listed. Hashes will be sorted by value using the Perl's cmp() function
779 (ASCIIbetical sort, in other words).
780  
781 =item *
782  
783 An anti-gotcha: subroutine names do not require the parens on them.
784 "get_colors" and "get_colors()" will work the same.
785  
786 =back
787  
788 =head1 INTERNAL, DEVELOPER-ONLY ROUTINES
789  
790 The following routines are used internally by FormMagick and are
791 documented here as a developers' reference. If you are using FormMagick
792 to develop web applications, you can skip this section entirely.
793  
794 =cut
795  
796 =head2 magic_wherenext
797  
798 We allow FM users to set the C<wherenext> param explicitly in their code,
799 to do branching of program logic. This routine checks to see if they
800 have a magic C<wherenext> param and returns it. Gives undef if it's not
801 set.
802  
803 =begin testing
804  
805 use CGI;
806  
807 $cgi = CGI->new({ wherenext => "foo" });
808 local $fm->{cgi} = $cgi;
809 is($fm->magic_wherenext(), "foo", "Found magic wherenext value");
810  
811 =end testing
812  
813 =cut
814  
815 sub magic_wherenext {
816 my $self = shift;
817 return $self->{cgi}->param("wherenext");
818 }
819  
820  
821 =head2 prepare_for_next_page
822  
823 This does all the things needed before going on to the next page.
824 Specifically, it validates the data from this page, and then if
825 validation was successful it puts the current page onto the page stack
826 and then sets page_number to whatever page we should be visiting next.
827  
828 =begin testing
829  
830 #
831 # First we test what happens when the user clicks Next normally.
832 #
833  
834 local $fm->{page_number} = 0;
835 local $fm->{page_stack} = "";
836 local $fm->{cgi} = CGI->new({
837 firstname => "Kirrily", # this should validate successfully.
838 Next => 1,
839 });
840  
841 $fm->prepare_for_next_page();
842 is($fm->{page_number}, 1, "Increment the page number when user clicks next");
843 is($fm->{page_stack}, 0, "Set page stack when user clicks next");
844  
845 #
846 # Now we're going to see what happens when the user just hits Enter
847 #
848  
849 local $fm->{page_number} = 0;
850 local $fm->{page_stack} = "";
851 local $fm->{cgi} = CGI->new({
852 firstname => "Kirrily",
853 });
854  
855 $fm->prepare_for_next_page();
856 is($fm->{page_number}, 1, "Increment the page number when user presses enter");
857 is($fm->{page_stack}, 0, "Set page stack when user presses enter");
858  
859 #
860 # What if there's a magic "wherenext" value set?
861 #
862  
863 local $fm->{page_number} = 0;
864 local $fm->{page_stack} = "";
865 local $fm->{cgi} = CGI->new({
866 firstname => "Kirrily",
867 wherenext => "More again",
868 });
869  
870 $fm->prepare_for_next_page();
871 is($fm->{page_number}, 2, "Branch when magic wherenext is set");
872 is($fm->{page_stack}, 0, "Set page stack when magic wherenext is set");
873  
874 =end testing
875  
876 =cut
877  
878  
879 sub prepare_for_next_page {
880 my ($self) = @_;
881  
882 $self->validate_page($self->{page_number});
883  
884 unless ($self->errors()) {
885 # ONLY do the page post event if the form passes validation
886 $self->page_post_event();
887
888 $self->push_page_stack($self->{page_number});
889 if ($self->magic_wherenext()) {
890 $self->{page_number} =
891 $self->get_page_by_name($self->magic_wherenext());
892 unless (defined $self->{page_number}) {
893 carp "Can't find next page from magic 'wherenext' param "
894 . $self->magic_wherenext() .
895 ". Do you actually have a page with that name?";
896 }
897 } else {
898 $self->{page_number}++;
899 }
900 }
901 $self->debug_msg("The page number is now $self->{page_number}");
902 $self->debug_msg("The page stack is now $self->{page_stack}");
903 }
904  
905 =head2 $fm->cleanup_checkboxes()
906  
907 Checkbox params only get passed around if they're checked. An unchecked
908 box doesn't send "checkbox=0" ... no, it just completely fails to send
909 anything at all. This is a PITA, as it's impossible to distinguish an
910 explicity unchecked box from one that never got seen at all.
911  
912 This subroutine is intended to clean up the mess, by checking the
913 checkboxes that were expected on the current page against what it
914 actually saw on the CGI parameters, and explicitly setting any missing
915 ones to 0.
916  
917 =cut
918  
919 sub cleanup_checkboxes {
920 my $fm = shift;
921 my $page = $fm->page();
922 my @fields = @{$page->{fields}};
923  
924 my @checkboxes;
925 foreach my $f (@fields) {
926 if ($f->{type} eq 'checkbox') {
927 push @checkboxes, $f->{id};
928 }
929 }
930  
931 my $clean_cgi = new CGI;
932 foreach my $c (@checkboxes) {
933 unless ($clean_cgi->param($c)) {
934 $fm->{cgi}->param(-name => $c, -value => '0');
935 }
936 }
937  
938 $fm->commit_session();
939  
940 }
941  
942 =head2 $fm->commit_session()
943  
944 Commits a session's details to disk, in the same way as CGI::Persistent.
945 Needed by cleanup_checkboxes().
946  
947 =cut
948  
949 sub commit_session {
950 my $fm = shift;
951 my $cgi = $fm->{cgi};
952  
953 my $fn = join "/", ($fm->{sessiondir},$cgi->param('.id'));
954 my $po = new Persistence::Object::Simple __Fn => $fn;
955  
956 my @names = $cgi->param ();
957 foreach ( @names ) {
958 $po->{$_} = $cgi->param( $_ ) unless $_ eq ".id";
959 }
960  
961 $po->commit();
962 }
963  
964 =head2 get_option_labels_and_values ($fieldinfo)
965  
966 returns labels and values for fields that require them, by running a
967 subroutine or whatever else is needed. Returns a hashref containing:
968  
969 { labels => \@options_labels, $vals => \@option_values }
970  
971 =begin testing
972  
973 my $fieldinfo = {
974 options => "'foo', 'bar', 'baz'",
975 };
976 my $result = $fm->get_option_labels_and_values($fieldinfo);
977 is_deeply($result->{labels}, [qw(foo bar baz)], "Picked up labels from array");
978 is_deeply($result->{vals}, [qw(foo bar baz)], "Picked up vals from array");
979  
980 $fieldinfo = {
981 options => "'foo' => 'zzz', 'bar' => 'yyy', 'baz' => 'xxx'",
982 };
983 $result = $fm->get_option_labels_and_values($fieldinfo);
984 is_deeply($result->{labels}, [qw(xxx yyy zzz)], "Picked up labels from hash");
985 is_deeply($result->{vals}, [qw(baz bar foo)], "Picked up vals from hash");
986  
987 =end testing
988  
989 =cut
990  
991 sub get_option_labels_and_values {
992  
993 my ($self, $fieldinfo) = @_;
994  
995 my @option_labels; # labels for items in a list
996 my @option_values; # the values hidden behind those labels
997  
998 $self->debug_msg(
999 "Options attribute appears to be '"
1000 . (defined $fieldinfo->{options} ? $fieldinfo->{options} : '')
1001 );
1002  
1003 my $options_attribute = $fieldinfo->{'options'} || "";
1004
1005 my $options_ref = $self->parse_options_attribute($options_attribute);
1006  
1007 # DWIM with the data that came in from the XML file or the options function,
1008 # since we may have gotten an array or a hash for those values.
1009 if (ref($options_ref) eq "HASH") {
1010 foreach my $k (sort {
1011 $options_ref->{$a} cmp $options_ref->{$b}
1012 } keys %$options_ref) {
1013 # the keys are the option field values, the values are the option text
1014 push @option_values, $k;
1015 push @option_labels, $options_ref->{$k};
1016 }
1017 } elsif (ref($options_ref) eq "ARRAY") {
1018 # labels are the same as values here. this is not a mistake.
1019 @option_labels = @$options_ref;
1020 @option_values = @$options_ref;
1021 $self->debug_msg("options ref is an array, with " . scalar(@$options_ref) . " elements, which are " . join(", ", @$options_ref));
1022 } else {
1023 $self->debug_msg("Something weird's going on.");
1024 return undef;
1025 }
1026  
1027 return {labels => \@option_labels, vals => \@option_values};
1028 }
1029  
1030  
1031 =pod
1032  
1033 =head2 parse_options_attribute($options_field)
1034  
1035 parses the options attibute from a field element and returns a
1036 reference to either a hash or an array containing the relevant data to
1037 fill in a select box or a radio group.
1038  
1039 =cut
1040  
1041 sub parse_options_attribute {
1042 my ($self, $options_field) = @_;
1043  
1044 # we need a reference to keep the options in, as we don't know if
1045 # they'll be a list or a scalar. When we've got what we want, we
1046 # can do a ref($options_ref) to find out what flavour we got.
1047  
1048 my $options_ref;
1049  
1050 $self->debug_msg("options field looks like $options_field");
1051  
1052 if ($options_field =~ /=>/) { # user supplied a hash
1053 $self->debug_msg("options_ref should be a hashref");
1054 $options_ref = { eval $options_field }; # make options_ref a hashref
1055 } elsif ($options_field =~ /,/) { # user supplied an array
1056 $self->debug_msg("options ref should be an arrayref");
1057 $options_ref = [ eval $options_field ]; # make options_ref an arrayref
1058 $self->debug_msg("we have " . scalar(@$options_ref) . " elements");
1059 } else { # user supplied a sub name
1060 $self->debug_msg("i think i should call an external routine");
1061 $options_field =~ s/\(.*\)$//; # strip parens
1062 $options_ref = $self->do_external_routine($options_field);
1063 }
1064 return $options_ref;
1065 }
1066  
1067 =head2 do_external_routine($self, $routine, @optional_args)
1068  
1069 Runs an external routine, for whatever purpose (filling in default values
1070 of fields, validation, etc). If anything is in @optional_args, the
1071 routine is called using those. If @optional_args is ommitted, then
1072 $self->{cgi} is passed. Returns the return value of the routine, or
1073 undef on failure. Also emits a warning (to your webserver's error log,
1074 most likely) if it can't run the routine.
1075  
1076 The routine is always called in the package which called FormMagick
1077 (usually main::, but possibly something else).
1078  
1079 The CGI object is passed to your routine, so you can do stuff like
1080 $cgi->param("foo") to it to find out CGI parameters and so on.
1081  
1082 =begin testing
1083  
1084 sub one {
1085 return 1;
1086 }
1087  
1088 sub zero {
1089 return 0;
1090 }
1091  
1092 sub add_1 {
1093 shift;
1094 my $sum = 1;
1095 $sum += $_ foreach @_;
1096 return $sum;
1097 };
1098  
1099 foreach my $expectations (
1100 { expected => 1, call_this => 'one' },
1101 { expected => 1, call_this => 'one()' },
1102 { expected => 0, call_this => 'zero()' },
1103 { expected => 1, call_this => 'add_1(0)' },
1104 { expected => 2, call_this => 'add_1(1)' },
1105 { expected => 6, call_this => 'add_1(2,3)' },
1106  
1107 # Error cases:
1108 { expected => undef, call_this => undef },
1109 { expected => undef, call_this => 'no_such_sub' },
1110 { expected => undef, call_this => 'not even possible' },
1111 ) {
1112 my $expected = $expectations->{expected};
1113 my $call_this = $expectations->{call_this};
1114 my $actual;
1115 {
1116 local $^W = 0; # Because we feed this bad input on purpose.
1117 $actual = $fm->do_external_routine($call_this);
1118 }
1119  
1120 my $description = "do_external_routine($call_this)";
1121  
1122 is($actual, $expected, $description);
1123 }
1124  
1125 =end testing
1126  
1127 =cut
1128  
1129 sub do_external_routine {
1130 my $self = shift;
1131 my $input_routine = shift;
1132 $self->debug_msg("Doing external routine $input_routine");
1133
1134 my ($routine, $argstr);
1135 my @args = ();
1136 if ($input_routine =~ /(.*?)\((.*)\)$/) {
1137 ($routine, $argstr) = ($1, $2);
1138 @args = eval "($argstr)";
1139 } elsif ($input_routine =~ /^(\w+)$/) {
1140 $routine = $1;
1141 } else {
1142 return undef;
1143 }
1144  
1145 @args = ($self, @args);
1146 CGI::FormMagick::Sub::call(
1147 package => $self->{calling_package},
1148 sub => $routine,
1149 args => \@args
1150 );
1151  
1152 }
1153  
1154 =pod
1155  
1156 =head1 SEE ALSO
1157  
1158 CGI::FormMagick::Utils
1159  
1160 CGI::FormMagick::Events
1161  
1162 CGI::FormMagick::Setup
1163  
1164 CGI::FormMagick::L10N
1165  
1166 CGI::FormMagick::Validator
1167  
1168 CGI::FormMagick::FAQ
1169  
1170 =head1 BUGS
1171  
1172 The validation attribute must be very carefully formatted, with spaces
1173 between the names of routines but not between the arguments to a
1174 routine. See description above.
1175  
1176 =head1 AUTHOR
1177  
1178 Kirrily "Skud" Robert <skud@infotrope.net>
1179  
1180 Contributors:
1181  
1182 Shane R. Landrum <slandrum@turing.csc.smith.edu>
1183  
1184 James Ramirez <jamesr@cogs.susx.ac.uk>
1185  
1186 More information about FormMagick may be found at
1187 http://sourceforge.net/projects/formmagick/
1188  
1189 =cut