Example #1
0
 /**
  * @inheritdoc
  */
 public function validate($input)
 {
     if (!is_scalar($input) || $input === '') {
         return false;
     }
     $input = str_replace(str_split($this->params['additionalChars']), '', (string) $input);
     return $input === '' || ctype_graph($input);
 }
 /**
  * @en Converts stream bytes into the array of numeric equivalents (or ASCII if you want so)
  * @ru Возвращает дамп в виде массива числовых значений (также может подбирать ASCII)
  *
  * $stream = "ABC1234\0";
  *
  * $dump = stream::dump($stream);             # Array
  *                                            # (
  *                                            #     [0] => 65 # equals ASCII dec `A`
  *                                            #     [1] => 66 # equals ASCII dec `B`
  *                                            #     [2] => 67 # equals ASCII dec `C`
  *                                            #     [3] => 49 # equals ASCII dec `1`
  *                                            #     [4] => 50 # equals ASCII dec `2`
  *                                            #     [5] => 51 # equals ASCII dec `3`
  *                                            #     [6] => 52 # equals ASCII dec `4`
  *                                            #     [7] => 0  # equals ASCII dec `\0`
  *                                            # )
  *
  * $dump = stream::dump($stream, true);       # Array
  *                                            # (
  *                                            #     [0] => 41 # equals ASCII hex `A`
  *                                            #     [1] => 42 # equals ASCII hex `B`
  *                                            #     [2] => 43 # equals ASCII hex `C`
  *                                            #     [3] => 31 # equals ASCII hex `1`
  *                                            #     [4] => 32 # equals ASCII hex `2`
  *                                            #     [5] => 33 # equals ASCII hex `3`
  *                                            #     [6] => 34 # equals ASCII hex `4`
  *                                            #     [7] => 0  # equals ASCII hex `\0`
  *                                            # )
  *
  * $dump = stream::dump($stream, true, true); # Array
  *                                            # (
  *                                            #     [0] => A
  *                                            #     [1] => B
  *                                            #     [2] => C
  *                                            #     [3] => 1
  *                                            #     [4] => 2
  *                                            #     [5] => 3
  *                                            #     [6] => 4
  *                                            #     [7] => 00
  *                                            # )
  *
  * @param string $stream
  * @param bool $hexdump
  * @param bool $decode_printable
  *
  * @return array
  */
 public static function dump($stream, $hexdump = false, $decode_printable = false)
 {
     $byte_array = string::explode($stream);
     $result = null;
     foreach ($byte_array as $byte) {
         if ($decode_printable !== false) {
             if (ctype_graph($byte)) {
                 $result[] = $byte;
                 continue;
             }
         }
         if ($hexdump !== false) {
             $result[] = bin2hex($byte);
             continue;
         }
         $result[] = ord($byte);
     }
     return $result;
 }
Example #3
0
<?php

/* Prototype  : bool ctype_graph(mixed $c)
 * Description: Checks for any printable character(s) except space 
 * Source code: ext/ctype/ctype.c 
 */
/*
 * Pass octal and hexadecimal values to ctype_graph() to test behaviour
 */
