Passed
Push — 1.0.0-dev ( 46666d...4e6922 )
by nguereza
02:47
created

FormValidation::_validateValidEmail()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
nc 3
nop 3
dl 0
loc 7
rs 10
c 3
b 0
f 0
1
<?php
2
    defined('ROOT_PATH') || exit('Access denied');
3
    /**
4
     * TNH Framework
5
     *
6
     * A simple PHP framework using HMVC architecture
7
     *
8
     * This content is released under the GNU GPL License (GPL)
9
     *
10
     * Copyright (C) 2017 Tony NGUEREZA
11
     *
12
     * This program is free software; you can redistribute it and/or
13
     * modify it under the terms of the GNU General Public License
14
     * as published by the Free Software Foundation; either version 3
15
     * of the License, or (at your option) any later version.
16
     *
17
     * This program is distributed in the hope that it will be useful,
18
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
     * GNU General Public License for more details.
21
     *
22
     * You should have received a copy of the GNU General Public License
23
     * along with this program; if not, write to the Free Software
24
     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
     */
26
27
28
        class FormValidation extends BaseClass {
29
		 
30
        /**
31
         * The form validation status
32
         * @var boolean
33
         */
34
        protected $_success = false;
35
36
        /**
37
         * The list of errors messages
38
         * @var array
39
         */
40
        protected $_errorsMessages = array();
41
        
42
        // Array of rule sets, fieldName => PIPE seperated ruleString
43
        protected $_rules = array();
44
        
45
        // Array of errors, niceName => Error Message
46
        protected $_errors = array();
47
        
48
        // Array of post Key => Nice name labels
49
        protected $_labels = array();
50
        
51
        /**
52
         * The errors delimiters
53
         * @var array
54
         */
55
        protected $_allErrorsDelimiter = array('<div class="error">', '</div>');
56
57
        /**
58
         * The each error delimiter
59
         * @var array
60
         */
61
        protected $_eachErrorDelimiter = array('<p class="error">', '</p>');
62
        
63
        /**
64
         * Indicated if need force the validation to be failed
65
         * @var boolean
66
         */
67
        protected $_forceFail = false;
68
69
        /**
70
         * The list of the error messages overrides by the original
71
         * @var array
72
         */
73
        protected $_errorMsgOverrides = array();
74
75
        /**
76
         * The data to be validated, the default is to use $_POST
77
         * @var array
78
         */
79
        private $data = array();
80
81
82
        /**
83
         * The database instance
84
         * @var object
85
         */
86
        private $databaseInstance = null;
87
88
        /**
89
         * Set all errors and rule sets empty, and sets success to false.
90
         *
91
         * @return void
92
         */
93
        public function __construct() {
94
            parent::__construct();
95
           
96
            //Load form validation language message
97
            Loader::lang('form_validation');
98
            $obj = & get_instance();
99
            $this->_errorsMessages = array(
100
                        'required'         => $obj->lang->get('fv_required'),
101
                        'min_length'       => $obj->lang->get('fv_min_length'),
102
                        'max_length'       => $obj->lang->get('fv_max_length'),
103
                        'exact_length'     => $obj->lang->get('fv_exact_length'),
104
                        'less_than'        => $obj->lang->get('fv_less_than'),
105
                        'greater_than'     => $obj->lang->get('fv_greater_than'),
106
                        'matches'          => $obj->lang->get('fv_matches'),
107
                        'valid_email'      => $obj->lang->get('fv_valid_email'),
108
                        'not_equal'        => array(
109
                                                'post:key' => $obj->lang->get('fv_not_equal_post_key'),
110
                                                'string'   => $obj->lang->get('fv_not_equal_string')
111
                                            ),
112
                        'depends'          => $obj->lang->get('fv_depends'),
113
                        'is_unique'        => $obj->lang->get('fv_is_unique'),
114
                        'is_unique_update' => $obj->lang->get('fv_is_unique_update'),
115
                        'exists'           => $obj->lang->get('fv_exists'),
116
                        'regex'            => $obj->lang->get('fv_regex'),
117
                        'in_list'          => $obj->lang->get('fv_in_list'),
118
                        'numeric'          => $obj->lang->get('fv_numeric'),
119
                        'callback'         => $obj->lang->get('fv_callback'),
120
                    );
121
            $this->_resetValidation();
122
            $this->setData($obj->request->post(null));
123
        }
124
125
        /**
126
         * Set the database instance
127
         * @param object $database the database instance
128
         */
129
        public function setDatabase(Database $database) {
130
            $this->databaseInstance = $database;
131
            return $this;
132
        }
133
134
        /**
135
         * Get the database instance
136
         * @return object the database instance
137
         */
138
        public function getDatabase() {
139
            return $this->databaseInstance;
140
        }
141
142
        /**
143
         * Reset the form validation instance
144
         */
145
        protected function _resetValidation() {
146
            $this->_rules                = array();
147
            $this->_labels               = array();
148
            $this->_errorMsgOverrides = array();
149
            $this->_errors               = array();
150
            $this->_success              = false;
151
            $this->_forceFail            = false;
152
            $this->data                  = array();
153
        }
154
155
        /**
156
         * Set the form validation data
157
         * @param array $data the values to be validated
158
         *
159
         * @return FormValidation Current instance of object.
160
         */
161
        public function setData(array $data) {
162
            $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
163
            $this->data = $data;
164
            return $this;
165
        }
166
167
        /**
168
         * Get the form validation data
169
         * @return array the form validation data to be validated
170
         */
171
        public function getData() {
172
            return $this->data;
173
        }
174
175
        /**
176
         * Get the validation function name to validate a rule
177
         *
178
         * @return string the function name
179
         */
180
        protected function _toCallCase($funcName, $prefix = '_validate') {
181
            $funcName = strtolower($funcName);
182
            $finalFuncName = $prefix;
183
            foreach (explode('_', $funcName) as $funcNamePart) {
184
                $finalFuncName .= strtoupper($funcNamePart[0]) . substr($funcNamePart, 1);
185
            }
186
            return $finalFuncName;
187
        }
188
189
        /**
190
         * Returns the boolean of the data status success. It goes by the simple
191
         *
192
         * @return boolean Whether or not the data validation has succeeded
193
         */
194
        public function isSuccess() {
195
            return $this->_success;
196
        }
197
198
        /**
199
         * Checks if the request method is POST or the Data to be validated is set
200
         *
201
         * @return boolean Whether or not the form has been submitted or the data is available for validation.
202
         */
203
        public function canDoValidation() {
204
            return get_instance()->request->method() === 'POST' || !empty($this->data);
205
        }
206
207
        /**
208
         * Runs _run once POST data has been submitted or data is set manually.
209
         *
210
         * @return boolean
211
         */
212
        public function run() {
213
            if ($this->canDoValidation()) {
214
                $this->logger->info('The data to validate are listed below: ' . stringfy_vars($this->getData()));
215
                $this->_run();
216
            }
217
            return $this->isSuccess();
218
        }
219
220
        /**
221
         * Validate the CSRF 
222
         * @return boolean
223
         */
224
        protected function validateCSRF() {
225
            if (get_instance()->request->method() == 'POST') {
226
                $this->logger->debug('Check if CSRF is enabled in configuration');
227
                //first check for CSRF
228
                if (get_config('csrf_enable', false) && !Security::validateCSRF()) {
229
                    show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
230
                    return false;
231
                } else {
232
                    $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
233
                }
234
            }
235
            return true;
236
        }
237
        
238
        /**
239
         * Takes and trims each data, if it has any rules, we parse the rule string and run
240
         * each rule against the data value. Sets _success to true if there are no errors
241
         * afterwards.
242
         */
243
        protected function _run() {
244
            //validate CSRF
245
            if (!$this->validateCSRF()) {
246
                return;
247
            }
248
            /////////////////////////////////////////////
249
            $this->_forceFail = false;
250
251
            foreach ($this->getData() as $inputName => $inputVal) {
252
                if (is_array($this->data[$inputName])) {
253
                    $this->data[$inputName] = array_map('trim', $this->data[$inputName]);
254
                } else {
255
                    $this->data[$inputName] = trim($this->data[$inputName]);
256
                }
257
258
                if (array_key_exists($inputName, $this->_rules)) {
259
                    foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
260
                        $this->_validateRule($inputName, $this->data[$inputName], $eachRule);
261
                    }
262
                }
263
            }
264
            $this->_success = empty($this->_errors) && $this->_forceFail === false;
265
        }
