1
0
mirror of https://github.com/e107inc/e107.git synced 2025-08-02 20:57:26 +02:00

Issue #4299 Fixes the "07 - Display name - Value not allowed" validation error during user registration.

This commit is contained in:
Cameron
2020-12-26 09:28:02 -08:00
parent 7989ebfc72
commit f6cdb9125c
3 changed files with 623 additions and 226 deletions

View File

@@ -15,7 +15,10 @@
* *
*/ */
if (!defined('e107_INIT')) { exit; } if (!defined('e107_INIT'))
{
exit;
}
// List of error numbers which may be returned from validation // List of error numbers which may be returned from validation
define('ERR_MISSING_VALUE', '01'); define('ERR_MISSING_VALUE', '01');
@@ -44,6 +47,7 @@ define('ERR_IMAGE_TOO_HIGH', '21');
// Default error messages // Default error messages
e107::includeLan(e_LANGUAGEDIR . e_LANGUAGE . '/admin/lan_validator.php'); e107::includeLan(e_LANGUAGEDIR . e_LANGUAGE . '/admin/lan_validator.php');
/** /**
* Validator class - used by e_model and its child classes * Validator class - used by e_model and its child classes
* *
@@ -55,10 +59,11 @@ e107::includeLan(e_LANGUAGEDIR.e_LANGUAGE.'/admin/lan_validator.php');
*/ */
class e_validator class e_validator
{ {
/** /**
* @var integer Unknown error code * @var integer Unknown error code
*/ */
const ERR_UNKNOWN = 0; public const ERR_UNKNOWN = 0;
/** /**
* @var integer Value not found error code * @var integer Value not found error code
@@ -232,6 +237,7 @@ class e_validator
*/ */
public function __construct($message_stack = '', $rules = array(), $optrules = array()) public function __construct($message_stack = '', $rules = array(), $optrules = array())
{ {
$this->setMessageStack($message_stack) $this->setMessageStack($message_stack)
->setRules($rules) ->setRules($rules)
->setOptionalRules($optrules); ->setOptionalRules($optrules);
@@ -245,8 +251,13 @@ class e_validator
*/ */
public function setMessageStack($mstack) public function setMessageStack($mstack)
{ {
if(!$mstack) $mstack = 'validator';
if (!$mstack)
{
$mstack = 'validator';
}
$this->_message_stack = $mstack; $this->_message_stack = $mstack;
return $this; return $this;
} }
@@ -256,7 +267,9 @@ class e_validator
*/ */
public function setRules($rules) public function setRules($rules)
{ {
$this->_required_rules = $rules; $this->_required_rules = $rules;
return $this; return $this;
} }
@@ -266,7 +279,9 @@ class e_validator
*/ */
public function setOptionalRules($rules) public function setOptionalRules($rules)
{ {
$this->_optional_rules = $rules; $this->_optional_rules = $rules;
return $this; return $this;
} }
@@ -279,7 +294,9 @@ class e_validator
*/ */
protected function addValidData($field_name, $value) protected function addValidData($field_name, $value)
{ {
$this->_valid_data[$field_name] = $value; $this->_valid_data[$field_name] = $value;
return $this; return $this;
} }
@@ -288,6 +305,7 @@ class e_validator
*/ */
public function getValidData() public function getValidData()
{ {
return $this->_valid_data; return $this->_valid_data;
} }
@@ -300,6 +318,7 @@ class e_validator
*/ */
function validate($data, $availableOnly = false) function validate($data, $availableOnly = false)
{ {
$this->reset(); $this->reset();
$rules = array_merge(array_keys($this->_required_rules), array_keys($this->_optional_rules)); $rules = array_merge(array_keys($this->_required_rules), array_keys($this->_optional_rules));
@@ -308,15 +327,22 @@ class e_validator
{ {
$this->setIsValidData(true); $this->setIsValidData(true);
$this->_valid_data = $data; $this->_valid_data = $data;
return true; return true;
} }
$fieldList = $rules; $fieldList = $rules;
if($availableOnly) $fieldList = array_keys($data); if ($availableOnly)
{
$fieldList = array_keys($data);
}
foreach ($rules as $field_name) foreach ($rules as $field_name)
{ {
if(!in_array($field_name, $fieldList)) continue; if (!in_array($field_name, $fieldList))
{
continue;
}
$value = varset($data[$field_name], null); $value = varset($data[$field_name], null);
$required = $this->isRequiredField($field_name); $required = $this->isRequiredField($field_name);
if (($required || $this->isOptionalField($field_name)) && !$this->validateField($field_name, $value, $required)) if (($required || $this->isOptionalField($field_name)) && !$this->validateField($field_name, $value, $required))
@@ -338,6 +364,7 @@ class e_validator
*/ */
function isRequiredField($name) function isRequiredField($name)
{ {
return isset($this->_required_rules[$name]); return isset($this->_required_rules[$name]);
} }
@@ -349,6 +376,7 @@ class e_validator
*/ */
function isOptionalField($name) function isOptionalField($name)
{ {
return isset($this->_optional_rules[$name]); return isset($this->_optional_rules[$name]);
} }
@@ -360,6 +388,7 @@ class e_validator
*/ */
function getFieldHelp($name, $required = true, $default = '') function getFieldHelp($name, $required = true, $default = '')
{ {
if ($required) if ($required)
{ {
$msg = (isset($this->_required_rules[$name][3]) ? $this->_required_rules[$name][3] : $default); $msg = (isset($this->_required_rules[$name][3]) ? $this->_required_rules[$name][3] : $default);
@@ -381,13 +410,17 @@ class e_validator
*/ */
function getFieldMessage($name, $value = '', $required = true) function getFieldMessage($name, $value = '', $required = true)
{ {
if ($required) if ($required)
{ {
if (!isset($this->_required_rules[$name][4])) if (!isset($this->_required_rules[$name][4]))
{ {
$msg = $this->getFieldHelp($name, true); $msg = $this->getFieldHelp($name);
}
else
{
$msg = $this->_required_rules[$name][4];
} }
else $msg = $this->_required_rules[$name][4];
} }
else else
{ {
@@ -395,7 +428,10 @@ class e_validator
{ {
$msg = $this->getFieldHelp($name, false); $msg = $this->getFieldHelp($name, false);
} }
else $msg = $this->_optional_rules[$name][4]; else
{
$msg = $this->_optional_rules[$name][4];
}
} }
return ($msg ? defset($msg, $msg) : ''); return ($msg ? defset($msg, $msg) : '');
@@ -407,6 +443,7 @@ class e_validator
*/ */
function getFieldName($name, $required = true) function getFieldName($name, $required = true)
{ {
if ($required) if ($required)
{ {
$msg = (isset($this->_required_rules[$name][2]) ? $this->_required_rules[$name][2] : $name); $msg = (isset($this->_required_rules[$name][2]) ? $this->_required_rules[$name][2] : $name);
@@ -429,6 +466,7 @@ class e_validator
*/ */
function validateField($name, $value, $required = true) function validateField($name, $value, $required = true)
{ {
if ($required) if ($required)
{ {
$type = $this->_required_rules[$name][0]; $type = $this->_required_rules[$name][0];
@@ -458,6 +496,7 @@ class e_validator
break; break;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
} }
$type = $this->_optional_rules[$name][0]; $type = $this->_optional_rules[$name][0];
@@ -470,9 +509,11 @@ class e_validator
if (empty($value)) if (empty($value))
{ {
$this->addValidateResult($name, self::ERR_GENERIC); $this->addValidateResult($name, self::ERR_GENERIC);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -480,9 +521,11 @@ class e_validator
if (!check_email($value)) if (!check_email($value))
{ {
$this->addValidateResult($name, self::ERR_INVALID_EMAIL); $this->addValidateResult($name, self::ERR_INVALID_EMAIL);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -491,9 +534,11 @@ class e_validator
if (!preg_match($cond, $value)) if (!preg_match($cond, $value))
{ {
$this->addValidateResult($name, self::ERR_INVALID_CHARS); $this->addValidateResult($name, self::ERR_INVALID_CHARS);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -501,9 +546,11 @@ class e_validator
if (!call_user_func($cond, $value)) if (!call_user_func($cond, $value))
{ {
$this->addValidateResult($name, self::ERR_INVALID_CHARS); $this->addValidateResult($name, self::ERR_INVALID_CHARS);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -511,9 +558,11 @@ class e_validator
if (!(is_object($value) && $value instanceof $cond)) if (!(is_object($value) && $value instanceof $cond))
{ {
$this->addValidateResult($name, self::ERR_INSTANCEOF_EXPECTED); $this->addValidateResult($name, self::ERR_INSTANCEOF_EXPECTED);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -522,6 +571,7 @@ class e_validator
if (!preg_match('/^-?[\d]+$/', $value)) // negative values support if (!preg_match('/^-?[\d]+$/', $value)) // negative values support
{ {
$this->addValidateResult($name, self::ERR_INT_EXPECTED); $this->addValidateResult($name, self::ERR_INT_EXPECTED);
return false; return false;
} }
// BC! Will be removed after we replace '-' with ':' separator! // BC! Will be removed after we replace '-' with ':' separator!
@@ -529,14 +579,17 @@ class e_validator
if (is_numeric($tmp[0]) && (integer) $tmp[0] > (integer) $value) if (is_numeric($tmp[0]) && (integer) $tmp[0] > (integer) $value)
{ {
$this->addValidateResult($name, self::ERR_TOO_LOW); $this->addValidateResult($name, self::ERR_TOO_LOW);
return false; return false;
} }
if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < (integer) $value) if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < (integer) $value)
{ {
$this->addValidateResult($name, self::ERR_TOO_HIGH); $this->addValidateResult($name, self::ERR_TOO_HIGH);
return false; return false;
} }
$this->addValidData($name, intval($value)); $this->addValidData($name, (int) $value);
return true; return true;
break; break;
@@ -545,21 +598,29 @@ class e_validator
case 'text': case 'text':
case 'varchar': case 'varchar':
$tmp = $this->parseMinMax($cond); $tmp = $this->parseMinMax($cond);
$length = e107::getParser()->ustrlen($value); $length = e107::getParser()->ustrlen($value);
if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length) if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_SHORT); $this->addValidateResult($name, self::ERR_TOO_SHORT);
return false; return false;
} }
if('varchar' == $type && !varset($tmp[1])) $tmp[1] = 255; if ('varchar' === $type && !varset($tmp[1]))
{
$tmp[1] = 255;
}
if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length) if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_LONG); $this->addValidateResult($name, self::ERR_TOO_LONG);
return false; return false;
} }
$this->addValidData($name, (string) $value); $this->addValidData($name, (string) $value);
return true; return true;
break; break;
@@ -569,10 +630,12 @@ class e_validator
if (!$value || !in_array($value, $tmp)) if (!$value || !in_array($value, $tmp))
{ {
$this->addValidateResult($name, self::ERR_FIELDS_MATCH); $this->addValidateResult($name, self::ERR_FIELDS_MATCH);
return false; return false;
} }
$this->addValidData($name, (string) $value); $this->addValidData($name, (string) $value);
return true; return true;
break; break;
@@ -581,20 +644,24 @@ class e_validator
if (!is_numeric($value)) if (!is_numeric($value))
{ {
$this->addValidateResult($name, self::ERR_FLOAT_EXPECTED); $this->addValidateResult($name, self::ERR_FLOAT_EXPECTED);
return false; return false;
} }
$tmp = $this->parseMinMax($cond); $tmp = $this->parseMinMax($cond);
if (is_numeric($tmp[0]) && (float) $tmp[0] > (float) $value) if (is_numeric($tmp[0]) && (float) $tmp[0] > (float) $value)
{ {
$this->addValidateResult($name, self::ERR_TOO_LOW); $this->addValidateResult($name, self::ERR_TOO_LOW);
return false; return false;
} }
if (is_numeric(varset($tmp[1])) && (float) $tmp[1] < (float) $value) if (is_numeric(varset($tmp[1])) && (float) $tmp[1] < (float) $value)
{ {
$this->addValidateResult($name, self::ERR_TOO_HIGH); $this->addValidateResult($name, self::ERR_TOO_HIGH);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -602,6 +669,7 @@ class e_validator
if (!is_array($value)) if (!is_array($value))
{ {
$this->addValidateResult($name, self::ERR_ARRAY_EXPECTED); $this->addValidateResult($name, self::ERR_ARRAY_EXPECTED);
return false; return false;
} }
$length = count($value); $length = count($value);
@@ -609,14 +677,17 @@ class e_validator
if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length) if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length)
{ {
$this->addValidateResult($name, self::ERR_ARRCOUNT_LOW); $this->addValidateResult($name, self::ERR_ARRCOUNT_LOW);
return false; return false;
} }
if (is_numeric(varset($tmp[1])) && (float) $tmp[1] < $length) if (is_numeric(varset($tmp[1])) && (float) $tmp[1] < $length)
{ {
$this->addValidateResult($name, self::ERR_ARRCOUNT_HIGH); $this->addValidateResult($name, self::ERR_ARRCOUNT_HIGH);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -626,11 +697,13 @@ class e_validator
if (!$value || !is_file($path)) if (!$value || !is_file($path))
{ {
$this->addValidateResult($name, self::ERR_NOT_FILE); $this->addValidateResult($name, self::ERR_NOT_FILE);
return false; return false;
} }
if (!empty($params['writable']) && !is_writable($path)) if (!empty($params['writable']) && !is_writable($path))
{ {
$this->addValidateResult($name, self::ERR_WRITABLE_FILE); $this->addValidateResult($name, self::ERR_WRITABLE_FILE);
return false; return false;
} }
if (!empty($params['size'])) if (!empty($params['size']))
@@ -640,20 +713,24 @@ class e_validator
if (!$fs || (integer) $tmp[0] > $fs) if (!$fs || (integer) $tmp[0] > $fs)
{ {
$this->addValidateResult($name, self::ERR_SIZEMIN_FILE); $this->addValidateResult($name, self::ERR_SIZEMIN_FILE);
return false; return false;
} }
elseif (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $fs) elseif (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $fs)
{ {
$this->addValidateResult($name, self::ERR_SIZEMAX_FILE); $this->addValidateResult($name, self::ERR_SIZEMAX_FILE);
return false; return false;
} }
} }
if (is_numeric(varset($params['maxlen'])) && (integer) $params['maxlen'] < e107::getParser()->ustrlen($value)) if (is_numeric(varset($params['maxlen'])) && (integer) $params['maxlen'] < e107::getParser()->ustrlen($value))
{ {
$this->addValidateResult($name, self::ERR_TOO_LONG); $this->addValidateResult($name, self::ERR_TOO_LONG);
return false; return false;
} }
$this->addValidData($name, $value); $this->addValidData($name, $value);
return true; return true;
break; break;
@@ -661,12 +738,14 @@ class e_validator
if (!is_array($value)) if (!is_array($value))
{ {
$this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE); $this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE);
return false; return false;
} }
if (!($value[0] && $value[1] && $value[0] == $value[1])) if (!($value[0] && $value[1] && $value[0] == $value[1]))
{ {
$this->addValidateResult($name, self::ERR_FIELDS_MATCH); $this->addValidateResult($name, self::ERR_FIELDS_MATCH);
return false; return false;
} }
@@ -678,15 +757,18 @@ class e_validator
if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length) if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_SHORT); $this->addValidateResult($name, self::ERR_TOO_SHORT);
return false; return false;
} }
if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length) if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_LONG); $this->addValidateResult($name, self::ERR_TOO_LONG);
return false; return false;
} }
} }
$this->addValidData($name, $value[0]); $this->addValidData($name, $value[0]);
return true; return true;
break; break;
@@ -694,11 +776,13 @@ class e_validator
if (!is_array($value)) if (!is_array($value))
{ {
$this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE); $this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE);
return false; return false;
} }
if (!($value[0] && $value[1] && $value[0] === $value[1])) if (!($value[0] && $value[1] && $value[0] === $value[1]))
{ {
$this->addValidateResult($name, self::ERR_FIELDS_MATCH); $this->addValidateResult($name, self::ERR_FIELDS_MATCH);
return false; return false;
} }
@@ -710,20 +794,24 @@ class e_validator
if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length) if (is_numeric($tmp[0]) && (integer) $tmp[0] > $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_SHORT); $this->addValidateResult($name, self::ERR_TOO_SHORT);
return false; return false;
} }
if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length) if (is_numeric(varset($tmp[1])) && (integer) $tmp[1] < $length)
{ {
$this->addValidateResult($name, self::ERR_TOO_LONG); $this->addValidateResult($name, self::ERR_TOO_LONG);
return false; return false;
} }
} }
$this->addValidData($name, $value[0]); $this->addValidData($name, $value[0]);
return true; return true;
break; break;
default: default:
$this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE); $this->addValidateResult($name, self::ERR_UNEXPECTED_VALUE);
return false; return false;
break; break;
} }
@@ -746,18 +834,25 @@ class e_validator
// return str_replace($search, $replace, $value); // return str_replace($search, $replace, $value);
// } // }
/**
* @param $string
* @return array
*/
protected function parseMinMax($string) protected function parseMinMax($string)
{ {
return explode(':', $this->_convertConditionBC($string), 2); return explode(':', $this->_convertConditionBC($string), 2);
} }
private function _convertConditionBC($condition) private function _convertConditionBC($condition)
{ {
// BC! Will be removed after we replace '-' with ':' separator! // BC! Will be removed after we replace '-' with ':' separator!
if (strpos($condition, ':') === false) if (strpos($condition, ':') === false)
{ {
return preg_replace('/^([0-9]+)-([0-9]+)$/', '$1:$2', $condition); return preg_replace('/^([0-9]+)-([0-9]+)$/', '$1:$2', $condition);
} }
return $condition; return $condition;
} }
@@ -772,6 +867,7 @@ class e_validator
*/ */
function addValidateMessage($field_title, $err_code = 0, $err_message = '', $custom = '') function addValidateMessage($field_title, $err_code = 0, $err_message = '', $custom = '')
{ {
$tp = e107::getParser(); $tp = e107::getParser();
$lanVars = array( $lanVars = array(
'x' => $field_title, 'x' => $field_title,
@@ -782,6 +878,7 @@ class e_validator
if ($custom) if ($custom)
{ {
e107::getMessage()->addStack(sprintf($err_message, $err_code, $field_title), $this->_message_stack, (true === $custom ? E_MESSAGE_ERROR : $custom)); e107::getMessage()->addStack(sprintf($err_message, $err_code, $field_title), $this->_message_stack, (true === $custom ? E_MESSAGE_ERROR : $custom));
return $this; return $this;
} }
@@ -835,6 +932,7 @@ class e_validator
*/ */
function getValidateMessages($clear = true) function getValidateMessages($clear = true)
{ {
return e107::getMessage()->getAll($this->_message_stack, true, $clear); return e107::getMessage()->getAll($this->_message_stack, true, $clear);
} }
@@ -847,6 +945,7 @@ class e_validator
*/ */
function renderValidateMessages($session = false, $clear = true) function renderValidateMessages($session = false, $clear = true)
{ {
return e107::getMessage()->render($this->_message_stack, $session, $clear); return e107::getMessage()->render($this->_message_stack, $session, $clear);
} }
@@ -856,7 +955,9 @@ class e_validator
*/ */
function clearValidateMessages($session = true) function clearValidateMessages($session = true)
{ {
e107::getMessage()->reset(false, $this->_message_stack, $session); e107::getMessage()->reset(false, $this->_message_stack, $session);
return $this; return $this;
} }
@@ -869,7 +970,9 @@ class e_validator
*/ */
function addValidateResult($name, $code) function addValidateResult($name, $code)
{ {
$this->_validation_results[$name] = $code; $this->_validation_results[$name] = $code;
return $this; return $this;
} }
@@ -881,6 +984,7 @@ class e_validator
*/ */
function getValidateResults($clear = true) function getValidateResults($clear = true)
{ {
return $this->_validation_results; return $this->_validation_results;
} }
@@ -893,6 +997,7 @@ class e_validator
*/ */
function getErrorCode($field, $default = 0) function getErrorCode($field, $default = 0)
{ {
return (isset($this->_validation_results[$field]) ? $this->_validation_results[$field] : $default); return (isset($this->_validation_results[$field]) ? $this->_validation_results[$field] : $default);
} }
@@ -904,7 +1009,9 @@ class e_validator
*/ */
function getErrorByCode($error_code) function getErrorByCode($error_code)
{ {
$lan = 'LAN_VALIDATE_' . $error_code; $lan = 'LAN_VALIDATE_' . $error_code;
return defset($lan, $lan); return defset($lan, $lan);
} }
@@ -913,7 +1020,9 @@ class e_validator
*/ */
function clearValidateResults() function clearValidateResults()
{ {
$this->_validation_results = array(); $this->_validation_results = array();
return $this; return $this;
} }
@@ -922,6 +1031,7 @@ class e_validator
*/ */
function isValid() function isValid()
{ {
return empty($this->_is_valid_data); return empty($this->_is_valid_data);
} }
@@ -933,7 +1043,9 @@ class e_validator
*/ */
public function setIsValidData($status) public function setIsValidData($status)
{ {
$this->_is_valid_data = (boolean) $status; $this->_is_valid_data = (boolean) $status;
return $this; return $this;
} }
@@ -943,6 +1055,7 @@ class e_validator
*/ */
function reset() function reset()
{ {
$this->setIsValidData(true); $this->setIsValidData(true);
$this->_valid_data = array(); $this->_valid_data = array();
$this->clearValidateResults() $this->clearValidateResults()
@@ -952,6 +1065,7 @@ class e_validator
} }
} }
/* /*
The validator functions use an array of parameters for each variable to be validated. The validator functions use an array of parameters for each variable to be validated.
@@ -977,17 +1091,22 @@ The validator functions use an array of parameters for each variable to be valid
In general, only define an option if its to be used In general, only define an option if its to be used
*/ */
/* [ Berckoff ] /* [ Berckoff ]
* Added "public static " to each method as the parser generates errors (and methods are called statically everywhere) * Added "public static " to each method as the parser generates errors (and methods are called statically everywhere)
*/ */
class validatorClass class validatorClass
{ {
// Passed an array of 'source' fields and an array of definitions to validate. The definition may include the name of a validation function. // Passed an array of 'source' fields and an array of definitions to validate. The definition may include the name of a validation function.
// Returns three arrays - one of validated results, one of failed fields and one of errors corresponding to the failed fields // Returns three arrays - one of validated results, one of failed fields and one of errors corresponding to the failed fields
// Normally processes only those source fields it finds (and for which it has a definition). If $addDefaults is true, sets defaults for those that have // Normally processes only those source fields it finds (and for which it has a definition). If $addDefaults is true, sets defaults for those that have
// ...one and aren't otherwise defined. // ...one and aren't otherwise defined.
public static function validateFields(&$sourceFields, &$definitions, $addDefaults = FALSE) public static function validateFields(&$sourceFields, &$definitions, $addDefaults = false)
{ {
$tp = e107::getParser(); $tp = e107::getParser();
$pref = e107::getPref(); $pref = e107::getPref();
@@ -1107,7 +1226,7 @@ class validatorClass
$v = trim($v); $v = trim($v);
if (is_numeric($v)) if (is_numeric($v))
{ {
$temp[] = intval($v); $temp[] = (int) $v;
} }
} }
$value = implode(',', array_unique($temp)); $value = implode(',', array_unique($temp));
@@ -1138,7 +1257,7 @@ class validatorClass
$value = $tp->toDB($value); $value = $tp->toDB($value);
break; break;
case 'intval' : case 'intval' :
$value = intval($value); $value = (int) $value;
break; break;
case 'avatar' : // Special case of an image - may be found in the avatars directory case 'avatar' : // Special case of an image - may be found in the avatars directory
if (preg_match('#[0-9\._]#', $value)) if (preg_match('#[0-9\._]#', $value))
@@ -1202,6 +1321,7 @@ class validatorClass
} }
} }
} }
return $ret; return $ret;
} }
@@ -1231,12 +1351,18 @@ class validatorClass
*/ */
public static function dbValidateArray(&$targetData, &$definitions, $targetTable, $userID = 0) public static function dbValidateArray(&$targetData, &$definitions, $targetTable, $userID = 0)
{ {
global $pref;
$u_sql = new db; $pref = e107::getPref();
$allOK = TRUE; $u_sql = e107::getDb('u_sql');
$userID = intval($userID); // Precautionary
$allOK = true;
$userID = (int) $userID; // Precautionary
$errMsg = ''; $errMsg = '';
if (!$targetTable) return FALSE;
if (!$targetTable)
{
return false;
}
foreach ($targetData['data'] as $f => $v) foreach ($targetData['data'] as $f => $v)
{ {
$errMsg = ''; $errMsg = '';
@@ -1246,6 +1372,7 @@ class validatorClass
if (!vartrue($options['fieldOptional']) || ($v != '')) if (!vartrue($options['fieldOptional']) || ($v != ''))
{ {
$toDo = explode(',', $options['vetMethod']); $toDo = explode(',', $options['vetMethod']);
foreach ($toDo as $vm) foreach ($toDo as $vm)
{ {
switch ($vm) switch ($vm)
@@ -1266,16 +1393,19 @@ class validatorClass
// echo "Duplicate check: {$f} = {$v} Result: {$temp}<br />"; // echo "Duplicate check: {$f} = {$v} Result: {$temp}<br />";
break; break;
case 2 : // Check against $pref case 2 : // Check against $pref
if (isset($options['vetParam']) && isset($pref[$options['vetParam']])) if (isset($options['vetParam']) && !empty($pref[$options['vetParam']]))
{ {
$tmp = explode(",", $pref[$options['vetParam']]); $tmp = explode(",", $pref[$options['vetParam']]);
foreach ($tmp as $disallow) foreach ($tmp as $disallow)
{ {
if ('!' == substr(trim($disallow), -1) && $v == str_replace('!', '', $disallow)) $disTrim = (string) trim($disallow);
if ('!' == substr($disTrim, -1) && $v == str_replace('!', '', $disallow))
{ // Exact match search (noticed with exclamation mark in the end of the word) { // Exact match search (noticed with exclamation mark in the end of the word)
$errMsg = ERR_DISALLOWED_TEXT_EXACT_MATCH; $errMsg = ERR_DISALLOWED_TEXT_EXACT_MATCH;
} }
elseif(stripos($v, trim($disallow)) !== false) elseif (stripos($v, $disTrim) !== false)
{ // Wild card search { // Wild card search
$errMsg = ERR_DISALLOWED_TEXT; $errMsg = ERR_DISALLOWED_TEXT;
} }
@@ -1305,7 +1435,10 @@ class validatorClass
default : default :
echo 'Invalid vetMethod: ' . $options['vetMethod'] . '<br />'; // Really a debug aid - should never get here echo 'Invalid vetMethod: ' . $options['vetMethod'] . '<br />'; // Really a debug aid - should never get here
} }
if ($errMsg) { break; } // Just trap first error if ($errMsg)
{
break;
} // Just trap first error
} }
// Add in other validation methods here // Add in other validation methods here
} }
@@ -1315,9 +1448,10 @@ class validatorClass
$targetData['errors'][$f] = $errMsg; $targetData['errors'][$f] = $errMsg;
$targetData['failed'][$f] = $v; $targetData['failed'][$f] = $v;
unset($targetData['data'][$f]); // Remove the valid entry unset($targetData['data'][$f]); // Remove the valid entry
$allOK = FALSE; $allOK = false;
} }
} }
return $allOK; return $allOK;
} }
@@ -1326,24 +1460,27 @@ class validatorClass
// Returns TRUE if no changes (which doesn't mean there are no errors - other routines may have found them). FALSE if new errors // Returns TRUE if no changes (which doesn't mean there are no errors - other routines may have found them). FALSE if new errors
public static function checkMandatory($fieldList, &$target) public static function checkMandatory($fieldList, &$target)
{ {
$fields = explode(',', $fieldList); $fields = explode(',', $fieldList);
$allOK = TRUE; $allOK = true;
foreach ($fields as $f) foreach ($fields as $f)
{ {
if (!isset($target['data'][$f]) && !isset($target['errors'][$f])) if (!isset($target['data'][$f]) && !isset($target['errors'][$f]))
{ {
$allOK = FALSE; $allOK = false;
$targetData['errors'][$f] = ERR_MISSING_VALUE; $targetData['errors'][$f] = ERR_MISSING_VALUE;
} }
} }
return $allOK; return $allOK;
} }
// Adds the _FIELD_TYPES array to the data, ready for saving in the DB. // Adds the _FIELD_TYPES array to the data, ready for saving in the DB.
// $fieldList is the standard definition array // $fieldList is the standard definition array
public static function addFieldTypes($fieldList, &$target, $auxList=FALSE) public static function addFieldTypes($fieldList, &$target, $auxList = false)
{ {
$target['_FIELD_TYPES'] = array(); // We should always want to recreate the array, even if it exists $target['_FIELD_TYPES'] = array(); // We should always want to recreate the array, even if it exists
foreach ($target['data'] as $k => $v) foreach ($target['data'] as $k => $v)
{ {
@@ -1362,20 +1499,28 @@ class validatorClass
// Given two arrays, returns an array of those elements in $input which are different from the corresponding element in $refs. // Given two arrays, returns an array of those elements in $input which are different from the corresponding element in $refs.
// If $addMissing == TRUE, includes any element in $input for which there isn't a corresponding element in $refs // If $addMissing == TRUE, includes any element in $input for which there isn't a corresponding element in $refs
public static function findChanges(&$input, &$refs, $addMissing = FALSE) public static function findChanges(&$input, &$refs, $addMissing = false)
{ {
$ret = array(); $ret = array();
foreach ($input as $k => $v) foreach ($input as $k => $v)
{ {
if (array_key_exists($k, $refs)) if (array_key_exists($k, $refs))
{ {
if ($refs[$k] != $v) { $ret[$k] = $v; } if ($refs[$k] != $v)
{
$ret[$k] = $v;
}
} }
else else
{ {
if ($addMissing) { $ret[$k] = $v; } if ($addMissing)
{
$ret[$k] = $v;
} }
} }
}
return $ret; return $ret;
} }
@@ -1388,11 +1533,15 @@ class validatorClass
// %x is the 'nice name' - possible if parameter list passed. Otherwise field name added // %x is the 'nice name' - possible if parameter list passed. Otherwise field name added
// $EOL is inserted after all messages except the last. // $EOL is inserted after all messages except the last.
// If $EOL is an empty string, returns an array of messages. // If $EOL is an empty string, returns an array of messages.
public static function makeErrorList($vars, $constPrefix, $format = '%n - %x %t: %v', $EOL = '<br />', $niceNames = NULL) public static function makeErrorList($vars, $constPrefix, $format = '%n - %x %t: %v', $EOL = '<br />', $niceNames = null)
{ {
if (count($vars['errors']) == 0) return '';
if (count($vars['errors']) == 0)
{
return '';
}
$eList = array(); $eList = array();
$checkNice = ($niceNames != NULL) && is_array($niceNames); $checkNice = ($niceNames != null) && is_array($niceNames);
foreach ($vars['errors'] as $f => $n) foreach ($vars['errors'] as $f => $n)
{ {
$curLine = $format; $curLine = $format;
@@ -1422,7 +1571,11 @@ class validatorClass
} }
$eList[] = $curLine; $eList[] = $curLine;
} }
if ($EOL == '') return $eList; if ($EOL == '')
{
return $eList;
}
return implode($EOL, $eList); return implode($EOL, $eList);
} }
} }

