Esempio n. 1
0
 public function validate()
 {
     $validator = new Validator();
     $aData = $this->export();
     foreach ($this->fields() as $alias => $field) {
         if (!empty($field['Validation'])) {
             $val_group = new ValidationRulesGroup();
             foreach ($field['Validation'] as $v_type => $v_params) {
                 if ($v_type == 'Required' && $v_params === false) {
                     continue;
                 }
                 if (!is_array($v_params)) {
                     $v_params = array($v_params);
                 }
                 $class_name = 'Validation' . $v_type . 'Rule';
                 $all_params = array_merge(array($alias, @$field['Title']), $v_params);
                 $val_group->add(new $class_name($all_params));
             }
             $validator->addGroup($val_group);
         }
     }
     if (($res = $validator->forceCheck($aData)) === true) {
         return true;
     } else {
         $this->errors = $res;
     }
     return false;
 }
Esempio n. 2
0
 static function validate(&$values, $validators, $defaults = array(), $names = array())
 {
     $filtered_values = array();
     foreach ($validators as $name => $options) {
         if (!isset($values[$name])) {
             $values[$name] = null;
         }
         if (!$options) {
             $options = array();
         }
         $validator = new Validator($options);
         $validator->setOption('required', true);
         if (!isset($options['array']) || $options['array'] === false) {
             $valid = !is_array($values[$name]) && $validator->validate($values[$name]);
         } else {
             $valid = is_array($values[$name]) && $validator->validateArray($values[$name]);
         }
         $key_name = isset($names[$name]) ? $names[$name] : $name;
         if ($valid) {
             $filtered_values[$key_name] = $values[$name];
         } else {
             if (isset($defaults[$name])) {
                 $filtered_values[$key_name] = $defaults[$name];
             } else {
                 $filtered_values[$key_name] = null;
             }
         }
     }
     return $values = $filtered_values;
 }
 /**
  * This function first gets values from mapped fields and then check these values against
  * Mollom web service and then notify callback object with the spam checking result.
  * @param Validator $validator
  * @return 	boolean		- true when Mollom confirms that the submission is ham (not spam)
  *						- false when Mollom confirms that the submission is spam 
  * 						- false when Mollom say 'unsure'. 
  *						  In this case, 'mollom_captcha_requested' session is set to true 
  *       				  so that Field() knows it's time to display captcha 			
  */
 public function validate($validator)
 {
     // Check that, if necessary, the user has given permission to check for spam
     $requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation');
     if ($requireConfirmation && !$this->Value()) {
         $validator->validationError($this->name, _t('AkismetField.NOTIFICATIONREQUIRED', 'You must give consent to submit this content to spam detection'), "error");
         return false;
     }
     // Check result
     $isSpam = $this->getIsSpam();
     if (!$isSpam) {
         return true;
     }
     // Save error message
     $errorMessage = _t('AkismetField.SPAM', "Your submission has been rejected because it was treated as spam.");
     // If spam should be allowed, let it pass and save it for later
     if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) {
         // In order to save spam but still display the spam message, we must mock a form message
         // without failing the validation
         $errors = array(array('fieldName' => $this->name, 'message' => $errorMessage, 'messageType' => 'error'));
         $formName = $this->getForm()->FormName();
         Session::set("FormInfo.{$formName}.errors", $errors);
         return true;
     } else {
         // Mark as spam
         $validator->validationError($this->name, $errorMessage, "error");
         return false;
     }
 }
