1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, 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;
44 function CI_Form_validation($rules = array())
46 $this->CI =& get_instance();
48 // Validation rules can be stored in a config file.
49 $this->_config_rules = $rules;
51 // Automatically load the form helper
52 $this->CI->load->helper('form');
54 // Set the character encoding in MB.
55 if (function_exists('mb_internal_encoding'))
57 mb_internal_encoding($this->CI->config->item('charset'));
60 log_message('debug', "Form Validation Class Initialized");
63 // --------------------------------------------------------------------
68 * This function takes an array of field names and validation
69 * rules as input, validates the info, and stores it
76 function set_rules($field, $label = '', $rules = '')
78 // No reason to set rules if we have no POST data
79 if (count($_POST) == 0)
84 // If an array was passed via the first parameter instead of indidual string
85 // values we cycle through it and recursively call this function.
88 foreach ($field as $row)
90 // Houston, we have a problem...
91 if ( ! isset($row['field']) OR ! isset($row['rules']))
96 // If the field label wasn't passed we use the field name
97 $label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
100 $this->set_rules($row['field'], $label, $row['rules']);
105 // No fields? Nothing to do...
106 if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
111 // If the field label wasn't passed we use the field name
112 $label = ($label == '') ? $field : $label;
114 // Is the field name an array? We test for the existence of a bracket "[" in
115 // the field name to determine this. If it is an array, we break it apart
116 // into its components so that we can fetch the corresponding POST data later
117 if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
119 // Note: Due to a bug in current() that affects some versions
120 // of PHP we can not pass function call directly into it
121 $x = explode('[', $field);
122 $indexes[] = current($x);
124 for ($i = 0; $i < count($matches['0']); $i++)
126 if ($matches['1'][$i] != '')
128 $indexes[] = $matches['1'][$i];
140 // Build our master array
141 $this->_field_data[$field] = array(
145 'is_array' => $is_array,
152 // --------------------------------------------------------------------
157 * Lets users set their own error messages on the fly. Note: The key
158 * name has to match the function name that it corresponds to.
165 function set_message($lang, $val = '')
167 if ( ! is_array($lang))
169 $lang = array($lang => $val);
172 $this->_error_messages = array_merge($this->_error_messages, $lang);
175 // --------------------------------------------------------------------
178 * Set The Error Delimiter
180 * Permits a prefix/suffix to be added to each error message
187 function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
189 $this->_error_prefix = $prefix;
190 $this->_error_suffix = $suffix;
193 // --------------------------------------------------------------------
198 * Gets the error message associated with a particular field
201 * @param string the field name
204 function error($field = '', $prefix = '', $suffix = '')
206 if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
213 $prefix = $this->_error_prefix;
218 $suffix = $this->_error_suffix;
221 return $prefix.$this->_field_data[$field]['error'].$suffix;
224 // --------------------------------------------------------------------
229 * Returns the error messages as a string, wrapped in the error delimiters
236 function error_string($prefix = '', $suffix = '')
238 // No errrors, validation passes!
239 if (count($this->_error_array) === 0)
246 $prefix = $this->_error_prefix;
251 $suffix = $this->_error_suffix;
254 // Generate the error string
256 foreach ($this->_error_array as $val)
260 $str .= $prefix.$val.$suffix."\n";
267 // --------------------------------------------------------------------
272 * This function does all the work.
277 function run($group = '')
279 // Do we even have any data to process? Mm?
280 if (count($_POST) == 0)
285 // Does the _field_data array containing the validation rules exist?
286 // If not, we look to see if they were assigned via a config file
287 if (count($this->_field_data) == 0)
289 // No validation rules? We're done...
290 if (count($this->_config_rules) == 0)
295 // Is there a validation rule for the particular URI being accessed?
296 $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
298 if ($uri != '' AND isset($this->_config_rules[$uri]))
300 $this->set_rules($this->_config_rules[$uri]);
304 $this->set_rules($this->_config_rules);
307 // We're we able to set the rules correctly?
308 if (count($this->_field_data) == 0)
310 log_message('debug', "Unable to find validation rules");
315 // Load the language file containing error messages
316 $this->CI->lang->load('form_validation');
318 // Cycle through the rules for each field, match the
319 // corresponding $_POST item and test for errors
320 foreach ($this->_field_data as $field => $row)
322 // Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
323 // Depending on whether the field name is an array or a string will determine where we get it from.
325 if ($row['is_array'] == TRUE)
327 $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
331 if (isset($_POST[$field]) AND $_POST[$field] != "")
333 $this->_field_data[$field]['postdata'] = $_POST[$field];
337 $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
340 // Did we end up with any errors?
341 $total_errors = count($this->_error_array);
343 if ($total_errors > 0)
345 $this->_safe_form_data = TRUE;
348 // Now we need to re-set the POST data with the new, processed data
349 $this->_reset_post_array();
351 // No errors, validation passes!
352 if ($total_errors == 0)
361 // --------------------------------------------------------------------
364 * Traverse a multidimensional $_POST array index until the data is found
372 function _reduce_array($array, $keys, $i = 0)
374 if (is_array($array))
376 if (isset($keys[$i]))
378 if (isset($array[$keys[$i]]))
380 $array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
396 // --------------------------------------------------------------------
399 * Re-populate the _POST array with our finalized and processed data
404 function _reset_post_array()
406 foreach ($this->_field_data as $field => $row)
408 if ( ! is_null($row['postdata']))
410 if ($row['is_array'] == FALSE)
412 if (isset($_POST[$row['field']]))
414 $_POST[$row['field']] = $this->prep_for_form($row['postdata']);
419 // start with a reference
422 // before we assign values, make a reference to the right POST key
423 if (count($row['keys']) == 1)
425 $post_ref =& $post_ref[current($row['keys'])];
429 foreach ($row['keys'] as $val)
431 $post_ref =& $post_ref[$val];
435 if (is_array($row['postdata']))
438 foreach ($row['postdata'] as $k => $v)
440 $array[$k] = $this->prep_for_form($v);
447 $post_ref = $this->prep_for_form($row['postdata']);
454 // --------------------------------------------------------------------
457 * Executes the Validation routines
466 function _execute($row, $rules, $postdata = NULL, $cycles = 0)
468 // If the $_POST data is an array we will run a recursive call
469 if (is_array($postdata))
471 foreach ($postdata as $key => $val)
473 $this->_execute($row, $rules, $val, $cycles);
480 // --------------------------------------------------------------------
482 // If the field is blank, but NOT required, no further tests are necessary
484 if ( ! in_array('required', $rules) AND is_null($postdata))
486 // Before we bail out, does the rule contain a callback?
487 if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
490 $rules = (array('1' => $match[1]));
498 // --------------------------------------------------------------------
500 // Isset Test. Typically this rule will only apply to checkboxes.
501 if (is_null($postdata) AND $callback == FALSE)
503 if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
505 // Set the message type
506 $type = (in_array('required', $rules)) ? 'required' : 'isset';
508 if ( ! isset($this->_error_messages[$type]))
510 if (FALSE === ($line = $this->CI->lang->line($type)))
512 $line = 'The field was not set';
517 $line = $this->_error_messages[$type];
520 // Build the error message
521 $message = sprintf($line, $this->_translate_fieldname($row['label']));
523 // Save the error message
524 $this->_field_data[$row['field']]['error'] = $message;
526 if ( ! isset($this->_error_array[$row['field']]))
528 $this->_error_array[$row['field']] = $message;
535 // --------------------------------------------------------------------
537 // Cycle through each rule and run it
538 foreach ($rules As $rule)
542 // We set the $postdata variable with the current data in our master array so that
543 // each cycle of the loop is dealing with the processed data from the last cycle
544 if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
546 // We shouldn't need this safety, but just in case there isn't an array index
547 // associated with this cycle we'll bail out
548 if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
553 $postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
558 $postdata = $this->_field_data[$row['field']]['postdata'];
561 // --------------------------------------------------------------------
563 // Is the rule a callback?
565 if (substr($rule, 0, 9) == 'callback_')
567 $rule = substr($rule, 9);
571 // Strip the parameter (if exists) from the rule
572 // Rules can contain a parameter: max_length[5]
574 if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
580 // Call the function that corresponds to the rule
581 if ($callback === TRUE)
583 if ( ! method_exists($this->CI, $rule))
588 // Run the function and grab the result
589 $result = $this->CI->$rule($postdata, $param);
591 // Re-assign the result to the master data array
592 if ($_in_array == TRUE)
594 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
598 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
601 // If the field isn't required and we just processed a callback we'll move on...
602 if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
609 if ( ! method_exists($this, $rule))
611 // If our own wrapper function doesn't exist we see if a native PHP function does.
612 // Users can use any native PHP function call that has one param.
613 if (function_exists($rule))
615 $result = $rule($postdata);
617 if ($_in_array == TRUE)
619 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
623 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
630 $result = $this->$rule($postdata, $param);
632 if ($_in_array == TRUE)
634 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
638 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
642 // Did the rule test negatively? If so, grab the error.
643 if ($result === FALSE)
645 if ( ! isset($this->_error_messages[$rule]))
647 if (FALSE === ($line = $this->CI->lang->line($rule)))
649 $line = 'Unable to access an error message corresponding to your field name.';
654 $line = $this->_error_messages[$rule];
657 // Is the parameter we are inserting into the error message the name
658 // of another field? If so we need to grab its "field label"
659 if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
661 $param = $this->_field_data[$param]['label'];
664 // Build the error message
665 $message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
667 // Save the error message
668 $this->_field_data[$row['field']]['error'] = $message;
670 if ( ! isset($this->_error_array[$row['field']]))
672 $this->_error_array[$row['field']] = $message;
680 // --------------------------------------------------------------------
683 * Translate a field name
686 * @param string the field name
689 function _translate_fieldname($fieldname)
691 // Do we need to translate the field name?
692 // We look for the prefix lang: to determine this
693 if (substr($fieldname, 0, 5) == 'lang:')
696 $line = substr($fieldname, 5);
698 // Were we able to translate the field name? If not we use $line
699 if (FALSE === ($fieldname = $this->CI->lang->line($line)))
708 // --------------------------------------------------------------------
711 * Get the value from a form
713 * Permits you to repopulate a form field with the value it was submitted
714 * with, or, if that value doesn't exist, with the default
717 * @param string the field name
721 function set_value($field = '', $default = '')
723 if ( ! isset($this->_field_data[$field]))
728 return $this->_field_data[$field]['postdata'];
731 // --------------------------------------------------------------------
736 * Enables pull-down lists to be set to the value the user
737 * selected in the event of an error
744 function set_select($field = '', $value = '', $default = FALSE)
746 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
748 if ($default === TRUE AND count($this->_field_data) === 0)
750 return ' selected="selected"';
755 $field = $this->_field_data[$field]['postdata'];
757 if (is_array($field))
759 if ( ! in_array($value, $field))
766 if (($field == '' OR $value == '') OR ($field != $value))
772 return ' selected="selected"';
775 // --------------------------------------------------------------------
780 * Enables radio buttons to be set to the value the user
781 * selected in the event of an error
788 function set_radio($field = '', $value = '', $default = FALSE)
790 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
792 if ($default === TRUE AND count($this->_field_data) === 0)
794 return ' checked="checked"';
799 $field = $this->_field_data[$field]['postdata'];
801 if (is_array($field))
803 if ( ! in_array($value, $field))
810 if (($field == '' OR $value == '') OR ($field != $value))
816 return ' checked="checked"';
819 // --------------------------------------------------------------------
824 * Enables checkboxes to be set to the value the user
825 * selected in the event of an error
832 function set_checkbox($field = '', $value = '', $default = FALSE)
834 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
836 if ($default === TRUE AND count($this->_field_data) === 0)
838 return ' checked="checked"';
843 $field = $this->_field_data[$field]['postdata'];
845 if (is_array($field))
847 if ( ! in_array($value, $field))
854 if (($field == '' OR $value == '') OR ($field != $value))
860 return ' checked="checked"';
863 // --------------------------------------------------------------------
872 function required($str)
874 if ( ! is_array($str))
876 return (trim($str) == '') ? FALSE : TRUE;
880 return ( ! empty($str));
884 // --------------------------------------------------------------------
887 * Match one field to another
894 function matches($str, $field)
896 if ( ! isset($_POST[$field]))
901 $field = $_POST[$field];
903 return ($str !== $field) ? FALSE : TRUE;
906 // --------------------------------------------------------------------
916 function min_length($str, $val)
918 if (preg_match("/[^0-9]/", $val))
923 if (function_exists('mb_strlen'))
925 return (mb_strlen($str) < $val) ? FALSE : TRUE;
928 return (strlen($str) < $val) ? FALSE : TRUE;
931 // --------------------------------------------------------------------
941 function max_length($str, $val)
943 if (preg_match("/[^0-9]/", $val))
948 if (function_exists('mb_strlen'))
950 return (mb_strlen($str) > $val) ? FALSE : TRUE;
953 return (strlen($str) > $val) ? FALSE : TRUE;
956 // --------------------------------------------------------------------
966 function exact_length($str, $val)
968 if (preg_match("/[^0-9]/", $val))
973 if (function_exists('mb_strlen'))
975 return (mb_strlen($str) != $val) ? FALSE : TRUE;
978 return (strlen($str) != $val) ? FALSE : TRUE;
981 // --------------------------------------------------------------------
990 function valid_email($str)
992 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
995 // --------------------------------------------------------------------
1004 function valid_emails($str)
1006 if (strpos($str, ',') === FALSE)
1008 return $this->valid_email(trim($str));
1011 foreach(explode(',', $str) as $email)
1013 if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
1022 // --------------------------------------------------------------------
1025 * Validate IP Address
1031 function valid_ip($ip)
1033 return $this->CI->input->valid_ip($ip);
1036 // --------------------------------------------------------------------
1045 function alpha($str)
1047 return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
1050 // --------------------------------------------------------------------
1059 function alpha_numeric($str)
1061 return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
1064 // --------------------------------------------------------------------
1067 * Alpha-numeric with underscores and dashes
1073 function alpha_dash($str)
1075 return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
1078 // --------------------------------------------------------------------
1087 function numeric($str)
1089 return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
1093 // --------------------------------------------------------------------
1102 function is_numeric($str)
1104 return ( ! is_numeric($str)) ? FALSE : TRUE;
1107 // --------------------------------------------------------------------
1116 function integer($str)
1118 return (bool)preg_match( '/^[\-+]?[0-9]+$/', $str);
1121 // --------------------------------------------------------------------
1124 * Is a Natural number (0,1,2,3, etc.)
1130 function is_natural($str)
1132 return (bool)preg_match( '/^[0-9]+$/', $str);
1135 // --------------------------------------------------------------------
1138 * Is a Natural number, but not a zero (1,2,3, etc.)
1144 function is_natural_no_zero($str)
1146 if ( ! preg_match( '/^[0-9]+$/', $str))
1159 // --------------------------------------------------------------------
1164 * Tests a string for characters outside of the Base64 alphabet
1165 * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
1171 function valid_base64($str)
1173 return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
1176 // --------------------------------------------------------------------
1179 * Prep data for form
1181 * This function allows HTML to be safely shown in a form.
1182 * Special characters are converted.
1188 function prep_for_form($data = '')
1190 if (is_array($data))
1192 foreach ($data as $key => $val)
1194 $data[$key] = $this->prep_for_form($val);
1200 if ($this->_safe_form_data == FALSE OR $data === '')
1205 return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
1208 // --------------------------------------------------------------------
1217 function prep_url($str = '')
1219 if ($str == 'http://' OR $str == '')
1224 if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
1226 $str = 'http://'.$str;
1232 // --------------------------------------------------------------------
1241 function strip_image_tags($str)
1243 return $this->CI->input->strip_image_tags($str);
1246 // --------------------------------------------------------------------
1255 function xss_clean($str)
1257 return $this->CI->input->xss_clean($str);
1260 // --------------------------------------------------------------------
1263 * Convert PHP tags to entities
1269 function encode_php_tags($str)
1271 return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
1275 // END Form Validation Class
1277 /* End of file Form_validation.php */
1278 /* Location: ./system/libraries/Form_validation.php */