266
267
        /**
268
         * Adds a rule to a form data validation field.
269
         *
270
         * @param string $inputField Name of the field or the data key to add a rule to
271
         * @param string $ruleSets PIPE seperated string of rules
272
         *
273
         * @return FormValidation Current instance of object.
274
         */
275
        public function setRule($inputField, $inputLabel, $ruleSets) {
276
            $this->_rules[$inputField] = $ruleSets;
277
            $this->_labels[$inputField] = $inputLabel;
278
            $this->logger->info('Set the field rule: name [' . $inputField . '], label [' . $inputLabel . '], rules [' . $ruleSets . ']');
279
            return $this;
280
        }
281
282
        /**
283
         * Takes an array of rules and uses setRule() to set them, accepts an array
284
         * of rule names rather than a pipe-delimited string as well.
285
         * @param array $ruleSets
286
         *
287
         * @return FormValidation Current instance of object.
288
         */
289
        public function setRules(array $ruleSets) {
290
            foreach ($ruleSets as $ruleSet) {
291
                $pipeDelimitedRules = null;
292
                if (is_array($ruleSet['rules'])) {
293
                    $pipeDelimitedRules = implode('|', $ruleSet['rules']);
294
                } else {
295
                    $pipeDelimitedRules = $ruleSet['rules'];
296
                }
297
                $this->setRule($ruleSet['name'], $ruleSet['label'], $pipeDelimitedRules);
298
            }
299
            return $this;
300
        }