Esempio n. 4
0
 public function Client()
 {
     $oValidator = new Validator();
     $aResult = array();
     $sTotalReport = '';
     while ($oRule = $oValidator->getCurrentRule()) {
         $oRule->InitUsers();
         while ($oUser = $oRule->getCurrentUser()) {
             $sValidateState = $oRule->Validate($oUser);
             if (!isset($aResult[$oUser->GetId()])) {
                 $aResult[$oUser->GetId()] = array('bot' => 0, 'human' => 0);
             }
             $aResult[$oUser->GetId()]['bot'] += $oRule->GetBotScore();
             $aResult[$oUser->GetId()]['human'] += $oRule->GetHumanScore();
         }
     }
     foreach ($aResult as $iUserId => $aData) {
         $sState = StateProcessor::getUserState($aData['bot'], $aData['human']);
         $this->PluginBotchecker_Botchecker_saveScore($iUserId, $aData, $sState);
         $sReportString = StateProcessor::processUserState($iUserId, $sState);
         if ($sReportString) {
             $sTotalReport = $sTotalReport . $sReportString . "<br>";
         }
     }
     $this->Mail_SetAdress(Config::Get('plugin.botchecker.notify_email'), '');
     $this->Mail_SetSubject('Bot checker report');
     $this->Mail_SetBody($sTotalReport);
     $this->Mail_setHTML();
     $this->Mail_Send();
     $this->Cache_Clean();
 }
 public function testTrans()
 {
     $translator = new DefaultValidatorTranslator();
     $validator = new Validator([], $translator);
     $result = $validator->validateValue(null, ['required' => true]);
     $this->assertEquals('Field must be filled in.', $result);
 }
Esempio n. 6
0
 public function getDriver()
 {
     static $driverObject = false;
     if (!$driverObject) {
         // firewalld is really slow. REALLY slow.
         if (file_exists("/usr/bin/firewall-cmd")) {
             $driver = "Firewalld";
         } else {
             $driver = "Iptables";
         }
         $fn = __DIR__ . "/drivers/{$driver}.class.php";
         if (!file_exists($fn)) {
             throw new \Exception("Unknown driver {$driver}");
         }
         // Note the double slash here so we don't escape the single quote.
         // Turn on syntax highlighting if it's not obvious.
         $class = '\\FreePBX\\modules\\Firewall\\Drivers\\' . $driver;
         // Do we need to load it?
         if (!class_exists($class)) {
             // Woah there, cowboy. This file COULD be run as root. If it is, then the Validator class should exist.
             if (class_exists('\\FreePBX\\modules\\Firewall\\Validator')) {
                 $v = new Validator();
                 $v->secureInclude("drivers/{$driver}.class.php");
             } else {
                 include $fn;
             }
         } else {
             // Debugging
             throw new \Exception("How did {$class} already exist?");
         }
         $driverObject = new $class();
     }
     return $driverObject;
 }
