Route and Results buttons updated.
[speedfreak] / Server / system / libraries / Validation.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3  * Validation library.
4  *
5  * $Id: Validation.php 4120 2009-03-25 19:22:31Z jheathco $
6  *
7  * @package    Validation
8  * @author     Kohana Team
9  * @copyright  (c) 2007-2008 Kohana Team
10  * @license    http://kohanaphp.com/license.html
11  */
12 class Validation_Core extends ArrayObject {
13
14         // Filters
15         protected $pre_filters = array();
16         protected $post_filters = array();
17
18         // Rules and callbacks
19         protected $rules = array();
20         protected $callbacks = array();
21
22         // Rules that are allowed to run on empty fields
23         protected $empty_rules = array('required', 'matches');
24
25         // Errors
26         protected $errors = array();
27         protected $messages = array();
28
29         // Fields that are expected to be arrays
30         protected $array_fields = array();
31
32         // Checks if there is data to validate.
33         protected $submitted;
34
35         /**
36          * Creates a new Validation instance.
37          *
38          * @param   array   array to use for validation
39          * @return  object
40          */
41         public static function factory(array $array)
42         {
43                 return new Validation($array);
44         }
45
46         /**
47          * Sets the unique "any field" key and creates an ArrayObject from the
48          * passed array.
49          *
50          * @param   array   array to validate
51          * @return  void
52          */
53         public function __construct(array $array)
54         {
55                 // The array is submitted if the array is not empty
56                 $this->submitted = ! empty($array);
57
58                 parent::__construct($array, ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST);
59         }
60
61         /**
62          * Magic clone method, clears errors and messages.
63          *
64          * @return  void
65          */
66         public function __clone()
67         {
68                 $this->errors = array();
69                 $this->messages = array();
70         }
71
72         /**
73          * Create a copy of the current validation rules and change the array.
74          *
75          * @chainable
76          * @param   array  new array to validate
77          * @return  Validation
78          */
79         public function copy(array $array)
80         {
81                 $copy = clone $this;
82
83                 $copy->exchangeArray($array);
84
85                 return $copy;
86         }
87
88         /**
89          * Test if the data has been submitted.
90          *
91          * @return  boolean
92          */
93         public function submitted($value = NULL)
94         {
95                 if (is_bool($value))
96                 {
97                         $this->submitted = $value;
98                 }
99
100                 return $this->submitted;
101         }
102
103         /**
104          * Returns an array of all the field names that have filters, rules, or callbacks.
105          *
106          * @return  array
107          */
108         public function field_names()
109         {
110                 // All the fields that are being validated
111                 $fields = array_keys(array_merge
112                 (
113                         $this->pre_filters,
114                         $this->rules,
115                         $this->callbacks,
116                         $this->post_filters
117                 ));
118
119                 // Remove wildcard fields
120                 $fields = array_diff($fields, array('*'));
121
122                 return $fields;
123         }
124
125         /**
126          * Returns the array values of the current object.
127          *
128          * @return  array
129          */
130         public function as_array()
131         {
132                 return $this->getArrayCopy();
133         }
134
135         /**
136          * Returns the ArrayObject values, removing all inputs without rules.
137          * To choose specific inputs, list the field name as arguments.
138          *
139          * @param   boolean  return only fields with filters, rules, and callbacks
140          * @return  array
141          */
142         public function safe_array()
143         {
144                 // Load choices
145                 $choices = func_get_args();
146                 $choices = empty($choices) ? NULL : array_combine($choices, $choices);
147
148                 // Get field names
149                 $fields = $this->field_names();
150
151                 $safe = array();
152                 foreach ($fields as $field)
153                 {
154                         if ($choices === NULL OR isset($choices[$field]))
155                         {
156                                 if (isset($this[$field]))
157                                 {
158                                         $value = $this[$field];
159
160                                         if (is_object($value))
161                                         {
162                                                 // Convert the value back into an array
163                                                 $value = $value->getArrayCopy();
164                                         }
165                                 }
166                                 else
167                                 {
168                                         // Even if the field is not in this array, it must be set
169                                         $value = NULL;
170                                 }
171
172                                 // Add the field to the array
173                                 $safe[$field] = $value;
174                         }
175                 }
176
177                 return $safe;
178         }
179
180         /**
181          * Add additional rules that will forced, even for empty fields. All arguments
182          * passed will be appended to the list.
183          *
184          * @chainable
185          * @param   string   rule name
186          * @return  object
187          */
188         public function allow_empty_rules($rules)
189         {
190                 // Any number of args are supported
191                 $rules = func_get_args();
192
193                 // Merge the allowed rules
194                 $this->empty_rules = array_merge($this->empty_rules, $rules);
195
196                 return $this;
197         }
198
199         /**
200          * Converts a filter, rule, or callback into a fully-qualified callback array.
201          *
202          * @return  mixed
203          */
204         protected function callback($callback)
205         {
206                 if (is_string($callback))
207                 {
208                         if (strpos($callback, '::') !== FALSE)
209                         {
210                                 $callback = explode('::', $callback);
211                         }
212                         elseif (function_exists($callback))
213                         {
214                                 // No need to check if the callback is a method
215                                 $callback = $callback;
216                         }
217                         elseif (method_exists($this, $callback))
218                         {
219                                 // The callback exists in Validation
220                                 $callback = array($this, $callback);
221                         }
222                         elseif (method_exists('valid', $callback))
223                         {
224                                 // The callback exists in valid::
225                                 $callback = array('valid', $callback);
226                         }
227                 }
228
229                 if ( ! is_callable($callback, FALSE))
230                 {
231                         if (is_array($callback))
232                         {
233                                 if (is_object($callback[0]))
234                                 {
235                                         // Object instance syntax
236                                         $name = get_class($callback[0]).'->'.$callback[1];
237                                 }
238                                 else
239                                 {
240                                         // Static class syntax
241                                         $name = $callback[0].'::'.$callback[1];
242                                 }
243                         }
244                         else
245                         {
246                                 // Function syntax
247                                 $name = $callback;
248                         }
249
250                         throw new Kohana_Exception('validation.not_callable', $name);
251                 }
252
253                 return $callback;
254         }
255
256         /**
257          * Add a pre-filter to one or more inputs. Pre-filters are applied before
258          * rules or callbacks are executed.
259          *
260          * @chainable
261          * @param   callback  filter
262          * @param   string    fields to apply filter to, use TRUE for all fields
263          * @return  object
264          */
265         public function pre_filter($filter, $field = TRUE)
266         {
267                 if ($field === TRUE OR $field === '*')
268                 {
269                         // Use wildcard
270                         $fields = array('*');
271                 }
272                 else
273                 {
274                         // Add the filter to specific inputs
275                         $fields = func_get_args();
276                         $fields = array_slice($fields, 1);
277                 }
278
279                 // Convert to a proper callback
280                 $filter = $this->callback($filter);
281
282                 foreach ($fields as $field)
283                 {
284                         // Add the filter to specified field
285                         $this->pre_filters[$field][] = $filter;
286                 }
287
288                 return $this;
289         }
290
291         /**
292          * Add a post-filter to one or more inputs. Post-filters are applied after
293          * rules and callbacks have been executed.
294          *
295          * @chainable
296          * @param   callback  filter
297          * @param   string    fields to apply filter to, use TRUE for all fields
298          * @return  object
299          */
300         public function post_filter($filter, $field = TRUE)
301         {
302                 if ($field === TRUE)
303                 {
304                         // Use wildcard
305                         $fields = array('*');
306                 }
307                 else
308                 {
309                         // Add the filter to specific inputs
310                         $fields = func_get_args();
311                         $fields = array_slice($fields, 1);
312                 }
313
314                 // Convert to a proper callback
315                 $filter = $this->callback($filter);
316
317                 foreach ($fields as $field)
318                 {
319                         // Add the filter to specified field
320                         $this->post_filters[$field][] = $filter;
321                 }
322
323                 return $this;
324         }
325
326         /**
327          * Add rules to a field. Validation rules may only return TRUE or FALSE and
328          * can not manipulate the value of a field.
329          *
330          * @chainable
331          * @param   string    field name
332          * @param   callback  rules (one or more arguments)
333          * @return  object
334          */
335         public function add_rules($field, $rules)
336         {
337                 // Get the rules
338                 $rules = func_get_args();
339                 $rules = array_slice($rules, 1);
340
341                 if ($field === TRUE)
342                 {
343                         // Use wildcard
344                         $field = '*';
345                 }
346
347                 foreach ($rules as $rule)
348                 {
349                         // Arguments for rule
350                         $args = NULL;
351
352                         if (is_string($rule))
353                         {
354                                 if (preg_match('/^([^\[]++)\[(.+)\]$/', $rule, $matches))
355                                 {
356                                         // Split the rule into the function and args
357                                         $rule = $matches[1];
358                                         $args = preg_split('/(?<!\\\\),\s*/', $matches[2]);
359
360                                         // Replace escaped comma with comma
361                                         $args = str_replace('\,', ',', $args);
362                                 }
363                         }
364
365                         if ($rule === 'is_array')
366                         {
367                                 // This field is expected to be an array
368                                 $this->array_fields[$field] = $field;
369                         }
370
371                         // Convert to a proper callback
372                         $rule = $this->callback($rule);
373
374                         // Add the rule, with args, to the field
375                         $this->rules[$field][] = array($rule, $args);
376                 }
377
378                 return $this;
379         }
380
381         /**
382          * Add callbacks to a field. Callbacks must accept the Validation object
383          * and the input name. Callback returns are not processed.
384          *
385          * @chainable
386          * @param   string     field name
387          * @param   callbacks  callbacks (unlimited number)
388          * @return  object
389          */
390         public function add_callbacks($field, $callbacks)
391         {
392                 // Get all callbacks as an array
393                 $callbacks = func_get_args();
394                 $callbacks = array_slice($callbacks, 1);
395
396                 if ($field === TRUE)
397                 {
398                         // Use wildcard
399                         $field = '*';
400                 }
401
402                 foreach ($callbacks as $callback)
403                 {
404                         // Convert to a proper callback
405                         $callback = $this->callback($callback);
406
407                         // Add the callback to specified field
408                         $this->callbacks[$field][] = $callback;
409                 }
410
411                 return $this;
412         }
413
414         /**
415          * Validate by processing pre-filters, rules, callbacks, and post-filters.
416          * All fields that have filters, rules, or callbacks will be initialized if
417          * they are undefined. Validation will only be run if there is data already
418          * in the array.
419          *
420          * @param   object  Validation object, used only for recursion
421          * @param   object  name of field for errors
422          * @return  bool
423          */
424         public function validate($object = NULL, $field_name = NULL)
425         {
426                 if ($object === NULL)
427                 {
428                         // Use the current object
429                         $object = $this;
430                 }
431
432                 // Get all field names
433                 $fields = $this->field_names();
434
435                 // Copy the array from the object, to optimize multiple sets
436                 $array = $this->getArrayCopy();
437
438                 foreach ($fields as $field)
439                 {
440                         if ($field === '*')
441                         {
442                                 // Ignore wildcard
443                                 continue;
444                         }
445
446                         if ( ! isset($array[$field]))
447                         {
448                                 if (isset($this->array_fields[$field]))
449                                 {
450                                         // This field must be an array
451                                         $array[$field] = array();
452                                 }
453                                 else
454                                 {
455                                         $array[$field] = NULL;
456                                 }
457                         }
458                 }
459
460                 // Swap the array back into the object
461                 $this->exchangeArray($array);
462
463                 // Get all defined field names
464                 $fields = array_keys($array);
465
466                 foreach ($this->pre_filters as $field => $callbacks)
467                 {
468                         foreach ($callbacks as $callback)
469                         {
470                                 if ($field === '*')
471                                 {
472                                         foreach ($fields as $f)
473                                         {
474                                                 $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]);
475                                         }
476                                 }
477                                 else
478                                 {
479                                         $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]);
480                                 }
481                         }
482                 }
483
484                 if ($this->submitted === FALSE)
485                         return FALSE;
486
487                 foreach ($this->rules as $field => $callbacks)
488                 {
489                         foreach ($callbacks as $callback)
490                         {
491                                 // Separate the callback and arguments
492                                 list ($callback, $args) = $callback;
493
494                                 // Function or method name of the rule
495                                 $rule = is_array($callback) ? $callback[1] : $callback;
496
497                                 if ($field === '*')
498                                 {
499                                         foreach ($fields as $f)
500                                         {
501                                                 // Note that continue, instead of break, is used when
502                                                 // applying rules using a wildcard, so that all fields
503                                                 // will be validated.
504
505                                                 if (isset($this->errors[$f]))
506                                                 {
507                                                         // Prevent other rules from being evaluated if an error has occurred
508                                                         continue;
509                                                 }
510
511                                                 if (empty($this[$f]) AND ! in_array($rule, $this->empty_rules))
512                                                 {
513                                                         // This rule does not need to be processed on empty fields
514                                                         continue;
515                                                 }
516
517                                                 if ($args === NULL)
518                                                 {
519                                                         if ( ! call_user_func($callback, $this[$f]))
520                                                         {
521                                                                 $this->errors[$f] = $rule;
522
523                                                                 // Stop validating this field when an error is found
524                                                                 continue;
525                                                         }
526                                                 }
527                                                 else
528                                                 {
529                                                         if ( ! call_user_func($callback, $this[$f], $args))
530                                                         {
531                                                                 $this->errors[$f] = $rule;
532
533                                                                 // Stop validating this field when an error is found
534                                                                 continue;
535                                                         }
536                                                 }
537                                         }
538                                 }
539                                 else
540                                 {
541                                         if (isset($this->errors[$field]))
542                                         {
543                                                 // Prevent other rules from being evaluated if an error has occurred
544                                                 break;
545                                         }
546
547                                         if ( ! in_array($rule, $this->empty_rules) AND ! $this->required($this[$field]))
548                                         {
549                                                 // This rule does not need to be processed on empty fields
550                                                 continue;
551                                         }
552
553                                         if ($args === NULL)
554                                         {
555                                                 if ( ! call_user_func($callback, $this[$field]))
556                                                 {
557                                                         $this->errors[$field] = $rule;
558
559                                                         // Stop validating this field when an error is found
560                                                         break;
561                                                 }
562                                         }
563                                         else
564                                         {
565                                                 if ( ! call_user_func($callback, $this[$field], $args))
566                                                 {
567                                                         $this->errors[$field] = $rule;
568
569                                                         // Stop validating this field when an error is found
570                                                         break;
571                                                 }
572                                         }
573                                 }
574                         }
575                 }
576
577                 foreach ($this->callbacks as $field => $callbacks)
578                 {
579                         foreach ($callbacks as $callback)
580                         {
581                                 if ($field === '*')
582                                 {
583                                         foreach ($fields as $f)
584                                         {
585                                                 // Note that continue, instead of break, is used when
586                                                 // applying rules using a wildcard, so that all fields
587                                                 // will be validated.
588
589                                                 if (isset($this->errors[$f]))
590                                                 {
591                                                         // Stop validating this field when an error is found
592                                                         continue;
593                                                 }
594
595                                                 call_user_func($callback, $this, $f);
596                                         }
597                                 }
598                                 else
599                                 {
600                                         if (isset($this->errors[$field]))
601                                         {
602                                                 // Stop validating this field when an error is found
603                                                 break;
604                                         }
605
606                                         call_user_func($callback, $this, $field);
607                                 }
608                         }
609                 }
610
611                 foreach ($this->post_filters as $field => $callbacks)
612                 {
613                         foreach ($callbacks as $callback)
614                         {
615                                 if ($field === '*')
616                                 {
617                                         foreach ($fields as $f)
618                                         {
619                                                 $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]);
620                                         }
621                                 }
622                                 else
623                                 {
624                                         $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]);
625                                 }
626                         }
627                 }
628
629                 // Return TRUE if there are no errors
630                 return $this->errors === array();
631         }
632
633         /**
634          * Add an error to an input.
635          *
636          * @chainable
637          * @param   string  input name
638          * @param   string  unique error name
639          * @return  object
640          */
641         public function add_error($field, $name)
642         {
643                 $this->errors[$field] = $name;
644
645                 return $this;
646         }
647
648         /**
649          * Sets or returns the message for an input.
650          *
651          * @chainable
652          * @param   string   input key
653          * @param   string   message to set
654          * @return  string|object
655          */
656         public function message($input = NULL, $message = NULL)
657         {
658                 if ($message === NULL)
659                 {
660                         if ($input === NULL)
661                         {
662                                 $messages = array();
663                                 $keys     = array_keys($this->messages);
664
665                                 foreach ($keys as $input)
666                                 {
667                                         $messages[] = $this->message($input);
668                                 }
669
670                                 return implode("\n", $messages);
671                         }
672
673                         // Return nothing if no message exists
674                         if (empty($this->messages[$input]))
675                                 return '';
676
677                         // Return the HTML message string
678                         return $this->messages[$input];
679                 }
680                 else
681                 {
682                         $this->messages[$input] = $message;
683                 }
684
685                 return $this;
686         }
687
688         /**
689          * Return the errors array.
690          *
691          * @param   boolean  load errors from a lang file
692          * @return  array
693          */
694         public function errors($file = NULL)
695         {
696                 if ($file === NULL)
697                 {
698                         return $this->errors;
699                 }
700                 else
701                 {
702
703                         $errors = array();
704                         foreach ($this->errors as $input => $error)
705                         {
706                                 // Key for this input error
707                                 $key = "$file.$input.$error";
708
709                                 if (($errors[$input] = Kohana::lang($key)) === $key)
710                                 {
711                                         // Get the default error message
712                                         $errors[$input] = Kohana::lang("$file.$input.default");
713                                 }
714                         }
715
716                         return $errors;
717                 }
718         }
719
720         /**
721          * Rule: required. Generates an error if the field has an empty value.
722          *
723          * @param   mixed   input value
724          * @return  bool
725          */
726         public function required($str)
727         {
728                 if (is_object($str) AND $str instanceof ArrayObject)
729                 {
730                         // Get the array from the ArrayObject
731                         $str = $str->getArrayCopy();
732                 }
733
734                 if (is_array($str))
735                 {
736                         return ! empty($str);
737                 }
738                 else
739                 {
740                         return ! ($str === '' OR $str === NULL OR $str === FALSE);
741                 }
742         }
743
744         /**
745          * Rule: matches. Generates an error if the field does not match one or more
746          * other fields.
747          *
748          * @param   mixed   input value
749          * @param   array   input names to match against
750          * @return  bool
751          */
752         public function matches($str, array $inputs)
753         {
754                 foreach ($inputs as $key)
755                 {
756                         if ($str !== (isset($this[$key]) ? $this[$key] : NULL))
757                                 return FALSE;
758                 }
759
760                 return TRUE;
761         }
762
763         /**
764          * Rule: length. Generates an error if the field is too long or too short.
765          *
766          * @param   mixed   input value
767          * @param   array   minimum, maximum, or exact length to match
768          * @return  bool
769          */
770         public function length($str, array $length)
771         {
772                 if ( ! is_string($str))
773                         return FALSE;
774
775                 $size = utf8::strlen($str);
776                 $status = FALSE;
777
778                 if (count($length) > 1)
779                 {
780                         list ($min, $max) = $length;
781
782                         if ($size >= $min AND $size <= $max)
783                         {
784                                 $status = TRUE;
785                         }
786                 }
787                 else
788                 {
789                         $status = ($size === (int) $length[0]);
790                 }
791
792                 return $status;
793         }
794
795         /**
796          * Rule: depends_on. Generates an error if the field does not depend on one
797          * or more other fields.
798          *
799          * @param   mixed   field name
800          * @param   array   field names to check dependency
801          * @return  bool
802          */
803         public function depends_on($field, array $fields)
804         {
805                 foreach ($fields as $depends_on)
806                 {
807                         if ( ! isset($this[$depends_on]) OR $this[$depends_on] == NULL)
808                                 return FALSE;
809                 }
810
811                 return TRUE;
812         }
813
814         /**
815          * Rule: chars. Generates an error if the field contains characters outside of the list.
816          *
817          * @param   string  field value
818          * @param   array   allowed characters
819          * @return  bool
820          */
821         public function chars($value, array $chars)
822         {
823                 return ! preg_match('![^'.implode('', $chars).']!u', $value);
824         }
825
826 } // End Validation