301
302
        /**
303
         * This method creates the global errors delimiter, each argument occurs once, at the beginning, and
304
         * end of the errors block respectively.
305
         *
306
         * @param string $start Before block of errors gets displayed, HTML allowed.
307
         * @param string $end After the block of errors gets displayed, HTML allowed.
308
         *
309
         * @return FormValidation Current instance of object.
310
         */
311
        public function setErrorsDelimiter($start, $end) {
312
            $this->_allErrorsDelimiter[0] = $start;
313
            $this->_allErrorsDelimiter[1] = $end;
314
            return $this;
315
        }
316
317
        /**
318
         * This is the individual error delimiter, each argument occurs once before and after
319
         * each individual error listed.
320
         *
321
         * @param string $start Displayed before each error.
322
         * @param string $end Displayed after each error.
323
         * 
324
         * @return FormValidation Current instance of object.
325
         */
326
        public function setErrorDelimiter($start, $end) {
327
            $this->_eachErrorDelimiter[0] = $start;
328
            $this->_eachErrorDelimiter[1] = $end;
329
            return $this;
330
        }
331
332
        /**
333
         * Get the each errors delimiters
334
         *
335
         * @return array
336
         */
337
        public function getErrorDelimiter() {
338
            return $this->_eachErrorDelimiter;
339
        }
340
341
        /**
342
         * Get the all errors delimiters
343
         *
344
         * @return array
345
         */
346
        public function getErrorsDelimiter() {
347
            return $this->_allErrorsDelimiter;
348
        }
349
350
        /**
351
         * This sets a custom error message that can override the default error phrase provided
352
         * by FormValidation, it can be used in the format of setMessage('rule', 'error phrase')
353
         * which will globally change the error phrase of that rule, or in the format of:
354
         * setMessage('rule', 'fieldname', 'error phrase') - which will only change the error phrase for
355
         * that rule, applied on that field.
356
         *
357
         * @return boolean True on success, false on failure.
358
         */
