source: trunk/lib/FormValidator.inc.php @ 493

Last change on this file since 493 was 493, checked in by anonymous, 10 years ago

Constructor for FormValidation?()

File size: 22.1 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * FormValidator.inc.php
25 *
26 * The FormValidator class provides a method for validating input from
27 * http requests and displaying errors.
28 *
29 * @requires  codebase/lib/Validator.inc.php
30 * @author    Quinn Comendant <quinn@strangecode.com>
31 * @version   1.8
32 *
33 * Example of use:
34---------------------------------------------------------------------
35// The object that validates form input.
36require_once 'codebase/lib/FormValidator.inc.php';
37$fv = new FormValidator();
38
39$fv->empty('field_name', sprintf(_("%s cannot be blank."), _("Field name")));
40$fv->stringLength('field_name', 0, 255, sprintf(_("%s must be %d-to-%d characters in length."), _("Field name"), 0, 255));
41$fv->isInteger('field_name', sprintf(_("%s must be an integer."), _("Field name")));
42$fv->checkRegex('field_name', '/^\d{4}$|^$/', true, sprintf(_("%s must be in MMYY format."), _("Field name")));
43$fv->numericRange('field_name', 0, 65535, sprintf(_("%s must be a number between %d and %d."), _("Field name"), 0, 65535));
44$fv->validatePhone('field_name');
45$fv->validateEmail('field_name');
46$fv->validateStrDate('field_name', sprintf(_("%s must be a valid date in YYYY-MM-DD format."), _("Field name")));
47if (is_null($var)) {
48    $fv->addError('field_name', sprintf(_("%s is invalid."), _("Field name")));
49}
50if ($fv->anyErrors()) {
51    // Errors!
52}
53---------------------------------------------------------------------
54 */
55
56// Credit card types are defined in class Validator.
57
58require_once 'codebase/lib/Validator.inc.php';
59
60class FormValidator {
61
62    // Class parameters.
63    protected $_params = array(
64        'error' => ' sc-msg-error ',
65        'warning' => ' sc-msg-warning ',
66        'notice' => ' sc-msg-notice ',
67        'success' => ' sc-msg-success ',
68    );
69
70    // Array filling with error messages.
71    public $errors = array();
72
73    /**
74     * FormValidator constructor.
75     *
76     * @access public
77     * @param array $params Configuration parameters for this object.
78     */
79    public function __construct($params=null)
80    {
81        // Set custom parameters.
82        $this->setParam($params);
83    }
84
85    /**
86     * Set (or overwrite existing) parameters by passing an array of new parameters.
87     *
88     * @access public
89     * @param  array    $params     Array of parameters (key => val pairs).
90     */
91    public function setParam($params)
92    {
93        $app =& App::getInstance();
94
95        if (isset($params) && is_array($params)) {
96            // Merge new parameters with old overriding only those passed.
97            $this->_params = array_merge($this->_params, $params);
98        } else {
99            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
100        }
101    }
102
103    /**
104     * Return the value of a parameter, if it exists.
105     *
106     * @access public
107     * @param string $param        Which parameter to return.
108     * @return mixed               Configured parameter value.
109     */
110    public function getParam($param)
111    {
112        $app =& App::getInstance();
113
114        if (array_key_exists($param, $this->_params)) {
115            return $this->_params[$param];
116        } else {
117            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
118            return null;
119        }
120    }
121
122    /**
123     * Return the current list of errors.
124     *
125     * @return array    an array of errors in the following arrangement:
126     *                  keys: the name of the variable with an error
127     *                  vals: the message to display for that error
128     */
129    public function getErrorList()
130    {
131        return $this->errors;
132    }
133
134    /**
135     * Add an error to the errors stack.
136     *
137     * @param   string $form_name   The name of the incoming form variable.
138     * @param   string $msg         The error message for that form.
139     * @param   int    $type        The type of message: MSG_NOTICE,
140     *                              MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
141     * @param   string $file        __FILE__.
142     * @param   string $line        __LINE__.
143     */
144    public function addError($form_name, $msg='', $type=MSG_ERR, $file=null, $line=null)
145    {
146        $this->errors[] = array(
147            'name' => $form_name,
148            'message' => $msg,
149            'type' => $type,
150            'file' => $file,
151            'line' => $line
152        );
153    }
154
155    /**
156     * Check whether any errors have been triggered.
157     *
158     * @param  string $form_name the name of the incoming form variable
159     *
160     * @return bool   true if any errors were found, or if found for
161     *                a variable of $form_name, false otherwise
162     */
163    public function anyErrors($form_name=null)
164    {
165        if (isset($form_name)) {
166            foreach ($this->errors as $err) {
167                if ($err['name'] == $form_name) {
168                    return $err['type'];
169                }
170            }
171            return false;
172        } else {
173            return (sizeof($this->errors) > 0);
174        }
175    }
176
177    /**
178     * Reset the error list.
179     */
180    public function resetErrorList()
181    {
182        $this->errors = array();
183    }
184
185    /**
186     * Prints the HTML for displaying error messages.
187     *
188     * @param   string  $above    Additional message to print above error messages (e.g. "Oops!").
189     * @param   string  $below    Additional message to print below error messages (e.g. "Please fix and resubmit").
190     * @param   string  $print_gotohash_js  Print a line of javascript that scrolls the browser window down to view any error messages.
191     * @param   string  $hash     The #hashtag to scroll to.
192     * @access  public
193     * @author  Quinn Comendant <quinn@strangecode.com>
194     * @since   15 Jul 2005 01:39:14
195     */
196    public function printErrorMessages($above='', $below='', $print_gotohash_js=false, $hash='sc-msg-formvalidator')
197    {
198        $app =& App::getInstance();
199        if ($this->anyErrors()) {
200            ?><div class="sc-msg" id="sc-msg-formvalidator"><?php
201            if ('' != $above) {
202                ?><div class="sc-above"><?php echo oTxt($above); ?></div><?php
203            }
204            foreach ($this->getErrorList() as $e) {
205                if ('' != $e['message'] && is_string($e['message'])) {
206                    if (error_reporting() > 0 && $app->getParam('display_errors') && isset($e['file']) && isset($e['line'])) {
207                        echo "\n<!-- [" . $e['file'] . ' : ' . $e['line'] . '] -->';
208                    }
209                    switch ($e['type']) {
210                    case MSG_ERR:
211                        echo '<div class="sc-msg-error">' . $e['message'] . '</div>';
212                        break;
213
214                    case MSG_WARNING:
215                        echo '<div class="sc-msg-warning">' . $e['message'] . '</div>';
216                        break;
217
218                    case MSG_SUCCESS:
219                        echo '<div class="sc-msg-success">' . $e['message'] . '</div>';
220                        break;
221
222                    case MSG_NOTICE:
223                    default:
224                        echo '<div class="sc-msg-notice">' . $e['message'] . '</div>';
225                        break;
226                    }
227                }
228            }
229            if ('' != $below) {
230                ?><div class="sc-below"><?php echo oTxt($below); ?></div><?php
231            }
232            ?></div><?php
233            if ($print_gotohash_js) {
234                ?>
235                <script type="text/javascript">
236                /* <![CDATA[ */
237                window.location.hash = '#<?php echo urlencode($hash); ?>';
238                /* ]]> */
239                </script>
240                <?php
241            }
242        }
243    }
244
245    /**
246     * If this form has an error, print an error marker like "<<".
247     *
248     * @param  string $form_name the name of the incoming form variable
249     * @param  string $marker    A string to print if there is an error. if
250     *                           not provided, use default.
251     */
252    public function err($form_name, $marker=null)
253    {
254        if (false !== ($type = $this->anyErrors($form_name))) {
255            if (isset($marker)) {
256                echo $marker;
257            } else {
258                switch ($type) {
259                case MSG_ERR:
260                default:
261                    echo $this->getParam('error');
262                    break;
263
264                case MSG_WARNING:
265                    echo $this->getParam('warning');
266                    break;
267
268                case MSG_NOTICE:
269                    echo $this->getParam('notice');
270                    break;
271
272                case MSG_SUCCESS:
273                    echo $this->getParam('success');
274                    break;
275                }
276            }
277        }
278    }
279
280    /**
281     * Ensure the length of string is non-zero.
282     *
283     * @param  string $form_name the name of the incoming form variable
284     * @param  string $msg       the message to display on error
285     *
286     * @return bool   true if form is not empty, false otherwise.
287     */
288    public function notEmpty($form_name, $msg='')
289    {
290        if (!Validator::isEmpty(getFormData($form_name))) {
291            return true;
292        } else {
293            $this->addError($form_name, $msg);
294            return false;
295        }
296    }
297
298    /*
299    * We were using the isEmpty method *wrong* all these years and should have been using notEmpty.
300    * But the fact is the only use is to ensure a value is not empty, so this function simply becomes
301    * an alias of the one-true notEmpty() function.
302    * @since    03 Jun 2006 22:56:46
303    */
304    public function isEmpty($form_name, $msg='')
305    {
306        $this->notEmpty($form_name, $msg);
307    }
308
309    /**
310     * Check whether input is a string.
311     *
312     * @param  string $form_name the name of the incoming form variable
313     * @param  string $msg       the message to display on error
314     *
315     * @return bool   true if form is a string, false otherwise.
316     */
317    public function isString($form_name, $msg='')
318    {
319        if (Validator::isString(getFormData($form_name))) {
320            return true;
321        } else {
322            $this->addError($form_name, $msg);
323            return false;
324        }
325    }
326
327    /**
328     * Check whether input is a number. Allows negative numbers.
329     *
330     * @param  string $form_name the name of the incoming form variable
331     * @param  string $msg       the message to display on error
332     *
333     * @return bool   true if no errors found, false otherwise
334     */
335    public function isNumber($form_name, $msg='')
336    {
337        if (Validator::isNumber(getFormData($form_name))) {
338            return true;
339        } else {
340            $this->addError($form_name, $msg);
341            return false;
342        }
343    }
344
345    /**
346     * addError if input is NOT an integer. Don't just use is_int() because the
347     * data coming from the user is *really* a string.
348     *
349     * @param  string $form_name the name of the incoming form variable
350     * @param  string $msg       the message to display on error
351     *
352     * @return bool   true if value is an integer
353     */
354    public function isInteger($form_name, $msg='', $negative_ok=false)
355    {
356        if (Validator::isInteger(getFormData($form_name), $negative_ok)) {
357            return true;
358        } else {
359            $this->addError($form_name, $msg);
360            return false;
361        }
362    }
363
364    /**
365     * Check whether input is a float. Don't just use is_float() because the
366     * data coming from the user is *really* a string. Integers will also
367     * pass this test.
368     *
369     * @param  string $form_name the name of the incoming form variable
370     * @param  string $msg       the message to display on error
371     *
372     * @return bool   true if value is a float
373     */
374    public function isFloat($form_name, $msg='', $negative_ok=false)
375    {
376        if (Validator::isFloat(getFormData($form_name), $negative_ok)) {
377            return true;
378        } else {
379            $this->addError($form_name, $msg);
380            return false;
381        }
382    }
383
384    /**
385     * Check whether input is an array.
386     *
387     * @param  string $form_name the name of the incoming form variable
388     * @param  string $msg       the message to display on error
389     *
390     * @return bool   true if value is a float
391     */
392    public function isArray($form_name, $msg='')
393    {
394        if (Validator::isArray(getFormData($form_name))) {
395            return true;
396        } else {
397            $this->addError($form_name, $msg);
398            return false;
399        }
400    }
401
402    /**
403     * Check whether input matches the specified perl regular expression
404     * pattern.
405     *
406     * @param  string $form_name        The name of the incoming form variable
407     * @param  int    $regex            Perl regex that the string must match
408     * @param  bool   $valid_on_match   Set to true to be valid if match, or false to be valid if the match fails.
409     * @param  string $msg              The message to display on error
410     *
411     * @return bool   true if value passes regex test
412     */
413    public function checkRegex($form_name, $regex, $valid_on_match=true, $msg='')
414    {
415        if (Validator::checkRegex(getFormData($form_name), $regex, $valid_on_match)) {
416            return true;
417        } else {
418            $this->addError($form_name, $msg);
419            return false;
420        }
421    }
422
423    /**
424     * Tests if the string length is between specified values. Whitespace excluded for min.
425     *
426     * @param  string $form_name the name of the incoming form variable
427     * @param  int    $min       minimum length of string, inclusive
428     * @param  int    $max       maximum length of string, inclusive
429     * @param  string $msg       the message to display on error
430     *
431     * @return bool   true if string length is within given boundaries
432     */
433    public function stringLength($form_name, $min, $max, $msg='')
434    {
435        if (Validator::stringLength(getFormData($form_name), $min, $max)) {
436            return true;
437        } else {
438            $this->addError($form_name, $msg);
439            return false;
440        }
441    }
442
443    /**
444     * Check whether input is within a valid numeric range.
445     *
446     * @param  string $form_name the name of the incoming form variable
447     * @param  int    $min       minimum value of number, inclusive
448     * @param  int    $max       maximum value of number, inclusive
449     * @param  string $msg       the message to display on error
450     *
451     * @return bool   true if no errors found, false otherwise
452     */
453    public function numericRange($form_name, $min, $max, $msg='')
454    {
455        if (Validator::numericRange(getFormData($form_name), $min, $max)) {
456            return true;
457        } else {
458            $this->addError($form_name, $msg);
459            return false;
460        }
461    }
462
463    /**
464     * Validates an email address based on the recommendations in RFC 3696.
465     * Is more loose than restrictive, to allow the many valid variants of
466     * email addresses while catching the most common mistakes.
467     * http://www.faqs.org/rfcs/rfc822.html
468     * http://www.faqs.org/rfcs/rfc2822.html
469     * http://www.faqs.org/rfcs/rfc3696.html
470     * http://www.faqs.org/rfcs/rfc1035.html
471     *
472     * @access  public
473     * @param   string  $form_name  The name of the incoming form variable.
474     * @return  bool    Validity of address.
475     * @author  Quinn Comendant <quinn@strangecode.com>
476     */
477    public function validateEmail($form_name, $strict=false)
478    {
479        $app =& App::getInstance();
480
481        $email = getFormData($form_name);
482
483        if ('' == trim($email)) {
484            // No email address provided, and that's okay.
485            return true;
486        }
487
488        // Validator::validateEmail() returns a value that relates to the Validate::EMAIL_* constants (defined in Validator.inc.php).
489        switch (Validator::validateEmail($email, $strict)) {
490        case Validator::EMAIL_REGEX_FAIL:
491            // Failed regex match.
492            $this->addError($form_name, sprintf(_("The email address <em>%s</em> is formatted incorrectly."), oTxt($email)));
493            $app->logMsg(sprintf('The email address %s is not valid.', oTxt($email)), LOG_DEBUG, __FILE__, __LINE__);
494            return false;
495
496        case Validator::EMAIL_LENGTH_FAIL :
497            // Failed length requirements.
498            $this->addError($form_name, sprintf(_("The email address <em>%s</em> is too long (email addresses must have fewer than 256 characters)."), oTxt($email)));
499            $app->logMsg(sprintf('The email address %s must contain less than 256 characters.', oTxt($email)), LOG_DEBUG, __FILE__, __LINE__);
500            return false;
501
502        case Validator::EMAIL_MX_FAIL :
503            // Failed MX record test.
504            $this->addError($form_name, sprintf(_("The email address <em>%s</em> does not have a valid domain name"), oTxt($email)));
505            $app->logMsg(sprintf('The email address %s does not have a valid domain name.', oTxt($email)), LOG_INFO, __FILE__, __LINE__);
506            return false;
507
508        case Validator::EMAIL_SUCCESS :
509        default :
510            return true;
511        }
512    }
513
514    /**
515     * Check whether input is a valid phone number. Notice: it is now set
516     * to allow characters like - or () or + so people can type in a phone
517     * number that looks like: +1 (530) 555-1212
518     *
519     * @param  string  $form_name the name of the incoming form variable
520     *
521     * @return bool    true if no errors found, false otherwise
522     */
523    public function validatePhone($form_name)
524    {
525        $app =& App::getInstance();
526
527        $phone = getFormData($form_name);
528
529        // Validator::validateEmail() returns a value that relates to the Validate::PHONE_* constants (defined in Validator.inc.php).
530        switch (Validator::validatePhone($phone)) {
531        case Validator::PHONE_REGEX_FAIL:
532            // Failed regex match.
533            $this->addError($form_name, sprintf(_("The phone number <em>%s</em> is not valid."), oTxt($phone)));
534            $app->logMsg(sprintf('The phone number %s is not valid.', oTxt($phone)), LOG_DEBUG, __FILE__, __LINE__);
535            return false;
536
537        case Validator::PHONE_LENGTH_FAIL :
538            // Failed length requirements.
539            $this->addError($form_name, sprintf(_("The phone number <em>%s</em> is too long (phone number must have fewer than 25 characters)."), oTxt($phone)));
540            $app->logMsg(sprintf('The phone number %s must contain less than 256 characters.', oTxt($phone)), LOG_DEBUG, __FILE__, __LINE__);
541            return false;
542
543        case Validator::PHONE_SUCCESS :
544        default :
545            return true;
546        }
547    }
548
549    /**
550     * Verifies that date can be processed by the strtotime function.
551     *
552     * @param  string  $form_name the name of the incoming form variable
553     * @param  string  $msg       the message to display on error
554     *
555     * @return bool    true if no errors found, false otherwise
556     */
557    public function validateStrDate($form_name, $msg='')
558    {
559        $app =& App::getInstance();
560
561        if (Validator::validateStrDate(getFormData($form_name, ''))) {
562            return true;
563        } else {
564            $this->addError($form_name, $msg);
565            $app->logMsg(sprintf('The string date %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
566            return false;
567        }
568    }
569
570
571    /**
572     * Verifies credit card number using the Luhn (mod 10) algorithm.
573     * http://en.wikipedia.org/wiki/Luhn_algorithm
574     *
575     * @param  string  $form_name   The name of the incoming form variable.
576     * @param  string  $cc_type     Optional, card type to do specific checks. One of the Validator::CC_TYPE_* constants.
577     *
578     * @return bool    true if no errors found, false otherwise
579     */
580    public function validateCCNumber($form_name, $cc_type=null)
581    {
582        $cc_num = getFormData($form_name);
583
584        if (Validator::validateCCNumber($cc_num, $cc_type)) {
585            return true;
586        } else {
587            $this->addError($form_name, sprintf(_("The credit card number you entered is not valid. Please check the number and try again."), $cc_num));
588            return false;
589        }
590    }
591
592    /**
593     * Check whether a file was selected for uploading. If file is missing, it's an error.
594     *
595     * @param  string $form_name the name of the incoming form variable
596     * @param  string $msg       the message to display on error
597     *
598     * @return bool   true if no errors found, false otherwise
599     */
600    public function fileUploaded($form_name, $msg='')
601    {
602        if (Validator::fileUploaded($form_name)) {
603            return true;
604        } else {
605            $this->addError($form_name, $msg);
606            return false;
607        }
608    }
609    /**
610     * Check whether a file was selected for uploading. If file is missing, it's an error.
611     *
612     * @param  string $form_name the name of the incoming form variable
613     * @param  string $msg       the message to display on error
614     *
615     * @return bool   true if no errors found, false otherwise
616     */
617    public function fileUploadSize($form_name, $msg='')
618    {
619        if (Validator::fileUploadSize($form_name)) {
620            return true;
621        } else {
622            $msg = '' == $msg ? sprintf(_("Maximum filesize exceeded. Got %s, but limit is %s."), humanFileSize($_SERVER['CONTENT_LENGTH']), humanFileSize(phpIniGetBytes('upload_max_filesize'))) : $msg;
623            $this->addError($form_name, $msg);
624            return false;
625        }
626    }
627
628} // THE END
629
Note: See TracBrowser for help on using the repository browser.