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());
 }
Beispiel #2
0
 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();
 }
 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());
 }
 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());
 }
 /**
  * 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();
 }
Beispiel #6
0
 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();
 }
Beispiel #7
0
 /**
  * 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();
 }
 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();
 }
 /**
  * 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";
             $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; charset=' . c('Garden.Charset', 'utf-8'), true);
                 // This is a jsonp request.
                 echo $Callback . '(' . json_encode($Data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . ');';
                 return true;
             } else {
                 safeHeader('Content-Type: application/json; charset=' . c('Garden.Charset', 'utf-8'), true);
                 // This is a regular json request.
                 echo json_encode($Data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                 return true;
             }
             break;
     }
     return false;
 }
Beispiel #10
0
 /**
  * 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;
     }
 }
 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();
 }
 /**
  * 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();
 }
 /**
  * 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;
 }
 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;
 }
Beispiel #15
0
 /**
  * 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;
 }
Beispiel #16
0
 /**
  * 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);
         return FALSE;
     }
 }
 /**
  *
  *
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function merge()
 {
     $this->permission('Garden.Settings.Manage');
     // This must be a postback.
     if (!$this->Request->isAuthenticatedPostBack()) {
         throw forbiddenException('GET');
     }
     $Validation = new Gdn_Validation();
     $Validation->applyRule('OldUserID', 'ValidateRequired');
     $Validation->applyRule('NewUserID', 'ValidateRequired');
     if ($Validation->validate($this->Request->Post())) {
         $Result = Gdn::userModel()->merge($this->Request->post('OldUserID'), $this->Request->post('NewUserID'));
         $this->setData($Result);
     } else {
         $this->Form->setValidationResults($Validation->results());
     }
     $this->render('Blank', 'Utility');
 }
Beispiel #18
0
 public function ProfileController_MyProfileEdit_Create($Sender, $Args)
 {
     $sfYaml = Gdn::Factory('sfYaml');
     $Sender->UserID = ArrayValue(0, $Args, '');
     $Sender->UserName = ArrayValue(1, $Args, '');
     $Sender->GetUserInfo($Sender->UserID, $Sender->UserName);
     $SessionUserID = Gdn::Session()->UserID;
     if ($Sender->User->UserID != $SessionUserID) {
         $Sender->Permission('Garden.Users.Edit');
         $MyMetaUserID = $Sender->User->UserID;
     } else {
         $MyMetaUserID = $SessionUserID = Gdn::Session()->UserID;
     }
     if (file_exists(dirname(__FILE__) . DS . 'mymeta.yml')) {
         $Meta = $sfYaml->load(dirname(__FILE__) . DS . 'mymeta.yml');
         $Sender->SetData('Example', false);
     } else {
         if (file_exists(dirname(__FILE__) . DS . 'mymeta.yml.example')) {
             $Meta = $sfYaml->load(dirname(__FILE__) . DS . 'mymeta.yml.example');
             $Sender->SetData('Example', true);
         }
     }
     $Sender->Form = new Gdn_Form();
     $ValidationFailed = false;
     if ($Sender->Form->AuthenticatedPostBack() === FALSE) {
         $Sender->Form->SetData($Sender->MyProfile);
     } else {
         $Data = $Sender->Form->FormValues();
         $Validation = new Gdn_Validation();
         foreach ($Data as $DataI => $DataV) {
             $Field = $Meta['MyMeta'][$DataI];
             if (GetValue('required', $Field)) {
                 $Validation->ApplyRule($DataI, 'Required', sprintf(T('%s is required'), $Field['name']));
             }
             foreach (GetValue('requiredwith', $Field) as $RequiredWith) {
                 if (!GetValue($RequiredWith, $Datarequired)) {
                     $Validation->ApplyRule($RequiredWith, 'Required', sprintf(T('%s is required with %s'), $Meta['MyMeta'][$RequiredWith]['name'], $Field['name']));
                 }
             }
             if (empty($DataV)) {
                 continue;
             }
             if ($V = GetValue('validate', $Field)) {
                 if (strpos($V, 'Validate') === 0) {
                     //Begins with
                     $V = substr($V, 8);
                     if (function_exists($V)) {
                         $Validation->AddRule($V, 'function:' . $V);
                     } else {
                         if (function_exists($V)) {
                             $Validation->AddRule($V, 'function:Validate' . $V);
                         }
                     }
                 }
                 $Validation->ApplyRule($DataI, $V, sprintf(T('%s not valid'), $Field['name']));
             }
             if ($R = GetValue('validateregex', $Field)) {
                 $Validation->AddRule($DataI, 'regex:`^' . $R . '$`i');
                 $Validation->ApplyRule($DataI, $DataI, sprintf(T('%s not valid'), $Field['name']));
             }
             if ($M = GetValue('maxchar', $Field)) {
                 $Validation->AddRule('MaxLen' . $DataI, 'regex:`^.{0,' . $M . '}$`is');
                 $Validation->ApplyRule($DataI, 'MaxLen' . $DataI, sprintf(T('%s not cannot be longer than %s chars'), $Field['name'], $M));
             }
         }
         $Validation->Validate($Data);
         if (count($Validation->Results()) == 0) {
             $MyMeta = array_intersect_key($Data, $Meta['MyMeta']);
             UserModel::SetMeta($MyMetaUserID, $MyMeta, 'MyMeta.');
         } else {
             $ValidationFailed = true;
         }
         $Sender->Form->SetValidationResults($Validation->Results());
     }
     if (!$ValidationFailed) {
         $Data = UserModel::GetMeta($MyMetaUserID, 'MyMeta.%', 'MyMeta.');
     }
     $MyMeta = array_intersect_key($Data, $Meta['MyMeta']);
     $Sender->SetData('Fields', $Meta['MyMeta']);
     $Sender->SetData('MyMeta', $MyMeta);
     $Sender->View = dirname(__FILE__) . DS . 'views' . DS . 'edit.php';
     $Sender->Render();
 }
Beispiel #19
0
 /**
  * @param unknown_type $FormPostValues
  * @param unknown_type $Insert
  * @return unknown
  * @todo add doc
  */
 public function Validate($FormPostValues, $Insert = FALSE)
 {
     return $this->Validation->Validate($FormPostValues, $Insert);
 }