359
        public function setMessage() {
360
            $numArgs = func_num_args();
361
            if ($numArgs == 2) {
362
               foreach ($this->post(null) as $key => $val) {
363
                    $this->_errorMsgOverrides[$key][func_get_arg(0)] = func_get_arg(1);
364
                }
365
                return true;
366
            } else if ($numArgs == 3) {
367
                $this->_errorMsgOverrides[func_get_arg(1)][func_get_arg(0)] = func_get_arg(2);
368
                 return true;
369
            }
370
            return false;
371
        }
372
373
        /**
374
         * Adds a custom error message in the errorSet array, that will
375
         * forcibly display it.
376
         *
377
         * @param string $inputName The form input name or data key
378
         * @param string $errorMessage Error to display
379
         *
380
         * @return formValidation Current instance of the object
381
         */
382
        public function setCustomError($inputName, $errorMessage) {
383
            $errorMessage = str_replace('%1', $this->_labels[$inputName], $errorMessage);
384
            $this->_errors[$inputName] = $errorMessage;
385
            return $this;
386
        }
387
388
        /**
389
         * Allows for an accesor to any/all post values, if a value of null is passed as the key, it
390
         * will recursively find all keys/values of the $_POST array or data array. It also automatically trims
391
         * all values.
392
         *
393
         * @param string $key Key of $this->data to be found, pass null for all Key => Val pairs.
394
         * @param boolean $trim Defaults to true, trims all $this->data values.
395
         * @return string|array Array of post or data values if null is passed as key, string if only one key is desired.
396
         */
397
        public function post($key = null, $trim = true) {
398
            $returnValue = null;
399
            if (is_null($key)) {
400
                $returnValue = array();
401
                foreach ($this->data  as $key => $val) {
402
                    $returnValue[$key] = $this->post($key, $trim);
403
                }
404
            } else if (array_key_exists($key, $this->data)) {
405
                $returnValue = $this->data[$key];
406
                if ($trim) {
407
                    if (is_array($this->data[$key])) {
408
                       $returnValue = array_map('trim', $this->data[$key]);
409
                    } else {
410
                        $returnValue = trim($this->data[$key]);
411
                    }
412
                }
413
            }
414
            return $returnValue;
415
        }
416
417
        /**
418
         * Gets all errors from errorSet and displays them, can be echo out from the
419
         * function or just returned.
420
         *
421
         * @param boolean $limit number of error to display or return
422
         * @param boolean $echo Whether or not the values are to be returned or displayed
423
         *
424
         * @return string|void Errors formatted for output
425
         */
426
        public function displayErrors($limit = null, $echo = true) {
427
            list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
428
            list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
429
            $errorOutput = $errorsStart;
430
            $i = 0;
431
            if (!empty($this->_errors)) {
432
                foreach ($this->_errors as $fieldName => $error) {
433
                    if ($i === $limit) { 
434
                        break; 
435
                    }
436
                    $errorOutput .= $errorStart;
437
                    $errorOutput .= $error;
438
                    $errorOutput .= $errorEnd;
439
                    $i++;
440
                }
441
            }
442
            $errorOutput .= $errorsEnd;
443
            if (!$echo) {
444
                return $errorOutput;
445
            }
446
            echo $errorOutput;
447
        }
448
449
        /**
450
         * Returns raw array of errors in no format instead of displaying them
451
         * formatted.
452
         *
453
         * @return array
454
         */
455
        public function returnErrors() {
456
            return $this->_errors;
457
        }
458
459
        /**
460
         * Breaks up a PIPE seperated string of rules, and puts them into an array.
461
         *
462
         * @param string $ruleString String to be parsed.
463
         *
464
         * @return array Array of each value in original string.
465
         */
