1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
\r
5 * An open source application development framework for PHP 4.3.2 or newer
\r
7 * @package CodeIgniter
\r
8 * @author ExpressionEngine Dev Team
\r
9 * @copyright Copyright (c) 2008, EllisLab, Inc.
\r
10 * @license http://codeigniter.com/user_guide/license.html
\r
11 * @link http://codeigniter.com
\r
12 * @since Version 1.0
\r
16 // ------------------------------------------------------------------------
\r
19 * Form Validation Class
\r
21 * @package CodeIgniter
\r
22 * @subpackage Libraries
\r
23 * @category Validation
\r
24 * @author ExpressionEngine Dev Team
\r
25 * @link http://codeigniter.com/user_guide/libraries/form_validation.html
\r
27 class CI_Form_validation {
\r
30 var $_field_data = array();
\r
31 var $_config_rules = array();
\r
32 var $_error_array = array();
\r
33 var $_error_messages = array();
\r
34 var $_error_prefix = '<p>';
\r
35 var $_error_suffix = '</p>';
\r
36 var $error_string = '';
\r
37 var $_safe_form_data = FALSE;
\r
44 function CI_Form_validation($rules = array())
\r
46 $this->CI =& get_instance();
\r
48 // Validation rules can be stored in a config file.
\r
49 $this->_config_rules = $rules;
\r
51 // Automatically load the form helper
\r
52 $this->CI->load->helper('form');
\r
54 // Set the character encoding in MB.
\r
55 if (function_exists('mb_internal_encoding'))
\r
57 mb_internal_encoding($this->CI->config->item('charset'));
\r
60 log_message('debug', "Validation Class Initialized");
\r
63 // --------------------------------------------------------------------
\r
68 * This function takes an array of field names and validation
\r
69 * rules as input, validates the info, and stores it
\r
76 function set_rules($field, $label = '', $rules = '')
\r
78 // No reason to set rules if we have no POST data
\r
79 if (count($_POST) == 0)
\r
84 // If an array was passed via the first parameter instead of indidual string
\r
85 // values we cycle through it and recursively call this function.
\r
86 if (is_array($field))
\r
88 foreach ($field as $row)
\r
90 // Houston, we have a problem...
\r
91 if ( ! isset($row['field']) OR ! isset($row['rules']))
\r
96 // If the field label wasn't passed we use the field name
\r
97 $label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
\r
100 $this->set_rules($row['field'], $label, $row['rules']);
\r
105 // No fields? Nothing to do...
\r
106 if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
\r
111 // If the field label wasn't passed we use the field name
\r
112 $label = ($label == '') ? $field : $label;
\r
114 // Is the field name an array? We test for the existence of a bracket "[" in
\r
115 // the field name to determine this. If it is an array, we break it apart
\r
116 // into its components so that we can fetch the corresponding POST data later
\r
117 if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
\r
119 // Note: Due to a bug in current() that affects some versions
\r
120 // of PHP we can not pass function call directly into it
\r
121 $x = explode('[', $field);
\r
122 $indexes[] = current($x);
\r
124 for ($i = 0; $i < count($matches['0']); $i++)
\r
126 if ($matches['1'][$i] != '')
\r
128 $indexes[] = $matches['1'][$i];
\r
136 $indexes = array();
\r
137 $is_array = FALSE;
\r
140 // Build our master array
\r
141 $this->_field_data[$field] = array(
\r
142 'field' => $field,
\r
143 'label' => $label,
\r
145 'is_array' => $is_array,
\r
146 'keys' => $indexes,
\r
147 'postdata' => NULL,
\r
152 // --------------------------------------------------------------------
\r
155 * Set Error Message
\r
157 * Lets users set their own error messages on the fly. Note: The key
\r
158 * name has to match the function name that it corresponds to.
\r
165 function set_message($lang, $val = '')
\r
167 if ( ! is_array($lang))
\r
169 $lang = array($lang => $val);
\r
172 $this->_error_messages = array_merge($this->_error_messages, $lang);
\r
175 // --------------------------------------------------------------------
\r
178 * Set The Error Delimiter
\r
180 * Permits a prefix/suffix to be added to each error message
\r
187 function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
\r
189 $this->_error_prefix = $prefix;
\r
190 $this->_error_suffix = $suffix;
\r
193 // --------------------------------------------------------------------
\r
196 * Get Error Message
\r
198 * Gets the error message associated with a particular field
\r
201 * @param string the field name
\r
204 function error($field = '', $prefix = '', $suffix = '')
\r
206 if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
\r
213 $prefix = $this->_error_prefix;
\r
218 $suffix = $this->_error_suffix;
\r
221 return $prefix.$this->_field_data[$field]['error'].$suffix;
\r
224 // --------------------------------------------------------------------
\r
229 * Returns the error messages as a string, wrapped in the error delimiters
\r
236 function error_string($prefix = '', $suffix = '')
\r
238 // No errrors, validation passes!
\r
239 if (count($this->_error_array) === 0)
\r
246 $prefix = $this->_error_prefix;
\r
251 $suffix = $this->_error_suffix;
\r
254 // Generate the error string
\r
256 foreach ($this->_error_array as $val)
\r
260 $str .= $prefix.$val.$suffix."\n";
\r
267 // --------------------------------------------------------------------
\r
270 * Run the Validator
\r
272 * This function does all the work.
\r
277 function run($group = '')
\r
279 // Do we even have any data to process? Mm?
\r
280 if (count($_POST) == 0)
\r
285 // Does the _field_data array containing the validation rules exist?
\r
286 // If not, we look to see if they were assigned via a config file
\r
287 if (count($this->_field_data) == 0)
\r
289 // No validation rules? We're done...
\r
290 if (count($this->_config_rules) == 0)
\r
295 // Is there a validation rule for the particular URI being accessed?
\r
296 $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
\r
298 if ($uri != '' AND isset($this->_config_rules[$uri]))
\r
300 $this->set_rules($this->_config_rules[$uri]);
\r
304 $this->set_rules($this->_config_rules);
\r
307 // We're we able to set the rules correctly?
\r
308 if (count($this->_field_data) == 0)
\r
310 log_message('debug', "Unable to find validation rules");
\r
315 // Load the language file containing error messages
\r
316 $this->CI->lang->load('form_validation');
\r
318 // Cycle through the rules for each field, match the
\r
319 // corresponding $_POST item and test for errors
\r
320 foreach ($this->_field_data as $field => $row)
\r
322 // Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
\r
323 // Depending on whether the field name is an array or a string will determine where we get it from.
\r
325 if ($row['is_array'] == TRUE)
\r
327 $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
\r
331 if (isset($_POST[$field]) AND $_POST[$field] != "")
\r
333 $this->_field_data[$field]['postdata'] = $_POST[$field];
\r
337 $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
\r
340 // Did we end up with any errors?
\r
341 $total_errors = count($this->_error_array);
\r
343 if ($total_errors > 0)
\r
345 $this->_safe_form_data = TRUE;
\r
348 // Now we need to re-set the POST data with the new, processed data
\r
349 $this->_reset_post_array();
\r
351 // No errors, validation passes!
\r
352 if ($total_errors == 0)
\r
357 // Validation fails
\r
361 // --------------------------------------------------------------------
\r
364 * Traverse a multidimensional $_POST array index until the data is found
\r
372 function _reduce_array($array, $keys, $i = 0)
\r
374 if (is_array($array))
\r
376 if (isset($keys[$i]))
\r
378 if (isset($array[$keys[$i]]))
\r
380 $array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
\r
396 // --------------------------------------------------------------------
\r
399 * Re-populate the _POST array with our finalized and processed data
\r
404 function _reset_post_array()
\r
406 foreach ($this->_field_data as $field => $row)
\r
408 if ( ! is_null($row['postdata']))
\r
410 if ($row['is_array'] == FALSE)
\r
412 if (isset($_POST[$row['field']]))
\r
414 $_POST[$row['field']] = $this->prep_for_form($row['postdata']);
\r
419 $post = '$_POST["';
\r
421 if (count($row['keys']) == 1)
\r
423 $post .= current($row['keys']);
\r
429 foreach ($row['keys'] as $val)
\r
433 $post .= $val.'"]';
\r
438 $post .= '["'.$val.'"]';
\r
442 if (is_array($row['postdata']))
\r
445 foreach ($row['postdata'] as $k => $v)
\r
447 $array[$k] = $this->prep_for_form($v);
\r
450 $post .= ' = $array;';
\r
454 $post .= ' = "'.$this->prep_for_form($row['postdata']).'";';
\r
463 // --------------------------------------------------------------------
\r
466 * Executes the Validation routines
\r
475 function _execute($row, $rules, $postdata = NULL, $cycles = 0)
\r
477 // If the $_POST data is an array we will run a recursive call
\r
478 if (is_array($postdata))
\r
480 foreach ($postdata as $key => $val)
\r
482 $this->_execute($row, $rules, $val, $cycles);
\r
489 // --------------------------------------------------------------------
\r
491 // If the field is blank, but NOT required, no further tests are necessary
\r
493 if ( ! in_array('required', $rules) AND is_null($postdata))
\r
495 // Before we bail out, does the rule contain a callback?
\r
496 if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
\r
499 $rules = (array('1' => $match[1]));
\r
507 // --------------------------------------------------------------------
\r
509 // Isset Test. Typically this rule will only apply to checkboxes.
\r
510 if (is_null($postdata) AND $callback == FALSE)
\r
512 if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
\r
514 // Set the message type
\r
515 $type = (in_array('required', $rules)) ? 'required' : 'isset';
\r
517 if ( ! isset($this->_error_messages[$type]))
\r
519 if (FALSE === ($line = $this->CI->lang->line($type)))
\r
521 $line = 'The field was not set';
\r
526 $line = $this->_error_messages[$type];
\r
529 // Build the error message
\r
530 $message = sprintf($line, $this->_translate_fieldname($row['label']));
\r
532 // Save the error message
\r
533 $this->_field_data[$row['field']]['error'] = $message;
\r
535 if ( ! isset($this->_error_array[$row['field']]))
\r
537 $this->_error_array[$row['field']] = $message;
\r
544 // --------------------------------------------------------------------
\r
546 // Cycle through each rule and run it
\r
547 foreach ($rules As $rule)
\r
549 $_in_array = FALSE;
\r
551 // We set the $postdata variable with the current data in our master array so that
\r
552 // each cycle of the loop is dealing with the processed data from the last cycle
\r
553 if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
\r
555 // We shouldn't need this safety, but just in case there isn't an array index
\r
556 // associated with this cycle we'll bail out
\r
557 if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
\r
562 $postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
\r
567 $postdata = $this->_field_data[$row['field']]['postdata'];
\r
570 // --------------------------------------------------------------------
\r
572 // Is the rule a callback?
\r
574 if (substr($rule, 0, 9) == 'callback_')
\r
576 $rule = substr($rule, 9);
\r
580 // Strip the parameter (if exists) from the rule
\r
581 // Rules can contain a parameter: max_length[5]
\r
583 if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
\r
586 $param = $match[2];
\r
589 // Call the function that corresponds to the rule
\r
590 if ($callback === TRUE)
\r
592 if ( ! method_exists($this->CI, $rule))
\r
597 // Run the function and grab the result
\r
598 $result = $this->CI->$rule($postdata, $param);
\r
600 // Re-assign the result to the master data array
\r
601 if ($_in_array == TRUE)
\r
603 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
\r
607 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
\r
610 // If the field isn't required and we just processed a callback we'll move on...
\r
611 if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
\r
618 if ( ! method_exists($this, $rule))
\r
620 // If our own wrapper function doesn't exist we see if a native PHP function does.
\r
621 // Users can use any native PHP function call that has one param.
\r
622 if (function_exists($rule))
\r
624 $result = $rule($postdata);
\r
626 if ($_in_array == TRUE)
\r
628 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
\r
632 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
\r
639 $result = $this->$rule($postdata, $param);
\r
641 if ($_in_array == TRUE)
\r
643 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
\r
647 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
\r
651 // Did the rule test negatively? If so, grab the error.
\r
652 if ($result === FALSE)
\r
654 if ( ! isset($this->_error_messages[$rule]))
\r
656 if (FALSE === ($line = $this->CI->lang->line($rule)))
\r
658 $line = 'Unable to access an error message corresponding to your field name.';
\r
663 $line = $this->_error_messages[$rule];
\r
666 // Build the error message
\r
667 $message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
\r
669 // Save the error message
\r
670 $this->_field_data[$row['field']]['error'] = $message;
\r
672 if ( ! isset($this->_error_array[$row['field']]))
\r
674 $this->_error_array[$row['field']] = $message;
\r
682 // --------------------------------------------------------------------
\r
685 * Translate a field name
\r
688 * @param string the field name
\r
691 function _translate_fieldname($fieldname)
\r
693 // Do we need to translate the field name?
\r
694 // We look for the prefix lang: to determine this
\r
695 if (substr($fieldname, 0, 5) == 'lang:')
\r
697 // Grab the variable
\r
698 $line = substr($fieldname, 5);
\r
700 // Were we able to translate the field name? If not we use $line
\r
701 if (FALSE === ($fieldname = $this->CI->lang->line($line)))
\r
710 // --------------------------------------------------------------------
\r
713 * Get the value from a form
\r
715 * Permits you to repopulate a form field with the value it was submitted
\r
716 * with, or, if that value doesn't exist, with the default
\r
719 * @param string the field name
\r
723 function set_value($field = '', $default = '')
\r
725 if ( ! isset($this->_field_data[$field]))
\r
730 return $this->_field_data[$field]['postdata'];
\r
733 // --------------------------------------------------------------------
\r
738 * Enables pull-down lists to be set to the value the user
\r
739 * selected in the event of an error
\r
746 function set_select($field = '', $value = '', $default = FALSE)
\r
748 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
\r
750 if ($default === TRUE AND count($this->_field_data) === 0)
\r
752 return ' selected="selected"';
\r
757 $field = $this->_field_data[$field]['postdata'];
\r
759 if (is_array($field))
\r
761 if ( ! in_array($value, $field))
\r
768 if (($field == '' OR $value == '') OR ($field != $value))
\r
774 return ' selected="selected"';
\r
777 // --------------------------------------------------------------------
\r
782 * Enables radio buttons to be set to the value the user
\r
783 * selected in the event of an error
\r
790 function set_radio($field = '', $value = '', $default = FALSE)
\r
792 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
\r
794 if ($default === TRUE AND count($this->_field_data) === 0)
\r
796 return ' checked="checked"';
\r
801 $field = $this->_field_data[$field]['postdata'];
\r
803 if (is_array($field))
\r
805 if ( ! in_array($value, $field))
\r
812 if (($field == '' OR $value == '') OR ($field != $value))
\r
818 return ' checked="checked"';
\r
821 // --------------------------------------------------------------------
\r
826 * Enables checkboxes to be set to the value the user
\r
827 * selected in the event of an error
\r
834 function set_checkbox($field = '', $value = '', $default = FALSE)
\r
836 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
\r
838 if ($default === TRUE AND count($this->_field_data) === 0)
\r
840 return ' checked="checked"';
\r
845 $field = $this->_field_data[$field]['postdata'];
\r
847 if (is_array($field))
\r
849 if ( ! in_array($value, $field))
\r
856 if (($field == '' OR $value == '') OR ($field != $value))
\r
862 return ' checked="checked"';
\r
865 // --------------------------------------------------------------------
\r
874 function required($str)
\r
876 if ( ! is_array($str))
\r
878 return (trim($str) == '') ? FALSE : TRUE;
\r
882 return ( ! empty($str));
\r
886 // --------------------------------------------------------------------
\r
889 * Match one field to another
\r
896 function matches($str, $field)
\r
898 if ( ! isset($_POST[$field]))
\r
903 $field = $_POST[$field];
\r
905 return ($str !== $field) ? FALSE : TRUE;
\r
908 // --------------------------------------------------------------------
\r
918 function min_length($str, $val)
\r
920 if (preg_match("/[^0-9]/", $val))
\r
925 if (function_exists('mb_strlen'))
\r
927 return (mb_strlen($str) < $val) ? FALSE : TRUE;
\r
930 return (strlen($str) < $val) ? FALSE : TRUE;
\r
933 // --------------------------------------------------------------------
\r
943 function max_length($str, $val)
\r
945 if (preg_match("/[^0-9]/", $val))
\r
950 if (function_exists('mb_strlen'))
\r
952 return (mb_strlen($str) > $val) ? FALSE : TRUE;
\r
955 return (strlen($str) > $val) ? FALSE : TRUE;
\r
958 // --------------------------------------------------------------------
\r
968 function exact_length($str, $val)
\r
970 if (preg_match("/[^0-9]/", $val))
\r
975 if (function_exists('mb_strlen'))
\r
977 return (mb_strlen($str) != $val) ? FALSE : TRUE;
\r
980 return (strlen($str) != $val) ? FALSE : TRUE;
\r
983 // --------------------------------------------------------------------
\r
992 function valid_email($str)
\r
994 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
\r
997 // --------------------------------------------------------------------
\r
1006 function valid_emails($str)
\r
1008 if (strpos($str, ',') === FALSE)
\r
1010 return $this->valid_email(trim($str));
\r
1013 foreach(explode(',', $str) as $email)
\r
1015 if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
\r
1024 // --------------------------------------------------------------------
\r
1027 * Validate IP Address
\r
1033 function valid_ip($ip)
\r
1035 return $this->CI->input->valid_ip($ip);
\r
1038 // --------------------------------------------------------------------
\r
1047 function alpha($str)
\r
1049 return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
\r
1052 // --------------------------------------------------------------------
\r
1061 function alpha_numeric($str)
\r
1063 return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
\r
1066 // --------------------------------------------------------------------
\r
1069 * Alpha-numeric with underscores and dashes
\r
1075 function alpha_dash($str)
\r
1077 return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
\r
1080 // --------------------------------------------------------------------
\r
1089 function numeric($str)
\r
1091 return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
\r
1095 // --------------------------------------------------------------------
\r
1104 function is_numeric($str)
\r
1106 return ( ! is_numeric($str)) ? FALSE : TRUE;
\r
1109 // --------------------------------------------------------------------
\r
1118 function integer($str)
\r
1120 return (bool)preg_match( '/^[\-+]?[0-9]+$/', $str);
\r
1123 // --------------------------------------------------------------------
\r
1126 * Is a Natural number (0,1,2,3, etc.)
\r
1132 function is_natural($str)
\r
1134 return (bool)preg_match( '/^[0-9]+$/', $str);
\r
1137 // --------------------------------------------------------------------
\r
1140 * Is a Natural number, but not a zero (1,2,3, etc.)
\r
1146 function is_natural_no_zero($str)
\r
1148 if ( ! preg_match( '/^[0-9]+$/', $str))
\r
1161 // --------------------------------------------------------------------
\r
1166 * Tests a string for characters outside of the Base64 alphabet
\r
1167 * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
\r
1173 function valid_base64($str)
\r
1175 return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
\r
1178 // --------------------------------------------------------------------
\r
1181 * Prep data for form
\r
1183 * This function allows HTML to be safely shown in a form.
\r
1184 * Special characters are converted.
\r
1190 function prep_for_form($data = '')
\r
1192 if (is_array($data))
\r
1194 foreach ($data as $key => $val)
\r
1196 $data[$key] = $this->prep_for_form($val);
\r
1202 if ($this->_safe_form_data == FALSE OR $data === '')
\r
1207 return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
\r
1210 // --------------------------------------------------------------------
\r
1219 function prep_url($str = '')
\r
1221 if ($str == 'http://' OR $str == '')
\r
1226 if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
\r
1228 $str = 'http://'.$str;
\r
1234 // --------------------------------------------------------------------
\r
1237 * Strip Image Tags
\r
1243 function strip_image_tags($str)
\r
1245 return $this->CI->input->strip_image_tags($str);
\r
1248 // --------------------------------------------------------------------
\r
1257 function xss_clean($str)
\r
1259 return $this->CI->input->xss_clean($str);
\r
1262 // --------------------------------------------------------------------
\r
1265 * Convert PHP tags to entities
\r
1271 function encode_php_tags($str)
\r
1273 return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
\r
1277 // END Form Validation Class
\r
1279 /* End of file Form_validation.php */
\r
1280 /* Location: ./system/libraries/Form_validation.php */