1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * Form Validation Class
21 * @package CodeIgniter
22 * @subpackage Libraries
23 * @category Validation
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/form_validation.html
27 class CI_Form_validation {
30 var $_field_data = array();
31 var $_config_rules = array();
32 var $_error_array = array();
33 var $_error_messages = array();
34 var $_error_prefix = '<p>';
35 var $_error_suffix = '</p>';
36 var $error_string = '';
37 var $_safe_form_data = FALSE;
43 public function __construct($rules = array())
45 $this->CI =& get_instance();
47 // Validation rules can be stored in a config file.
48 $this->_config_rules = $rules;
50 // Automatically load the form helper
51 $this->CI->load->helper('form');
53 // Set the character encoding in MB.
54 if (function_exists('mb_internal_encoding'))
56 mb_internal_encoding($this->CI->config->item('charset'));
59 log_message('debug', "Form Validation Class Initialized");
62 // --------------------------------------------------------------------
67 * This function takes an array of field names and validation
68 * rules as input, validates the info, and stores it
75 function set_rules($field, $label = '', $rules = '')
77 // No reason to set rules if we have no POST data
78 if (count($_POST) == 0)
83 // If an array was passed via the first parameter instead of indidual string
84 // values we cycle through it and recursively call this function.
87 foreach ($field as $row)
89 // Houston, we have a problem...
90 if ( ! isset($row['field']) OR ! isset($row['rules']))
95 // If the field label wasn't passed we use the field name
96 $label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
99 $this->set_rules($row['field'], $label, $row['rules']);
104 // No fields? Nothing to do...
105 if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
110 // If the field label wasn't passed we use the field name
111 $label = ($label == '') ? $field : $label;
113 // Is the field name an array? We test for the existence of a bracket "[" in
114 // the field name to determine this. If it is an array, we break it apart
115 // into its components so that we can fetch the corresponding POST data later
116 if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
118 // Note: Due to a bug in current() that affects some versions
119 // of PHP we can not pass function call directly into it
120 $x = explode('[', $field);
121 $indexes[] = current($x);
123 for ($i = 0; $i < count($matches['0']); $i++)
125 if ($matches['1'][$i] != '')
127 $indexes[] = $matches['1'][$i];
139 // Build our master array
140 $this->_field_data[$field] = array(
144 'is_array' => $is_array,
153 // --------------------------------------------------------------------
158 * Lets users set their own error messages on the fly. Note: The key
159 * name has to match the function name that it corresponds to.
166 function set_message($lang, $val = '')
168 if ( ! is_array($lang))
170 $lang = array($lang => $val);
173 $this->_error_messages = array_merge($this->_error_messages, $lang);
178 // --------------------------------------------------------------------
181 * Set The Error Delimiter
183 * Permits a prefix/suffix to be added to each error message
190 function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
192 $this->_error_prefix = $prefix;
193 $this->_error_suffix = $suffix;
198 // --------------------------------------------------------------------
203 * Gets the error message associated with a particular field
206 * @param string the field name
209 function error($field = '', $prefix = '', $suffix = '')
211 if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
218 $prefix = $this->_error_prefix;
223 $suffix = $this->_error_suffix;
226 return $prefix.$this->_field_data[$field]['error'].$suffix;
229 // --------------------------------------------------------------------
234 * Returns the error messages as a string, wrapped in the error delimiters
241 function error_string($prefix = '', $suffix = '')
243 // No errrors, validation passes!
244 if (count($this->_error_array) === 0)
251 $prefix = $this->_error_prefix;
256 $suffix = $this->_error_suffix;
259 // Generate the error string
261 foreach ($this->_error_array as $val)
265 $str .= $prefix.$val.$suffix."\n";
272 // --------------------------------------------------------------------
277 * This function does all the work.
282 function run($group = '')
284 // Do we even have any data to process? Mm?
285 if (count($_POST) == 0)
290 // Does the _field_data array containing the validation rules exist?
291 // If not, we look to see if they were assigned via a config file
292 if (count($this->_field_data) == 0)
294 // No validation rules? We're done...
295 if (count($this->_config_rules) == 0)
300 // Is there a validation rule for the particular URI being accessed?
301 $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
303 if ($uri != '' AND isset($this->_config_rules[$uri]))
305 $this->set_rules($this->_config_rules[$uri]);
309 $this->set_rules($this->_config_rules);
312 // We're we able to set the rules correctly?
313 if (count($this->_field_data) == 0)
315 log_message('debug', "Unable to find validation rules");
320 // Load the language file containing error messages
321 $this->CI->lang->load('form_validation');
323 // Cycle through the rules for each field, match the
324 // corresponding $_POST item and test for errors
325 foreach ($this->_field_data as $field => $row)
327 // Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
328 // Depending on whether the field name is an array or a string will determine where we get it from.
330 if ($row['is_array'] == TRUE)
332 $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
336 if (isset($_POST[$field]) AND $_POST[$field] != "")
338 $this->_field_data[$field]['postdata'] = $_POST[$field];
342 $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
345 // Did we end up with any errors?
346 $total_errors = count($this->_error_array);
348 if ($total_errors > 0)
350 $this->_safe_form_data = TRUE;
353 // Now we need to re-set the POST data with the new, processed data
354 $this->_reset_post_array();
356 // No errors, validation passes!
357 if ($total_errors == 0)
366 // --------------------------------------------------------------------
369 * Traverse a multidimensional $_POST array index until the data is found
377 function _reduce_array($array, $keys, $i = 0)
379 if (is_array($array))
381 if (isset($keys[$i]))
383 if (isset($array[$keys[$i]]))
385 $array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
401 // --------------------------------------------------------------------
404 * Re-populate the _POST array with our finalized and processed data
409 function _reset_post_array()
411 foreach ($this->_field_data as $field => $row)
413 if ( ! is_null($row['postdata']))
415 if ($row['is_array'] == FALSE)
417 if (isset($_POST[$row['field']]))
419 $_POST[$row['field']] = $this->prep_for_form($row['postdata']);
424 // start with a reference
427 // before we assign values, make a reference to the right POST key
428 if (count($row['keys']) == 1)
430 $post_ref =& $post_ref[current($row['keys'])];
434 foreach ($row['keys'] as $val)
436 $post_ref =& $post_ref[$val];
440 if (is_array($row['postdata']))
443 foreach ($row['postdata'] as $k => $v)
445 $array[$k] = $this->prep_for_form($v);
452 $post_ref = $this->prep_for_form($row['postdata']);
459 // --------------------------------------------------------------------
462 * Executes the Validation routines
471 function _execute($row, $rules, $postdata = NULL, $cycles = 0)
473 // If the $_POST data is an array we will run a recursive call
474 if (is_array($postdata))
476 foreach ($postdata as $key => $val)
478 $this->_execute($row, $rules, $val, $cycles);
485 // --------------------------------------------------------------------
487 // If the field is blank, but NOT required, no further tests are necessary
489 if ( ! in_array('required', $rules) AND is_null($postdata))
491 // Before we bail out, does the rule contain a callback?
492 if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
495 $rules = (array('1' => $match[1]));
503 // --------------------------------------------------------------------
505 // Isset Test. Typically this rule will only apply to checkboxes.
506 if (is_null($postdata) AND $callback == FALSE)
508 if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
510 // Set the message type
511 $type = (in_array('required', $rules)) ? 'required' : 'isset';
513 if ( ! isset($this->_error_messages[$type]))
515 if (FALSE === ($line = $this->CI->lang->line($type)))
517 $line = 'The field was not set';
522 $line = $this->_error_messages[$type];
525 // Build the error message
526 $message = sprintf($line, $this->_translate_fieldname($row['label']));
528 // Save the error message
529 $this->_field_data[$row['field']]['error'] = $message;
531 if ( ! isset($this->_error_array[$row['field']]))
533 $this->_error_array[$row['field']] = $message;
540 // --------------------------------------------------------------------
542 // Cycle through each rule and run it
543 foreach ($rules As $rule)
547 // We set the $postdata variable with the current data in our master array so that
548 // each cycle of the loop is dealing with the processed data from the last cycle
549 if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
551 // We shouldn't need this safety, but just in case there isn't an array index
552 // associated with this cycle we'll bail out
553 if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
558 $postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
563 $postdata = $this->_field_data[$row['field']]['postdata'];
566 // --------------------------------------------------------------------
568 // Is the rule a callback?
570 if (substr($rule, 0, 9) == 'callback_')
572 $rule = substr($rule, 9);
576 // Strip the parameter (if exists) from the rule
577 // Rules can contain a parameter: max_length[5]
579 if (preg_match("/(.*?)\[(.*)\]/", $rule, $match))
585 // Call the function that corresponds to the rule
586 if ($callback === TRUE)
588 if ( ! method_exists($this->CI, $rule))
593 // Run the function and grab the result
594 $result = $this->CI->$rule($postdata, $param);
596 // Re-assign the result to the master data array
597 if ($_in_array == TRUE)
599 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
603 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
606 // If the field isn't required and we just processed a callback we'll move on...
607 if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
614 if ( ! method_exists($this, $rule))
616 // If our own wrapper function doesn't exist we see if a native PHP function does.
617 // Users can use any native PHP function call that has one param.
618 if (function_exists($rule))
620 $result = $rule($postdata);
622 if ($_in_array == TRUE)
624 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
628 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
635 $result = $this->$rule($postdata, $param);
637 if ($_in_array == TRUE)
639 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
643 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
647 // Did the rule test negatively? If so, grab the error.
648 if ($result === FALSE)
650 if ( ! isset($this->_error_messages[$rule]))
652 if (FALSE === ($line = $this->CI->lang->line($rule)))
654 $line = 'Unable to access an error message corresponding to your field name.';
659 $line = $this->_error_messages[$rule];
662 // Is the parameter we are inserting into the error message the name
663 // of another field? If so we need to grab its "field label"
664 if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
666 $param = $this->_translate_fieldname($this->_field_data[$param]['label']);
669 // Build the error message
670 $message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
672 // Save the error message
673 $this->_field_data[$row['field']]['error'] = $message;
675 if ( ! isset($this->_error_array[$row['field']]))
677 $this->_error_array[$row['field']] = $message;
685 // --------------------------------------------------------------------
688 * Translate a field name
691 * @param string the field name
694 function _translate_fieldname($fieldname)
696 // Do we need to translate the field name?
697 // We look for the prefix lang: to determine this
698 if (substr($fieldname, 0, 5) == 'lang:')
701 $line = substr($fieldname, 5);
703 // Were we able to translate the field name? If not we use $line
704 if (FALSE === ($fieldname = $this->CI->lang->line($line)))
713 // --------------------------------------------------------------------
716 * Get the value from a form
718 * Permits you to repopulate a form field with the value it was submitted
719 * with, or, if that value doesn't exist, with the default
722 * @param string the field name
726 function set_value($field = '', $default = '')
728 if ( ! isset($this->_field_data[$field]))
733 // If the data is an array output them one at a time.
734 // E.g: form_input('name[]', set_value('name[]');
735 if (is_array($this->_field_data[$field]['postdata']))
737 return array_shift($this->_field_data[$field]['postdata']);
740 return $this->_field_data[$field]['postdata'];
743 // --------------------------------------------------------------------
748 * Enables pull-down lists to be set to the value the user
749 * selected in the event of an error
756 function set_select($field = '', $value = '', $default = FALSE)
758 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
760 if ($default === TRUE AND count($this->_field_data) === 0)
762 return ' selected="selected"';
767 $field = $this->_field_data[$field]['postdata'];
769 if (is_array($field))
771 if ( ! in_array($value, $field))
778 if (($field == '' OR $value == '') OR ($field != $value))
784 return ' selected="selected"';
787 // --------------------------------------------------------------------
792 * Enables radio buttons to be set to the value the user
793 * selected in the event of an error
800 function set_radio($field = '', $value = '', $default = FALSE)
802 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
804 if ($default === TRUE AND count($this->_field_data) === 0)
806 return ' checked="checked"';
811 $field = $this->_field_data[$field]['postdata'];
813 if (is_array($field))
815 if ( ! in_array($value, $field))
822 if (($field == '' OR $value == '') OR ($field != $value))
828 return ' checked="checked"';
831 // --------------------------------------------------------------------
836 * Enables checkboxes to be set to the value the user
837 * selected in the event of an error
844 function set_checkbox($field = '', $value = '', $default = FALSE)
846 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
848 if ($default === TRUE AND count($this->_field_data) === 0)
850 return ' checked="checked"';
855 $field = $this->_field_data[$field]['postdata'];
857 if (is_array($field))
859 if ( ! in_array($value, $field))
866 if (($field == '' OR $value == '') OR ($field != $value))
872 return ' checked="checked"';
875 // --------------------------------------------------------------------
884 function required($str)
886 if ( ! is_array($str))
888 return (trim($str) == '') ? FALSE : TRUE;
892 return ( ! empty($str));
896 // --------------------------------------------------------------------
899 * Performs a Regular Expression match test.
906 function regex_match($str, $regex)
908 if ( ! preg_match($regex, $str))
916 // --------------------------------------------------------------------
919 * Match one field to another
926 function matches($str, $field)
928 if ( ! isset($_POST[$field]))
933 $field = $_POST[$field];
935 return ($str !== $field) ? FALSE : TRUE;
938 // --------------------------------------------------------------------
948 function min_length($str, $val)
950 if (preg_match("/[^0-9]/", $val))
955 if (function_exists('mb_strlen'))
957 return (mb_strlen($str) < $val) ? FALSE : TRUE;
960 return (strlen($str) < $val) ? FALSE : TRUE;
963 // --------------------------------------------------------------------
973 function max_length($str, $val)
975 if (preg_match("/[^0-9]/", $val))
980 if (function_exists('mb_strlen'))
982 return (mb_strlen($str) > $val) ? FALSE : TRUE;
985 return (strlen($str) > $val) ? FALSE : TRUE;
988 // --------------------------------------------------------------------
998 function exact_length($str, $val)
1000 if (preg_match("/[^0-9]/", $val))
1005 if (function_exists('mb_strlen'))
1007 return (mb_strlen($str) != $val) ? FALSE : TRUE;
1010 return (strlen($str) != $val) ? FALSE : TRUE;
1013 // --------------------------------------------------------------------
1022 function valid_email($str)
1024 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
1027 // --------------------------------------------------------------------
1036 function valid_emails($str)
1038 if (strpos($str, ',') === FALSE)
1040 return $this->valid_email(trim($str));
1043 foreach (explode(',', $str) as $email)
1045 if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
1054 // --------------------------------------------------------------------
1057 * Validate IP Address
1063 function valid_ip($ip)
1065 return $this->CI->input->valid_ip($ip);
1068 // --------------------------------------------------------------------
1077 function alpha($str)
1079 return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
1082 // --------------------------------------------------------------------
1091 function alpha_numeric($str)
1093 return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
1096 // --------------------------------------------------------------------
1099 * Alpha-numeric with underscores and dashes
1105 function alpha_dash($str)
1107 return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
1110 // --------------------------------------------------------------------
1119 function numeric($str)
1121 return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
1125 // --------------------------------------------------------------------
1134 function is_numeric($str)
1136 return ( ! is_numeric($str)) ? FALSE : TRUE;
1139 // --------------------------------------------------------------------
1148 function integer($str)
1150 return (bool) preg_match('/^[\-+]?[0-9]+$/', $str);
1153 // --------------------------------------------------------------------
1162 function decimal($str)
1164 return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str);
1167 // --------------------------------------------------------------------
1176 function greater_than($str, $min)
1178 if ( ! is_numeric($str))
1185 // --------------------------------------------------------------------
1194 function less_than($str, $max)
1196 if ( ! is_numeric($str))
1203 // --------------------------------------------------------------------
1206 * Is a Natural number (0,1,2,3, etc.)
1212 function is_natural($str)
1214 return (bool) preg_match( '/^[0-9]+$/', $str);
1217 // --------------------------------------------------------------------
1220 * Is a Natural number, but not a zero (1,2,3, etc.)
1226 function is_natural_no_zero($str)
1228 if ( ! preg_match( '/^[0-9]+$/', $str))
1241 // --------------------------------------------------------------------
1246 * Tests a string for characters outside of the Base64 alphabet
1247 * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
1253 function valid_base64($str)
1255 return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
1258 // --------------------------------------------------------------------
1261 * Prep data for form
1263 * This function allows HTML to be safely shown in a form.
1264 * Special characters are converted.
1270 function prep_for_form($data = '')
1272 if (is_array($data))
1274 foreach ($data as $key => $val)
1276 $data[$key] = $this->prep_for_form($val);
1282 if ($this->_safe_form_data == FALSE OR $data === '')
1287 return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
1290 // --------------------------------------------------------------------
1299 function prep_url($str = '')
1301 if ($str == 'http://' OR $str == '')
1306 if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
1308 $str = 'http://'.$str;
1314 // --------------------------------------------------------------------
1323 function strip_image_tags($str)
1325 return $this->CI->input->strip_image_tags($str);
1328 // --------------------------------------------------------------------
1337 function xss_clean($str)
1339 return $this->CI->security->xss_clean($str);
1342 // --------------------------------------------------------------------
1345 * Convert PHP tags to entities
1351 function encode_php_tags($str)
1353 return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
1357 // END Form Validation Class
1359 /* End of file Form_validation.php */
1360 /* Location: ./system/libraries/Form_validation.php */