本文整理汇总了PHP中Gdn_Validation类的典型用法代码示例。如果您正苦于以下问题:PHP Gdn_Validation类的具体用法?PHP Gdn_Validation怎么用?PHP Gdn_Validation使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Gdn_Validation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: Validate
public function Validate($Criteria, $Form)
{
$Validation = new Gdn_Validation();
$Validation->ApplyRules(array(array('Name' => 'SocialNetwork', 'Validation' => array('Required'))));
$Validation->Validate($Criteria);
$Form->SetValidationResults($Validation->Results());
}
示例2: Delete
public function Delete($RoleID = FALSE)
{
$this->Title(Translate('Delete Role'));
$this->Permission('Garden.Roles.Manage');
$this->AddSideMenu('garden/role');
$Role = $this->RoleModel->GetByRoleID($RoleID);
if ($Role->Deletable == '0') {
$this->Form->AddError('You cannot delete this role.');
}
// Make sure the form knows which item we are deleting.
$this->Form->AddHidden('RoleID', $RoleID);
// Figure out how many users will be affected by this deletion
$this->AffectedUsers = $this->RoleModel->GetUserCount($RoleID);
// Figure out how many users will be orphaned by this deletion
$this->OrphanedUsers = $this->RoleModel->GetUserCount($RoleID, TRUE);
// Get a list of roles other than this one that can act as a replacement
$this->ReplacementRoles = $this->RoleModel->GetByNotRoleID($RoleID);
if ($this->Form->AuthenticatedPostBack()) {
// Make sure that a replacement role has been selected if there were going to be orphaned users
if ($this->OrphanedUsers > 0) {
$Validation = new Gdn_Validation();
$Validation->ApplyRule('ReplacementRoleID', 'Required', 'You must choose a replacement role for orphaned users.');
$Validation->Validate($this->Form->FormValues());
$this->Form->SetValidationResults($Validation->Results());
}
if ($this->Form->ErrorCount() == 0) {
// Go ahead and delete the Role
$this->RoleModel->Delete($RoleID, $this->Form->GetValue('ReplacementRoleID'));
$this->RedirectUrl = Url('garden/role');
$this->StatusMessage = Gdn::Translate('Deleting role...');
}
}
$this->Render();
}
示例3: Validate
public function Validate($Criteria, $Form)
{
$Validation = new Gdn_Validation();
$Validation->ApplyRules(array(array('Name' => 'Target', 'Validation' => array('Required', 'Integer')), array('Name' => 'Duration', 'Validation' => array('Required', 'Integer')), array('Name' => 'Period', 'Validation' => 'Required')));
$Validation->Validate($Criteria);
$Form->SetValidationResults($Validation->Results());
}
示例4: Validate
public function Validate($Criteria, $Form)
{
$Validation = new Gdn_Validation();
foreach ($Criteria as $ActionID => $Target) {
$Validation->ApplyRule($ActionID, 'Integer');
}
$Validation->Validate($Criteria);
$Form->SetValidationResults($Validation->Results());
}
示例5: validate
/**
* Validate data to be used as class properties.
*
* @param array $Parameters .
* @return string|true True on success or string (message) on error.
*/
public function validate($Parameters = array())
{
$validation = new Gdn_Validation();
// Validate integer properties.
$validation->applyRule('expiry', 'Integer');
$validation->applyRule('limit', 'Integer');
$validation->applyRule('bodylimit', 'Integer');
$validation->applyRule('titlelimit', 'Integer');
$validation->applyRule('group', 'Integer');
// Validate selection.
$validation->applyRule('selection', 'String');
// Validate selector.
$validation->applyRule('selector', 'Required');
$selectorWhitelist = array('role', 'rank', 'category', 'score', 'promoted');
if (isset($Parameters['selector']) && !in_array($Parameters['selector'], $selectorWhitelist)) {
$validation->addValidationResult('selector', 'Invalid selector.');
}
// Validate ContentType.
$typeWhitelist = array('all', 'discussions', 'comments');
if (isset($Parameters['contenttype']) && !in_array($Parameters['contenttype'], $typeWhitelist)) {
$validation->addValidationResult('contenttype', 'Invalid contenttype.');
}
$result = $validation->validate($Parameters);
return $result === true ? true : $validation->resultsText();
}
示例6: SettingsController_UsefulFunctions_Create
public function SettingsController_UsefulFunctions_Create($Sender)
{
$Sender->Permission('Garden.Plugins.Manage');
$Sender->AddSideMenu();
$Sender->Title('UsefulFunctions Settings');
$Validation = new Gdn_Validation();
$Validation->ApplyRule('Plugins.UsefulFunctions.TimerTick.SecretKey', array('Required'));
$ConfigurationModel = new Gdn_ConfigurationModel($Validation);
$Sender->Form->SetModel($ConfigurationModel);
$ConfigurationModel->SetField(array('Plugins.UsefulFunctions.TimerTick.SecretKey'));
if ($Sender->Form->AuthenticatedPostBack()) {
//$FormValues = $Sender->Form->FormValues();
$Saved = $Sender->Form->Save();
if ($Saved) {
$Sender->InformMessage(T('Saved'), array('Sprite' => 'Check', 'CssClass' => 'Dismissable AutoDismiss'));
}
} else {
$Sender->Form->SetData($ConfigurationModel->Data);
}
$Sender->View = dirname(__FILE__) . '/views/settings.php';
$Sender->Render();
}
示例7: delete
/**
* Remove a role.
*
* @since 2.0.0
* @access public
*/
public function delete($RoleID = false)
{
if (!$this->_permission($RoleID)) {
return;
}
$this->title(t('Delete Role'));
$this->addSideMenu('dashboard/role');
$Role = $this->RoleModel->getByRoleID($RoleID);
if ($Role->Deletable == '0') {
$this->Form->addError('You cannot delete this role.');
}
// Make sure the form knows which item we are deleting.
$this->Form->addHidden('RoleID', $RoleID);
// Figure out how many users will be affected by this deletion
$this->AffectedUsers = $this->RoleModel->getUserCount($RoleID);
// Figure out how many users will be orphaned by this deletion
$this->OrphanedUsers = $this->RoleModel->getUserCount($RoleID, true);
// Get a list of roles other than this one that can act as a replacement
$this->ReplacementRoles = $this->RoleModel->getByNotRoleID($RoleID);
if ($this->Form->authenticatedPostBack()) {
// Make sure that a replacement role has been selected if there were going to be orphaned users
if ($this->OrphanedUsers > 0) {
$Validation = new Gdn_Validation();
$Validation->applyRule('ReplacementRoleID', 'Required', 'You must choose a replacement role for orphaned users.');
$Validation->validate($this->Form->formValues());
$this->Form->setValidationResults($Validation->results());
}
if ($this->Form->errorCount() == 0) {
// Go ahead and delete the Role
$this->RoleModel->deleteAndReplace($RoleID, $this->Form->getValue('ReplacementRoleID'));
$this->RedirectUrl = url('dashboard/role');
$this->informMessage(t('Deleting role...'));
}
}
$this->render();
}
示例8: Create
protected function Create($Sender)
{
$Sender->Permission('Garden.Email.Manage');
$Sender->CanGiveJobToCron = C('EnabledPlugins.PluginUtils') !== False;
$Validation = new Gdn_Validation();
$Validation->ApplyRule('RecipientEmailList', array('Required', 'ValidateEmail'));
$Validation->ApplyRule('Subject', 'Required');
$Validation->ApplyRule('Body', 'Required');
$Sender->DrawConfirmSend = False;
if ($Sender->Form->AuthenticatedPostBack() != False) {
$FormValues = $Sender->Form->FormValues();
$ValidationResult = $Validation->Validate($FormValues);
$Sender->Form->SetValidationResults($Validation->Results());
if ($ValidationResult) {
$Emails = $this->GetUserEmails($FormValues);
$Sender->CountEmails = count($Emails);
if ($Sender->CountEmails == 0) {
$Sender->Form->AddError('No one to send');
}
}
if ($Sender->Form->ErrorCount() == 0) {
$Sender->DrawConfirmSend = True;
if (ArrayValue('ConfirmSend', $FormValues)) {
$Sent = $this->Send($Emails, $FormValues);
if ($Sent != False) {
$Sender->StatusMessage = T('Your message was successfully sent.');
}
}
}
} else {
$SupportAddress = C('Garden.Email.SupportAddress');
if (!$SupportAddress) {
$SupportAddress = 'noreply@' . Gdn::Request()->Host();
}
$Sender->Form->SetValue('RecipientEmailList', $SupportAddress);
}
$Sender->View = $this->GetView('create.php');
$RoleModel = Gdn::Factory('RoleModel');
$Sender->RoleData = $RoleModel->Get();
$Sender->Render();
}
示例9: renderData
/**
* Render the data array.
*
* @param null $Data
* @return bool
* @throws Exception
*/
public function renderData($Data = null)
{
if ($Data === null) {
$Data = array();
// Remove standard and "protected" data from the top level.
foreach ($this->Data as $Key => $Value) {
if ($Key && in_array($Key, array('Title', 'Breadcrumbs'))) {
continue;
}
if (isset($Key[0]) && $Key[0] === '_') {
continue;
// protected
}
$Data[$Key] = $Value;
}
unset($this->Data);
}
// Massage the data for better rendering.
foreach ($Data as $Key => $Value) {
if (is_a($Value, 'Gdn_DataSet')) {
$Data[$Key] = $Value->resultArray();
}
}
$CleanOutut = c('Api.Clean', true);
if ($CleanOutut) {
// Remove values that should not be transmitted via api
$Remove = array('Password', 'HashMethod', 'TransientKey', 'Permissions', 'Attributes', 'AccessToken');
// Remove PersonalInfo values for unprivileged requests.
if (!Gdn::session()->checkPermission('Garden.Moderation.Manage')) {
$Remove[] = 'InsertIPAddress';
$Remove[] = 'UpdateIPAddress';
$Remove[] = 'LastIPAddress';
$Remove[] = 'AllIPAddresses';
$Remove[] = 'Fingerprint';
if (C('Api.Clean.Email', true)) {
$Remove[] = 'Email';
}
$Remove[] = 'DateOfBirth';
$Remove[] = 'Preferences';
$Remove[] = 'Banned';
$Remove[] = 'Admin';
$Remove[] = 'Confirmed';
$Remove[] = 'Verified';
$Remove[] = 'DiscoveryText';
$Remove[] = 'InviteUserID';
$Remove[] = 'DateSetInvitations';
$Remove[] = 'CountInvitations';
$Remove[] = 'CountNotifications';
$Remove[] = 'CountBookmarks';
$Remove[] = 'CountDrafts';
$Remove[] = 'HourOffset';
$Remove[] = 'Gender';
$Remove[] = 'Punished';
$Remove[] = 'Troll';
}
$Data = removeKeysFromNestedArray($Data, $Remove);
}
if (debug() && ($Trace = trace())) {
// Clear passwords from the trace.
array_walk_recursive($Trace, function (&$Value, $Key) {
if (in_array(strtolower($Key), array('password'))) {
$Value = '***';
}
});
$Data['Trace'] = $Trace;
}
// Make sure the database connection is closed before exiting.
$this->EventArguments['Data'] =& $Data;
$this->finalize();
// Add error information from the form.
if (isset($this->Form) && sizeof($this->Form->validationResults())) {
$this->statusCode(400);
$Data['Code'] = 400;
$Data['Exception'] = Gdn_Validation::resultsAsText($this->Form->validationResults());
}
$this->sendHeaders();
// Check for a special view.
$ViewLocation = $this->fetchViewLocation(($this->View ? $this->View : $this->RequestMethod) . '_' . strtolower($this->deliveryMethod()), false, false, false);
if (file_exists($ViewLocation)) {
include $ViewLocation;
return;
}
// Add schemes to to urls.
if (!c('Garden.AllowSSL') || c('Garden.ForceSSL')) {
$r = array_walk_recursive($Data, array('Gdn_Controller', '_FixUrlScheme'), Gdn::request()->scheme());
}
if (ob_get_level()) {
ob_clean();
}
switch ($this->deliveryMethod()) {
case DELIVERY_METHOD_XML:
safeHeader('Content-Type: text/xml', true);
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
//.........这里部分代码省略.........
示例10: validateRule
/**
* Validates a rule on the form and adds its result to the errors collection.
*
* @param string $FieldName The name of the field to validate.
* @param string|array $Rule The rule to validate against.
* @param string $CustomError A custom error string.
* @return bool Whether or not the rule succeeded.
*
* @see Gdn_Validation::ValidateRule()
*/
public function validateRule($FieldName, $Rule, $CustomError = '')
{
$Value = $this->getFormValue($FieldName);
$Valid = Gdn_Validation::validateRule($Value, $FieldName, $Rule, $CustomError);
if ($Valid === true) {
return true;
} else {
$this->addError('@' . $Valid, $FieldName);
return false;
}
}
示例11: Index
public function Index()
{
$this->Permission('Garden.Import');
// This permission doesn't exist, so only users with Admin == '1' will succeed.
$Timer = new Gdn_Timer();
// Determine the current step.
$this->Form = new Gdn_Form();
$Imp = new ImportModel();
$Imp->LoadState();
if ($Imp->CurrentStep < 1) {
// Check to see if there is a file.
$ImportPath = Gdn::Config('Garden.Import.ImportPath');
$Validation = new Gdn_Validation();
if (strcasecmp(Gdn::Request()->RequestMethod(), 'post') == 0) {
$Upload = new Gdn_Upload();
$Validation = new Gdn_Validation();
$TmpFile = $Upload->ValidateUpload('ImportFile', FALSE);
if ($TmpFile) {
$Filename = $_FILES['ImportFile']['name'];
$Extension = pathinfo($Filename, PATHINFO_EXTENSION);
$TargetFolder = PATH_ROOT . DS . 'uploads' . DS . 'import';
if (!file_exists($TargetFolder)) {
mkdir($TargetFolder, 0777, TRUE);
}
$ImportPath = $Upload->GenerateTargetName(PATH_ROOT . DS . 'uploads' . DS . 'import', $Extension);
$Upload->SaveAs($TmpFile, $ImportPath);
$Imp->ImportPath = $ImportPath;
$Imp->Data['OriginalFilename'] = basename($Filename);
} elseif (!$Imp->ImportPath) {
// There was no file uploaded this request or before.
$Validation->AddValidationResult('ImportFile', $Upload->Exception);
}
// Validate the overwrite.
if (strcasecmp($this->Form->GetFormValue('Overwrite'), 'Overwrite') == 0) {
$Validation->ApplyRule('Email', 'Required');
$Validation->ApplyRule('Password', 'Required');
}
if ($Validation->Validate($this->Form->FormValues())) {
$Imp->Overwrite($this->Form->GetFormValue('Overwrite', 'Overwrite'), $this->Form->GetFormValue('Email'), $this->Form->GetFormValue('Password'));
$this->View = 'Info';
} else {
$this->Form->SetValidationResults($Validation->Results());
}
} else {
// Search for an existing file that was uploaded by the web admin.
$ImportPaths = SafeGlob(PATH_ROOT . DS . 'uploads' . DS . 'import' . DS . 'import.*');
if ($ImportPaths) {
$ImportPath = $ImportPaths[0];
if (in_array(pathinfo($ImportPath, PATHINFO_EXTENSION), array('gz', 'txt'))) {
$Imp->ImportPath = $ImportPath;
$Imp->Data['OriginalFilename'] = basename($ImportPath);
}
}
}
$Imp->SaveState();
} else {
$this->View = 'Info';
}
$this->SetData('Header', $Imp->GetImportHeader());
$this->SetData('ImportPath', $Imp->ImportPath);
$this->SetData('OriginalFilename', GetValue('OriginalFilename', $Imp->Data));
$this->Render();
}
示例12: avatars
/**
* Settings page for managing avatar settings.
*
* Displays the current avatar and exposes the following config settings:
* Garden.Thumbnail.Size
* Garden.Profile.MaxWidth
* Garden.Profile.MaxHeight
*/
public function avatars()
{
$this->permission('Garden.Community.Manage');
$this->addSideMenu('dashboard/settings/avatars');
$this->addJsFile('avatars.js');
$this->title(t('Avatars'));
$validation = new Gdn_Validation();
$validation->applyRule('Garden.Thumbnail.Size', 'Integer', t('Thumbnail size must be an integer.'));
$validation->applyRule('Garden.Profile.MaxWidth', 'Integer', t('Max avatar width must be an integer.'));
$validation->applyRule('Garden.Profile.MaxHeight', 'Integer', t('Max avatar height must be an integer.'));
$configurationModel = new Gdn_ConfigurationModel($validation);
$configurationModel->setField(array('Garden.Thumbnail.Size', 'Garden.Profile.MaxWidth', 'Garden.Profile.MaxHeight'));
$this->Form->setModel($configurationModel);
$this->setData('avatar', UserModel::getDefaultAvatarUrl());
if (!$this->Form->authenticatedPostBack()) {
$this->Form->setData($configurationModel->Data);
$this->setData('lessHidden', 'Hidden');
// show advanced settings only if we're in a post-back
} else {
$this->setData('moreHidden', 'Hidden');
if ($this->Form->save() !== false) {
$this->informMessage(t("Your settings have been saved."));
}
}
$this->render();
}
示例13: CheckUser
/**
* Add ban data to all Get requests.
*
* @since 2.0.18
* @access public
*
* @param mixed User data (array or object).
* @param Gdn_Validation $Validation
* @param bool $UpdateBlocks
* @return bool Whether user is banned.
*/
public static function CheckUser($User, $Validation = NULL, $UpdateBlocks = FALSE, &$BansFound = NULL)
{
$Bans = self::AllBans();
$Fields = array('Name' => 'Name', 'Email' => 'Email', 'IPAddress' => 'LastIPAddress');
$Banned = array();
if (!$BansFound) {
$BansFound = array();
}
foreach ($Bans as $Ban) {
// Convert ban to regex.
$Parts = explode('*', str_replace('%', '*', $Ban['BanValue']));
$Parts = array_map('preg_quote', $Parts);
$Regex = '`^' . implode('.*', $Parts) . '$`i';
if (preg_match($Regex, GetValue($Fields[$Ban['BanType']], $User))) {
$Banned[$Ban['BanType']] = TRUE;
$BansFound[] = $Ban;
if ($UpdateBlocks) {
Gdn::SQL()->Update('Ban')->Set('CountBlockedRegistrations', 'CountBlockedRegistrations + 1', FALSE, FALSE)->Where('BanID', $Ban['BanID'])->Put();
}
}
}
// Add the validation results.
if ($Validation) {
foreach ($Banned as $BanType => $Value) {
$Validation->AddValidationResult(Gdn_Form::LabelCode($BanType), 'ValidateBanned');
}
}
return count($Banned) == 0;
}
示例14: RenderData
public function RenderData($Data = NULL)
{
if ($Data === NULL) {
$Data = array();
// Remove standard and "protected" data from the top level.
foreach ($this->Data as $Key => $Value) {
if ($Key && in_array($Key, array('Title', 'Breadcrumbs'))) {
continue;
}
if (isset($Key[0]) && $Key[0] === '_') {
continue;
}
// protected
$Data[$Key] = $Value;
}
unset($this->Data);
}
// Massage the data for better rendering.
foreach ($Data as $Key => $Value) {
if (is_a($Value, 'Gdn_DataSet')) {
$Data[$Key] = $Value->ResultArray();
}
}
$CleanOutut = C('Api.Clean', TRUE);
if ($CleanOutut) {
// Remove values that should not be transmitted via api
$Remove = array('Password', 'HashMethod', 'TransientKey', 'Permissions', 'Attributes', 'AccessToken');
if (!Gdn::Session()->CheckPermission('Garden.Moderation.Manage')) {
$Remove[] = 'InsertIPAddress';
$Remove[] = 'UpdateIPAddress';
$Remove[] = 'LastIPAddress';
$Remove[] = 'AllIPAddresses';
$Remove[] = 'Fingerprint';
if (C('Api.Clean.Email', TRUE)) {
$Remove[] = 'Email';
}
$Remove[] = 'DateOfBirth';
}
$Data = RemoveKeysFromNestedArray($Data, $Remove);
}
if (Debug() && ($Trace = Trace())) {
// Clear passwords from the trace.
array_walk_recursive($Trace, function (&$Value, $Key) {
if (in_array(strtolower($Key), array('password'))) {
$Value = '***';
}
});
$Data['Trace'] = $Trace;
}
// Make sure the database connection is closed before exiting.
$this->EventArguments['Data'] =& $Data;
$this->Finalize();
// Add error information from the form.
if (isset($this->Form) && sizeof($this->Form->ValidationResults())) {
$this->StatusCode(400);
$Data['Code'] = 400;
$Data['Exception'] = Gdn_Validation::ResultsAsText($this->Form->ValidationResults());
}
// $this->SendHeaders();
// Check for a special view.
$ViewLocation = $this->FetchViewLocation(($this->View ? $this->View : $this->RequestMethod) . '_' . strtolower($this->DeliveryMethod()), FALSE, FALSE, FALSE);
if (file_exists($ViewLocation)) {
include $ViewLocation;
return;
}
// Add schemes to to urls.
if (!C('Garden.AllowSSL') || C('Garden.ForceSSL')) {
$r = array_walk_recursive($Data, array('Gdn_Controller', '_FixUrlScheme'), Gdn::Request()->Scheme());
}
@ob_clean();
switch ($this->DeliveryMethod()) {
case DELIVERY_METHOD_XML:
safeHeader('Content-Type: text/xml', TRUE);
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$this->_RenderXml($Data);
return TRUE;
break;
case DELIVERY_METHOD_PLAIN:
return TRUE;
break;
case DELIVERY_METHOD_JSON:
default:
if (($Callback = $this->Request->Get('callback', FALSE)) && $this->AllowJSONP()) {
safeHeader('Content-Type: application/javascript', TRUE);
// This is a jsonp request.
echo $Callback . '(' . json_encode($Data) . ');';
return TRUE;
} else {
safeHeader('Content-Type: application/json', TRUE);
// This is a regular json request.
echo json_encode($Data);
return TRUE;
}
break;
}
return FALSE;
}
示例15: checkUser
/**
* Add ban data to all Get requests.
*
* @since 2.0.18
* @access public
*
* @param mixed User data (array or object).
* @param Gdn_Validation $Validation
* @param bool $UpdateBlocks
* @return bool Whether user is banned.
*/
public static function checkUser($User, $Validation = null, $UpdateBlocks = false, &$BansFound = null)
{
$Bans = self::AllBans();
$Fields = array('Name' => 'Name', 'Email' => 'Email', 'IPAddress' => 'LastIPAddress');
$Banned = array();
if (!$BansFound) {
$BansFound = array();
}
foreach ($Bans as $Ban) {
// Convert ban to regex.
$Parts = explode('*', str_replace('%', '*', $Ban['BanValue']));
$Parts = array_map('preg_quote', $Parts);
$Regex = '`^' . implode('.*', $Parts) . '$`i';
$value = val($Fields[$Ban['BanType']], $User);
if ($Ban['BanType'] === 'IPAddress') {
$value = ipDecode($value);
}
if (preg_match($Regex, $value)) {
$Banned[$Ban['BanType']] = true;
$BansFound[] = $Ban;
if ($UpdateBlocks) {
Gdn::sql()->update('Ban')->set('CountBlockedRegistrations', 'CountBlockedRegistrations + 1', false, false)->where('BanID', $Ban['BanID'])->put();
}
}
}
// Add the validation results.
if ($Validation) {
foreach ($Banned as $BanType => $Value) {
$Validation->addValidationResult(Gdn_Form::LabelCode($BanType), 'ValidateBanned');
}
}
return count($Banned) == 0;
}