addHidden() public method

If the $ForceValue parameter remains FALSE, it will grab the value into the hidden input from the form on postback. Otherwise it will always force the assigned value to the input regardless of postback.
public addHidden ( string $FieldName, string $Value = null, boolean $ForceValue = false )
$FieldName string The name of the field being added as a hidden input on the form.
$Value string The value being assigned in the hidden input. Unless $ForceValue is changed to TRUE, this field will be retrieved from the form upon postback.
$ForceValue boolean
コード例 #1
0
 /**
  * Confirmation page.
  *
  * @since 2.0.?
  * @access public
  *
  * @param string $Action Type of action.
  * @param array $LogIDs Numeric IDs of items to confirm.
  */
 public function confirm()
 {
     if (!Gdn::request()->isAuthenticatedPostBack(true)) {
         throw new Exception('Requires POST', 405);
     }
     $this->permission(array('Garden.Moderation.Manage', 'Moderation.Spam.Manage', 'Moderation.ModerationQueue.Manage'), false);
     $Action = Gdn::request()->post('Action', false);
     $LogIDs = Gdn::request()->post('IDs', false);
     $this->Form->addHidden('LogIDs', $LogIDs);
     $this->Form->IDPrefix = 'Confirm_';
     if (trim($LogIDs)) {
         $LogIDArray = explode(',', $LogIDs);
     } else {
         $LogIDArray = array();
     }
     // We also want to collect the users from the log.
     $Logs = $this->LogModel->getIDs($LogIDArray);
     $Users = array();
     foreach ($Logs as $Log) {
         $UserID = $Log['RecordUserID'];
         if (!$UserID) {
             continue;
         }
         $Users[$UserID] = array('UserID' => $UserID);
     }
     Gdn::userModel()->joinUsers($Users, array('UserID'));
     $this->setData('Users', $Users);
     $this->setData('Action', $Action);
     $this->setData('ActionUrl', url('/log/' . $Action));
     $this->setData('ItemCount', count($LogIDArray));
     $this->render();
 }
コード例 #2
0
 /**
  * Move a category to a different parent.
  *
  * @param int $categoryID Unique ID for the category to move.
  * @throws Exception if category is not found.
  */
 public function moveCategory($categoryID)
 {
     // Check permission
     $this->permission(['Garden.Community.Manage', 'Garden.Settings.Manage'], false);
     $category = CategoryModel::categories($categoryID);
     if (!$category) {
         throw notFoundException();
     }
     $this->Form->setModel($this->CategoryModel);
     $this->Form->addHidden('CategoryID', $categoryID);
     $this->setData('Category', $category);
     $parentCategories = CategoryModel::getAncestors($categoryID);
     array_pop($parentCategories);
     if (!empty($parentCategories)) {
         $this->setData('ParentCategories', array_column($parentCategories, 'Name', 'CategoryID'));
     }
     if ($this->Form->authenticatedPostBack()) {
         // Verify we're only attempting to save specific values.
         $this->Form->formValues(['CategoryID' => $this->Form->getValue('CategoryID'), 'ParentCategoryID' => $this->Form->getValue('ParentCategoryID')]);
         $this->Form->save();
     } else {
         $this->Form->setData($category);
     }
     $this->render();
 }
