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
protected $_field_data = array();
31
protected $_config_rules = array();
32
protected $_error_array = array();
33
protected $_error_messages = array();
34
protected $_error_prefix = '<p>';
35
protected $_error_suffix = '</p>';
36
protected $error_string = '';
37
protected $_safe_form_data = FALSE;
42
public function __construct($rules = array())
44
$this->CI =& get_instance();
46
// Validation rules can be stored in a config file.
47
$this->_config_rules = $rules;
49
// Automatically load the form helper
50
$this->CI->load->helper('form');
52
// Set the character encoding in MB.
53
if (function_exists('mb_internal_encoding'))
55
mb_internal_encoding($this->CI->config->item('charset'));
58
log_message('debug', "Form Validation Class Initialized");
61
// --------------------------------------------------------------------
66
* This function takes an array of field names and validation
67
* rules as input, validates the info, and stores it
74
public function set_rules($field, $label = '', $rules = '')
76
// No reason to set rules if we have no POST data
77
if (count($_POST) == 0)
82
// If an array was passed via the first parameter instead of indidual string
83
// values we cycle through it and recursively call this function.
86
foreach ($field as $row)
88
// Houston, we have a problem...
89
if ( ! isset($row['field']) OR ! isset($row['rules']))
94
// If the field label wasn't passed we use the field name
95
$label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
98
$this->set_rules($row['field'], $label, $row['rules']);
103
// No fields? Nothing to do...
104
if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
109
// If the field label wasn't passed we use the field name
110
$label = ($label == '') ? $field : $label;
112
// Is the field name an array? We test for the existence of a bracket "[" in
113
// the field name to determine this. If it is an array, we break it apart
114
// into its components so that we can fetch the corresponding POST data later
115
if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
117
// Note: Due to a bug in current() that affects some versions
118
// of PHP we can not pass function call directly into it
119
$x = explode('[', $field);
120
$indexes[] = current($x);
122
for ($i = 0; $i < count($matches['0']); $i++)
124
if ($matches['1'][$i] != '')
126
$indexes[] = $matches['1'][$i];
138
// Build our master array
139
$this->_field_data[$field] = array(
143
'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
public 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);
177
// --------------------------------------------------------------------
180
* Set The Error Delimiter
182
* Permits a prefix/suffix to be added to each error message
189
public function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
191
$this->_error_prefix = $prefix;
192
$this->_error_suffix = $suffix;
197
// --------------------------------------------------------------------
202
* Gets the error message associated with a particular field
205
* @param string the field name
208
public function error($field = '', $prefix = '', $suffix = '')
210
if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
217
$prefix = $this->_error_prefix;
222
$suffix = $this->_error_suffix;
225
return $prefix.$this->_field_data[$field]['error'].$suffix;
228
// --------------------------------------------------------------------
233
* Returns the error messages as a string, wrapped in the error delimiters
240
public function error_string($prefix = '', $suffix = '')
242
// No errrors, validation passes!
243
if (count($this->_error_array) === 0)
250
$prefix = $this->_error_prefix;
255
$suffix = $this->_error_suffix;
258
// Generate the error string
260
foreach ($this->_error_array as $val)
264
$str .= $prefix.$val.$suffix."\n";
271
// --------------------------------------------------------------------
276
* This function does all the work.
281
public function run($group = '')
283
// Do we even have any data to process? Mm?
284
if (count($_POST) == 0)
289
// Does the _field_data array containing the validation rules exist?
290
// If not, we look to see if they were assigned via a config file
291
if (count($this->_field_data) == 0)
293
// No validation rules? We're done...
294
if (count($this->_config_rules) == 0)
299
// Is there a validation rule for the particular URI being accessed?
300
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
302
if ($uri != '' AND isset($this->_config_rules[$uri]))
304
$this->set_rules($this->_config_rules[$uri]);
308
$this->set_rules($this->_config_rules);
311
// We're we able to set the rules correctly?
312
if (count($this->_field_data) == 0)
314
log_message('debug', "Unable to find validation rules");
319
// Load the language file containing error messages
320
$this->CI->lang->load('form_validation');
322
// Cycle through the rules for each field, match the
323
// corresponding $_POST item and test for errors
324
foreach ($this->_field_data as $field => $row)
326
// Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
327
// Depending on whether the field name is an array or a string will determine where we get it from.
329
if ($row['is_array'] == TRUE)
331
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
335
if (isset($_POST[$field]) AND $_POST[$field] != "")
337
$this->_field_data[$field]['postdata'] = $_POST[$field];
341
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
344
// Did we end up with any errors?
345
$total_errors = count($this->_error_array);
347
if ($total_errors > 0)
349
$this->_safe_form_data = TRUE;
352
// Now we need to re-set the POST data with the new, processed data
353
$this->_reset_post_array();
355
// No errors, validation passes!
356
if ($total_errors == 0)
365
// --------------------------------------------------------------------
368
* Traverse a multidimensional $_POST array index until the data is found
376
protected function _reduce_array($array, $keys, $i = 0)
378
if (is_array($array))
380
if (isset($keys[$i]))
382
if (isset($array[$keys[$i]]))
384
$array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
400
// --------------------------------------------------------------------
403
* Re-populate the _POST array with our finalized and processed data
408
protected function _reset_post_array()
410
foreach ($this->_field_data as $field => $row)
412
if ( ! is_null($row['postdata']))
414
if ($row['is_array'] == FALSE)
416
if (isset($_POST[$row['field']]))
418
$_POST[$row['field']] = $this->prep_for_form($row['postdata']);
423
// start with a reference
426
// before we assign values, make a reference to the right POST key
427
if (count($row['keys']) == 1)
429
$post_ref =& $post_ref[current($row['keys'])];
433
foreach ($row['keys'] as $val)
435
$post_ref =& $post_ref[$val];
439
if (is_array($row['postdata']))
442
foreach ($row['postdata'] as $k => $v)
444
$array[$k] = $this->prep_for_form($v);
451
$post_ref = $this->prep_for_form($row['postdata']);
458
// --------------------------------------------------------------------
461
* Executes the Validation routines
470
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
472
// If the $_POST data is an array we will run a recursive call
473
if (is_array($postdata))
475
foreach ($postdata as $key => $val)
477
$this->_execute($row, $rules, $val, $cycles);
484
// --------------------------------------------------------------------
486
// If the field is blank, but NOT required, no further tests are necessary
488
if ( ! in_array('required', $rules) AND is_null($postdata))
490
// Before we bail out, does the rule contain a callback?
491
if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match))
494
$rules = (array('1' => $match[1]));
502
// --------------------------------------------------------------------
504
// Isset Test. Typically this rule will only apply to checkboxes.
505
if (is_null($postdata) AND $callback == FALSE)
507
if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
509
// Set the message type
510
$type = (in_array('required', $rules)) ? 'required' : 'isset';
512
if ( ! isset($this->_error_messages[$type]))
514
if (FALSE === ($line = $this->CI->lang->line($type)))
516
$line = 'The field was not set';
521
$line = $this->_error_messages[$type];
524
// Build the error message
525
$message = sprintf($line, $this->_translate_fieldname($row['label']));
527
// Save the error message
528
$this->_field_data[$row['field']]['error'] = $message;
530
if ( ! isset($this->_error_array[$row['field']]))
532
$this->_error_array[$row['field']] = $message;
539
// --------------------------------------------------------------------
541
// Cycle through each rule and run it
542
foreach ($rules As $rule)
546
// We set the $postdata variable with the current data in our master array so that
547
// each cycle of the loop is dealing with the processed data from the last cycle
548
if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
550
// We shouldn't need this safety, but just in case there isn't an array index
551
// associated with this cycle we'll bail out
552
if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
557
$postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
562
$postdata = $this->_field_data[$row['field']]['postdata'];
565
// --------------------------------------------------------------------
567
// Is the rule a callback?
569
if (substr($rule, 0, 9) == 'callback_')
571
$rule = substr($rule, 9);
575
// Strip the parameter (if exists) from the rule
576
// Rules can contain a parameter: max_length[5]
578
if (preg_match("/(.*?)\[(.*)\]/", $rule, $match))
584
// Call the function that corresponds to the rule
585
if ($callback === TRUE)
587
if ( ! method_exists($this->CI, $rule))
592
// Run the function and grab the result
593
$result = $this->CI->$rule($postdata, $param);
595
// Re-assign the result to the master data array
596
if ($_in_array == TRUE)
598
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
602
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
605
// If the field isn't required and we just processed a callback we'll move on...
606
if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
613
if ( ! method_exists($this, $rule))
615
// If our own wrapper function doesn't exist we see if a native PHP function does.
616
// Users can use any native PHP function call that has one param.
617
if (function_exists($rule))
619
$result = $rule($postdata);
621
if ($_in_array == TRUE)
623
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
627
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
632
log_message('debug', "Unable to find validation rule: ".$rule);
638
$result = $this->$rule($postdata, $param);
640
if ($_in_array == TRUE)
642
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
646
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
650
// Did the rule test negatively? If so, grab the error.
651
if ($result === FALSE)
653
if ( ! isset($this->_error_messages[$rule]))
655
if (FALSE === ($line = $this->CI->lang->line($rule)))
657
$line = 'Unable to access an error message corresponding to your field name.';
662
$line = $this->_error_messages[$rule];
665
// Is the parameter we are inserting into the error message the name
666
// of another field? If so we need to grab its "field label"
667
if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
669
$param = $this->_translate_fieldname($this->_field_data[$param]['label']);
672
// Build the error message
673
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
675
// Save the error message
676
$this->_field_data[$row['field']]['error'] = $message;
678
if ( ! isset($this->_error_array[$row['field']]))
680
$this->_error_array[$row['field']] = $message;
688
// --------------------------------------------------------------------
691
* Translate a field name
694
* @param string the field name
697
protected function _translate_fieldname($fieldname)
699
// Do we need to translate the field name?
700
// We look for the prefix lang: to determine this
701
if (substr($fieldname, 0, 5) == 'lang:')
704
$line = substr($fieldname, 5);
706
// Were we able to translate the field name? If not we use $line
707
if (FALSE === ($fieldname = $this->CI->lang->line($line)))
716
// --------------------------------------------------------------------
719
* Get the value from a form
721
* Permits you to repopulate a form field with the value it was submitted
722
* with, or, if that value doesn't exist, with the default
725
* @param string the field name
729
public function set_value($field = '', $default = '')
731
if ( ! isset($this->_field_data[$field]))
736
// If the data is an array output them one at a time.
737
// E.g: form_input('name[]', set_value('name[]');
738
if (is_array($this->_field_data[$field]['postdata']))
740
return array_shift($this->_field_data[$field]['postdata']);
743
return $this->_field_data[$field]['postdata'];
746
// --------------------------------------------------------------------
751
* Enables pull-down lists to be set to the value the user
752
* selected in the event of an error
759
public function set_select($field = '', $value = '', $default = FALSE)
761
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
763
if ($default === TRUE AND count($this->_field_data) === 0)
765
return ' selected="selected"';
770
$field = $this->_field_data[$field]['postdata'];
772
if (is_array($field))
774
if ( ! in_array($value, $field))
781
if (($field == '' OR $value == '') OR ($field != $value))
787
return ' selected="selected"';
790
// --------------------------------------------------------------------
795
* Enables radio buttons to be set to the value the user
796
* selected in the event of an error
803
public function set_radio($field = '', $value = '', $default = FALSE)
805
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
807
if ($default === TRUE AND count($this->_field_data) === 0)
809
return ' checked="checked"';
814
$field = $this->_field_data[$field]['postdata'];
816
if (is_array($field))
818
if ( ! in_array($value, $field))
825
if (($field == '' OR $value == '') OR ($field != $value))
831
return ' checked="checked"';
834
// --------------------------------------------------------------------
839
* Enables checkboxes to be set to the value the user
840
* selected in the event of an error
847
public function set_checkbox($field = '', $value = '', $default = FALSE)
849
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
851
if ($default === TRUE AND count($this->_field_data) === 0)
853
return ' checked="checked"';
858
$field = $this->_field_data[$field]['postdata'];
860
if (is_array($field))
862
if ( ! in_array($value, $field))
869
if (($field == '' OR $value == '') OR ($field != $value))
875
return ' checked="checked"';
878
// --------------------------------------------------------------------
887
public function required($str)
889
if ( ! is_array($str))
891
return (trim($str) == '') ? FALSE : TRUE;
895
return ( ! empty($str));
899
// --------------------------------------------------------------------
902
* Performs a Regular Expression match test.
909
public function regex_match($str, $regex)
911
if ( ! preg_match($regex, $str))
919
// --------------------------------------------------------------------
922
* Match one field to another
929
public function matches($str, $field)
931
if ( ! isset($_POST[$field]))
936
$field = $_POST[$field];
938
return ($str !== $field) ? FALSE : TRUE;
941
// --------------------------------------------------------------------
944
* Match one field to another
951
public function is_unique($str, $field)
953
list($table, $field)=explode('.', $field);
954
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
956
return $query->num_rows() === 0;
959
// --------------------------------------------------------------------
969
public function min_length($str, $val)
971
if (preg_match("/[^0-9]/", $val))
976
if (function_exists('mb_strlen'))
978
return (mb_strlen($str) < $val) ? FALSE : TRUE;
981
return (strlen($str) < $val) ? FALSE : TRUE;
984
// --------------------------------------------------------------------
994
public function max_length($str, $val)
996
if (preg_match("/[^0-9]/", $val))
1001
if (function_exists('mb_strlen'))
1003
return (mb_strlen($str) > $val) ? FALSE : TRUE;
1006
return (strlen($str) > $val) ? FALSE : TRUE;
1009
// --------------------------------------------------------------------
1019
public function exact_length($str, $val)
1021
if (preg_match("/[^0-9]/", $val))
1026
if (function_exists('mb_strlen'))
1028
return (mb_strlen($str) != $val) ? FALSE : TRUE;
1031
return (strlen($str) != $val) ? FALSE : TRUE;
1034
// --------------------------------------------------------------------
1043
public function valid_email($str)
1045
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
1048
// --------------------------------------------------------------------
1057
public function valid_emails($str)
1059
if (strpos($str, ',') === FALSE)
1061
return $this->valid_email(trim($str));
1064
foreach (explode(',', $str) as $email)
1066
if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
1075
// --------------------------------------------------------------------
1078
* Validate IP Address
1082
* @param string "ipv4" or "ipv6" to validate a specific ip format
1085
public function valid_ip($ip, $which = '')
1087
return $this->CI->input->valid_ip($ip, $which);
1090
// --------------------------------------------------------------------
1099
public function alpha($str)
1101
return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
1104
// --------------------------------------------------------------------
1113
public function alpha_numeric($str)
1115
return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
1118
// --------------------------------------------------------------------
1121
* Alpha-numeric with underscores and dashes
1127
public function alpha_dash($str)
1129
return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
1132
// --------------------------------------------------------------------
1141
public function numeric($str)
1143
return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
1147
// --------------------------------------------------------------------
1156
public function is_numeric($str)
1158
return ( ! is_numeric($str)) ? FALSE : TRUE;
1161
// --------------------------------------------------------------------
1170
public function integer($str)
1172
return (bool) preg_match('/^[\-+]?[0-9]+$/', $str);
1175
// --------------------------------------------------------------------
1184
public function decimal($str)
1186
return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str);
1189
// --------------------------------------------------------------------
1198
public function greater_than($str, $min)
1200
if ( ! is_numeric($str))
1207
// --------------------------------------------------------------------
1216
public function less_than($str, $max)
1218
if ( ! is_numeric($str))
1225
// --------------------------------------------------------------------
1228
* Is a Natural number (0,1,2,3, etc.)
1234
public function is_natural($str)
1236
return (bool) preg_match( '/^[0-9]+$/', $str);
1239
// --------------------------------------------------------------------
1242
* Is a Natural number, but not a zero (1,2,3, etc.)
1248
public function is_natural_no_zero($str)
1250
if ( ! preg_match( '/^[0-9]+$/', $str))
1263
// --------------------------------------------------------------------
1268
* Tests a string for characters outside of the Base64 alphabet
1269
* as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
1275
public function valid_base64($str)
1277
return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
1280
// --------------------------------------------------------------------
1283
* Prep data for form
1285
* This function allows HTML to be safely shown in a form.
1286
* Special characters are converted.
1292
public function prep_for_form($data = '')
1294
if (is_array($data))
1296
foreach ($data as $key => $val)
1298
$data[$key] = $this->prep_for_form($val);
1304
if ($this->_safe_form_data == FALSE OR $data === '')
1309
return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
1312
// --------------------------------------------------------------------
1321
public function prep_url($str = '')
1323
if ($str == 'http://' OR $str == '')
1328
if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
1330
$str = 'http://'.$str;
1336
// --------------------------------------------------------------------
1345
public function strip_image_tags($str)
1347
return $this->CI->input->strip_image_tags($str);
1350
// --------------------------------------------------------------------
1359
public function xss_clean($str)
1361
return $this->CI->security->xss_clean($str);
1364
// --------------------------------------------------------------------
1367
* Convert PHP tags to entities
1373
public function encode_php_tags($str)
1375
return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
1379
// END Form Validation Class
1381
/* End of file Form_validation.php */
1382
/* Location: ./system/libraries/Form_validation.php */