466
        protected function _parseRuleString($ruleString) {
467
            $ruleSets = array();
468
            /*
469
            //////////////// hack for regex rule that can contain "|"
470
            */
471
            if (strpos($ruleString, 'regex') !== false) {
472
                $regexRule = array();
473
                $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
474
                preg_match($rule, $ruleString, $regexRule);
475
                $ruleStringTemp = preg_replace($rule, '', $ruleString);
476
                if (!empty($regexRule[0])) {
477
                    $ruleSets[] = $regexRule[0];
478
                }
479
                 $ruleStringRegex = explode('|', $ruleStringTemp);
480
                foreach ($ruleStringRegex as $rule) {
481
                    $rule = trim($rule);
482
                    if ($rule) {
483
                        $ruleSets[] = $rule;
484
                    }
485
                }
486
                 
487
            }
488
            /***********************************/
489
            else {
490
                if (strpos($ruleString, '|') !== FALSE) {
491
                    $ruleSets = explode('|', $ruleString);
492
                } else {
493
                    $ruleSets[] = $ruleString;
494
                }
495
            }
496
            return $ruleSets;
497
        }
498
499
        /**
500
         * Returns whether or not a field obtains the rule "required".
501
         *
502
         * @param string $fieldName Field to check if required.
503
         *
504
         * @return boolean Whether or not the field is required.
505
         */
506
        protected function _fieldIsRequired($fieldName) {
507
            $rules = $this->_parseRuleString($this->_rules[$fieldName]);
508
            return (in_array('required', $rules));
509
        }
510
511
        /**
512
         * Takes a data input name, it's value, and the rule it's being validated against (ex: max_length[16])
513
         * and adds an error to the errorSet if it fails validation of the rule.
514
         *
515
         * @param string $inputName Name or key of the validation data
516
         * @param string $inputVal Value of the validation data
517
         * @param string $ruleName Rule to be validated against, including args (exact_length[5])
518
         * @return void
519
         */
520
        protected function _validateRule($inputName, $inputVal, $ruleName) {
521
            if (is_array($inputVal)) {
0 ignored issues
show
introduced by
The condition is_array($inputVal) is always false.
Loading history...
522
                foreach ($inputVal as $value) {
523
                    $this->_validateRule($inputName, $value, $ruleName);
524
                }
525
                return;
526
            }
527
            $this->logger->debug('Rule validation of field [' . $inputName . '], value [' . $inputVal . '], rule [' . $ruleName . ']');
528
            // Array to store args
529
            $ruleArgs = array();
530
531
            preg_match('/\[(.*)\]/', $ruleName, $ruleArgs);
532
533
            // Get the rule arguments, realRule is just the base rule name
534
            // Like min_length instead of min_length[3]
535
            $ruleName = preg_replace('/\[(.*)\]/', '', $ruleName);
536
            
537
            if (method_exists($this, $this->_toCallCase($ruleName))) {
538
                $methodToCall = $this->_toCallCase($ruleName);
539
                call_user_func(array($this, $methodToCall), $inputName, $ruleName, $ruleArgs);
540
            }
541
            return;
542
        }
543
544
        /**
545
         * Set error for the given field or key
546
         *
547
         * @param string $inputName the input or key name
548
         * @param string $ruleName the rule name
549
         * @param array|string $replacements
550
         */
551
        protected function _setError($inputName, $ruleName, $replacements = array()) {
552
            $rulePhraseKeyParts = explode(',', $ruleName);
553
            $rulePhrase = null;
554
            foreach ($rulePhraseKeyParts as $rulePhraseKeyPart) {
555
                if (array_key_exists($rulePhraseKeyPart, $this->_errorsMessages)) {
556
                    $rulePhrase = $this->_errorsMessages[$rulePhraseKeyPart];
557
                } else {
558
                    $rulePhrase = $rulePhrase[$rulePhraseKeyPart];
559
                }
560
            }
561
            // Any overrides?
562
            if (array_key_exists($inputName, $this->_errorMsgOverrides) && array_key_exists($ruleName, $this->_errorMsgOverrides[$inputName])) {
563
                $rulePhrase = $this->_errorMsgOverrides[$inputName][$ruleName];
564
            }
565
            // Type cast to array in case it's a string
566
            $replacements = (array) $replacements;
567
            $replacementCount = count($replacements);
568
            for ($i = 1; $i <= $replacementCount; $i++) {
569
                $key = $i - 1;
570
                $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
571
            }
572
            if (!array_key_exists($inputName, $this->_errors)) {
573
                $this->_errors[$inputName] = $rulePhrase;
574
            }
575
        }