Esempio n. 7
0
function lxReport()
{
    global $DB, $C, $L, $t;
    $v = new Validator();
    $v->Register($_REQUEST['message'], V_EMPTY, "{$L['REQUIRED_FIELD']}: {$L['REPORT']}");
    // Verify captcha code
    if ($C['report_captcha']) {
        VerifyCaptcha($v);
    }
    // Check dsbl.org for spam submissions
    if ($C['dsbl_report'] && CheckDsbl($_SERVER['REMOTE_ADDR'])) {
        $v->SetError($L['DSBL_MATCHED']);
    }
    if (!$v->Validate()) {
        $errors = join('<br />', $v->GetErrors());
        lxShReport($errors);
        return;
    }
    $link = $DB->Row('SELECT * FROM lx_links JOIN lx_link_fields USING (link_id) WHERE lx_links.link_id=?', array($_REQUEST['id']));
    if ($link) {
        $DB->Update('INSERT INTO lx_reports VALUES (?,?,?,?,?)', array(null, $_REQUEST['id'], $_REQUEST['message'], MYSQL_NOW, $_SERVER['REMOTE_ADDR']));
        $t->assign_by_ref('link', $link);
    }
    $t->display('report-submitted.tpl');
}
Esempio n. 8
0
function txReportAdd()
{
    global $DB, $C, $L, $t, $domain;
    $gallery = $DB->Row('SELECT * FROM `tx_galleries` WHERE `gallery_id`=?', array($_REQUEST['id']));
    $v = new Validator();
    $v->Register($_REQUEST['reason'], V_EMPTY, sprintf($L['REQUIRED_FIELD'], $L['REPORT']));
    if (!$gallery) {
        $v->SetError($L['BAD_GALLERY_ID']);
    }
    if ($C['report_captcha']) {
        VerifyCaptcha($v);
    }
    if (!$v->Validate()) {
        return $v->ValidationError('txShReportAdd', TRUE);
    }
    $DB->Update('INSERT INTO `tx_reports` VALUES (?,?,?,?,?)', array(null, $gallery['gallery_id'], $_SERVER['REMOTE_ADDR'], MYSQL_NOW, $_REQUEST['reason']));
    $_REQUEST['report_id'] = $DB->InsertID();
    $t->assign_by_ref('report', $_REQUEST);
    $t->display($domain['template_prefix'] . 'report-complete.tpl');
    flush();
    // See if we need to e-mail any administrators
    $reports_waiting = $DB->Count('SELECT COUNT(*) FROM `tx_reports`');
    $t->assign('reports_waiting', $reports_waiting);
    $administrators =& $DB->FetchAll('SELECT * FROM `tx_administrators`');
    foreach ($administrators as $administrator) {
        if ($administrator['reports_waiting'] > 0) {
            if ($administrator['notifications'] & E_CHEAT_REPORT && $reports_waiting % $administrator['reports_waiting'] == 0) {
                SendMail($administrator['email'], 'email-admin-reports.tpl', $t);
            }
        }
    }
}
Esempio n. 9
0
 public function sendEmail()
 {
     try {
         $emails = explode(',', $this->_correo);
         $to = [];
         foreach ($emails as $email) {
             $params = ['mail' => ['requerido' => 1, 'validador' => 'esEmail', 'mensaje' => utf8_encode('El correo no es v&aacute;lido.')]];
             $destinatario = ['name' => $email, 'mail' => $email];
             $form = new Validator($destinatario, $params);
             if ($form->validate() === false) {
                 throw new Exception('El correo ' . $email . ' no es v&aacute;lido.');
             }
             $to[] = $destinatario;
         }
         $this->_template = ParserTemplate::parseTemplate($this->_template, $this->_info);
         // $subject = '', $body = '', $to = array(), $cc = array(), $bcc = array(), $att = array()
         if (Mailer::sendMail($this->_subject, $this->_template, $to, $this->_cc)) {
             return true;
         } else {
             return false;
         }
     } catch (phpmailerException $e) {
         $this->_PDOConn->rollBack();
         return false;
     }
 }
