Essentially overwrites whatever was retrieved from the form.
public setFormValue ( string $FieldName, mixed $Value = null ) | ||
$FieldName | string | The name of the field to set the value of. |
$Value | mixed | The new value of $FieldName. |
/** * Start a new conversation. * * @since 2.0.0 * @access public * * @param string $Recipient Username of the recipient. */ public function add($Recipient = '') { $this->permission('Conversations.Conversations.Add'); $this->Form->setModel($this->ConversationModel); // Set recipient limit if (!checkPermission('Garden.Moderation.Manage') && c('Conversations.MaxRecipients')) { $this->addDefinition('MaxRecipients', c('Conversations.MaxRecipients')); $this->setData('MaxRecipients', c('Conversations.MaxRecipients')); } if ($this->Form->authenticatedPostBack()) { $RecipientUserIDs = array(); $To = explode(',', $this->Form->getFormValue('To', '')); $UserModel = new UserModel(); foreach ($To as $Name) { if (trim($Name) != '') { $User = $UserModel->getByUsername(trim($Name)); if (is_object($User)) { $RecipientUserIDs[] = $User->UserID; } } } // Enforce MaxRecipients if (!$this->ConversationModel->addUserAllowed(0, count($RecipientUserIDs))) { // Reuse the Info message now as an error. $this->Form->addError(sprintf(plural($this->data('MaxRecipients'), "You are limited to %s recipient.", "You are limited to %s recipients."), c('Conversations.MaxRecipients'))); } $this->EventArguments['Recipients'] = $RecipientUserIDs; $this->fireEvent('BeforeAddConversation'); $this->Form->setFormValue('RecipientUserID', $RecipientUserIDs); $ConversationID = $this->Form->save($this->ConversationMessageModel); if ($ConversationID !== false) { $Target = $this->Form->getFormValue('Target', 'messages/' . $ConversationID); $this->RedirectUrl = url($Target); $Conversation = $this->ConversationModel->getID($ConversationID, Gdn::session()->UserID); $NewMessageID = val('FirstMessageID', $Conversation); $this->EventArguments['MessageID'] = $NewMessageID; $this->fireEvent('AfterConversationSave'); } } else { if ($Recipient != '') { $this->Form->setValue('To', $Recipient); } } if ($Target = Gdn::request()->get('Target')) { $this->Form->addHidden('Target', $Target); } Gdn_Theme::section('PostConversation'); $this->title(t('New Conversation')); $this->setData('Breadcrumbs', array(array('Name' => t('Inbox'), 'Url' => '/messages/inbox'), array('Name' => $this->data('Title'), 'Url' => 'messages/add'))); $this->CssClass = 'NoPanel'; $this->render(); }
/** * Upload new version of an existing addon. * * @param int $AddonID Addon ID specified. * @throws Exception Addon not Found. */ public function newVersion($AddonID = '') { $Session = Gdn::session(); $Addon = $this->AddonModel->getID($AddonID); if (!$Addon) { throw notFoundException('Addon'); } if ($Addon['InsertUserID'] != $Session->UserID) { $this->permission('Addons.Addon.Manage'); } $this->addModule('AddonHelpModule'); $this->Form->setModel($this->AddonModel); $this->Form->addHidden('AddonID', $AddonID); if ($this->Form->authenticatedPostBack()) { $AnalyzedAddon = $this->handleAddonUpload(); if ($Addon['Description2'] != $AnalyzedAddon['Description2'] && $Addon['Description2'] != '') { $this->Form->setFormValue('Description2', $Addon['Description2']); } $AnalyzedAddon['AddonID'] = $AddonID; $this->Form->setFormValue('AddonID', $AddonID); // If there were no errors, save the addon version. if ($this->Form->errorCount() == 0) { $NewVersionID = $this->Form->save(false); if ($NewVersionID) { $this->setData('Addon', $AnalyzedAddon); $Addon = $this->AddonModel->getID($AddonID); $this->setData('Url', url('/addon/' . AddonModel::slug($Addon, true), true)); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $this->RedirectUrl = $this->data('Url'); } } } } $this->render(); }
/** * Captcha-authenticated registration. Used by default. * * Events: RegistrationSuccessful * * @access private * @since 2.0.0 */ private function registerCaptcha() { Gdn::userModel()->addPasswordStrength($this); if ($this->Form->isPostBack() === true) { // Add validation rules that are not enforced by the model $this->UserModel->defineSchema(); $this->UserModel->Validation->applyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->applyRule('TermsOfService', 'Required', t('You must agree to the terms of service.')); $this->UserModel->Validation->applyRule('Password', 'Required'); $this->UserModel->Validation->applyRule('Password', 'Strength'); $this->UserModel->Validation->applyRule('Password', 'Match'); // $this->UserModel->Validation->applyRule('DateOfBirth', 'MinimumAge'); $this->fireEvent('RegisterValidation'); try { $Values = $this->Form->formValues(); $Values = $this->UserModel->filterForm($Values, true); unset($Values['Roles']); $AuthUserID = $this->UserModel->register($Values); $this->setData('UserID', $AuthUserID); if ($AuthUserID == UserModel::REDIRECT_APPROVE) { $this->Form->setFormValue('Target', '/entry/registerthanks'); $this->_setRedirect(); return; } elseif (!$AuthUserID) { $this->Form->setValidationResults($this->UserModel->validationResults()); if (!in_array($this->_DeliveryType, [DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA])) { $this->_DeliveryType = DELIVERY_TYPE_MESSAGE; } } else { // The user has been created successfully, so sign in now. if (!Gdn::session()->isValid()) { Gdn::session()->start($AuthUserID, true, (bool) $this->Form->getFormValue('RememberMe')); } try { $this->UserModel->SendWelcomeEmail($AuthUserID, '', 'Register'); } catch (Exception $Ex) { } $this->fireEvent('RegistrationSuccessful'); // ... and redirect them appropriately $Route = $this->RedirectTo(); if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = url($Route); } else { if ($Route !== false) { redirect($Route); } } } } catch (Exception $Ex) { $this->Form->addError($Ex); } } $this->render(); }
/** * Manage options for a mobile theme. * * @since 2.0.0 * @access public * @param string $Style Unique ID. * @todo Why is this in a giant try/catch block? */ public function mobileThemeOptions($Style = null) { $this->permission('Garden.Settings.Manage'); try { $this->addJsFile('addons.js'); $this->addSideMenu('dashboard/settings/mobilethemeoptions'); $ThemeManager = Gdn::themeManager(); $EnabledThemeName = $ThemeManager->mobileTheme(); $EnabledThemeInfo = $ThemeManager->getThemeInfo($EnabledThemeName); $this->setData('ThemeInfo', $EnabledThemeInfo); if ($this->Form->authenticatedPostBack()) { // Save the styles to the config. $StyleKey = $this->Form->getFormValue('StyleKey'); $ConfigSaveData = array('Garden.MobileThemeOptions.Styles.Key' => $StyleKey, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.{$StyleKey}.Basename")); // Save the text to the locale. $Translations = array(); foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Default) { $Value = $this->Form->getFormValue($this->Form->escapeString('Text_' . $Key)); $ConfigSaveData["ThemeOption.{$Key}"] = $Value; //$this->Form->setFormValue('Text_'.$Key, $Value); } saveToConfig($ConfigSaveData); $this->informMessage(t("Your changes have been saved.")); } elseif ($Style) { saveToConfig(array('Garden.MobileThemeOptions.Styles.Key' => $Style, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.{$Style}.Basename"))); } $this->setData('ThemeOptions', c('Garden.MobileThemeOptions')); $StyleKey = $this->data('ThemeOptions.Styles.Key'); if (!$this->Form->authenticatedPostBack()) { foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Options) { $Default = val('Default', $Options, ''); $Value = c("ThemeOption.{$Key}", '#DEFAULT#'); if ($Value === '#DEFAULT#') { $Value = $Default; } $this->Form->setFormValue($this->Form->escapeString('Text_' . $Key), $Value); } } $this->setData('ThemeFolder', $EnabledThemeName); $this->title(t('Mobile Theme Options')); $this->Form->addHidden('StyleKey', $StyleKey); } catch (Exception $Ex) { $this->Form->addError($Ex); } $this->render('themeoptions'); }
/** * Set new password for current user. * * @since 2.0.0 * @access public */ public function password() { $this->permission('Garden.SignIn.Allow'); // Don't allow password editing if using SSO Connect ONLY. // This is for security. We encountered the case where a customer charges // for membership using their external application and use SSO to let // their customers into Vanilla. If you allow those people to change their // password in Vanilla, they will then be able to log into Vanilla using // Vanilla's login form regardless of the state of their membership in the // external app. if (c('Garden.Registration.Method') == 'Connect') { Gdn::dispatcher()->dispatch('DefaultPermission'); exit; } Gdn::userModel()->addPasswordStrength($this); // Get user data and set up form $this->getUserInfo(); $this->Form->setModel($this->UserModel); $this->addDefinition('Username', $this->User->Name); if ($this->Form->authenticatedPostBack() === true) { $this->Form->setFormValue('UserID', $this->User->UserID); $this->UserModel->defineSchema(); // $this->UserModel->Validation->AddValidationField('OldPassword', $this->Form->formValues()); // No password may have been set if they have only signed in with a connect plugin if (!$this->User->HashMethod || $this->User->HashMethod == "Vanilla") { $this->UserModel->Validation->applyRule('OldPassword', 'Required'); $this->UserModel->Validation->applyRule('OldPassword', 'OldPassword', 'Your old password was incorrect.'); } $this->UserModel->Validation->applyRule('Password', 'Required'); $this->UserModel->Validation->applyRule('Password', 'Strength'); $this->UserModel->Validation->applyRule('Password', 'Match'); if ($this->Form->save()) { $this->informMessage(sprite('Check', 'InformSprite') . t('Your password has been changed.'), 'Dismissable AutoDismiss HasSprite'); $this->Form->clearInputs(); Logger::event('password_change', Logger::INFO, '{InsertName} changed password.'); } else { Logger::event('password_change_failure', Logger::INFO, '{InsertName} failed to change password.', array('Error' => $this->Form->errorString())); } } $this->title(t('Change My Password')); $this->_setBreadcrumbs(t('Change My Password'), '/profile/password'); $this->render(); }
/** * Edit a user account. * * @since 2.0.0 * @access public * @param int $UserID Unique ID. */ public function edit($UserID) { $this->permission('Garden.Users.Edit'); // Page setup $this->addJsFile('user.js'); $this->title(t('Edit User')); $this->addSideMenu('dashboard/user'); // Only admins can reassign roles $RoleModel = new RoleModel(); $AllRoles = $RoleModel->getArray(); $RoleData = $RoleModel->getAssignable(); $UserModel = new UserModel(); $User = $UserModel->getID($UserID, DATASET_TYPE_ARRAY); // Determine if username can be edited $CanEditUsername = (bool) c("Garden.Profile.EditUsernames") || Gdn::session()->checkPermission('Garden.Users.Edit'); $this->setData('_CanEditUsername', $CanEditUsername); // Determine if emails can be edited $CanEditEmail = Gdn::session()->checkPermission('Garden.Users.Edit'); $this->setData('_CanEditEmail', $CanEditEmail); // Decide if they have ability to confirm users $Confirmed = (bool) valr('Confirmed', $User); $CanConfirmEmail = UserModel::RequireConfirmEmail() && Gdn::session()->checkPermission('Garden.Users.Edit'); $this->setData('_CanConfirmEmail', $CanConfirmEmail); $this->setData('_EmailConfirmed', $Confirmed); $User['ConfirmEmail'] = (int) $Confirmed; // Determine whether user being edited is privileged (can escalate permissions) $UserModel = new UserModel(); $EditingPrivilegedUser = $UserModel->checkPermission($User, 'Garden.Settings.Manage'); // Determine our password reset options // Anyone with user editing my force reset over email $this->ResetOptions = array(0 => t('Keep current password.'), 'Auto' => t('Force user to reset their password and send email notification.')); // Only admins may manually reset passwords for other admins if (checkPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser) { $this->ResetOptions['Manual'] = t('Manually set user password. No email notification.'); } // Set the model on the form. $this->Form->setModel($UserModel); // Make sure the form knows which item we are editing. $this->Form->addHidden('UserID', $UserID); try { $AllowEditing = true; $this->EventArguments['AllowEditing'] =& $AllowEditing; $this->EventArguments['TargetUser'] =& $User; // These are all the 'effective' roles for this edit action. This list can // be trimmed down from the real list to allow subsets of roles to be // edited. $this->EventArguments['RoleData'] =& $RoleData; $UserRoleData = $UserModel->getRoles($UserID)->resultArray(); $RoleIDs = array_column($UserRoleData, 'RoleID'); $RoleNames = array_column($UserRoleData, 'Name'); $UserRoleData = arrayCombine($RoleIDs, $RoleNames); $this->EventArguments['UserRoleData'] =& $UserRoleData; $this->fireEvent("BeforeUserEdit"); $this->setData('AllowEditing', $AllowEditing); $this->Form->setData($User); if ($this->Form->authenticatedPostBack()) { if (!$CanEditUsername) { $this->Form->setFormValue("Name", $User['Name']); } // Allow mods to confirm/unconfirm emails $this->Form->removeFormValue('Confirmed'); $Confirmation = $this->Form->getFormValue('ConfirmEmail', null); $Confirmation = !is_null($Confirmation) ? (bool) $Confirmation : null; if ($CanConfirmEmail && is_bool($Confirmation)) { $this->Form->setFormValue('Confirmed', (int) $Confirmation); } $ResetPassword = $this->Form->getValue('ResetPassword', false); // If we're an admin or this isn't a privileged user, allow manual setting of password $AllowManualReset = checkPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser; if ($ResetPassword == 'Manual' && $AllowManualReset) { // If a new password was specified, add it to the form's collection $NewPassword = $this->Form->getValue('NewPassword', ''); $this->Form->setFormValue('Password', $NewPassword); } // Role changes // These are the new roles the editing user wishes to apply to the target // user, adjusted for his ability to affect those roles $RequestedRoles = $this->Form->getFormValue('RoleID'); if (!is_array($RequestedRoles)) { $RequestedRoles = array(); } $RequestedRoles = array_flip($RequestedRoles); $UserNewRoles = array_intersect_key($RoleData, $RequestedRoles); // These roles will stay turned on regardless of the form submission contents // because the editing user does not have permission to modify them $ImmutableRoles = array_diff_key($AllRoles, $RoleData); $UserImmutableRoles = array_intersect_key($ImmutableRoles, $UserRoleData); // Apply immutable roles foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) { $UserNewRoles[$IMRoleID] = $IMRoleName; } // Put the data back into the forum object as if the user had submitted // this themselves $this->Form->setFormValue('RoleID', array_keys($UserNewRoles)); if ($this->Form->save(array('SaveRoles' => true)) !== false) { if ($this->Form->getValue('ResetPassword', '') == 'Auto') { $UserModel->PasswordRequest($User['Email']); $UserModel->setField($UserID, 'HashMethod', 'Reset'); } $this->informMessage(t('Your changes have been saved.')); } $UserRoleData = $UserNewRoles; } } catch (Exception $Ex) { $this->Form->addError($Ex); } $this->setData('User', $User); $this->setData('Roles', $RoleData); $this->setData('UserRoles', $UserRoleData); $this->render(); }
/** * Create or update a comment. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error. */ public function comment($DiscussionID = '') { // Get $DiscussionID from RequestArgs if valid if ($DiscussionID == '' && count($this->RequestArgs)) { if (is_numeric($this->RequestArgs[0])) { $DiscussionID = $this->RequestArgs[0]; } } // If invalid $DiscussionID, get from form. $this->Form->setModel($this->CommentModel); $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0); // Set discussion data $this->DiscussionID = $DiscussionID; $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID); // Is this an embedded comment being posted to a discussion that doesn't exist yet? $vanilla_type = $this->Form->getFormValue('vanilla_type', ''); $vanilla_url = $this->Form->getFormValue('vanilla_url', ''); $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', ''); $Attributes = array('ForeignUrl' => $vanilla_url); $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', ''); $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != ''; // Only allow vanilla identifiers of 32 chars or less - md5 if larger if (strlen($vanilla_identifier) > 32) { $Attributes['vanilla_identifier'] = $vanilla_identifier; $vanilla_identifier = md5($vanilla_identifier); } if (!$Discussion && $isEmbeddedComments) { $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type); if ($Discussion) { $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID; $this->Form->setValue('DiscussionID', $DiscussionID); } } // If so, create it! if (!$Discussion && $isEmbeddedComments) { // Add these values back to the form if they exist! $this->Form->addHidden('vanilla_identifier', $vanilla_identifier); $this->Form->addHidden('vanilla_type', $vanilla_type); $this->Form->addHidden('vanilla_url', $vanilla_url); $this->Form->addHidden('vanilla_category_id', $vanilla_category_id); $PageInfo = fetchPageInfo($vanilla_url); if (!($Title = $this->Form->getFormValue('Name'))) { $Title = val('Title', $PageInfo, ''); if ($Title == '') { $Title = t('Undefined discussion subject.'); if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") { $Title .= ' ' . t('Page timed out.'); } } } $Description = val('Description', $PageInfo, ''); $Images = val('Images', $PageInfo, array()); $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); if (!$Description && count($Images) == 0) { $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } else { $Body = formatString(' <div class="EmbeddedContent">{Image}<strong>{Title}</strong> <p>{Excerpt}</p> <p><a href="{Url}">{LinkText}</a></p> <div class="ClearFix"></div> </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText)); } if ($Body == '') { $Body = $vanilla_url; } if ($Body == '') { $Body = t('Undefined discussion body.'); } // Validate the CategoryID for inserting. $Category = CategoryModel::categories($vanilla_category_id); if (!$Category) { $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0); if ($vanilla_category_id <= 0) { // No default category defined, so grab the first non-root category and use that. $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID; // No categories in the db? default to 0 if (!$vanilla_category_id) { $vanilla_category_id = 0; } } } else { $vanilla_category_id = $Category['CategoryID']; } $EmbedUserID = c('Garden.Embed.UserID'); if ($EmbedUserID) { $EmbedUser = Gdn::userModel()->getID($EmbedUserID); } if (!$EmbedUserID || !$EmbedUser) { $EmbedUserID = Gdn::userModel()->getSystemUserID(); } $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes)); $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData; $this->fireEvent('BeforeEmbedDiscussion'); $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData); $ValidationResults = $this->DiscussionModel->validationResults(); if (count($ValidationResults) == 0 && $DiscussionID > 0) { $this->Form->addHidden('DiscussionID', $DiscussionID); // Put this in the form so reposts won't cause new discussions. $this->Form->setFormValue('DiscussionID', $DiscussionID); // Put this in the form values so it is used when saving comments. $this->setJson('DiscussionID', $DiscussionID); $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false)); // Update the category discussion count if ($vanilla_category_id > 0) { $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID); } } } // If no discussion was found, error out if (!$Discussion) { $this->Form->addError(t('Failed to find discussion for commenting.')); } /** * Special care is taken for embedded comments. Since we don't currently use an advanced editor for these * comments, we may need to apply certain filters and fixes to the data to maintain its intended display * with the input format (e.g. maintaining newlines). */ if ($isEmbeddedComments) { $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter')); switch ($inputFormatter) { case 'Wysiwyg': $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body'))); break; } } $PermissionCategoryID = val('PermissionCategoryID', $Discussion); // Setup head $this->addJsFile('jquery.autosize.min.js'); $this->addJsFile('autosave.js'); $this->addJsFile('post.js'); // Setup comment model, $CommentID, $DraftID $Session = Gdn::session(); $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : ''; $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : ''; $this->EventArguments['CommentID'] = $CommentID; $this->EventArguments['DraftID'] = $DraftID; // Determine whether we are editing $Editing = $CommentID > 0 || $DraftID > 0; $this->EventArguments['Editing'] = $Editing; // If closed, cancel & go to discussion if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) { redirect(DiscussionUrl($Discussion)); } // Add hidden IDs to form $this->Form->addHidden('DiscussionID', $DiscussionID); $this->Form->addHidden('CommentID', $CommentID); $this->Form->addHidden('DraftID', $DraftID, true); // Check permissions if ($Discussion && $Editing) { // Permission to edit if ($this->Comment->InsertUserID != $Session->UserID) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure that content can (still) be edited. $EditContentTimeout = c('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure only moderators can edit closed things if ($Discussion->Closed) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } $this->Form->setFormValue('CommentID', $CommentID); } elseif ($Discussion) { // Permission to add $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID); } if ($this->Form->authenticatedPostBack()) { // Save as a draft? $FormValues = $this->Form->formValues(); $FormValues = $this->CommentModel->filterForm($FormValues); if (!$Editing) { unset($FormValues['CommentID']); } if ($DraftID == 0) { $DraftID = $this->Form->getFormValue('DraftID', 0); } $Type = GetIncomingValue('Type'); $Draft = $Type == 'Draft'; $this->EventArguments['Draft'] = $Draft; $Preview = $Type == 'Preview'; if ($Draft) { $DraftID = $this->DraftModel->save($FormValues); $this->Form->addHidden('DraftID', $DraftID, true); $this->Form->setValidationResults($this->DraftModel->validationResults()); } elseif (!$Preview) { // Fix an undefined title if we can. if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) { $Set = array('Name' => $this->Form->getFormValue('Name')); if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) { $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set); } $Inserted = !$CommentID; $CommentID = $this->CommentModel->save($FormValues); // The comment is now half-saved. if (is_numeric($CommentID) && $CommentID > 0) { if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) { $this->CommentModel->save2($CommentID, $Inserted, true, true); } else { $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax'); } // $Discussion = $this->DiscussionModel->getID($DiscussionID); $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false)); $this->EventArguments['Discussion'] = $Discussion; $this->EventArguments['Comment'] = $Comment; $this->fireEvent('AfterCommentSave'); } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) { $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.'); } $this->Form->setValidationResults($this->CommentModel->validationResults()); if ($CommentID > 0 && $DraftID > 0) { $this->DraftModel->delete($DraftID); } } // Handle non-ajax requests first: if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { if ($this->Form->errorCount() == 0) { // Make sure that this form knows what comment we are editing. if ($CommentID > 0) { $this->Form->addHidden('CommentID', $CommentID); } // If the comment was not a draft if (!$Draft) { // Redirect to the new comment. if ($CommentID > 0) { redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}"); } elseif ($CommentID == SPAM) { $this->setData('DiscussionUrl', DiscussionUrl($Discussion)); $this->View = 'Spam'; } } elseif ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = val('Body', $FormValues, ''); $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter')); $this->addAsset('Content', $this->fetchView('preview')); } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } } } else { // Handle ajax-based requests if ($this->Form->errorCount() > 0) { // Return the form errors $this->errorMessage($this->Form->errors()); } else { // Make sure that the ajax request form knows about the newly created comment or draft id $this->setJson('CommentID', $CommentID); $this->setJson('DraftID', $DraftID); if ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = val('Body', $FormValues, ''); $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter')); $this->View = 'preview'; } elseif (!$Draft) { // If the comment was not a draft // If Editing a comment if ($Editing) { // Just reload the comment in question $this->Offset = 1; $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('Discussion', $Discussion); // Load the discussion $this->ControllerName = 'discussion'; $this->View = 'comments'; // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID); } else { // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments. $OrderBy = valr('0.0', $this->CommentModel->orderBy()); // $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID')); // $DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly'); // if (!$Redirect) { // // Otherwise load all new comments that the user hasn't seen yet // $LastCommentID = $this->Form->getFormValue('LastCommentID'); // if (!is_numeric($LastCommentID)) // $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly // // // Don't reload the first comment if this new comment is the first one. // $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID); // // Do not load more than a single page of data... // $Limit = c('Vanilla.Comments.PerPage', 30); // // // Redirect if the new new comment isn't on the same page. // $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit); // } // if ($Redirect) { // // The user posted a comment on a page other than the last one, so just redirect to the last page. // $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true); // } else { // // Make sure to load all new comments since the page was last loaded by this user // if ($DisplayNewCommentOnly) $this->Offset = $this->CommentModel->GetOffset($CommentID); $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('NewComments', true); $this->ClassName = 'DiscussionController'; $this->ControllerName = 'discussion'; $this->View = 'comments'; // } // Make sure to set the user's discussion watch records $CountComments = $this->CommentModel->getCount($DiscussionID); $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments; $Offset = $CountComments - $Limit; $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments); } } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } // And update the draft count $UserModel = Gdn::userModel(); $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0); $this->setJson('MyDrafts', t('My Drafts')); $this->setJson('CountDrafts', $CountDrafts); } } } elseif ($this->Request->isPostBack()) { throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401); } else { // Load form if (isset($this->Comment)) { $this->Form->setData((array) $this->Comment); } } // Include data for FireEvent if (property_exists($this, 'Discussion')) { $this->EventArguments['Discussion'] = $this->Discussion; } if (property_exists($this, 'Comment')) { $this->EventArguments['Comment'] = $this->Comment; } $this->fireEvent('BeforeCommentRender'); if ($this->deliveryType() == DELIVERY_TYPE_DATA) { if ($this->data('Comments') instanceof Gdn_DataSet) { $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY); if ($Comment) { $Photo = $Comment['InsertPhoto']; if (strpos($Photo, '//') === false) { $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s')); } $Comment['InsertPhoto'] = $Photo; } $this->Data = array('Comment' => $Comment); } $this->RenderData($this->Data); } else { require_once $this->fetchViewLocation('helper_functions', 'Discussion'); // Render default view. $this->render(); } }
/** * Set user's photo (avatar). * * @since 2.0.0 * @access public * @param mixed $UserReference Unique identifier, possible username or ID. * @param string $Username . */ public function picture($UserReference = '', $Username = '', $UserID = '') { if (!Gdn::session()->checkRankedPermission(c('Garden.Profile.EditPhotos', true))) { throw forbiddenException('@Editing user photos has been disabled.'); } // Permission checks $this->permission(array('Garden.Profiles.Edit', 'Moderation.Profiles.Edit', 'Garden.ProfilePicture.Edit'), false); $Session = Gdn::session(); if (!$Session->isValid()) { $this->Form->addError('You must be authenticated in order to use this form.'); } // Check ability to manipulate image $ImageManipOk = false; if (function_exists('gd_info')) { $GdInfo = gd_info(); $GdVersion = preg_replace('/[a-z ()]+/i', '', $GdInfo['GD Version']); if ($GdVersion < 2) { throw new Exception(sprintf(t("This installation of GD is too old (v%s). Vanilla requires at least version 2 or compatible."), $GdVersion)); } } else { throw new Exception(sprintf(t("Unable to detect PHP GD installed on this system. Vanilla requires GD version 2 or better."))); } // Get user data & prep form. if ($this->Form->authenticatedPostBack() && $this->Form->getFormValue('UserID')) { $UserID = $this->Form->getFormValue('UserID'); } $this->getUserInfo($UserReference, $Username, $UserID, true); $this->Form->setModel($this->UserModel); if ($this->Form->authenticatedPostBack() === true) { $this->Form->setFormValue('UserID', $this->User->UserID); // Set user's Photo attribute to a URL, provided the current user has proper permission to do so. $photoUrl = $this->Form->getFormValue('Url', false); if ($photoUrl && Gdn::session()->checkPermission('Garden.Settings.Manage')) { if (isUrl($photoUrl) && filter_var($photoUrl, FILTER_VALIDATE_URL)) { $UserPhoto = $photoUrl; } else { $this->Form->addError('Invalid photo URL'); } } else { $UploadImage = new Gdn_UploadImage(); try { // Validate the upload $TmpImage = $UploadImage->ValidateUpload('Picture'); // Generate the target image name. $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS, '', true); $Basename = pathinfo($TargetImage, PATHINFO_BASENAME); $Subdir = stringBeginsWith(dirname($TargetImage), PATH_UPLOADS . '/', false, true); // Delete any previously uploaded image. $UploadImage->delete(changeBasename($this->User->Photo, 'p%s')); // Save the uploaded image in profile size. $Props = $UploadImage->SaveImageAs($TmpImage, "userpics/{$Subdir}/p{$Basename}", c('Garden.Profile.MaxHeight', 1000), c('Garden.Profile.MaxWidth', 250), array('SaveGif' => c('Garden.Thumbnail.SaveGif'))); $UserPhoto = sprintf($Props['SaveFormat'], "userpics/{$Subdir}/{$Basename}"); // // Save the uploaded image in preview size // $UploadImage->SaveImageAs( // $TmpImage, // 'userpics/t'.$ImageBaseName, // Gdn::config('Garden.Preview.MaxHeight', 100), // Gdn::config('Garden.Preview.MaxWidth', 75) // ); // Save the uploaded image in thumbnail size $ThumbSize = Gdn::config('Garden.Thumbnail.Size', 40); $UploadImage->saveImageAs($TmpImage, "userpics/{$Subdir}/n{$Basename}", $ThumbSize, $ThumbSize, array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif'))); } catch (Exception $Ex) { // Throw the exception on API calls. if ($this->deliveryType() === DELIVERY_TYPE_DATA) { throw $Ex; } $this->Form->addError($Ex); } } // If there were no errors, associate the image with the user if ($this->Form->errorCount() == 0) { if (!$this->UserModel->save(array('UserID' => $this->User->UserID, 'Photo' => $UserPhoto), array('CheckExisting' => true))) { $this->Form->setValidationResults($this->UserModel->validationResults()); } else { $this->User->Photo = $UserPhoto; setValue('Photo', $this->Data['Profile'], $UserPhoto); setValue('PhotoUrl', $this->Data['Profile'], Gdn_Upload::url(changeBasename($UserPhoto, 'n%s'))); } } // If there were no problems, redirect back to the user account if ($this->Form->errorCount() == 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) { $this->informMessage(sprite('Check', 'InformSprite') . t('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite'); redirect($this->deliveryType() == DELIVERY_TYPE_VIEW ? userUrl($this->User) : userUrl($this->User, '', 'picture')); } } if ($this->Form->errorCount() > 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) { $this->deliveryType(DELIVERY_TYPE_ALL); } $this->title(t('Change Picture')); $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture')); $this->render(); }
/** * Editing a category. * * @since 2.0.0 * @access public * * @param int $CategoryID Unique ID of the category to be updated. */ public function editCategory($CategoryID = '') { // Check permission $this->permission('Garden.Community.Manage'); // Set up models $RoleModel = new RoleModel(); $PermissionModel = Gdn::permissionModel(); $this->Form->setModel($this->CategoryModel); if (!$CategoryID && $this->Form->authenticatedPostBack()) { if ($ID = $this->Form->getFormValue('CategoryID')) { $CategoryID = $ID; } } // Get category data $this->Category = $this->CategoryModel->getID($CategoryID); if (!$this->Category) { throw notFoundException('Category'); } $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID; // Set up head $this->addJsFile('jquery.alphanumeric.js'); $this->addJsFile('categories.js'); $this->addJsFile('jquery.gardencheckboxgrid.js'); $this->title(t('Edit Category')); $this->addSideMenu('vanilla/settings/managecategories'); // Make sure the form knows which item we are editing. $this->Form->addHidden('CategoryID', $CategoryID); $this->setData('CategoryID', $CategoryID); // Load all roles with editable permissions $this->RoleArray = $RoleModel->getArray(); $this->fireEvent('AddEditCategory'); if ($this->Form->authenticatedPostBack()) { $this->setupDiscussionTypes($this->Category); $Upload = new Gdn_Upload(); $TmpImage = $Upload->validateUpload('PhotoUpload', false); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Save the uploaded image $Parts = $Upload->saveAs($TmpImage, $ImageBaseName); $this->Form->setFormValue('Photo', $Parts['SaveName']); } $this->Form->setFormValue('CustomPoints', (bool) $this->Form->getFormValue('CustomPoints')); if ($this->Form->save()) { $Category = CategoryModel::categories($CategoryID); $this->setData('Category', $Category); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { redirect('vanilla/settings/managecategories'); } } } else { $this->Form->setData($this->Category); $this->setupDiscussionTypes($this->Category); $this->Form->setValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID); } // Get all of the currently selected role/permission combinations for this junction. $Permissions = $PermissionModel->getJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions)); $Permissions = $PermissionModel->unpivotPermissions($Permissions, true); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $this->setData('PermissionData', $Permissions, true); } // Render default view $this->render(); }
/** * Editing a category. * * @since 2.0.0 * @param int|string $CategoryID Unique ID of the category to be updated. * @throws Exception when category cannot be found. */ public function editCategory($CategoryID = '') { // Check permission $this->permission(['Garden.Community.Manage', 'Garden.Settings.Manage'], false); // Set up models $RoleModel = new RoleModel(); $PermissionModel = Gdn::permissionModel(); $this->Form->setModel($this->CategoryModel); if (!$CategoryID && $this->Form->authenticatedPostBack()) { if ($ID = $this->Form->getFormValue('CategoryID')) { $CategoryID = $ID; } } // Get category data $this->Category = CategoryModel::categories($CategoryID); if (!$this->Category) { throw notFoundException('Category'); } // Category data is expected to be in the form of an object. $this->Category = (object) $this->Category; $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID; $displayAsOptions = categoryModel::getDisplayAsOptions(); // Restrict "Display As" types based on parent. $parentCategory = $this->CategoryModel->getID($this->Category->ParentCategoryID); $parentDisplay = val('DisplayAs', $parentCategory); if ($parentDisplay === 'Flat') { unset($displayAsOptions['Heading']); } // Set up head $this->addJsFile('jquery.alphanumeric.js'); $this->addJsFile('manage-categories.js'); $this->addJsFile('jquery.gardencheckboxgrid.js'); $this->title(t('Edit Category')); $this->setHighlightRoute('vanilla/settings/categories'); // Make sure the form knows which item we are editing. $this->Form->addHidden('CategoryID', $CategoryID); $this->setData('CategoryID', $CategoryID); // Load all roles with editable permissions $this->RoleArray = $RoleModel->getArray(); $this->fireAs('SettingsController'); $this->fireEvent('AddEditCategory'); if ($this->Form->authenticatedPostBack()) { $this->setupDiscussionTypes($this->Category); $Upload = new Gdn_Upload(); $TmpImage = $Upload->validateUpload('PhotoUpload', false); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Save the uploaded image $Parts = $Upload->saveAs($TmpImage, $ImageBaseName); $this->Form->setFormValue('Photo', $Parts['SaveName']); } $this->Form->setFormValue('CustomPoints', (bool) $this->Form->getFormValue('CustomPoints')); // Enforces tinyint values on boolean fields to comply with strict mode $this->Form->setFormValue('HideAllDiscussions', forceBool($this->Form->getFormValue('HideAllDiscussions'), '0', '1', '0')); $this->Form->setFormValue('Archived', forceBool($this->Form->getFormValue('Archived'), '0', '1', '0')); $this->Form->setFormValue('AllowFileUploads', forceBool($this->Form->getFormValue('AllowFileUploads'), '0', '1', '0')); if ($parentDisplay === 'Flat' && $this->Form->getFormValue('DisplayAs') === 'Heading') { $this->Form->addError('Cannot display as a heading when your parent category is displayed flat.', 'DisplayAs'); } if ($this->Form->save()) { $Category = CategoryModel::categories($CategoryID); $this->setData('Category', $Category); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $destination = $this->categoryPageByParent($parentCategory); redirect($destination); } elseif ($this->deliveryType() === DELIVERY_TYPE_DATA && method_exists($this, 'getCategory')) { $this->Data = []; $this->getCategory($CategoryID); return; } } } else { $this->Form->setData($this->Category); $this->setupDiscussionTypes($this->Category); $this->Form->setValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID); } // Get all of the currently selected role/permission combinations for this junction. $Permissions = $PermissionModel->getJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions)); $Permissions = $PermissionModel->unpivotPermissions($Permissions, true); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $this->setData('PermissionData', $Permissions, true); } // Render default view $this->setData('Operation', 'Edit'); $this->setData('DisplayAsOptions', $displayAsOptions); $this->render(); }
/** * Create a controller to deal with plugin settings in dashboard. * * @param Gdn_Controller $sender. * @param Gdn_Controller $args. */ public function settingsEndpoint($sender, $args) { $sender->permission('Garden.Settings.Manage'); $model = new Gdn_AuthenticationProviderModel(); /* @var Gdn_Form $form */ $form = new Gdn_Form(); $form->setModel($model); $sender->Form = $form; if (!$form->AuthenticatedPostBack()) { $provider = $this->provider(); $form->setData($provider); } else { $form->setFormValue('AuthenticationKey', $this->getProviderKey()); $sender->Form->validateRule('AssociationKey', 'ValidateRequired', 'You must provide a unique AccountID.'); $sender->Form->validateRule('AssociationSecret', 'ValidateRequired', 'You must provide a Secret'); $sender->Form->validateRule('AuthorizeUrl', 'isUrl', 'You must provide a complete URL in the Authorize Url field.'); $sender->Form->validateRule('TokenUrl', 'isUrl', 'You must provide a complete URL in the Token Url field.'); // To satisfy the AuthenticationProviderModel, create a BaseUrl. $baseUrlParts = parse_url($form->getValue('AuthorizeUrl')); $baseUrl = val('scheme', $baseUrlParts) && val('host', $baseUrlParts) ? val('scheme', $baseUrlParts) . '://' . val('host', $baseUrlParts) : null; if ($baseUrl) { $form->setFormValue('BaseUrl', $baseUrl); $form->setFormValue('SignInUrl', $baseUrl); // kludge for default provider } if ($form->save()) { $sender->informMessage(t('Saved')); } } // Set up the form. $formFields = ['AssociationKey' => ['LabelCode' => 'Client ID', 'Description' => 'Enter the unique ID of the authentication application.'], 'AssociationSecret' => ['LabelCode' => 'Secret', 'Description' => 'Enter the secret provided by the authentication provider.'], 'AuthorizeUrl' => ['LabelCode' => 'Authorize Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve the authorization token for a user.'], 'TokenUrl' => ['LabelCode' => 'Token Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve the authorization token for a user.'], 'ProfileUrl' => ['LabelCode' => 'Profile Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve a user\'s profile.']]; $formFields = $formFields + $this->getSettingsFormFields(); $formFields['IsDefault'] = ['LabelCode' => 'Make this connection your default signin method.', 'Control' => 'checkbox']; $sender->setData('_Form', $formFields); $sender->addSideMenu(); if (!$sender->data('Title')) { $sender->setData('Title', sprintf(T('%s Settings'), 'Oauth2 SSO')); } $view = $this->settingsView ? $this->settingsView : 'plugins/oauth2'; // Create send the possible redirect URLs that will be required by Oculus and display them in the dashboard. // Use Gdn::Request instead of convience function so that we can return http and https. $redirectUrls = Gdn::request()->url('/entry/' . $this->getProviderKey(), true, true); $sender->setData('redirectUrls', $redirectUrls); $sender->render('settings', '', 'plugins/' . $view); }
/** * * * @param $Sender * @param bool|false $PocketID * @return mixed * @throws Gdn_UserException */ protected function _addEdit($Sender, $PocketID = false) { $Form = new Gdn_Form(); $PocketModel = new Gdn_Model('Pocket'); $Form->setModel($PocketModel); $Sender->ConditionModule = new ConditionModule($Sender); $Sender->Form = $Form; if ($Form->authenticatedPostBack()) { // Save the pocket. if ($PocketID !== false) { $Form->setFormValue('PocketID', $PocketID); } // Convert the form data into a format digestable by the database. $Repeat = $Form->getFormValue('RepeatType'); switch ($Repeat) { case Pocket::REPEAT_EVERY: $PocketModel->Validation->applyRule('EveryFrequency', 'Integer'); $PocketModel->Validation->applyRule('EveryBegin', 'Integer'); $Frequency = $Form->getFormValue('EveryFrequency', 1); if (!$Frequency || !validateInteger($Frequency) || $Frequency < 1) { $Frequency = 1; } $Repeat .= ' ' . $Frequency; if ($Form->getFormValue('EveryBegin', 1) > 1) { $Repeat .= ',' . $Form->getFormValue('EveryBegin'); } break; case Pocket::REPEAT_INDEX: $PocketModel->Validation->addRule('IntegerArray', 'function:ValidateIntegerArray'); $PocketModel->Validation->applyRule('Indexes', 'IntegerArray'); $Indexes = explode(',', $Form->getFormValue('Indexes', '')); $Indexes = array_map('trim', $Indexes); $Repeat .= ' ' . implode(',', $Indexes); break; default: break; } $Form->setFormValue('Repeat', $Repeat); $Form->setFormValue('Sort', 0); $Form->setFormValue('Format', 'Raw'); $Condition = Gdn_Condition::toString($Sender->ConditionModule->conditions(true)); $Form->setFormValue('Condition', $Condition); if ($Form->getFormValue('Ad', 0)) { $Form->setFormValue('Type', Pocket::TYPE_AD); } else { $Form->setFormValue('Type', Pocket::TYPE_DEFAULT); } $Saved = $Form->save(); if ($Saved) { $Sender->StatusMessage = t('Your changes have been saved.'); $Sender->RedirectUrl = url('settings/pockets'); } } else { if ($PocketID !== false) { // Load the pocket. $Pocket = $PocketModel->getWhere(array('PocketID' => $PocketID))->firstRow(DATASET_TYPE_ARRAY); if (!$Pocket) { return Gdn::dispatcher()->dispatch('Default404'); } // Convert some of the pocket data into a format digestable by the form. list($RepeatType, $RepeatFrequency) = Pocket::parseRepeat($Pocket['Repeat']); $Pocket['RepeatType'] = $RepeatType; $Pocket['EveryFrequency'] = GetValue(0, $RepeatFrequency, 1); $Pocket['EveryBegin'] = GetValue(1, $RepeatFrequency, 1); $Pocket['Indexes'] = implode(',', $RepeatFrequency); $Pocket['Ad'] = $Pocket['Type'] == Pocket::TYPE_AD; $Sender->ConditionModule->conditions(Gdn_Condition::fromString($Pocket['Condition'])); $Form->setData($Pocket); } else { // Default the repeat. $Form->setFormValue('RepeatType', Pocket::REPEAT_ONCE); } } $Sender->Form = $Form; $Sender->setData('Locations', $this->Locations); $Sender->setData('LocationsArray', $this->getLocationsArray()); $Sender->setData('Pages', array('' => '(' . T('All') . ')', 'activity' => 'activity', 'comments' => 'comments', 'dashboard' => 'dashboard', 'discussions' => 'discussions', 'inbox' => 'inbox', 'profile' => 'profile')); return $Sender->render('AddEdit', '', 'plugins/Pockets'); }