576
577
        /**
578
         * Used to run a callback for the callback rule, as well as pass in a default
579
         * argument of the data value. For example the username field having a rule:
580
         * callback[userExists] will call the function userExists() with parameter data[username].
581
         *
582
         * @param type $inputArg
583
         * @param string $callbackFunc
584
         *
585
         * @return boolean
586
         */
587
        protected function _runCallback($inputArg, $callbackFunc) {
588
            return call_user_func($callbackFunc, $inputArg);
589
        }
590
591
        /**
592
         * Gets a specific label of a specific field input name.
593
         *
594
         * @param string $inputName
595
         *
596
         * @return string
597
         */
598
        protected function _getLabel($inputName) {
599
            return (array_key_exists($inputName, $this->_labels)) ? $this->_labels[$inputName] : $inputName;
600
        }
601
		
602
        /**
603
         * Peform validation for the rule "required"
604
         * @param  string $inputName the form field or data key name used
605
         * @param  string $ruleName  the rule name for this validation ("required")
606
         * @param  array  $ruleArgs  the rules argument
607
         */
608
        protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
609
            $inputVal = $this->post($inputName);
610
            if ($inputVal == '') {
611
                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
612
            }
613
        }
614
615
        /**
616
         * Perform validation for the honey pot so means for the validation to be failed
617
         * @param  string $inputName the form field or data key name used
618
         * @param  string $ruleName  the rule name for this validation
619
         * @param  array  $ruleArgs  the rules argument
620
         */
621
        protected function _validateHoneypot($inputName, $ruleName, array $ruleArgs) {
622
            if ($this->data[$inputName] != '') {
623
                $this->_forceFail = true;
624
            }
625
        }
626
627
        /**
628
         * Peform validation for the rule "callback"
629
         * @param  string $inputName the form field or data key name used
630
         * @param  string $ruleName  the rule name for this validation ("callback")
631
         * @param  array  $ruleArgs  the rules argument
632
         */
633
        protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
634
            if (function_exists($ruleArgs[1]) && array_key_exists($inputName, $this->data)) {
635
                $result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
636
                if (!$result) {
637
                    $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
638
                }
639
            }
640
        }
641
642
        /**
643
         * Peform validation for the rule "depends"
644
         * @param  string $inputName the form field or data key name used
645
         * @param  string $ruleName  the rule name for this validation ("depends")
646
         * @param  array  $ruleArgs  the rules argument
647
         */
648
        protected function _validateDepends($inputName, $ruleName, array $ruleArgs) {
649
            if (array_key_exists($ruleArgs[1], $this->_errors)) {
650
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
651
            }
652
        }
653
654
        /**
655
         * Peform validation for the rule "not_equal"
656
         * @param  string $inputName the form field or data key name used
657
         * @param  string $ruleName  the rule name for this validation ("not_equal")
658
         * @param  array  $ruleArgs  the rules argument
659
         */
660
        protected function _validateNotEqual($inputName, $ruleName, array $ruleArgs) {
661
            $canNotEqual = explode(',', $ruleArgs[1]);
662
            foreach ($canNotEqual as $doNotEqual) {
663
                $inputVal = $this->post($inputName);
664
                if (preg_match('/post:(.*)/', $doNotEqual)) {
665
                    if ($inputVal == $this->data[str_replace('post:', '', $doNotEqual)]) {
666
                        $this->_setError($inputName, $ruleName . ',post:key', array($this->_getLabel($inputName), $this->_getLabel(str_replace('post:', '', $doNotEqual))));
667
                        continue;
668
                    }
669
                } else {
670
                    if ($inputVal == $doNotEqual) {
671
                        $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
672
                        continue;
673
                    }
674
                }
675
            }
676
        }
677
678
        /**
679
         * Peform validation for the rule "matches"
680
         * @param  string $inputName the form field or data key name used
681
         * @param  string $ruleName  the rule name for this validation ("matches")
682
         * @param  array  $ruleArgs  the rules argument
683
         */