Beispiel #20
0
 /**
  *
  *
  * @param $pluginName
  * @param Gdn_Validation $validation
  * @param bool $setup
  * @return bool
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function enablePlugin($pluginName, $validation, $setup = true)
 {
     // Check to see if the plugin is already enabled.
     if ($this->addonManager->isEnabled($pluginName, Addon::TYPE_ADDON)) {
         throw new Gdn_UserException(t('The plugin is already enabled.'));
     }
     $addon = $this->addonManager->lookupAddon($pluginName);
     if (!$addon) {
         throw notFoundException('Plugin');
     }
     if (!$validation instanceof Gdn_Validation) {
         $validation = new Gdn_Validation();
     }
     try {
         $this->addonManager->checkRequirements($addon, true);
         $addon->test(true);
     } catch (\Exception $ex) {
         $validation->addValidationResult('addon', '@' . $ex->getMessage());
         return false;
     }
     // Enable this addon's requirements.
     $requirements = $this->addonManager->lookupRequirements($addon, AddonManager::REQ_DISABLED);
     foreach ($requirements as $addonKey => $row) {
         $requiredAddon = $this->addonManager->lookupAddon($addonKey);
         $this->enableAddon($requiredAddon, $setup);
     }
     // Enable the addon.
     $this->enableAddon($addon, $setup);
     // Refresh the locale just in case there are some translations needed this request.
     Gdn::locale()->refresh();
     $this->EventArguments['AddonName'] = $addon->getRawKey();
     $this->fireEvent('AddonEnabled');
     return true;
 }
 /**
  * Main import page.
  *
  * @since 2.0.0
  * @access public
  */
 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();
     // Search for the list of acceptable imports.
     $ImportPaths = array();
     $ExistingPaths = SafeGlob(PATH_UPLOADS . '/export*', array('gz', 'txt'));
     $ExistingPaths2 = SafeGlob(PATH_UPLOADS . '/porter/export*', array('gz'));
     $ExistingPaths = array_merge($ExistingPaths, $ExistingPaths2);
     foreach ($ExistingPaths as $Path) {
         $ImportPaths[$Path] = basename($Path);
     }
     // Add the database as a path.
     $ImportPaths = array_merge(array('db:' => t('This Database')), $ImportPaths);
     if ($Imp->CurrentStep < 1) {
         // Check to see if there is a file.
         $ImportPath = c('Garden.Import.ImportPath');
         $Validation = new Gdn_Validation();
         if (strcasecmp(Gdn::request()->requestMethod(), 'post') == 0) {
             $Upload = new Gdn_Upload();
             $Validation = new Gdn_Validation();
             if (count($ImportPaths) > 0) {
                 $Validation->applyRule('PathSelect', 'Required', t('You must select a file to import.'));
             }
             if (count($ImportPaths) == 0 || $this->Form->getFormValue('PathSelect') == 'NEW') {
                 $TmpFile = $Upload->ValidateUpload('ImportFile', false);
             } else {
                 $TmpFile = '';
             }
             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;
                 $this->Form->setFormValue('PathSelect', $ImportPath);
                 $UploadedFiles = val('UploadedFiles', $Imp->Data);
                 $UploadedFiles[$ImportPath] = basename($Filename);
                 $Imp->Data['UploadedFiles'] = $UploadedFiles;
             } elseif ($PathSelect = $this->Form->getFormValue('PathSelect')) {
                 if ($PathSelect == 'NEW') {
                     $Validation->addValidationResult('ImportFile', 'ValidateRequired');
                 } else {
                     $Imp->ImportPath = $PathSelect;
                 }
             } elseif (!$Imp->ImportPath && count($ImportPaths) == 0) {
                 // There was no file uploaded this request or before.
                 $Validation->addValidationResult('ImportFile', $Upload->Exception);
             }
             // Validate the overwrite.
             if (true || strcasecmp($this->Form->getFormValue('Overwrite'), 'Overwrite') == 0) {
                 if (!stringBeginsWith($this->Form->getFormValue('PathSelect'), 'Db:', true)) {
                     $Validation->applyRule('Email', 'Required');
                 }
             }
             if ($Validation->validate($this->Form->formValues())) {
                 $this->Form->setFormValue('Overwrite', 'overwrite');
                 $Imp->fromPost($this->Form->formValues());
                 $this->View = 'Info';
             } else {
                 $this->Form->setValidationResults($Validation->results());
             }
         } else {
             $this->Form->setFormValue('PathSelect', $Imp->ImportPath);
         }
         $Imp->saveState();
     } else {
         $this->setData('Steps', $Imp->steps());
         $this->View = 'Info';
     }
     if (!stringBeginsWith($Imp->ImportPath, 'db:') && !file_exists($Imp->ImportPath)) {
         $Imp->deleteState();
     }
     try {
         $UploadedFiles = val('UploadedFiles', $Imp->Data, array());
         $ImportPaths = array_merge($ImportPaths, $UploadedFiles);
         $this->setData('ImportPaths', $ImportPaths);
         $this->setData('Header', $Imp->getImportHeader());
         $this->setData('Stats', val('Stats', $Imp->Data, array()));
         $this->setData('GenerateSQL', val('GenerateSQL', $Imp->Data));
         $this->setData('ImportPath', $Imp->ImportPath);
         $this->setData('OriginalFilename', val('OriginalFilename', $Imp->Data));
         $this->setData('CurrentStep', $Imp->CurrentStep);
         $this->setData('LoadSpeedWarning', $Imp->loadTableType(false) == 'LoadTableWithInsert');
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $Imp->saveState();
         $this->View = 'Index';
     }
     $this->render();
 }
 /**
  * You can manually award badges to users for special cases
  *
  * @param int $UserID
  * @throws Gdn_UserException
  */
 public function Award($UserID)
 {
     // Check permission
     $this->Permission('Yaga.Badges.Add');
     $this->AddSideMenu('badge/settings');
     // Only allow awarding if some badges exist
     if (!$this->BadgeModel->GetCount()) {
         throw new Gdn_UserException(T('Yaga.Error.NoBadges'));
     }
     $UserModel = Gdn::UserModel();
     $User = $UserModel->GetID($UserID);
     $this->SetData('Username', $User->Name);
     $Badges = $this->BadgeModel->Get();
     $Badgelist = array();
     foreach ($Badges as $Badge) {
         $Badgelist[$Badge->BadgeID] = $Badge->Name;
     }
     $this->SetData('Badges', $Badgelist);
     if ($this->Form->IsPostBack() == FALSE) {
         // Add the user id field
         $this->Form->AddHidden('UserID', $User->UserID);
     } else {
         $Validation = new Gdn_Validation();
         $Validation->ApplyRule('UserID', 'ValidateRequired');
         $Validation->ApplyRule('BadgeID', 'ValidateRequired');
         if ($Validation->Validate($this->Request->Post())) {
             $FormValues = $this->Form->FormValues();
             if ($this->BadgeAwardModel->Exists($FormValues['UserID'], $FormValues['BadgeID'])) {
                 $this->Form->AddError(sprintf(T('Yaga.Badge.AlreadyAwarded'), $User->Name), 'BadgeID');
                 // Need to respecify the user id
                 $this->Form->AddHidden('UserID', $User->UserID);
             }
             if ($this->Form->ErrorCount() == 0) {
                 $this->BadgeAwardModel->Award($FormValues['BadgeID'], $FormValues['UserID'], Gdn::Session()->UserID, $FormValues['Reason']);
                 if ($this->Request->Get('Target')) {
                     $this->RedirectUrl = $this->Request->Get('Target');
                 } elseif ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
                     $this->RedirectUrl = Url(UserUrl($User));
                 } else {
                     $this->JsonTarget('', '', 'Refresh');
                 }
             }
         } else {
             $this->Form->SetValidationResults($Validation->Results());
         }
     }
     $this->Render();
 }