View File

@@ -0,0 +1,243 @@
<?php
class validatorClassTest extends \Codeception\Test\Unit
{
/** @var validatorClass */
protected $vc;
protected $vettingInfo;
protected function _before()
{
try
{
$this->vc = $this->make('validatorClass');
}
catch(Exception $e)
{
$this->assertTrue(false, $e->getMessage());
}
$this->vettingInfo = array (
'user_name' =>
array (
'niceName' => 'Display name',
'fieldType' => 'string',
'vetMethod' => '1,2',
'vetParam' => 'signup_disallow_text',
'srcName' => 'username',
'stripTags' => true,
'stripChars' => '/ |\\#|\\=|\\$/',
'fixedBlock' => 'anonymous',
'minLength' => 2,
'maxLength' => '20',
),
'user_loginname' =>
array (
'niceName' => 'Login Name',
'fieldType' => 'string',
'vetMethod' => '1',
'vetParam' => '',
'srcName' => 'loginname',
'stripTags' => true,
'stripChars' => '#[^\\p{L}\\p{M}a-z0-9_\\.]#ui',
'minLength' => 2,
'maxLength' => '30',
),
'user_login' =>
array (
'niceName' => 'Real Name',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'realname',
'dbClean' => 'toDB',
'stripTags' => true,
'stripChars' => '#<|>#i',
),
'user_customtitle' =>
array (
'niceName' => 'Custom title',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'customtitle',
'dbClean' => 'toDB',
'enablePref' => 'signup_option_customtitle',
'stripTags' => true,
'stripChars' => '#<|>#i',
),
'user_password' =>
array (
'niceName' => 'Password',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'password1',
'dataType' => 2,
'minLength' => '6',
),
'user_sess' =>
array (
'niceName' => 'Photograph',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'stripChars' => '#"|\'|(|)#',
'dbClean' => 'image',
'imagePath' => 'e107_media/b4d51b59e5/avatars/upload/',
'maxHeight' => '80',
'maxWidth' => '80',
),
'user_image' =>
array (
'niceName' => 'Avatar',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'image',
'stripChars' => '#"|\'|(|)#',
'dbClean' => 'avatar',
),
'user_email' =>
array (
'niceName' => 'Email address',
'fieldType' => 'string',
'vetMethod' => '1,3',
'vetParam' => '',
'fieldOptional' => '0',
'srcName' => 'email',
'dbClean' => 'toDB',
),
'user_signature' =>
array (
'niceName' => 'Signature',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'signature',
'dbClean' => 'toDB',
),
'user_hideemail' =>
array (
'niceName' => 'Hide email',
'fieldType' => 'int',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'hideemail',
'dbClean' => 'intval',
),
'user_xup' =>
array (
'niceName' => 'XUP File',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'user_xup',
'dbClean' => 'toDB',
),
'user_class' =>
array (
'niceName' => 'User class',
'fieldType' => 'string',
'vetMethod' => '0',
'vetParam' => '',
'srcName' => 'class',
'dataType' => '1',
),
);
}
/*
public function testAddFieldTypes()
{
}
*/
public function testDbValidateArray()
{
$posted = array (
'data' =>
array (
'user_name' => 'user11',
'user_loginname' => 'user11',
'user_password' => 'Test1234',
'user_email' => 'user11@test.com',
'user_hideemail' => 1,
),
'failed' => array (),
'errors' => array (),
);
$expected = $posted;
$vc = $this->vc;
$vc::dbValidateArray($posted, $this->vettingInfo, 'user', 0);
$this->assertSame($expected, $posted);
}
/*
public function testFindChanges()
{
}
public function testCheckMandatory()
{
}
public function testMakeErrorList()
{
}
*/
public function testValidateFields()
{
// Signup posted data.
$posted = array (
'e-token' => 'faefb3f337edb39dbc0c91abee497b94',
'simulation' => '1',
'loginname' => 'user11',
'email' => 'user11@test.com',
'email2' => '',
'password1' => 'Test1234',
'password2' => 'Test1234',
'register' => 'Register',
'hideemail' => 1,
'email_confirm' => 'user11@test.com',
'username' => 'user11',
);
$expected = array (
'data' =>
array (
'user_name' => 'user11',
'user_loginname' => 'user11',
'user_password' => 'Test1234',
'user_email' => 'user11@test.com',
'user_hideemail' => 1,
),
'failed' => array (),
'errors' => array (),
);
$vc = $this->vc;
$result = $vc::validateFields($posted, $this->vettingInfo, true);
$this->assertSame($expected, $result);
}
}

View File

@@ -207,11 +207,12 @@ if (isset($_POST['register']) && intval($pref['user_reg']) === 1)
// Now validate everything // Now validate everything
$allData = validatorClass::validateFields($_POST,$userMethods->userVettingInfo, TRUE); // Do basic validation $allData = validatorClass::validateFields($_POST,$userMethods->userVettingInfo, TRUE); // Do basic validation
validatorClass::checkMandatory('user_name,user_loginname', $allData); // Check for missing fields (email done in userValidation() )
validatorClass::checkMandatory('user_name,user_loginname', $allData);
// Check for missing fields (email done in userValidation() )
validatorClass::dbValidateArray($allData, $userMethods->userVettingInfo, 'user', 0); // Do basic DB-related checks validatorClass::dbValidateArray($allData, $userMethods->userVettingInfo, 'user', 0); // Do basic DB-related checks
$userMethods->userValidation($allData); $userMethods->userValidation($allData);
$savePassword = null; $savePassword = null;
if (!isset($allData['errors']['user_password'])) if (!isset($allData['errors']['user_password']))