684
        protected function _validateMatches($inputName, $ruleName, array $ruleArgs) {
685
            $inputVal = $this->post($inputName);
686
            if ($inputVal != $this->data[$ruleArgs[1]]) {
687
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
688
            }
689
        }
690
691
        /**
692
         * Peform validation for the rule "valid_email"
693
         * @param  string $inputName the form field or data key name used
694
         * @param  string $ruleName  the rule name for this validation ("valid_email")
695
         * @param  array  $ruleArgs  the rules argument
696
         */
697
        protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
698
            $inputVal = $this->post($inputName);
699
            if (!preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
0 ignored issues
show
Bug introduced by
It seems like $inputVal can also be of type array; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

699
            if (!preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", /** @scrutinizer ignore-type */ $inputVal)) {
Loading history...
700
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
701
                    return;
702
                }
703
                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
704
            }
705
        }
706
707
        /**
708
         * Peform validation for the rule "exact_length"
709
         * @param  string $inputName the form field or data key name used
710
         * @param  string $ruleName  the rule name for this validation ("exact_length")
711
         * @param  array  $ruleArgs  the rules argument
712
         */
713
        protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
714
            $inputVal = $this->post($inputName);
715
            if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
0 ignored issues
show
Bug introduced by
It seems like $inputVal can also be of type array; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

715
            if (strlen(/** @scrutinizer ignore-type */ $inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
Loading history...
716
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
717
                    return;
718
                }
719
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
720
            }
721
        }
722
723
        /**
724
         * Peform validation for the rule "max_length"
725
         * @param  string $inputName the form field or data key name used
726
         * @param  string $ruleName  the rule name for this validation ("max_length")
727
         * @param  array  $ruleArgs  the rules argument
728
         */
729
        protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
730
            $inputVal = $this->post($inputName);
731
            if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
0 ignored issues
show
Bug introduced by
It seems like $inputVal can also be of type array; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

731
            if (strlen(/** @scrutinizer ignore-type */ $inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
Loading history...
732
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
733
            }
734
        }
735
736
        /**
737
         * Peform validation for the rule "min_length"
738
         * @param  string $inputName the form field or data key name used
739
         * @param  string $ruleName  the rule name for this validation ("min_length")
740
         * @param  array  $ruleArgs  the rules argument
741
         */
742
        protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
743
            $inputVal = $this->post($inputName);
744
            if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
0 ignored issues
show
Bug introduced by
It seems like $inputVal can also be of type array; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

744
            if (strlen(/** @scrutinizer ignore-type */ $inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
Loading history...
745
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
746
            }
747
        }
748
    	
749
        /**
750
         * Peform validation for the rule "less_than"
751
         * @param  string $inputName the form field or data key name used
752
         * @param  string $ruleName  the rule name for this validation ("less_than")
753
         * @param  array  $ruleArgs  the rules argument
754
         */
755
        protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
756
            $inputVal = $this->post($inputName);
757
            if ($inputVal >= $ruleArgs[1]) { 
758
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
759
            }
760
        }
761
    	
762
        /**
763
         * Peform validation for the rule "greater_than"
764
         * @param  string $inputName the form field or data key name used
765
         * @param  string $ruleName  the rule name for this validation ("greater_than")
766
         * @param  array  $ruleArgs  the rules argument
767
         */
768
        protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
769
            $inputVal = $this->post($inputName);
770
            if ($inputVal <= $ruleArgs[1]) {
771
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
772
            }
773
        }
774
    	
775
        /**
776
         * Peform validation for the rule "numeric"
777
         * @param  string $inputName the form field or data key name used
778
         * @param  string $ruleName  the rule name for this validation ("numeric")
779
         * @param  array  $ruleArgs  the rules argument
780
         */
781
        protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
782
            $inputVal = $this->post($inputName);
783
            if (!is_numeric($inputVal)) {
784
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
785
                    return;
786
                }
787
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
788
            }
789
        }
790
791
        /**
792
         * Peform validation for the rule "in_list"
793
         * @param  string $inputName the form field or data key name used
794
         * @param  string $ruleName  the rule name for this validation ("in_list")
795
         * @param  array  $ruleArgs  the rules argument
796
         */