Beispiel #23
0
 /**
  * @param unknown_type $FormPostValues
  * @param unknown_type $Insert
  * @return unknown
  * @todo add doc
  */
 public function Validate($FormPostValues, $Insert = FALSE)
 {
     $this->DefineSchema();
     return $this->Validation->Validate($FormPostValues, $Insert);
 }
 /**
  * You can manually award ranks to users for special cases
  *
  * @param int $UserID
  * @throws Gdn_UserException
  */
 public function Promote($UserID)
 {
     // Check permission
     $this->Permission('Yaga.Ranks.Add');
     $this->AddSideMenu('rank/settings');
     // Only allow awarding if some ranks exist
     if (!$this->RankModel->GetCount()) {
         throw new Gdn_UserException(T('Yaga.Error.NoRanks'));
     }
     $UserModel = Gdn::UserModel();
     $User = $UserModel->GetID($UserID);
     $this->SetData('Username', $User->Name);
     $Ranks = $this->RankModel->Get();
     $Ranklist = array();
     foreach ($Ranks as $Rank) {
         $Ranklist[$Rank->RankID] = $Rank->Name;
     }
     $this->SetData('Ranks', $Ranklist);
     if ($this->Form->IsPostBack() == FALSE) {
         // Add the user id field
         $this->Form->AddHidden('UserID', $User->UserID);
     } else {
         $Validation = new Gdn_Validation();
         $Validation->ApplyRule('UserID', 'ValidateRequired');
         $Validation->ApplyRule('RankID', 'ValidateRequired');
         if ($Validation->Validate($this->Request->Post())) {
             $FormValues = $this->Form->FormValues();
             if ($this->Form->ErrorCount() == 0) {
                 $this->RankModel->Set($FormValues['RankID'], $FormValues['UserID'], $FormValues['RecordActivity']);
                 $UserModel->SetField($UserID, 'RankProgression', $FormValues['RankProgression']);
                 if ($this->Request->Get('Target')) {
                     $this->RedirectUrl = $this->Request->Get('Target');
                 } elseif ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
                     $this->RedirectUrl = Url(UserUrl($User));
                 } else {
                     $this->JsonTarget('', '', 'Refresh');
                 }
             }
         } else {
             $this->Form->SetValidationResults($Validation->Results());
         }
     }
     $this->Render();
 }