]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole/Model/CDBI/FromCGI.pm
9baaf9efe916c3117a44b60ae7cc0ffb7781ccad
[maypole.git] / lib / Maypole / Model / CDBI / FromCGI.pm
1 package Maypole::Model::CDBI::FromCGI;
2 use strict;
3 use warnings;
4
5 =head1 NAME
6
7 Maypole::Model:CDBI::FromCGI - Validate form input and populate Model objects
8
9 =head1 SYNOPSIS
10
11   $obj = $class->create_from_cgi($r);
12   $obj = $class->create_from_cgi($r, { params => {data1=>...}, required => [..],
13                  ignore => [...], all => [...]);
14   $obj = $class->create_from_cgi($h, $options); # CDBI::FromCGI style, see docs
15
16   $obj->update_from_cgi($r);
17   $obj->update_from_cgi($h, $options);
18
19   $obj = $obj->add_to_from_cgi($r);
20   $obj = $obj->add_to_from_cgi($r, { params => {...} } );
21   
22   # This does not work like in CDBI::FromCGI and probably never will :
23   # $class->update_from_cgi($h, @columns);
24
25
26 =head1 DESCRIPTION
27
28 Provides a way to validate form input and populate Model Objects, based
29 on Class::DBI::FromCGI.
30
31 =cut
32
33
34 # The base base model class for apps 
35 # provides good search and create functions
36
37 use base qw(Exporter); 
38 use CGI::Untaint;
39 use Maypole::Constants;
40 use CGI::Untaint::Maypole;
41 our $Untainter = 'CGI::Untaint::Maypole';
42
43 our @EXPORT = qw/update_from_cgi create_from_cgi untaint_columns add_to_from_cgi
44     cgi_update_errors untaint_type validate_inputs validate_all _do_update_all 
45     _do_create_all _create_related classify_form_inputs/;
46
47
48
49 use Data::Dumper; # for debugging
50
51 =head1 METHODS
52
53 =head2 untaint_columns
54
55 Replicates Class::DBI::FromCGI method of same name :
56
57   __PACKAGE__->untaint_columns(
58     printable => [qw/Title Director/],
59     integer   => [qw/DomesticGross NumExplodingSheep],
60     date      => [qw/OpeningDate/],
61   );
62
63 =cut
64
65 sub untaint_columns {
66     die "untaint_columns() needs a hash" unless @_ % 2;
67     my ($class, %args) = @_;
68     $class->mk_classdata('__untaint_types')
69         unless $class->can('__untaint_types');
70     my %types = %{ $class->__untaint_types || {} };
71     while (my ($type, $ref) = each(%args)) {
72         $types{$type} = $ref;
73     }
74     $class->__untaint_types(\%types);
75 }
76
77 =head2 untaint_type
78
79   gets the  untaint type for a column as set in "untaint_types"
80
81 =cut
82
83 # get/set untaint_type for a column
84 sub untaint_type {
85     my ($class, $field, $new_type) = @_;
86     my %handler = __PACKAGE__->_untaint_handlers($class);
87     return $handler{$field} if $handler{$field};
88     my $handler = eval {
89         local $SIG{__WARN__} = sub { };
90         my $type = $class->column_type($field) or die;
91         _column_type_for($type);
92     };
93     return $handler || undef;
94 }
95
96 =head2 cgi_update_errors
97
98 Returns errors that ocurred during an operation.
99
100 =cut
101
102 sub cgi_update_errors { %{ shift->{_cgi_update_error} || {} } }
103
104
105
106 =head2 create_from_cgi
107
108 Based on the same method in Class::DBI::FromCGI.
109
110 Creates  multiple objects  from a  cgi form. 
111 Errors are returned in cgi_update_errors
112
113 It can be called Maypole style passing the Maypole request object as the
114 first arg, or Class::DBI::FromCGI style passing the Untaint Handler ($h)
115 as the first arg. 
116
117 A hashref of options can be passed as the second argument. Unlike 
118 in the CDBI equivalent, you can *not* pass a list as the second argument.
119 Options can be :
120  params -- hashref of cgi data to use instead of $r->params,
121  required -- list of fields that are required
122  ignore   -- list of fields to ignore
123  all      -- list of all fields (defaults to $class->columns)
124
125 =cut
126
127 sub create_from_cgi {
128   my ($self, $r, $opts) = @_;
129   $self->_croak( "create_from_cgi can only be called as a class method")
130     if ref $self;
131   my ($errors, $validated);
132   
133   
134   if ($r->isa('CGI::Untaint')) { # FromCGI interface compatibility
135     ($validated, $errors) = $self->validate_inputs($r,$opts); 
136   } else {
137     my $params = $opts->{params} || $r->params;
138     $opts->{params} = $self->classify_form_inputs($params);
139     ($validated, $errors) = $self->validate_all($r, $opts);
140   }
141
142   if (keys %$errors) {
143     return bless { _cgi_update_error => $errors }, $self;
144   }
145
146   # Insert all the data
147   my ($obj, $err ) = $self->_do_create_all($validated); 
148   if ($err) {
149     return bless { _cgi_update_error => $err }, $self;
150   }
151   return $obj;
152 }
153
154
155 =head2 update_from_cgi
156
157 Replicates the Class::DBI::FromCGI method of same name. It updates an object and
158 returns 1 upon success. It can take the same arguments as create_form_cgi. 
159 If errors, it sets the cgi_update_errors.
160
161 =cut
162
163 sub update_from_cgi {
164   my ($self, $r, $opts) = @_;
165   $self->_croak( "update_from_cgi can only be called as an object method") unless ref $self;
166   my ($errors, $validated);
167   $self->{_cgi_update_error} = {};
168   $opts->{updating} = 1;
169
170   # FromCGI interface compatibility 
171   if ($r->isa('CGI::Untaint')) {
172     # REHASH the $opts for updating:
173     # 1: we ignore any fields we dont have parmeter for. (safe ?)
174     # 2: we dont want to update fields unless they change
175
176     my @ignore = @{$opts->{ignore} || []};
177     push @ignore, $self->primary_column->name;
178     my $raw = $r->raw_data;
179     #print "*** raw data ****" . Dumper($raw);
180     foreach my $field ($self->columns) {
181       #print "*** field is $field ***\n";
182         if (not defined $raw->{$field}) {
183                         push @ignore, $field->name; 
184                         #print "*** ignoring $field because it is not present ***\n";
185                         next;
186         }
187         # stupid inflation , cant get at raw db value easy, must call
188         # deflate ***FIXME****
189         my $cur_val = ref $self->$field ? $self->$field->id : $self->$field;
190         if ($raw->{$field} eq $cur_val) {
191                         #print "*** ignoring $field because unchanged ***\n";
192                         push @ignore, "$field"; 
193         }
194     }
195     $opts->{ignore} = \@ignore;
196     ($validated, $errors) = $self->validate_inputs($r,$opts); 
197   } else {
198     my $params = $opts->{params} || $r->params;
199     $opts->{params} = $self->classify_form_inputs($params);
200     ($validated, $errors) = $self->validate_all($r, $opts);
201     #print "*** errors for validate all   ****" . Dumper($errors);
202   }
203
204   if (keys %$errors) {
205     #print "*** we have errors   ****" . Dumper($errors);
206     $self->{_cgi_update_error} = $errors;
207     return;
208   }
209
210   # Update all the data
211   my ($obj, $err ) = $self->_do_update_all($validated); 
212   if ($err) {
213     $self->{_cgi_update_error} = $err;
214     return; 
215   }
216   return 1;
217 }
218
219 =head2 add_to_from_cgi
220
221 $obj->add_to_from_cgi($r[, $opts]); 
222
223 Like add_to_* for has_many relationships but will add nay objects it can 
224 figure out from the data.  It returns a list of objects it creates or nothing
225 on error. Call cgi_update_errors with the calling object to get errors.
226 Fatal errors are in the respective "FATAL" key.
227
228 =cut
229
230 sub add_to_from_cgi {
231   my ($self, $r, $opts) = @_;
232   $self->_croak( "add_to_from_cgi can only be called as an object method")
233     unless ref $self;
234   my ($errors, $validated, @created);
235    
236   my $params = $opts->{params} || $r->params;
237   $opts->{params} = $self->classify_form_inputs($params);
238   ($validated, $errors) = $self->validate_all($r, $opts);
239
240   
241   if (keys %$errors) {
242     $self->{_cgi_update_error} = $errors;
243         return;
244   }
245
246   # Insert all the data
247   foreach my $hm (keys %$validated) { 
248         my ($obj, $errs) = $self->_create_related($hm, $validated->{$hm}); 
249         if (not $errs) {
250                 push @created, $obj;
251         }else {
252                 $errors->{$hm} = $errs;
253         }
254   }
255   
256   if (keys %$errors) {
257     $self->{_cgi_update_error} = $errors;
258         return;
259   }
260
261   return @created;
262 }
263
264  
265
266
267 =head2 validate_all
268
269 Validates (untaints) a hash of possibly mixed table data. 
270 Returns validated and errors ($validated, $errors).
271 If no errors then undef in that spot.
272
273 =cut
274
275 sub validate_all {
276   my ($self, $r, $opts) = @_;
277   my $class = ref $self || $self;
278   my $classified = $opts->{params};
279   my $updating   = $opts->{updating};
280
281   # Base case - validate this classes data
282   $opts->{all}   ||= eval{ $r->config->{$self->table}{all_cols} }               ||
283     [$self->columns('All')];
284   $opts->{required} ||= eval{ $r->config->{$self->table}{required_cols} } ||    
285         [];
286   my $ignore = $opts->{ignore} || eval{ $r->config->{$self->table}{ignore_cols} }       
287     || [];
288   push @$ignore, $self->primary_column->name if $updating;
289   
290   # Ignore hashes of foreign inputs. This takes care of required has_a's 
291   # for main object that we have foreign inputs for. 
292   foreach (keys %$classified) {
293     push @$ignore, $_ if  ref $classified->{$_} eq 'HASH'; 
294   }
295   $opts->{ignore} = $ignore;
296   my $h = $Untainter->new($classified);
297   my ($validated, $errs) = $self->validate_inputs($h, $opts);
298
299   # Validate all foreign input
300         
301   #warn "Classified data is " . Dumper($classified); 
302   foreach my $field (keys %$classified) {
303     if (ref $classified->{$field} eq "HASH") {
304       my $data = $classified->{$field};
305           my $ignore = [];
306       my @usr_entered_vals = ();
307       foreach ( values %$data ) {
308                 push @usr_entered_vals, $_  if $_  ne '';
309       }
310
311       # filled in values
312       # IF we have some inputs for the related
313       if ( @usr_entered_vals ) {
314                 # We need to ignore us if we are a required has_a in this foreign class
315                 my $rel_meta = $self->related_meta($r, $field);
316             my $fclass   = $rel_meta->{foreign_class};
317                 my $fmeta    = $fclass->meta_info('has_a');
318                 for (keys %$fmeta) {
319                         if ($fmeta->{$_}{foreign_class} eq $class) {
320                                 push @$ignore, $_;
321                         }
322                 }
323                 my ($valid, $ferrs) = $fclass->validate_all($r,
324                 {params => $data, updating => $updating, ignore => $ignore } );         
325
326                 $errs->{$field} = $ferrs if $ferrs;
327                 $validated->{$field} = $valid;
328
329       } else { 
330                 # Check this foreign object is not requeired
331                 my %req = map { $_ => 1 } $opts->{required};
332                 if ($req{$field}) {
333                         $errs->{$field}{FATAL} = "This is required. Please enter the required fields in this section." 
334                         }
335                 }
336         }
337   }
338   #warn "Validated inputs are " . Dumper($validated);
339   undef $errs unless keys %$errs;
340   return ($validated, $errs);   
341 }
342
343
344
345 =head2 validate_inputs
346
347 $self->validate_inputs($h, $opts);
348
349 This is the main validation method to validate inputs for a single class.
350 Most of the time you use validate_all.
351
352 Returns validated and errors.
353
354 If no errors then undef in that slot.
355
356 Note: This method is currently experimental (in 2.11) and may be subject to change
357 without notice.
358
359 =cut
360
361 sub validate_inputs {
362   my ($self, $h, $opts) = @_;
363   my $updating = $opts->{updating};
364   my %required = map { $_ => 1 } @{$opts->{required}};
365   my %seen;
366   $seen{$_}++ foreach @{$opts->{ignore}};
367   my $errors    = {}; 
368   my $fields    = {};
369   $opts->{all} = [ $self->columns ] unless @{$opts->{all} || [] } ;
370   foreach my $field (@{$opts->{required}}, @{$opts->{all}}) {
371     next if $seen{$field}++;
372     my $type = $self->untaint_type($field) or 
373       do { warn "No untaint type for $self 's field $field. Ignoring.";
374            next;
375          };
376     my $value = $h->extract("-as_$type" => $field);
377     my $err = $h->error;
378
379     # Required field error 
380     if ($required{$field} and !ref($value) and $err =~ /^No input for/) {
381       $errors->{$field} = "You must supply '$field'" 
382     } elsif ($err) {
383
384       # 1: No inupt entered
385       if ($err =~ /^No input for/) {
386                                 # A : Updating -- set the field to undef or '' 
387         if ($updating) { 
388           $fields->{$field} = eval{$self->column_nullable($field)} ? 
389             undef : ''; 
390         }
391                                 # B : Creating -- dont set a value and RDMS will put default
392       }
393
394       # 2: A real untaint error -- just set the error 
395       elsif ($err !~ /^No parameter for/) {
396         $errors->{$field} =  $err;
397       }
398     } else {
399       $fields->{$field} = $value
400     }
401   }
402   undef $errors unless keys %$errors;
403   return ($fields, $errors);
404 }
405
406
407 ##################
408 # _do_create_all #
409 ##################
410
411 # Untaints and Creates objects from hashed params.
412 # Returns parent object and errors ($obj, $errors).  
413 # If no errors, then undef in that slot.
414 sub _do_create_all {
415   my ($self, $validated) = @_;
416   my $class = ref $self  || $self;
417   my ($errors, $accssr); 
418
419   # Separate out related objects' data from main hash 
420   my %related;
421   foreach (keys %$validated) {
422     $related{$_}= delete $validated->{$_} if ref $validated->{$_} eq 'HASH';
423   }
424   # Make has_own/a rel type objects and put id in parent's data hash 
425 #  foreach $accssr (keys %related) {
426 #    my $rel_meta = $self->related_meta('r', $accssr); 
427 #    $self->_croak("No relationship found for $accssr to $class.")
428 #      unless $rel_meta;
429 #    my $rel_type   = $rel_meta->{name};
430 #    if ($rel_type =~ /(^has_own$|^has_a$)/) {
431 #      my $fclass= $rel_meta->{foreign_class};
432 #      my ($rel_obj, $errs) = $fclass->_do_create_all($related{$accssr});
433 #      # put id in parent's data hash 
434 #      if (not keys %$errs) {
435 #       $validated->{$accssr} = $rel_obj->id;
436 #      } else {
437 #       $errors->{$accssr} = $errs;
438 #      }
439 #      delete $related{$accssr}; # done with this 
440 #    }
441 #  }
442
443   # Make main object -- base case
444   #warn "\n*** validated data is " . Dumper($validated). "***\n";
445   my $me_obj  = eval { $self->create($validated) };
446   if ($@) { 
447         warn "Just failed making a " . $self. " FATAL Error is $@"
448                 if (eval{$self->model_debug});  
449     $errors->{FATAL} = $@; 
450     return (undef, $errors);
451   }
452         
453   if (eval{$self->model_debug}) {
454     if ($me_obj) {
455       warn "Just made a $self : $me_obj ( " . $me_obj->id . ")";
456     } else {
457       warn "Just failed making a " . $self. " FATAL Error is $@" if not $me_obj;
458     }
459   }
460
461   # Make other related (must_have, might_have, has_many  etc )
462   foreach $accssr ( keys %related ) {
463     my ($rel_obj, $errs) = 
464       $me_obj->_create_related($accssr, $related{$accssr});
465     $errors->{$accssr} = $errs if $errs;
466         
467   }
468   #warn "Errors are " . Dumper($errors);
469
470   undef $errors unless keys %$errors;
471   return ($me_obj, $errors);
472 }
473
474
475 ##################
476 # _do_update_all #
477 ##################
478
479 #  Updates objects from hashed untainted data 
480 # Returns 1 
481
482 sub _do_update_all {
483         my ($self, $validated) = @_;
484         my ($errors, $accssr); 
485
486         #  Separate out related objects' data from main hash 
487         my %related;
488         foreach (keys %$validated) {
489                 $related{$_}= delete $validated->{$_} if ref $validated->{$_} eq 'HASH';
490         }
491         # Update main obj 
492         # set does not work with IsA right now so we set each col individually
493         #$self->set(%$validated);
494         my $old = $self->autoupdate(0); 
495         for (keys %$validated) {
496                 $self->$_($validated->{$_});
497         }
498         $self->update;
499         $self->autoupdate($old);
500
501         # Update related
502         foreach $accssr (keys %related) {
503                 my $fobj = $self->$accssr;
504                 my $validated = $related{$accssr};
505                 if ($fobj) {
506                         my $old = $fobj->autoupdate(0); 
507                         for (keys %$validated) {
508                                 $fobj->$_($validated->{$_});
509                         }
510                         $fobj->update;
511                         $fobj->autoupdate($old);
512                 }
513                 else { 
514                         $fobj = $self->_create_related($accssr, $related{$accssr});
515                 }       
516         }
517         return 1;
518 }
519         
520
521 ###################
522 # _create_related #
523 ###################
524
525 # Creates and automatically relates newly created object to calling object 
526 # Returns related object and errors ($obj, $errors).  
527 # If no errors, then undef in that slot.
528
529 sub _create_related {
530         # self is object or class, accssr is accssr to relationship, params are 
531         # data for relobject, and created is the array ref to store objs we 
532         # create (optional).
533         my ( $self, $accssr, $params, $created )  = @_;
534         $self->_croak ("Can't make related object without a parent $self object") 
535                 unless ref $self;
536         $created      ||= [];
537         my  $rel_meta = $self->related_meta('r',$accssr);
538     if (!$rel_meta) {
539                 $self->_croak("No relationship for $accssr in " . ref($self));
540         }
541         my $rel_type  = $rel_meta->{name};
542         my $fclass    = $rel_meta->{foreign_class};
543         #warn " Dumper of meta is " . Dumper($rel_meta);
544         
545
546         my ($rel, $errs); 
547
548         # Set up params for might_have, has_many, etc
549         if ($rel_type ne 'has_own' and $rel_type ne 'has_a') {
550
551                 # Foreign Key meta data not very standardized in CDBI
552                 my $fkey= $rel_meta->{args}{foreign_key} || $rel_meta->{foreign_column};
553                 unless ($fkey) { die " Could not determine foreign key for $fclass"; }
554                 my %data = (%$params, $fkey => $self->id);
555                 %data = ( %data, %{$rel_meta->{args}->{constraint} || {}} );
556                 #warn "Data is " . Dumper(\%data);
557             ($rel, $errs) =  $fclass->_do_create_all(\%data, $created);
558         }
559         else { 
560             ($rel, $errs) =  $fclass->_do_create_all($params, $created);
561                 unless ($errs) {
562                         $self->$accssr($rel->id);
563                         $self->update;
564                 }
565         }
566         return ($rel, $errs);
567 }
568
569
570
571                 
572 =head2  classify_form_inputs
573
574 $self->classify_form_inputs($params[, $delimiter]);
575
576 Foreign inputs are inputs that have data for a related table.
577 They come named so we can tell which related class they belong to.
578 This assumes the form : $accessor . $delimeter . $column recursively 
579 classifies them into hashes. It returns a hashref.
580
581 =cut
582
583 sub classify_form_inputs {
584         my ($self, $params, $delimiter) = @_;
585         my %hashed = ();
586         my $bottom_level;
587         $delimiter ||= $self->foreign_input_delimiter;
588         foreach my $input_name (keys %$params) {
589                 my @accssrs  = split /$delimiter/, $input_name;
590                 my $col_name = pop @accssrs;    
591                 $bottom_level = \%hashed;
592                 while ( my $a  = shift @accssrs ) {
593                         $bottom_level->{$a} ||= {};
594                         $bottom_level = $bottom_level->{$a};  # point to bottom level
595                 }
596                 # now insert parameter at bottom level keyed on col name
597                 $bottom_level->{$col_name} = $params->{$input_name};
598         }
599         return  \%hashed;
600 }
601
602 sub _untaint_handlers {
603     my ($me, $them) = @_;
604     return () unless $them->can('__untaint_types');
605     my %type = %{ $them->__untaint_types || {} };
606     my %h;
607     @h{ @{ $type{$_} } } = ($_) x @{ $type{$_} } foreach keys %type;
608     return %h;
609 }
610
611 sub _column_type_for {
612     my $type = lc shift;
613     $type =~ s/\(.*//;
614     my %map = (
615         varchar   => 'printable',
616         char      => 'printable',
617         text      => 'printable',
618         tinyint   => 'integer',
619         smallint  => 'integer',
620         mediumint => 'integer',
621         int       => 'integer',
622         integer   => 'integer',
623         bigint    => 'integer',
624         year      => 'integer',
625         date      => 'date',
626     );
627     return $map{$type} || "";
628 }
629
630 =head1 MAINTAINER 
631
632 Maypole Developers
633
634 =head1 AUTHORS
635
636 Peter Speltz, Aaron Trevena 
637
638 =head1 AUTHORS EMERITUS
639
640 Tony Bowden
641
642 =head1 TODO
643
644 * Tests
645 * add_to_from_cgi, search_from_cgi
646 * complete documentation
647 * ensure full backward compatibility with Class::DBI::FromCGI
648
649 =head1 BUGS and QUERIES
650
651 Please direct all correspondence regarding this module to:
652  Maypole list.
653
654 =head1 COPYRIGHT AND LICENSE
655
656 Copyright 2003-2004 by Peter Speltz 
657
658 This library is free software; you can redistribute it and/or modify
659 it under the same terms as Perl itself.
660
661 =head1 SEE ALSO
662
663 L<Class::DBI>, L<Class::DBI::FromCGI>
664
665 =cut
666
667 1;
668
669