797
        protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
798
            $inputVal = $this->post($inputName);
799
            $list = explode(',', $ruleArgs[1]);
800
            $list = array_map('trim', $list);
801
            if (!in_array($inputVal, $list)) {
802
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
803
                    return;
804
                }
805
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
806
            }
807
        }
808
809
        /**
810
         * Peform validation for the rule "regex"
811
         * @param  string $inputName the form field or data key name used
812
         * @param  string $ruleName  the rule name for this validation ("regex")
813
         * @param  array  $ruleArgs  the rules argument
814
         */
815
        protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
816
            $inputVal = $this->post($inputName);
817
            $regex = $ruleArgs[1];
818
            if (!preg_match($regex, $inputVal)) {
0 ignored issues
show
Bug introduced by
It seems like $inputVal can also be of type array; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

818
            if (!preg_match($regex, /** @scrutinizer ignore-type */ $inputVal)) {
Loading history...
819
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
820
                    return;
821
                }
822
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
823
            }
824
        }
825
		
826
        /**
827
         * Peform validation for the rule "exists"
828
         * @param  string $inputName the form field or data key name used
829
         * @param  string $ruleName  the rule name for this validation ("exists")
830
         * @param  array  $ruleArgs  the rules argument
831
         */
832
        protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
833
            $inputVal = $this->post($inputName);
834
            if (!is_object($this->databaseInstance)) {
835
                $obj = & get_instance();
836
                if (isset($obj->database)) {
837
                    $this->databaseInstance = $obj->database;
838
                } 
839
            }
840
            list($table, $column) = explode('.', $ruleArgs[1]);
841
            $this->databaseInstance->getQueryBuilder()->from($table)
842
                                                        ->where($column, $inputVal);
843
            $this->databaseInstance->get();
844
            if ($this->databaseInstance->numRows() <= 0) {
845
                if (!$this->_fieldIsRequired($inputName) && strlen($this->data[$inputName]) <= 0) {
846
                    return;
847
                }
848
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
849
            }
850
        }
851
852
        /**
853
         * Peform validation for the rule "is_unique"
854
         * @param  string $inputName the form field or data key name used
855
         * @param  string $ruleName  the rule name for this validation ("is_unique")
856
         * @param  array  $ruleArgs  the rules argument
857
         */
858
        protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
859
            $inputVal = $this->post($inputName);
860
            if (!is_object($this->databaseInstance)) {
861
                $obj = & get_instance();
862
                if (isset($obj->database)) {
863
                    $this->databaseInstance = $obj->database;
864
                } 
865
            }
866
            list($table, $column) = explode('.', $ruleArgs[1]);
867
            $this->databaseInstance->getQueryBuilder()->from($table)
868
                                                        ->where($column, $inputVal);
869
            $this->databaseInstance->get();
870
            if ($this->databaseInstance->numRows() > 0) {
871
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
872
            }
873
        }
874
    	
875
        /**
876
         * Peform validation for the rule "is_unique_update"
877
         * @param  string $inputName the form field or data key name used
878
         * @param  string $ruleName  the rule name for this validation ("is_unique_update")
879
         * @param  array  $ruleArgs  the rules argument
880
         */
881
        protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
882
            $inputVal = $this->post($inputName);
883
            if (!is_object($this->databaseInstance)) {
884
                $obj = & get_instance();
885
                if (isset($obj->database)) {
886
                    $this->databaseInstance = $obj->database;
887
                } 
888
            }
889
            $data = explode(',', $ruleArgs[1]);
890
            if (count($data) < 2) {
891
                return;
892
            }
893
            list($table, $column) = explode('.', $data[0]);
894
            list($field, $val)    = explode('=', $data[1]);
895
            $this->databaseInstance->getQueryBuilder()->from($table)
896
                                                        ->where($column, $inputVal)
897
                                                        ->where($field, '!=', trim($val));
898
            $this->databaseInstance->get();
899
            if ($this->databaseInstance->numRows() > 0) {
900
                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
901
            }
902
        }
903
        
904
    }
905