コード例 #3
0
 /**
  * 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');
 }
コード例 #4
0
 /**
  * Set the icon for an addon.
  *
  * @param int $AddonID Specified addon id.
  * @throws Exception Addon not found.
  */
 public function icon($AddonID = '')
 {
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     $Addon = $this->AddonModel->getID($AddonID);
     if (!$Addon) {
         throw notFoundException('Addon');
     }
     if ($Session->UserID != $Addon['InsertUserID']) {
         $this->permission('Addons.Addon.Manage');
     }
     $this->addModule('AddonHelpModule', 'Panel');
     $this->Form->setModel($this->AddonModel);
     $this->Form->addHidden('AddonID', $AddonID);
     if ($this->Form->authenticatedPostBack()) {
         $UploadImage = new Gdn_UploadImage();
         try {
             // Validate the upload
             $imageLocation = $UploadImage->validateUpload('Icon');
             $TargetImage = $this->saveIcon($imageLocation);
         } catch (Exception $ex) {
             $this->Form->addError($ex);
         }
         // If there were no errors, remove the old picture and insert the picture
         if ($this->Form->errorCount() == 0) {
             if ($Addon['Icon']) {
                 $UploadImage->delete($Addon['Icon']);
             }
             $this->AddonModel->save(array('AddonID' => $AddonID, 'Icon' => $TargetImage));
         }
         // If there were no problems, redirect back to the addon
         if ($this->Form->errorCount() == 0) {
             $this->RedirectUrl = Url('/addon/' . AddonModel::slug($Addon));
         }
     }
     $this->render();
 }
コード例 #5
0
 /**
  * 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();
 }
コード例 #6
0
 /**
  * Invitation-only registration. Requires code.
  *
  * @param int $InvitationCode
  * @since 2.0.0
  */
 public function registerInvitation($InvitationCode = 0)
 {
     $this->Form->setModel($this->UserModel);
     // Define gender dropdown options
     $this->GenderOptions = array('u' => t('Unspecified'), 'm' => t('Male'), 'f' => t('Female'));
     if (!$this->Form->isPostBack()) {
         $this->Form->setValue('InvitationCode', $InvitationCode);
     }
     $InvitationModel = new InvitationModel();
     // Look for the invitation.
     $Invitation = $InvitationModel->getWhere(array('Code' => $this->Form->getValue('InvitationCode')))->firstRow(DATASET_TYPE_ARRAY);
     if (!$Invitation) {
         $this->Form->addError('Invitation not found.', 'Code');
     } else {
         if ($Expires = val('DateExpires', $Invitation)) {
             $Expires = Gdn_Format::toTimestamp($Expires);
             if ($Expires <= time()) {
             }
         }
     }
     $this->Form->addHidden('ClientHour', date('Y-m-d H:00'));
     // Use the server's current hour as a default
     $this->Form->addHidden('Target', $this->target());
     Gdn::userModel()->addPasswordStrength($this);
     if ($this->Form->isPostBack() === true) {
         $this->InvitationCode = $this->Form->getValue('InvitationCode');
         // 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, array('Method' => 'Invitation'));
             $this->setData('UserID', $AuthUserID);
             if (!$AuthUserID) {
                 $this->Form->setValidationResults($this->UserModel->validationResults());
             } else {
                 // The user has been created successfully, so sign in now.
                 Gdn::session()->start($AuthUserID);
                 if ($this->Form->getFormValue('RememberMe')) {
                     Gdn::authenticator()->setIdentity($AuthUserID, true);
                 }
                 $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);
         }
     } else {
         // Set some form defaults.
         if ($Name = val('Name', $Invitation)) {
             $this->Form->setValue('Name', $Name);
         }
         $this->InvitationCode = $InvitationCode;
     }
     // Make sure that the hour offset for new users gets defined when their account is created
     $this->addJsFile('entry.js');
     $this->render();
 }