Esempio n. 10
0
 /**
  * Runs all asserts
  *
  * @param array $aExpectedResult
  */
 protected function runAsserts($aExpectedResult)
 {
     $oConfig = oxRegistry::getConfig();
     $oValidator = new Validator($oConfig);
     if (isset($aExpectedResult['blocks'])) {
         $this->assertTrue($oValidator->checkBlocks($aExpectedResult['blocks']), 'Blocks do not match expectations');
     }
     if (isset($aExpectedResult['extend'])) {
         $this->assertTrue($oValidator->checkExtensions($aExpectedResult['extend']), 'Extensions do not match expectations');
     }
     if (isset($aExpectedResult['files'])) {
         $this->assertTrue($oValidator->checkFiles($aExpectedResult['files']), 'Files do not match expectations');
     }
     if (isset($aExpectedResult['events'])) {
         $this->assertTrue($oValidator->checkEvents($aExpectedResult['events']), 'Events do not match expectations');
     }
     if (isset($aExpectedResult['settings'])) {
         $this->assertTrue($oValidator->checkConfigAmount($aExpectedResult['settings']), 'Configs do not match expectations');
     }
     if (isset($aExpectedResult['versions'])) {
         $this->assertTrue($oValidator->checkVersions($aExpectedResult['versions']), 'Versions do not match expectations');
     }
     if (isset($aExpectedResult['templates'])) {
         $this->assertTrue($oValidator->checkTemplates($aExpectedResult['templates']), 'Templates do not match expectations');
     }
     if (isset($aExpectedResult['disabledModules'])) {
         $this->assertTrue($oValidator->checkDisabledModules($aExpectedResult['disabledModules']), 'Disabled modules do not match expectations');
     }
     if (isset($aExpectedResult['settings_values'])) {
         $this->assertTrue($oValidator->checkConfigValues($aExpectedResult['settings_values']), 'Config values does not match expectations');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function checkEncoding($str, $encoding)
 {
     if (!(bool) $this->on) {
         return true;
     }
     return $this->validator->checkEncoding($str, $encoding);
 }
 function assertNotValid($data, $errors)
 {
     $validator = new Validator();
     $validator->check($data, $this->schema);
     $this->assertEquals($errors, $validator->getErrors(), print_r($validator->getErrors(), true));
     $this->assertFalse($validator->isValid());
 }
Esempio n. 13
0
 public function testValidateNegative()
 {
     $history = $this->getMock('Magento\\Sales\\Model\\Order\\Status\\History', ['hasData'], [], '', false);
     $history->expects($this->any())->method('hasData')->with('parent_id')->will($this->returnValue(false));
     $validator = new Validator();
     $this->assertEquals(['Order Id is a required field'], $validator->validate($history));
 }
Esempio n. 14
0
 public function create()
 {
     $firstname = $_POST['firstname'];
     $lastname = $_POST['lastname'];
     $email = $_POST['email'];
     $username = $_POST['username'];
     $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
     $conn = Db::getConnection();
     $sql = "SELECT *\n\t\t\t\tFROM users";
     $q = $conn->prepare($sql);
     $q->execute();
     $users = $q->fetchAll(\PDO::FETCH_ASSOC);
     $validator = new Validator();
     $error = $validator->validateRegisterForm($_POST, $users);
     //echo '<pre>'; var_dump($error); echo '</pre>';die();
     if ($error) {
         //echo '<pre>'; var_dump($error);die(); echo '</pre>';
         $html = new Html($this->controllerName);
         $html->error = $error;
         //echo '<pre>'; var_dump($html->error);die(); echo '</pre>';
         //;kweojn'dlfv'dlfkv
         $html->render('index');
     } else {
         $newUserSql = "INSERT INTO users\n\t\t\t(`firstname`, `lastname`, `email`, `username`, `password`, `admin`)\n\t\t\tVALUES\n\t\t\t('{$firstname}', '{$lastname}', '{$email}', '{$username}', '{$password}', '0')";
         $q = $conn->prepare($newUserSql);
         $q->execute();
         header('Location: /login/index');
     }
 }
Esempio n. 15
0
 public function combine(Validator $validator)
 {
     $validators = $validator->getValidators();
     foreach ($validators as $validator) {
         $this->validators[] = $validator;
     }
 }
Esempio n. 16
0
 public static function edit($data)
 {
     $p = array('title' => array('required' => true, 'type' => 'string', 'maxlength' => 140, 'label' => 'Titulo'), 'text' => array('required' => true, 'type' => 'string', 'label' => 'Texto'), 'image' => array('required' => false, 'type' => 'thumbnail', 'label' => 'Imagen'), 'tags' => array('required' => false, 'type' => 'string', 'label' => 'Tags'));
     $v = new Validator();
     $response = $v->validate($data, $p);
     if (!$response['success']) {
         return M::cr(false, $data, $response['msg']);
     }
     PDOSql::$pdobj = pdoConnect();
     if (isset($_FILES['image']['name'])) {
         $response = File::up2Web($_FILES['image']);
         if ($response->success) {
             // remove old image...
             if (isset($data['old_image'])) {
                 File::unlinkWeb($data['old_image']);
             }
             $image = $response->data[0];
         } else {
             return M::cr(false, $data, $response->msg);
         }
     } else {
         $image = '';
     }
     $params = array($data['title'], $data['text'], $image, $data['tags'], $data['id'], $_SESSION['userNAME']);
     $where = array(' id = ?', 'author = ?');
     $query = "UPDATE entries SET title = ?, text = ?, image = ?, tags = ? {%WHERE%}";
     PDOSql::update($query, $params, $where);
     return M::cr(true, array(), 'Se han actualizado los datos correctamente');
 }
function form_process()
{
    if (isset($_GET['send'])) {
        $validation = new Validator();
        $struct = array('sucesso' => true, 'error_messages' => array(), 'fields' => array());
        $formID = $_GET['formID'];
        $emailMsg = '';
        global $congeladoForm;
        $form = $congeladoForm->forms;
        if (isset($form[$formID]) && is_array($form[$formID])) {
            $formFields = $form[$formID];
            foreach ($formFields as $fieldname => $fieldrules) {
                $fieldvalue = isset($_GET[$fieldname]) ? $_GET[$fieldname] : '';
                $valid = $validation->validate_field($formID, $fieldname, $fieldvalue);
                if ($valid === true) {
                    $struct['fields'][$fieldname] = $fieldvalue;
                    $emailMsg .= $fieldname . ': ' . $fieldvalue . "\n\n";
                } else {
                    $struct['sucesso'] = false;
                    $struct['error_messages'][$fieldname] = $valid;
                }
            }
        }
        //Callback with the value chain ready for use
        if ($struct['sucesso']) {
            //Values of ADMIN
            $opcoes = get_option('congeladoform');
            if (is_array($opcoes) && isset($opcoes[$formID]) && is_array($opcoes[$formID]) && isset($opcoes[$formID]['email']) && !empty($opcoes[$formID]['email'])) {
                $emailTo = $opcoes[$formID]['email'];
            } else {
                $emailTo = get_option('admin_email');
            }
            if ($_GET['assunto']) {
                $subjectTo = $_GET['assunto'];
            } else {
                $subjectTo = $opcoes[$_GET['formID']]['assunto'];
            }
            //save
            if (is_array($opcoes) && isset($opcoes[$formID]) && is_array($opcoes[$formID]) && isset($opcoes[$formID]['save']) && $opcoes[$formID]['save'] == 1) {
                $rows = get_option('congeladoform_saved_' . $formID);
                if (!is_array($rows)) {
                    $rows = array();
                }
                array_push($rows, $struct['fields']);
                delete_option('congeladoform_saved_' . $formID);
                add_option('congeladoform_saved_' . $formID, $rows, '', 'no');
            }
            $struct['sucesso'] = wp_mail($emailTo, $subjectTo, $emailMsg);
            if (!$struct['sucesso']) {
                $struct['error_messages']['general'] = 'Falha ao enviar o e-mail';
            }
        }
        //returns true and clears the form in JS
        print json_encode($struct);
    } else {
        header("HTTP/1.1 400 Bad Request");
    }
    die;
}
 /**
  * Validate this field as a valid hostname
  *
  * @param Validator $validator
  * @return bool
  */
 public function validate($validator)
 {
     if ($this->checkHostname($this->Value())) {
         return true;
     }
     $validator->validationError($this->getName(), _t("DomainNameField.INVALID_DOMAIN", "Invalid domain name"), "validation");
     return false;
 }
Esempio n. 19
0
 function TestInvalidAddres()
 {
     $validator = new Validator();
     $this->assertTrue(1 == $validator->CheckValidAddress("Point Cook"));
     $this->assertTrue(1 == $validator->CheckValidAddress("Hawthorn East"));
     $this->assertFalse(1 == $validator->CheckValidAddress("G@@@@lenferrie *(7 Hawthorn"));
     $this->assertFalse(1 == $validator->CheckValidAddress("hjagsdhjtest()*(*##Q()*#(@"));
 }
Esempio n. 20
0
 /**
  * Validate this field
  *
  * @param Validator $validator
  * @return bool
  */
 public function validate($validator)
 {
     if (!is_null($this->maxLength) && mb_strlen($this->value) > $this->maxLength) {
         $validator->validationError($this->name, _t('TextField.VALIDATEMAXLENGTH', 'The value for {name} must not exceed {maxLength} characters in length', array('name' => $this->getName(), 'maxLength' => $this->maxLength)), "validation");
         return false;
     }
     return true;
 }
 public function throwStoreResourceFailedException($message = 'Failed to store your requested resource.', Validator $validator = null)
 {
     if ($validator instanceof Validator) {
         throw new \Dingo\Api\Exception\StoreResourceFailedException($message, $validator->errors());
     } else {
         throw new \Dingo\Api\Exception\StoreResourceFailedException($message);
     }
 }
Esempio n. 22
0
 public function setPassword($string)
 {
     $validator = new Validator();
     if ($validator->validatePassword($string) == false) {
     } else {
         $this->password = hash('sha256', $string);
     }
 }
Esempio n. 23
0
 /**
  * Takes an array of unprocessed parameters,
  * and sets them on a new Validator object,
  * which is returned and ready to process the parameters.
  *
  * @since 1.8
  *
  * @param array $params
  * @param array $printRequests
  * @param boolean $unknownInvalid
  *
  * @return Validator
  */
 public static function getValidatorForParams(array $params, array $printRequests = array(), $unknownInvalid = true)
 {
     $paramDefinitions = self::getParameters();
     $paramDefinitions['format']->setPrintRequests($printRequests);
     $validator = new Validator('SMW query', $unknownInvalid);
     $validator->setParameters($params, $paramDefinitions, false);
     return $validator;
 }
 function TestInvalidPassword()
 {
     $validator = new Validator();
     $this->assertTrue(1 == $validator->CheckValidPassword("AS2#fjas91"));
     $this->assertTrue(1 == $validator->CheckValidPassword("asD@#r345f"));
     $this->assertFalse(1 == $validator->CheckValidPassword("password"));
     $this->assertFalse(1 == $validator->CheckValidPassword("test"));
 }
Esempio n. 25
0
 public function validateUniqueEmailFailed(array $data)
 {
     $v = new Validator($data, array(new Unique("email", "field must be unique", "customer")));
     if (!$v->execute()) {
         print_r($v->getErrors());
     } else {
         return true;
     }
 }
Esempio n. 26
0
 public function testValidator()
 {
     // Emulate the WordPress wp_kses function
     $wp_kses = function ($x) {
         return str_replace("<script>", "", $x);
     };
     $validator = new Validator(array("app_id" => "foo<script>"), $wp_kses);
     $this->assertEquals("foo", $validator->validAppId());
 }
Esempio n. 27
0
 function validate()
 {
     $validator = new Validator($this->_value);
     if ($this->isRequired()) {
         $validator->required(sprintf("%s cannot be blank", $this->getName()));
     }
     $this->_errors = $validator->allErrors();
     return $this->allErrors();
 }
Esempio n. 28
0
 public function isValid()
 {
     $validator = new Validator($this->getData());
     $check = $validator->validate($this->getRules());
     if (!$check) {
         $this->setErrors($validator->errors);
     }
     return $check;
 }
Esempio n. 29
0
 function returnFileValidationError()
 {
     //Make sure we return a complete validation error to be displayed to the user.
     $validator_obj = new Validator();
     $validator_stats = array('total_records' => 1, 'valid_records' => 0);
     $validator_obj->isTrue('file', FALSE, TTi18n::getText('Please upload file again'));
     $validator[0] = $validator_obj->getErrorsArray();
     return $this->returnHandler(FALSE, 'IMPORT_FILE', TTi18n::getText('INVALID DATA'), $validator, $validator_stats);
 }
 /**
  * Handles the save of metabox values.
  *
  * @param $postID
  *
  * @return mixed
  */
 public function save($postID)
 {
     $validator = new Validator();
     $http = herbert('http');
     if (!$validator->validateSave($this->nonce, $this->name, $postID)) {
         return $postID;
     }
     update_post_meta($postID, $this->metaKey, $http->get('apiposts_enable_api'));
 }