echo "*** Testing ctype_graph() : usage variations ***\n";
$orig = setlocale(LC_CTYPE, "C");
$octal_values = array(061, 062, 063, 064);
$hex_values = array(0x31, 0x32, 0x33, 0x34);
echo "\n-- Octal Values --\n";
$iterator = 1;
foreach ($octal_values as $c) {
    echo "-- Iteration {$iterator} --\n";
    var_dump(ctype_graph($c));
    $iterator++;
}
echo "\n-- Hexadecimal Values --\n";
$iterator = 1;
foreach ($hex_values as $c) {
    echo "-- Iteration {$iterator} --\n";
    var_dump(ctype_graph($c));
    $iterator++;
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
Example #4
0
<?php

require_once 'init.php.inc';
if (function_exists('ctype_graph')) {
    $this->isTrue(ctype_graph('fjsdiopfhsiofnuios'), _WT('Original ctype_graph fails to validate random letters.'));
    $this->isTrue(ctype_graph('FELMNFKLFDSNFSKLFNSDL'), _WT('Original ctype_graph fails to validate random uppercase letters.'));
    $this->isTrue(ctype_graph('0123456789azertyuiopqsdfghjklmwxcvbn'), _WT('Original ctype_graph fails to validate [0-9a-z].'));
    $this->isTrue(ctype_graph('5686541641'), _WT('Original ctype_graph fails to validate random numbers.'));
    $this->isTrue(ctype_graph('5A1C9B3F'), _WT('Original ctype_graph fails to validate random hexadecimal numbers.'));
    $this->isTrue(ctype_graph('0123456789azertyuiopqsdfghjklmwxcvbn?'), _WT('Original ctype_graph fails to validate [0-9a-z?].'));
    $this->isTrue(ctype_graph('1.5'), _WT('Original ctype_graph fails to validate a float number.'));
    $this->isTrue(ctype_graph('?*#'), _WT('Original ctype_graph fails to validate punctuation.'));
    $this->isFalse(ctype_graph("\r\n\t"), _WT('Original ctype_graph returns true for control characters.'));
    $this->isFalse(ctype_graph(' '), _WT('Original ctype_graph returns true for a space.'));
    $this->isFalse(ctype_graph(''), _WT('Original ctype_graph returns true for the empty string.'));
    $this->isFalse(ctype_graph(null), _WT('Original ctype_graph returns true for a null value.'));
}
$this->isTrue(emul_ctype_graph('fjsdiopfhsiofnuios'), _WT('Emulated ctype_graph fails to validate random letters.'));
$this->isTrue(emul_ctype_graph('FELMNFKLFDSNFSKLFNSDL'), _WT('Emulated ctype_graph fails to validate random uppercase letters.'));
$this->isTrue(emul_ctype_graph('0123456789azertyuiopqsdfghjklmwxcvbn'), _WT('Emulated ctype_graph fails to validate [0-9a-z].'));
$this->isTrue(emul_ctype_graph('5686541641'), _WT('Emulated ctype_graph fails to validate random numbers.'));
$this->isTrue(emul_ctype_graph('5A1C9B3F'), _WT('Emulated ctype_graph fails to validate random hexadecimal numbers.'));
$this->isTrue(emul_ctype_graph('0123456789azertyuiopqsdfghjklmwxcvbn?'), _WT('Emulated ctype_graph fails to validate [0-9a-z?].'));
$this->isTrue(emul_ctype_graph('1.5'), _WT('Emulated ctype_graph fails to validate a float number.'));
$this->isTrue(emul_ctype_graph('?*#'), _WT('Emulated ctype_graph fails to validate punctuation.'));
$this->isFalse(emul_ctype_graph("\r\n\t"), _WT('Emulated ctype_graph returns true for control characters.'));
$this->isFalse(emul_ctype_graph(' '), _WT('Emulated ctype_graph returns true for a space.'));
$this->isFalse(emul_ctype_graph(''), _WT('Emulated ctype_graph returns true for the empty string.'));
$this->isFalse(emul_ctype_graph(null), _WT('Emulated ctype_graph returns true for a null value.'));
Example #5
0
 /**
  * Validate a string as a one-time-password.
  * A valid OTP should consist of 32-48 printable characters.
  *
  * @param string $otp
  *   String to Validate
  *
  * @return boolean
  *   True if the OTP is valid, false on error.
  */
 public function validOtp($otp)
 {
     $length = strlen($otp);
     /* Check length. */
     if ($length > 48 || $length < 32) {
         return false;
     }
     /* Check for printable charcters (no whitespace). */
     return ctype_graph($otp);
 }
 /**
  * @param string $value
  *
  * @return bool
  */
 public static function hasGraphicalCharsOnly($value)
 {
     return \ctype_graph($value);
 }
 public static function isSingleline($data, $options = array())
 {
     return ctype_graph($data);
 }
 private function _passwordHash(&$data, $value)
 {
     $data['passwordHash'] = ctype_graph($value) && strlen($value) >= 60 ? $value : '';
 }
Example #9
0
 /**
  * Determine whether all characters in a string are visible characters.
  *
  * Whitespace and control characters are not visible characters.
  *
  * @param string $s
  * @return bool Returns `false` if `$s` is empty.
  */
 public static function isVisible($s)
 {
     return ctype_graph($s);
 }
Example #10
0
 /**
  * 是否是可见的字符
  *
  * @param mixed $value
  *
  * @return boolean
  */
 static function isGraph($value)
 {
     return ctype_graph($value);
 }
Example #11
0
function insertExecute()
{
    $iConn = IDB::conn();
    //must have DB as variable to pass to mysqli_real_escape() via iformReq()
    $redirect = THIS_PAGE;
    //global var used for following formReq redirection on failure
    $FirstName = strip_tags(iformReq('FirstName', $iConn));
    $LastName = strip_tags(iformReq('LastName', $iConn));
    $Email = strip_tags(iformReq('Email', $iConn));
    //next check for specific issues with data
    if (!ctype_graph($_POST['FirstName']) || !ctype_graph($_POST['LastName'])) {
        //data must be alphanumeric or punctuation only
        feedback("First and Last Name must contain letters, numbers or punctuation");
        myRedirect(THIS_PAGE);
    }
    if (!onlyEmail($_POST['Email'])) {
        //data must be alphanumeric or punctuation only
        feedback("Data entered for email is not valid");
        myRedirect(THIS_PAGE);
    }
    //build string for SQL insert with replacement vars, %s for string, %d for digits
    $sql = "INSERT INTO test_Customers (FirstName, LastName, Email) VALUES ('%s','%s','%s')";
    # sprintf() allows us to filter (parameterize) form data
    $sql = sprintf($sql, $FirstName, $LastName, $Email);
    @mysqli_query($iConn, $sql) or die(trigger_error(mysqli_error($iConn), E_USER_ERROR));
    #feedback success or failure of update
    if (mysqli_affected_rows($iConn) > 0) {
        //success!  provide feedback, chance to change another!
        feedback("Customer Added Successfully!", "notice");
    } else {
        //Problem!  Provide feedback!
        feedback("Customer NOT added!");
    }
    myRedirect(THIS_PAGE);
}
 /**
  * Input validation driver/controller.
  */
 protected function validateInput(&$input, $kind, $type, $min, $max, $pattern, $noEmptyString = true, $specificValue = false, array $rangeOfValues = NULL, &$errorMessage = NULL)
 {
     $tempVar = NULL;
     $length = mb_strlen($input);
     if ($this->equal($type, 'string') && is_string($input)) {
         $tempVar = $input;
         $this->stringTest($input, $kind, $length, $min, $max, $pattern, $errorMessage);
     } elseif ($this->equal($type, 'int') && ctype_graph($input) && ctype_digit($input) && is_int((int) $input)) {
         $tempVar = (int) $input;
         //Cast string to integer datatype
         $this->integerTest($input, $tempVar, $min, $max, $pattern, $errorMessage);
     } elseif ($this->equal($type, 'float') && ctype_graph($input) && is_numeric($input) && is_float((double) $input)) {
         $tempVar = (double) $input;
         $this->floatTest($input, $tempVar, $min, $max, $pattern, $errorMessage);
     } else {
         $errorMessage = 'Invalid data entered!';
     }
     //A null error message indicates that all previous tests have passed.
     if ($this->equal($errorMessage, '') && $this->matchingTest($tempVar, $noEmptyString, $specificValue, $rangeOfValues, $errorMessage)) {
         return true;
     }
     return false;
 }
Example #13
0
<?php

/* Prototype  : bool ctype_graph(mixed $c)
 * Description: Checks for any printable character(s) except space 
 * Source code: ext/ctype/ctype.c 
 */
/*
 * Pass strings containing different character types to ctype_graph() to test
 * which are considered valid printable character only strings
 */
echo "*** Testing ctype_graph() : usage variations ***\n";
$orig = setlocale(LC_CTYPE, "C");
$values = array("This string contains just letters and spaces", "but this one contains some numbers too 123+456 = 678", "", " ", "a", "ABCXYZ", "abcxyz", "ABCXYZ123DEF456", "abczyz123DEF456", "\r\n", "123", "03F", ")speci@! ch@r\$(", '@!$*', 'ABC', 'abc', 'ABC123', 'abc123', "abc123\n", 'abc 123', '', ' ', base64_decode("w4DDoMOHw6fDiMOo"), "!\$%^&*()_+-={}[]:;@~'#<,>.?/", "\"ABC\"", "String\twith\ttabs", "Sample string with newline\n", "123 ABC XYZ");
$iterator = 1;
foreach ($values as $value) {
    echo "\n-- Iteration {$iterator} --\n";
    var_dump(ctype_graph($value));
    $iterator++;
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
Example #14
0
 public function validate($data) : bool
 {
     return ctype_graph($data);
 }
Example #15
0
<?php

/* Prototype  : bool ctype_graph(mixed $c)
 * Description: Checks for any printable character(s) except space 
 * Source code: ext/ctype/ctype.c 
 */
/*
 * Pass different integers to ctype_graph() to test which character codes are considered
 * valid visibly printable characters
 */
echo "*** Testing ctype_graph() : usage variations ***\n";
$orig = setlocale(LC_CTYPE, "C");
for ($i = 0; $i < 256; $i++) {
    if (ctype_graph($i)) {
        echo "character code {$i} is a printable character\n";
    }
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
Example #16
0
 public function isGraph($string = '')
 {
     if (!is_string($string)) {
         return Error::set(lang('Error', 'stringParameter', '1.(string)'));
     }
     return ctype_graph($string);
 }
Example #17
0
File: Tag.php Project: g4z/poop
 /**
  * Test value is printable character but not whitespace
  * @return bool
  */
 public function isGraph()
 {
     return ctype_graph($this->value);
 }
Example #18
0
 /**
  * Recursive helper for writing XML element(s)
  *
  * @param XMLWriter    $xml  XMLWriter instance
  * @param array|string $data element(s) to write
  * @param string       $root root tag for nested elements
  */
 private static function __from_array(XMLWriter &$xml, $data, $root = '')
 {
     if (is_array($data)) {
         foreach ($data as $index => $element) {
             if (is_int($index)) {
                 $root = $root ? Inflector::singular($root) : 'element_' . $index;
             } else {
                 $root = $index;
             }
             $xml->startElement($root);
             if (is_array($element)) {
                 self::__from_array($xml, $element, $root);
             } else {
                 if (ctype_alnum($element) or ctype_graph($element) or strpos($element, ' ') > -1) {
                     $xml->writeCdata($element);
                 } else {
                     $xml->writeRaw($element);
                 }
             }
             $xml->endElement();
         }
     }
 }
Example #19
0
 /**
  * 是否是可见的字符
  *
  * @param mixed $value
  *
  * @return boolean
  */
 static function validate_is_graph($value)
 {
     return ctype_graph($value);
 }
Example #20
0
//get an unset variable
$unset_var = 10;
unset($unset_var);
// get a class
class classA
{
    public function __toString()
    {
        return "myClass";
    }
}
// heredoc string
$heredoc = <<<EOT
hiWorld!
EOT;
// get a resource variable
$fp = fopen(__FILE__, "r");
// unexpected values to be passed to $c argument
$inputs = array(0, 1, 12345, -2345, 10.5, -10.5, 123456789000.0, 1.23456789E-9, 0.5, NULL, null, true, false, TRUE, FALSE, "", '', array(), "string", 'string', $heredoc, new classA(), @$undefined_var, @$unset_var, $fp);
// loop through each element of $inputs to check the behavior of ctype_graph()
$iterator = 1;
foreach ($inputs as $input) {
    echo "\n-- Iteration {$iterator} --\n";
    var_dump(ctype_graph($input));
    $iterator++;
}
fclose($fp);
setlocale(LC_CTYPE, $orig);
?>
===DONE===
function updateExecute()
{
    if (!is_numeric($_POST['CustomerID'])) {
        //data must be alphanumeric only
        feedback("id passed was not a number. (error code #" . createErrorCode(THIS_PAGE, __LINE__) . ")", "error");
        myRedirect(THIS_PAGE);
    }
    $iConn = IDB::conn();
    //must have DB as variable to pass to mysqli_real_escape() via iformReq()
    $redirect = THIS_PAGE;
    //global var used for following formReq redirection on failure
    $CustomerID = iformReq('CustomerID', $iConn);
    //calls mysqli_real_escape() internally, to check form data
    $FirstName = strip_tags(iformReq('FirstName', $iConn));
    $LastName = strip_tags(iformReq('LastName', $iConn));
    $Email = strip_tags(iformReq('Email', $iConn));
    //next check for specific issues with data
    if (!ctype_graph($_POST['FirstName']) || !ctype_graph($_POST['LastName'])) {
        //data must be alphanumeric or punctuation only
        feedback("First and Last Name must contain letters, numbers or punctuation", "warning");
        myRedirect(THIS_PAGE);
    }
    if (!onlyEmail($_POST['Email'])) {
        //data must be alphanumeric or punctuation only
        feedback("Data entered for email is not valid", "warning");
        myRedirect(THIS_PAGE);
    }
    //build string for SQL insert with replacement vars, %s for string, %d for digits
    $sql = "UPDATE test_Customers set  \n    FirstName='%s',\n    LastName='%s',\n    Email='%s'\n     WHERE CustomerID=%d";
    # sprintf() allows us to filter (parameterize) form data
    $sql = sprintf($sql, $FirstName, $LastName, $Email, (int) $CustomerID);
    @mysqli_query($iConn, $sql) or die(trigger_error(mysqli_error($iConn), E_USER_ERROR));
    #feedback success or failure of update
    if (mysqli_affected_rows($iConn) > 0) {
        //success!  provide feedback, chance to change another!
        feedback("Data Updated Successfully!", "success");
    } else {
        //Problem!  Provide feedback!
        feedback("Data NOT changed!", "warning");
    }
    myRedirect(THIS_PAGE);
}
Example #22
0
 /**
  * @param string $value
  * @param string $message
  *
  * @throws AssertionException
  */
 public static function hasGraphicalCharsOnly($value, $message = '')
 {
     if (false === ctype_graph($value)) {
         throw new AssertionException($message ? $message : self::ASSERT_HAS_GRAPHICAL_CHARS_ONLY);
     }
 }
Example #23
0
 protected function ctypeFunction($input)
 {
     return ctype_graph($input);
 }
 * @see admin_dashboard.php
 * @todo none
 */
require '../inc_0700/config_inc.php';
#provides configuration, pathing, error handling, db credentials
if (isset($_POST['em']) && isset($_POST['pw'])) {
    //if POST is set, prepare to process form data
    $params = array('em', 'pw', 'red');
    #required fields for login	- true disallows other fields
    if (!required_params($params, true)) {
        //abort - required fields not sent
        feedback("Data not properly submitted. (error code #" . createErrorCode(THIS_PAGE, __LINE__) . ")", "error");
        myRedirect($config->adminLogin);
        die;
    }
    if (!ctype_graph($_POST['pw'])) {
        //data must be alphanumeric or punctuation only
        feedback("Illegal characters were entered. (error code #" . createErrorCode(THIS_PAGE, __LINE__) . ")", "error");
        myRedirect($config->adminLogin);
    }
    if (!onlyEmail($_POST['em'])) {
        //login must be a legal email address only
        feedback("Illegal characters were entered. (error code #" . createErrorCode(THIS_PAGE, __LINE__) . ")", "error");
        myRedirect($config->adminLogin);
    }
    // Remove all illegal characters
    $Email = trim($_POST['em']);
    $Email = filter_var($Email, FILTER_SANITIZE_STRING);
    $Password = trim($_POST['pw']);
    $Password = filter_var($Password, FILTER_SANITIZE_EMAIL);
    /*
Example #25
0
 /**
  *
  */
 public function register($username, $password, $confirmPassword, $email, $gender, $birthdate, $securityCode)
 {
     if (preg_match('/[^' . Flux::config('UsernameAllowedChars') . ']/', $username)) {
         throw new Flux_RegisterError('Caractere(s) inválido usados no nome de usuário', Flux_RegisterError::INVALID_USERNAME);
     } elseif (strlen($username) < Flux::config('MinUsernameLength')) {
         throw new Flux_RegisterError('Nome de usuário é muito curto', Flux_RegisterError::USERNAME_TOO_SHORT);
     } elseif (strlen($username) > Flux::config('MaxUsernameLength')) {
         throw new Flux_RegisterError('Nome de usuário é muito longo', Flux_RegisterError::USERNAME_TOO_LONG);
     } elseif (!Flux::config('AllowUserInPassword') && stripos($password, $username) !== false) {
         throw new Flux_RegisterError('Senha contém o nome de usuário', Flux_RegisterError::USERNAME_IN_PASSWORD);
     } elseif (!ctype_graph($password)) {
         throw new Flux_RegisterError('Caractere(s) inválido usado na senha', Flux_RegisterError::INVALID_PASSWORD);
     } elseif (strlen($password) < Flux::config('MinPasswordLength')) {
         throw new Flux_RegisterError('Senha é muito curta', Flux_RegisterError::PASSWORD_TOO_SHORT);
     } elseif (strlen($password) > Flux::config('MaxPasswordLength')) {
         throw new Flux_RegisterError('Senha é muito longa', Flux_RegisterError::PASSWORD_TOO_LONG);
     } elseif ($password !== $confirmPassword) {
         throw new Flux_RegisterError('Senhas não combinam', Flux_RegisterError::PASSWORD_MISMATCH);
     } elseif (Flux::config('PasswordMinUpper') > 0 && preg_match_all('/[A-Z]/', $password, $matches) < Flux::config('PasswordMinUpper')) {
         throw new Flux_RegisterError('As senhas devem conter pelo menos ' + intval(Flux::config('PasswordMinUpper')) + ' letra(s) maiúscula(s)', Flux_RegisterError::PASSWORD_NEED_UPPER);
     } elseif (Flux::config('PasswordMinLower') > 0 && preg_match_all('/[a-z]/', $password, $matches) < Flux::config('PasswordMinLower')) {
         throw new Flux_RegisterError('As senhas devem conter pelo menos ' + intval(Flux::config('PasswordMinLower')) + ' letra(s) minúscula(s)', Flux_RegisterError::PASSWORD_NEED_LOWER);
     } elseif (Flux::config('PasswordMinNumber') > 0 && preg_match_all('/[0-9]/', $password, $matches) < Flux::config('PasswordMinNumber')) {
         throw new Flux_RegisterError('As senhas devem conter pelo menos ' + intval(Flux::config('PasswordMinNumber')) + ' número(s)', Flux_RegisterError::PASSWORD_NEED_NUMBER);
     } elseif (Flux::config('PasswordMinSymbol') > 0 && preg_match_all('/[^A-Za-z0-9]/', $password, $matches) < Flux::config('PasswordMinSymbol')) {
         throw new Flux_RegisterError('As senhas devem conter pelo menos ' + intval(Flux::config('PasswordMinSymbol')) + ' símbolo(s)', Flux_RegisterError::PASSWORD_NEED_SYMBOL);
     } elseif (Flux::config('PasswordMaxSymbols') > 0 && preg_match_all('/[^A-Za-z0-9]/', $password, $matches) > Flux::config('PasswordMaxSymbols')) {
         throw new Flux_RegisterError('As senhas não podem conter mais de ' + intval(Flux::config('PasswordMaxSymbols')) + ' Caracteres', Flux_RegisterError::PASSWORD_MAX_SYMBOLS);
     } elseif (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9\\._-]+@([a-zA-Z0-9]+\\.)([a-zA-Z0-9]+)$/', $email)) {
         throw new Flux_RegisterError('Endereço de e-mail inválido', Flux_RegisterError::INVALID_EMAIL_ADDRESS);
     } elseif (!in_array(strtoupper($gender), array('M', 'F'))) {
         throw new Flux_RegisterError('Gênero inválido', Flux_RegisterError::INVALID_GENDER);
     } elseif (($birthdatestamp = strtotime($birthdate)) === false || date('Y-m-d', $birthdatestamp) != $birthdate) {
         throw new Flux_RegisterError('Data de nascimento inválida', Flux_RegisterError::INVALID_BIRTHDATE);
     } elseif (Flux::config('UseCaptcha')) {
         if (Flux::config('EnableReCaptcha')) {
             require_once 'recaptcha/recaptchalib.php';
             $resp = recaptcha_check_answer(Flux::config('ReCaptchaPrivateKey'), $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
             if (!$resp->is_valid) {
                 throw new Flux_RegisterError('Código de segurança inválido', Flux_RegisterError::INVALID_SECURITY_CODE);
             }
         } elseif (strtolower($securityCode) !== strtolower(Flux::$sessionData->securityCode)) {
             throw new Flux_RegisterError('Código de segurança inválido', Flux_RegisterError::INVALID_SECURITY_CODE);
         }
     }
     $sql = "SELECT userid FROM {$this->loginDatabase}.login WHERE ";
     if ($this->config->getNoCase()) {
         $sql .= 'LOWER(userid) = LOWER(?) ';
     } else {
         $sql .= 'BINARY userid = ? ';
     }
     $sql .= 'LIMIT 1';
     $sth = $this->connection->getStatement($sql);
     $sth->execute(array($username));
     $res = $sth->fetch();
     if ($res) {
         throw new Flux_RegisterError('Nome de usuário já está em uso', Flux_RegisterError::USERNAME_ALREADY_TAKEN);
     }
     if (!Flux::config('AllowDuplicateEmails')) {
         $sql = "SELECT email FROM {$this->loginDatabase}.login WHERE email = ? LIMIT 1";
         $sth = $this->connection->getStatement($sql);
         $sth->execute(array($email));
         $res = $sth->fetch();
         if ($res) {
             throw new Flux_RegisterError('Endereço de e-mail já está em uso', Flux_RegisterError::EMAIL_ADDRESS_IN_USE);
         }
     }
     if ($this->config->getUseMD5()) {
         $password = Flux::hashPassword($password);
     }
     $sql = "INSERT INTO {$this->loginDatabase}.login (userid, user_pass, email, sex, group_id, birthdate) VALUES (?, ?, ?, ?, ?, ?)";
     $sth = $this->connection->getStatement($sql);
     $res = $sth->execute(array($username, $password, $email, $gender, (int) $this->config->getGroupID(), date('Y-m-d', $birthdatestamp)));
     if ($res) {
         $idsth = $this->connection->getStatement("SELECT LAST_INSERT_ID() AS account_id");
         $idsth->execute();
         $idres = $idsth->fetch();
         $createTable = Flux::config('FluxTables.AccountCreateTable');
         $sql = "INSERT INTO {$this->loginDatabase}.{$createTable} (account_id, userid, user_pass, sex, email, reg_date, reg_ip, confirmed) ";
         $sql .= "VALUES (?, ?, ?, ?, ?, NOW(), ?, 1)";
         $sth = $this->connection->getStatement($sql);
         $sth->execute(array($idres->account_id, $username, $password, $gender, $email, $_SERVER['REMOTE_ADDR']));
         return $idres->account_id;
     } else {
         return false;
     }
 }
Example #26
0
 /**
  *
  */
 public function register($username, $password, $confirmPassword, $email, $gender, $birthdate, $securityCode)
 {
     if (preg_match('/^[^' . Flux::config('UsernameAllowedChars') . ']$/', $username)) {
         throw new Flux_RegisterError('Invalid character(s) used in username', Flux_RegisterError::INVALID_USERNAME);
     } elseif (strlen($username) < Flux::config('MinUsernameLength')) {
         throw new Flux_RegisterError('Username is too short', Flux_RegisterError::USERNAME_TOO_SHORT);
     } elseif (strlen($username) > Flux::config('MaxUsernameLength')) {
         throw new Flux_RegisterError('Username is too long', Flux_RegisterError::USERNAME_TOO_LONG);
     } elseif (!Flux::config('AllowUserInPassword') && stripos($password, $username) !== false) {
         throw new Flux_RegisterError('Password contains username', Flux_RegisterError::USERNAME_IN_PASSWORD);
     } elseif (!ctype_graph($password)) {
         throw new Flux_RegisterError('Invalid character(s) used in password', Flux_RegisterError::INVALID_PASSWORD);
     } elseif (strlen($password) < Flux::config('MinPasswordLength')) {
         throw new Flux_RegisterError('Password is too short', Flux_RegisterError::PASSWORD_TOO_SHORT);
     } elseif (strlen($password) > Flux::config('MaxPasswordLength')) {
         throw new Flux_RegisterError('Password is too long', Flux_RegisterError::PASSWORD_TOO_LONG);
     } elseif ($password !== $confirmPassword) {
         throw new Flux_RegisterError('Passwords do not match', Flux_RegisterError::PASSWORD_MISMATCH);
     } elseif (Flux::config('PasswordMinUpper') > 0 && preg_match_all('/[A-Z]/', $password, $matches) < Flux::config('PasswordMinUpper')) {
         throw new Flux_RegisterError('Passwords must contain at least ' + intval(Flux::config('PasswordMinUpper')) + ' uppercase letter(s)', Flux_RegisterError::PASSWORD_NEED_UPPER);
     } elseif (Flux::config('PasswordMinLower') > 0 && preg_match_all('/[a-z]/', $password, $matches) < Flux::config('PasswordMinLower')) {
         throw new Flux_RegisterError('Passwords must contain at least ' + intval(Flux::config('PasswordMinLower')) + ' lowercase letter(s)', Flux_RegisterError::PASSWORD_NEED_LOWER);
     } elseif (Flux::config('PasswordMinNumber') > 0 && preg_match_all('/[0-9]/', $password, $matches) < Flux::config('PasswordMinNumber')) {
         throw new Flux_RegisterError('Passwords must contain at least ' + intval(Flux::config('PasswordMinNumber')) + ' number(s)', Flux_RegisterError::PASSWORD_NEED_NUMBER);
     } elseif (Flux::config('PasswordMinSymbol') > 0 && preg_match_all('/[^A-Za-z0-9]/', $password, $matches) < Flux::config('PasswordMinSymbol')) {
         throw new Flux_RegisterError('Passwords must contain at least ' + intval(Flux::config('PasswordMinSymbol')) + ' symbol(s)', Flux_RegisterError::PASSWORD_NEED_SYMBOL);
     } elseif (!preg_match('/^(.+?)@(.+?)$/', $email)) {
         throw new Flux_RegisterError('Invalid e-mail address', Flux_RegisterError::INVALID_EMAIL_ADDRESS);
     } elseif (!in_array(strtoupper($gender), array('M', 'F'))) {
         throw new Flux_RegisterError('Invalid gender', Flux_RegisterError::INVALID_GENDER);
     } elseif (($birthdatestamp = strtotime($birthdate)) === false || date('Y-m-d', $birthdatestamp) != $birthdate) {
         throw new Flux_RegisterError('Invalid birthdate', Flux_RegisterError::INVALID_BIRTHDATE);
     } elseif (Flux::config('UseCaptcha')) {
         if (Flux::config('EnableReCaptcha')) {
             require_once 'recaptcha/recaptchalib.php';
             $resp = recaptcha_check_answer(Flux::config('ReCaptchaPrivateKey'), $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
             if (!$resp->is_valid) {
                 throw new Flux_RegisterError('Invalid security code', Flux_RegisterError::INVALID_SECURITY_CODE);
             }
         } elseif (strtolower($securityCode) !== strtolower(Flux::$sessionData->securityCode)) {
             throw new Flux_RegisterError('Invalid security code', Flux_RegisterError::INVALID_SECURITY_CODE);
         }
     }
     $sql = "SELECT userid FROM {$this->loginDatabase}.login WHERE ";
     if ($this->config->getNoCase()) {
         $sql .= 'LOWER(userid) = LOWER(?) ';
     } else {
         $sql .= 'BINARY userid = ? ';
     }
     $sql .= 'LIMIT 1';
     $sth = $this->connection->getStatement($sql);
     $sth->execute(array($username));
     $res = $sth->fetch();
     if ($res) {
         throw new Flux_RegisterError('Username is already taken', Flux_RegisterError::USERNAME_ALREADY_TAKEN);
     }
     if (!Flux::config('AllowDuplicateEmails')) {
         $sql = "SELECT email FROM {$this->loginDatabase}.login WHERE email = ? LIMIT 1";
         $sth = $this->connection->getStatement($sql);
         $sth->execute(array($email));
         $res = $sth->fetch();
         if ($res) {
             throw new Flux_RegisterError('E-mail address is already in use', Flux_RegisterError::EMAIL_ADDRESS_IN_USE);
         }
     }
     if ($this->config->getUseMD5()) {
         $password = Flux::hashPassword($password);
     }
     $sql = "INSERT INTO {$this->loginDatabase}.login (userid, user_pass, email, sex, group_id, birthdate) VALUES (?, ?, ?, ?, ?, ?)";
     $sth = $this->connection->getStatement($sql);
     $res = $sth->execute(array($username, $password, $email, $gender, (int) $this->config->getGroupID(), date('Y-m-d', $birthdatestamp)));
     if ($res) {
         $idsth = $this->connection->getStatement("SELECT LAST_INSERT_ID() AS account_id");
         $idsth->execute();
         $idres = $idsth->fetch();
         $createTable = Flux::config('FluxTables.AccountCreateTable');
         $sql = "INSERT INTO {$this->loginDatabase}.{$createTable} (account_id, userid, user_pass, sex, email, reg_date, reg_ip, confirmed) ";
         $sql .= "VALUES (?, ?, ?, ?, ?, NOW(), ?, 1)";
         $sth = $this->connection->getStatement($sql);
         $sth->execute(array($idres->account_id, $username, $password, $gender, $email, $_SERVER['REMOTE_ADDR']));
         return $idres->account_id;
     } else {
         return false;
     }
 }
 public function AddLang($langId, $tags, $chooseLangText, $modxLangName, $rootName, $serverName, $langNames, $isLTR, $save = TRUE)
 {
     if (!is_string($langId) || !ctype_graph($langId)) {
         return FALSE;
     }
     if ($this->IsActiveLangId($langId)) {
         return FALSE;
     }
     if ($this->IsInactiveLangId($langId)) {
         return FALSE;
     }
     if (!is_array($langNames)) {
         return FALSE;
     }
     $success = $this->AddActiveLangId($langId);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     $success = $this->SetLangTagsText($langId, $tags, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     $success = $this->SetRootName($langId, $rootName, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     $success = $this->SetServerName($langId, $serverName, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     $success = $this->SetIsLTR($langId, $isLTR, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     $success = $this->SetChooseLangText($langId, $chooseLangText, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     foreach ($langNames as $whichLangId => $name) {
         $success = $this->SetLangName($langId, $name, $whichLangId, FALSE);
         if (!$success) {
             $this->Reload();
             return FALSE;
         }
     }
     $success = $this->SetMODxLangName($langId, $modxLangName, FALSE);
     if (!$success) {
         $this->Reload();
         return FALSE;
     }
     if ($save) {
         return $this->SaveCurrentSettings();
     }
     return TRUE;
 }
Example #28
0
 $currentPassword = $params->get('currentpass');
 $newPassword = $params->get('newpass');
 $confirmNewPassword = $params->get('confirmnewpass');
 $useGMPassSecurity = $session->account->group_level < Flux::config('EnableGMPassSecurity');
 $passwordMinLength = $useGMPassSecurity ? Flux::config('GMMinPasswordLength') : Flux::config('MinPasswordLength');
 $passwordMinUpper = $useGMPassSecurity ? Flux::config('GMPasswordMinUpper') : Flux::config('PasswordMinUpper');
 $passwordMinLower = $useGMPassSecurity ? Flux::config('GMPasswordMinLower') : Flux::config('PasswordMinLower');
 $passwordMinNumber = $useGMPassSecurity ? Flux::config('GMPasswordMinNumber') : Flux::config('PasswordMinNumber');
 $passwordMinSymbol = $useGMPassSecurity ? Flux::config('GMPasswordMinSymbol') : Flux::config('PasswordMinSymbol');
 if (!$currentPassword) {
     $errorMessage = Flux::message('NeedCurrentPassword');
 } elseif (!$newPassword) {
     $errorMessage = Flux::message('NeedNewPassword');
 } elseif (!Flux::config('AllowUserInPassword') && stripos($newPassword, $session->account->userid) !== false) {
     $errorMessage = Flux::message('NewPasswordHasUsername');
 } elseif (!ctype_graph($newPassword)) {
     $errorMessage = Flux::message('NewPasswordInvalid');
 } elseif (strlen($newPassword) < $passwordMinLength) {
     $errorMessage = sprintf(Flux::message('PasswordTooShort'), $passwordMinLength, Flux::config('MaxPasswordLength'));
 } elseif (strlen($newPassword) > Flux::config('MaxPasswordLength')) {
     $errorMessage = sprintf(Flux::message('PasswordTooLong'), $passwordMinLength, Flux::config('MaxPasswordLength'));
 } elseif (!$confirmNewPassword) {
     $errorMessage = Flux::message('ConfirmNewPassword');
 } elseif ($newPassword != $confirmNewPassword) {
     $errorMessage = Flux::message('PasswordsDoNotMatch');
 } elseif ($newPassword == $currentPassword) {
     $errorMessage = Flux::message('NewPasswordSameAsOld');
 } elseif (Flux::config('PasswordMinUpper') > 0 && preg_match_all('/[A-Z]/', $newPassword, $matches) < $passwordMinUpper) {
     $errorMessage = sprintf(Flux::message('NewPasswordNeedUpper'), $passwordMinUpper);
 } elseif (Flux::config('PasswordMinLower') > 0 && preg_match_all('/[a-z]/', $newPassword, $matches) < $passwordMinLower) {
     $errorMessage = sprintf(Flux::message('NewPasswordNeedLower'), $passwordMinLower);
Example #29
0
 function ctype_print($text)
 {
     return ctype_punct($text) && ctype_graph($text);
 }
Example #30
0
 function validate($str, $vtype = NULL, $option = NULL)
 {
     # check for required fields
     if (is_null($vtype)) {
         return !empty($str) ? true : false;
     }
     switch ($vtype) {
         case strtolower('alnum'):
             return preg_match('/^[a-z0-9 ]*$/i', utf8_decode($str)) ? true : false;
             break;
         case strtolower('alpha'):
             return preg_match('/^[a-z ]*$/i', utf8_decode($str)) ? true : false;
             break;
         case strtolower('control'):
             return ctype_cntrl(utf8_decode($str)) ? true : false;
             break;
         case strtolower('digit'):
         case strtolower('number'):
         case strtolower('numeric'):
             return preg_match('/^[0-9,.]*$/i', utf8_decode($str)) ? true : false;
             break;
         case strtolower('graph'):
             return ctype_graph(utf8_decode($str)) ? true : false;
             break;
         case strtolower('lower'):
             return ctype_lower(utf8_decode($str)) ? true : false;
             break;
         case strtolower('print'):
             return ctype_print(utf8_decode($str)) ? true : false;
             break;
         case strtolower('punct'):
         case strtolower('punctuation'):
             return ctype_punct(utf8_decode($str)) ? true : false;
             break;
         case strtolower('space'):
         case strtolower('whitespace'):
             return ctype_space(utf8_decode($str)) ? true : false;
             break;
         case strtolower('upper'):
             return ctype_upper(utf8_decode($str)) ? true : false;
             break;
         case strtolower('xdigit'):
         case strtolower('hexa'):
             return ctype_xdigit(utf8_decode($str)) ? true : false;
             break;
         case strtolower('length'):
             # for length
             if (is_null($option) || !is_numeric($option)) {
                 return 'The length is not specified or is invalid in third argument!';
             }
             return strlen(utf8_decode($str)) > $length ? false : true;
             break;
         case strtolower('regex'):
             # for regex
             if (is_null($option)) {
                 return 'The pattern is not specified or is invalid in third argument!';
             }
             return preg_match("'" . $option . "'", $str) ? true : false;
             break;
         case strtolower('email'):
             return !preg_match("/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,6}\$/ix", $str) ? false : true;
             break;
         case strtolower('string'):
             return is_string(utf8_decode($str)) ? true : false;
             break;
         case strtolower('float'):
             return filter_var($str, FILTER_VALIDATE_FLOAT) === true ? true : false;
             break;
         case strtolower('url'):
         case strtolower('web'):
             return filter_var($str, FILTER_VALIDATE_URL) === true ? true : false;
             break;
         case strtolower('ipv4'):
             return filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === true ? true : false;
             break;
         case strtolower('ipv6'):
             return filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === true ? true : false;
             break;
         default:
             print "Invalid Validator Type Specified !!";
             exit;
     }
 }