コード例 #7
0
 /**
  * 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();
     }
 }
コード例 #8
0
 /**
  * Set user's thumbnail (crop & center photo).
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Unique identifier, possible username or ID.
  * @param string $Username .
  */
 public function thumbnail($UserReference = '', $Username = '')
 {
     if (!c('Garden.Profile.EditPhotos', true)) {
         throw forbiddenException('@Editing user photos has been disabled.');
     }
     // Initial permission checks (valid user)
     $this->permission('Garden.SignIn.Allow');
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     // Need some extra JS
     // jcrop update jan28, 2014 as jQuery upgrade to 1.10.2 no longer
     // supported browser()
     $this->addJsFile('jquery.jcrop.min.js');
     $this->addJsFile('profile.js');
     $this->getUserInfo($UserReference, $Username, '', true);
     // Permission check (correct user)
     if ($this->User->UserID != $Session->UserID && !checkPermission('Garden.Users.Edit') && !checkPermission('Moderation.Profiles.Edit')) {
         throw new Exception(t('You cannot edit the thumbnail of another member.'));
     }
     // Form prep
     $this->Form->setModel($this->UserModel);
     $this->Form->addHidden('UserID', $this->User->UserID);
     // Confirm we have a photo to manipulate
     if (!$this->User->Photo) {
         $this->Form->addError('You must first upload a picture before you can create a thumbnail.');
     }
     // Define the thumbnail size
     $this->ThumbSize = Gdn::config('Garden.Thumbnail.Size', 40);
     // Define the source (profile sized) picture & dimensions.
     $Basename = changeBasename($this->User->Photo, 'p%s');
     $Upload = new Gdn_UploadImage();
     $PhotoParsed = Gdn_Upload::Parse($Basename);
     $Source = $Upload->CopyLocal($Basename);
     if (!$Source) {
         $this->Form->addError('You cannot edit the thumbnail of an externally linked profile picture.');
     } else {
         $this->SourceSize = getimagesize($Source);
     }
     // We actually need to upload a new file to help with cdb ttls.
     $NewPhoto = $Upload->generateTargetName('userpics', trim(pathinfo($this->User->Photo, PATHINFO_EXTENSION), '.'), true);
     // Add some more hidden form fields for jcrop
     $this->Form->addHidden('x', '0');
     $this->Form->addHidden('y', '0');
     $this->Form->addHidden('w', $this->ThumbSize);
     $this->Form->addHidden('h', $this->ThumbSize);
     $this->Form->addHidden('HeightSource', $this->SourceSize[1]);
     $this->Form->addHidden('WidthSource', $this->SourceSize[0]);
     $this->Form->addHidden('ThumbSize', $this->ThumbSize);
     if ($this->Form->authenticatedPostBack() === true) {
         try {
             // Get the dimensions from the form.
             Gdn_UploadImage::SaveImageAs($Source, changeBasename($NewPhoto, 'n%s'), $this->ThumbSize, $this->ThumbSize, array('Crop' => true, 'SourceX' => $this->Form->getValue('x'), 'SourceY' => $this->Form->getValue('y'), 'SourceWidth' => $this->Form->getValue('w'), 'SourceHeight' => $this->Form->getValue('h')));
             // Save new profile picture.
             $Parsed = $Upload->SaveAs($Source, changeBasename($NewPhoto, 'p%s'));
             $UserPhoto = sprintf($Parsed['SaveFormat'], $NewPhoto);
             // Save the new photo info.
             Gdn::userModel()->setField($this->User->UserID, 'Photo', $UserPhoto);
             // Remove the old profile picture.
             @$Upload->delete($Basename);
         } catch (Exception $Ex) {
             $this->Form->addError($Ex);
         }
         // If there were no problems, redirect back to the user account
         if ($this->Form->errorCount() == 0) {
             redirect(userUrl($this->User, '', 'picture'));
             $this->informMessage(sprite('Check', 'InformSprite') . t('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite');
         }
     }
     // Delete the source image if it is externally hosted.
     if ($PhotoParsed['Type']) {
         @unlink($Source);
     }
     $this->title(t('Edit My Thumbnail'));
     $this->_setBreadcrumbs(t('Edit My Thumbnail'), '/profile/thumbnail');
     $this->render();
 }
コード例 #9
0
 /**
  * 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();
 }
コード例 #10
0
 /**
  * Shows all uncleared messages within a conversation for the viewing user
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $ConversationID Unique ID of conversation to view.
  * @param int $Offset Number to skip.
  * @param int $Limit Number to show.
  */
 public function index($ConversationID = false, $Offset = -1, $Limit = '')
 {
     $this->Offset = $Offset;
     $Session = Gdn::session();
     Gdn_Theme::section('Conversation');
     // Figure out Conversation ID
     if (!is_numeric($ConversationID) || $ConversationID < 0) {
         $ConversationID = 0;
     }
     // Form setup for adding comments
     $this->Form->setModel($this->ConversationMessageModel);
     $this->Form->addHidden('ConversationID', $ConversationID);
     // Check permissions on the recipients.
     $InConversation = $this->ConversationModel->inConversation($ConversationID, Gdn::session()->UserID);
     if (!$InConversation) {
         // Conversation moderation must be enabled and they must have permission
         if (!c('Conversations.Moderation.Allow', false)) {
             throw permissionException();
         }
         $this->permission('Conversations.Moderation.Manage');
     }
     $this->Conversation = $this->ConversationModel->getID($ConversationID);
     $this->Conversation->Participants = $this->ConversationModel->getRecipients($ConversationID);
     $this->setData('Conversation', $this->Conversation);
     // Bad conversation? Redirect
     if ($this->Conversation === false) {
         throw notFoundException('Conversation');
     }
     // Get limit
     if ($Limit == '' || !is_numeric($Limit) || $Limit < 0) {
         $Limit = Gdn::config('Conversations.Messages.PerPage', 50);
     }
     // Calculate counts
     if (!is_numeric($this->Offset) || $this->Offset < 0) {
         // Round down to the appropriate offset based on the user's read messages & messages per page
         $CountReadMessages = $this->Conversation->CountMessages - $this->Conversation->CountNewMessages;
         if ($CountReadMessages < 0) {
             $CountReadMessages = 0;
         }
         if ($CountReadMessages > $this->Conversation->CountMessages) {
             $CountReadMessages = $this->Conversation->CountMessages;
         }
         // (((67 comments / 10 perpage) = 6.7) rounded down = 6) * 10 perpage = offset 60;
         $this->Offset = floor($CountReadMessages / $Limit) * $Limit;
         // Send the hash link in.
         if ($CountReadMessages > 1) {
             $this->addDefinition('LocationHash', '#Item_' . $CountReadMessages);
         }
     }
     // Fetch message data
     $this->MessageData = $this->ConversationMessageModel->get($ConversationID, $Session->UserID, $this->Offset, $Limit);
     $this->EventArguments['MessageData'] = $this->MessageData;
     $this->fireEvent('beforeMessages');
     $this->setData('Messages', $this->MessageData);
     // Figure out who's participating.
     $ParticipantTitle = ConversationModel::participantTitle($this->Conversation, true);
     $this->Participants = $ParticipantTitle;
     $this->title(strip_tags($this->Participants));
     // $CountMessages = $this->ConversationMessageModel->getCount($ConversationID, $Session->UserID);
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->getPager('MorePager', $this);
     $this->Pager->MoreCode = 'Newer Messages';
     $this->Pager->LessCode = 'Older Messages';
     $this->Pager->ClientID = 'Pager';
     $this->Pager->configure($this->Offset, $Limit, $this->Conversation->CountMessages, 'messages/' . $ConversationID . '/%1$s/%2$s/');
     // Mark the conversation as ready by this user.
     $this->ConversationModel->markRead($ConversationID, $Session->UserID);
     // Deliver json data if necessary
     if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         $this->setJson('LessRow', $this->Pager->toString('less'));
         $this->setJson('MoreRow', $this->Pager->toString('more'));
         $this->View = 'messages';
     }
     // Add modules.
     $ClearHistoryModule = new ClearHistoryModule($this);
     $ClearHistoryModule->conversationID($ConversationID);
     $this->addModule($ClearHistoryModule);
     $InThisConversationModule = new InThisConversationModule($this);
     $InThisConversationModule->setData($this->Conversation->Participants);
     $this->addModule($InThisConversationModule);
     // Doesn't make sense for people who can't even start conversations to be adding people
     if (checkPermission('Conversations.Conversations.Add')) {
         $this->addModule('AddPeopleModule');
     }
     $Subject = $this->data('Conversation.Subject');
     if (!$Subject) {
         $Subject = t('Message');
     }
     $this->Data['Breadcrumbs'][] = array('Name' => $Subject, 'Url' => url('', '//'));
     // Render view
     $this->render();
 }