If $FieldName isn't found in the form, it returns $Default.
public getFormValue ( string $FieldName, mixed $Default = '' ) : unknown | ||
$FieldName | string | The name of the field to get the value of. |
$Default | mixed | The default value to return if $FieldName isn't found. |
리턴 | unknown |
/** * * @param Gdn_Controller $Sender * @throws Exception */ public function __construct($Sender = null) { if (property_exists($Sender, 'Conversation')) { $this->Conversation = $Sender->Conversation; } // Allowed to use this module? $this->AddUserAllowed = $Sender->ConversationModel->addUserAllowed($this->Conversation->ConversationID); $this->Form = Gdn::factory('Form', 'AddPeople'); // If the form was posted back, check for people to add to the conversation if ($this->Form->authenticatedPostBack()) { // Defer exceptions until they try to use the form so we don't fill our logs if (!$this->AddUserAllowed || !checkPermission('Conversations.Conversations.Add')) { throw permissionException(); } $NewRecipientUserIDs = array(); $NewRecipients = explode(',', $this->Form->getFormValue('AddPeople', '')); $UserModel = Gdn::factory("UserModel"); foreach ($NewRecipients as $Name) { if (trim($Name) != '') { $User = $UserModel->getByUsername(trim($Name)); if (is_object($User)) { $NewRecipientUserIDs[] = $User->UserID; } } } $Sender->ConversationModel->addUserToConversation($this->Conversation->ConversationID, $NewRecipientUserIDs); $Sender->informMessage(t('Your changes were saved.')); $Sender->RedirectUrl = url('/messages/' . $this->Conversation->ConversationID); } $this->_ApplicationFolder = $Sender->Application; $this->_ThemeFolder = $Sender->Theme; }
/** Grab the values from the form into the conditions array. */ protected function _FromForm() { $Form = new Gdn_Form(); $Px = $this->Prefix; $Types = (array) $Form->getFormValue($Px . 'Type', array()); $PermissionFields = (array) $Form->getFormValue($Px . 'PermissionField', array()); $RoleFields = (array) $Form->getFormValue($Px . 'RoleField', array()); $Fields = (array) $Form->getFormValue($Px . 'Field', array()); $Expressions = (array) $Form->getFormValue($Px . 'Expr', array()); $Conditions = array(); for ($i = 0; $i < count($Types) - 1; $i++) { $Condition = array($Types[$i]); switch ($Types[$i]) { case Gdn_Condition::PERMISSION: $Condition[1] = val($i, $PermissionFields, ''); break; case Gdn_Condition::REQUEST: $Condition[1] = val($i, $Fields, ''); $Condition[2] = val($i, $Expressions, ''); break; case Gdn_Condition::ROLE: $Condition[1] = val($i, $RoleFields); break; case '': $Condition[1] = ''; break; default: continue; } $Conditions[] = $Condition; } return $Conditions; }
/** * Default search functionality. * * @since 2.0.0 * @access public * @param int $Page Page number. */ public function index($Page = '') { $this->addJsFile('search.js'); $this->title(t('Search')); saveToConfig('Garden.Format.EmbedSize', '160x90', false); Gdn_Theme::section('SearchResults'); list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20)); $this->setData('_Limit', $Limit); $Search = $this->Form->getFormValue('Search'); $Mode = $this->Form->getFormValue('Mode'); if ($Mode) { $this->SearchModel->ForceSearchMode = $Mode; } try { $ResultSet = $this->SearchModel->Search($Search, $Offset, $Limit); } catch (Gdn_UserException $Ex) { $this->Form->addError($Ex); $ResultSet = array(); } catch (Exception $Ex) { LogException($Ex); $this->Form->addError($Ex); $ResultSet = array(); } Gdn::userModel()->joinUsers($ResultSet, array('UserID')); // Fix up the summaries. $SearchTerms = explode(' ', Gdn_Format::text($Search)); foreach ($ResultSet as &$Row) { $Row['Summary'] = SearchExcerpt(Gdn_Format::plainText($Row['Summary'], $Row['Format']), $SearchTerms); $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']); $Row['Format'] = 'Html'; } $this->setData('SearchResults', $ResultSet, true); $this->setData('SearchTerm', Gdn_Format::text($Search), true); if ($ResultSet) { $NumResults = count($ResultSet); } else { $NumResults = 0; } if ($NumResults == $Offset + $Limit) { $NumResults++; } // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->Pager = $PagerFactory->GetPager('MorePager', $this); $this->Pager->MoreCode = 'More Results'; $this->Pager->LessCode = 'Previous Results'; $this->Pager->ClientID = 'Pager'; $this->Pager->configure($Offset, $Limit, $NumResults, 'dashboard/search/%1$s/%2$s/?Search=' . Gdn_Format::url($Search)); // if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { // $this->setJson('LessRow', $this->Pager->toString('less')); // $this->setJson('MoreRow', $this->Pager->toString('more')); // $this->View = 'results'; // } $this->canonicalUrl(url('search', true)); $this->render(); }
public function notSpam($LogIDs) { $this->permission(array('Garden.Moderation.Manage', 'Moderation.Spam.Manage'), false); if (!$this->Request->isPostBack()) { throw permissionException('Javascript'); } $Logs = array(); // Verify the appropriate users. $UserIDs = $this->Form->getFormValue('UserID', array()); if (!is_array($UserIDs)) { $UserIDs = array(); } foreach ($UserIDs as $UserID) { Gdn::userModel()->setField($UserID, 'Verified', true); $Logs = array_merge($Logs, $this->LogModel->getWhere(array('Operation' => 'Spam', 'RecordUserID' => $UserID))); } // Grab the logs. $Logs = array_merge($Logs, $this->LogModel->getIDs($LogIDs)); // try { foreach ($Logs as $Log) { $this->LogModel->restore($Log); } // } catch (Exception $Ex) { // $this->Form->addError($Ex->getMessage()); // } $this->LogModel->recalculate(); $this->setData('Complete'); $this->setData('Count', count($Logs)); $this->render('Blank', 'Utility'); }
/** * Look for users with an invalid role and apply the role specified to those users. */ public function fixUserRole() { $this->permission('Garden.Settings.Manage'); if ($this->Request->isAuthenticatedPostBack()) { if (validateRequired($this->Form->getFormValue('DefaultUserRole'))) { $this->Model->fixUserRole($this->Form->getFormValue('DefaultUserRole')); $this->setData('CompletedFix', true); } } $this->render(); }
/** * Set where to go after signin. * * @access public * @since 2.0.0 * * @param string $Target Where we're requested to go to. * @return string URL to actually go to (validated & safe). */ public function target($Target = false) { if ($Target === false) { $Target = $this->Form->getFormValue('Target', false); if (!$Target) { $Target = $this->Request->get('Target', '/'); } } // Make sure that the target is a valid url. if (!preg_match('`(^https?://)`', $Target)) { $Target = '/' . ltrim($Target, '/'); // Never redirect back to signin. if (preg_match('`^/entry/signin`i', $Target)) { $Target = '/'; } } else { $MyHostname = parse_url(Gdn::request()->domain(), PHP_URL_HOST); $TargetHostname = parse_url($Target, PHP_URL_HOST); // Only allow external redirects to trusted domains. $TrustedDomains = c('Garden.TrustedDomains', true); // Trusted domains were previously saved in config as an array. if ($TrustedDomains && $TrustedDomains !== true && !is_array($TrustedDomains)) { $TrustedDomains = explode("\n", $TrustedDomains); } if (is_array($TrustedDomains)) { // Add this domain to the trusted hosts. $TrustedDomains[] = $MyHostname; $this->EventArguments['TrustedDomains'] =& $TrustedDomains; $this->fireEvent('BeforeTargetReturn'); } if ($TrustedDomains === true) { return $Target; } elseif (count($TrustedDomains) == 0) { // Only allow http redirects if they are to the same host name. if ($MyHostname != $TargetHostname) { $Target = ''; } } else { // Loop the trusted domains looking for a match $Match = false; foreach ($TrustedDomains as $TrustedDomain) { if (stringEndsWith($TargetHostname, $TrustedDomain, true)) { $Match = true; } } if (!$Match) { $Target = ''; } } } return $Target; }
/** * Add a message to a conversation. * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of the conversation. */ public function addMessage($ConversationID = '') { $this->Form->setModel($this->ConversationMessageModel); if (is_numeric($ConversationID) && $ConversationID > 0) { $this->Form->addHidden('ConversationID', $ConversationID); } if ($this->Form->authenticatedPostBack()) { $ConversationID = $this->Form->getFormValue('ConversationID', ''); // Make sure the user posting to the conversation is actually // a member of it, or is allowed, like an admin. if (!checkPermission('Garden.Moderation.Manage')) { $UserID = Gdn::session()->UserID; $ValidConversationMember = $this->ConversationModel->validConversationMember($ConversationID, $UserID); if (!$ValidConversationMember) { throw permissionException(); } } $Conversation = $this->ConversationModel->getID($ConversationID, Gdn::session()->UserID); $this->EventArguments['Conversation'] = $Conversation; $this->EventArguments['ConversationID'] = $ConversationID; $this->fireEvent('BeforeAddMessage'); $NewMessageID = $this->Form->save(); if ($NewMessageID) { if ($this->deliveryType() == DELIVERY_TYPE_ALL) { redirect('messages/' . $ConversationID . '/#' . $NewMessageID, 302); } $this->setJson('MessageID', $NewMessageID); $this->EventArguments['MessageID'] = $NewMessageID; $this->fireEvent('AfterMessageSave'); // If this was not a full-page delivery type, return the partial response // Load all new messages that the user hasn't seen yet (including theirs) $LastMessageID = $this->Form->getFormValue('LastMessageID'); if (!is_numeric($LastMessageID)) { $LastMessageID = $NewMessageID - 1; } $Session = Gdn::session(); $MessageData = $this->ConversationMessageModel->getNew($ConversationID, $LastMessageID); $this->Conversation = $Conversation; $this->MessageData = $MessageData; $this->setData('Messages', $MessageData); $this->View = 'messages'; } else { // Handle ajax based errors... if ($this->deliveryType() != DELIVERY_TYPE_ALL) { $this->errorMessage($this->Form->errors()); } } } $this->render(); }
/** * Prompts new admins how to get started using new install. * * @since 2.0.0 * @access public */ public function gettingStarted() { $this->permission('Garden.Settings.Manage'); $this->setData('Title', t('Getting Started')); $this->addSideMenu('dashboard/settings/gettingstarted'); $this->TextEnterEmails = t('TextEnterEmails', 'Type email addresses separated by commas here'); if ($this->Form->authenticatedPostBack()) { // Do invitations to new members. $Message = $this->Form->getFormValue('InvitationMessage'); $Message = trim($Message); $Recipients = $this->Form->getFormValue('Recipients'); if ($Recipients == $this->TextEnterEmails) { $Recipients = ''; } $Recipients = explode(',', $Recipients); $CountRecipients = 0; foreach ($Recipients as $Recipient) { if (trim($Recipient) != '') { $CountRecipients++; if (!validateEmail($Recipient)) { $this->Form->addError(sprintf(t('%s is not a valid email address'), $Recipient)); } } } if ($CountRecipients == 0) { $this->Form->addError(t('You must provide at least one recipient')); } if ($this->Form->errorCount() == 0) { $Email = new Gdn_Email(); $Email->subject(t('Check out my new community!')); $emailTemplate = $Email->getEmailTemplate(); $emailTemplate->setMessage($Message, true)->setButton(externalUrl('/'), t('Check it out')); $Email->setEmailTemplate($emailTemplate); foreach ($Recipients as $Recipient) { if (trim($Recipient) != '') { $Email->to($Recipient); try { $Email->send(); } catch (Exception $ex) { $this->Form->addError($ex); } } } } if ($this->Form->errorCount() == 0) { $this->informMessage(t('Your invitations were sent successfully.')); } } $this->render(); }
/** * Default search functionality. * * @since 2.0.0 * @access public * @param int $Page Page number. */ public function index($Page = '') { $this->addJsFile('search.js'); $this->title(t('Search')); saveToConfig('Garden.Format.EmbedSize', '160x90', false); Gdn_Theme::section('SearchResults'); list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20)); $this->setData('_Limit', $Limit); $Search = $this->Form->getFormValue('Search'); $Mode = $this->Form->getFormValue('Mode'); if ($Mode) { $this->SearchModel->ForceSearchMode = $Mode; } try { $ResultSet = $this->SearchModel->search($Search, $Offset, $Limit); } catch (Gdn_UserException $Ex) { $this->Form->addError($Ex); $ResultSet = array(); } catch (Exception $Ex) { LogException($Ex); $this->Form->addError($Ex); $ResultSet = array(); } Gdn::userModel()->joinUsers($ResultSet, array('UserID')); // Fix up the summaries. $SearchTerms = explode(' ', Gdn_Format::text($Search)); foreach ($ResultSet as &$Row) { $Row['Summary'] = searchExcerpt(htmlspecialchars(Gdn_Format::plainText($Row['Summary'], $Row['Format'])), $SearchTerms); $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']); $Row['Format'] = 'Html'; } $this->setData('SearchResults', $ResultSet, true); $this->setData('SearchTerm', Gdn_Format::text($Search), true); $this->setData('_CurrentRecords', count($ResultSet)); $this->canonicalUrl(url('search', true)); $this->render(); }
/** * Manage options for a mobile theme. * * @since 2.0.0 * @access public * @todo Why is this in a giant try/catch block? */ public function mobileThemeOptions() { $this->permission('Garden.Settings.Manage'); try { $this->addJsFile('addons.js'); $this->setHighlightRoute('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->fireEvent['AfterSaveThemeOptions']; $this->informMessage(t("Your changes have been saved.")); } $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 where to go after signin. * * @access public * @since 2.0.0 * * @param string $Target Where we're requested to go to. * @return string URL to actually go to (validated & safe). */ public function target($Target = false) { if ($Target === false) { $Target = $this->Form->getFormValue('Target', false); if (!$Target) { $Target = $this->Request->get('Target', $this->Request->get('target', '/')); } } // Make sure that the target is a valid url. if (!preg_match('`(^https?://)`', $Target)) { $Target = '/' . ltrim($Target, '/'); // Never redirect back to signin. if (preg_match('`^/entry/signin`i', $Target)) { $Target = '/'; } } return $Target; }
/** * Delete a screenshot from an addon. * * @param string $AddonPictureID Picture id to remove. * @throws Gdn_UserException No permission to delete this picture. */ public function deletePicture($AddonPictureID = '') { $AddonPictureModel = new Gdn_Model('AddonPicture'); $Picture = $AddonPictureModel->getWhere(array('AddonPictureID' => $AddonPictureID))->firstRow(); $AddonModel = new AddonModel(); $Addon = $AddonModel->getID($Picture->AddonID); $Session = Gdn::session(); if ($Session->UserID != $Addon['InsertUserID'] && !$Session->checkPermission('Addons.Addon.Manage')) { throw permissionException(); } if ($this->Form->authenticatedPostBack() && $this->Form->getFormValue('Yes')) { if ($Picture) { $Upload = new Gdn_Upload(); $Upload->delete(changeBasename($Picture->File, 'ao%s')); $Upload->delete(changeBasename($Picture->File, 'at%s')); $AddonPictureModel->delete(array('AddonPictureID' => $AddonPictureID)); } $this->RedirectUrl = url('/addon/' . $Picture->AddonID); } $this->render('deletepicture'); }
/** * * * @throws Exception */ public function setHourOffset() { $Form = new Gdn_Form(); if ($Form->authenticatedPostBack()) { if (!Gdn::session()->isValid()) { throw permissionException('Garden.SignIn.Allow'); } $HourOffset = $Form->getFormValue('HourOffset'); Gdn::userModel()->setField(Gdn::session()->UserID, 'HourOffset', $HourOffset); $this->setData('Result', true); $this->setData('HourOffset', $HourOffset); $time = time(); $this->setData('UTCDateTime', gmdate('r', $time)); $this->setData('UserDateTime', gmdate('r', $time + $HourOffset * 3600)); } else { throw forbiddenException('GET'); } $this->render('Blank'); }
/** * Allows user to bookmark or unbookmark a discussion. * * If the discussion isn't bookmarked by the user, this bookmarks it. * If it is already bookmarked, this unbookmarks it. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique discussion ID. */ public function bookmark($DiscussionID = null) { // Make sure we are posting back. if (!$this->Request->isAuthenticatedPostBack()) { throw permissionException('Javascript'); } $Session = Gdn::session(); if (!$Session->UserID) { throw permissionException('SignedIn'); } // Check the form to see if the data was posted. $Form = new Gdn_Form(); $DiscussionID = $Form->getFormValue('DiscussionID', $DiscussionID); $Bookmark = $Form->getFormValue('Bookmark', null); $UserID = $Form->getFormValue('UserID', $Session->UserID); // Check the permission on the user. if ($UserID != $Session->UserID) { $this->permission('Garden.Moderation.Manage'); } $Discussion = $this->DiscussionModel->getID($DiscussionID); if (!$Discussion) { throw notFoundException('Discussion'); } $Bookmark = $this->DiscussionModel->bookmark($DiscussionID, $UserID, $Bookmark); // Set the new value for api calls and json targets. $this->setData(array('UserID' => $UserID, 'DiscussionID' => $DiscussionID, 'Bookmarked' => (bool) $Bookmark)); setValue('Bookmarked', $Discussion, (int) $Bookmark); // Update the user's bookmark count $CountBookmarks = $this->DiscussionModel->setUserBookmarkCount($UserID); $this->jsonTarget('.User-CountBookmarks', (string) $CountBookmarks); // Short circuit if this is an api call. if ($this->deliveryType() === DELIVERY_TYPE_DATA) { $this->render('Blank', 'Utility', 'Dashboard'); return; } // Return the appropriate bookmark. require_once $this->fetchViewLocation('helper_functions', 'Discussions'); $Html = bookmarkButton($Discussion); // $this->jsonTarget(".Section-DiscussionList #Discussion_$DiscussionID .Bookmark,.Section-Discussion .PageTitle .Bookmark", $Html, 'ReplaceWith'); $this->jsonTarget("!element", $Html, 'ReplaceWith'); // Add the bookmark to the bookmarks module. if ($Bookmark) { // Grab the individual bookmark and send it to the client. $Bookmarks = new BookmarkedModule($this); if ($CountBookmarks == 1) { // When there is only one bookmark we have to get the whole module. $Target = '#Panel'; $Type = 'Append'; $Bookmarks->getData(); $Data = $Bookmarks->toString(); } else { $Target = '#Bookmark_List'; $Type = 'Prepend'; $Loc = $Bookmarks->fetchViewLocation('discussion'); ob_start(); include $Loc; $Data = ob_get_clean(); } $this->jsonTarget($Target, $Data, $Type); } else { // Send command to remove bookmark html. if ($CountBookmarks == 0) { $this->jsonTarget('#Bookmarks', null, 'Remove'); } else { $this->jsonTarget('#Bookmark_' . $DiscussionID, null, 'Remove'); } } $this->render('Blank', 'Utility', 'Dashboard'); }
/** * 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(); } }
/** * * * @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'); }
/** * Set user's photo (avatar). * * @since 2.0.0 * @access public * * @param mixed $userReference Unique identifier, possible username or ID. * @param string $username The username. * @param string $userID The user's ID. * * @throws Exception * @throws Gdn_UserException */ public function picture($userReference = '', $username = '', $userID = '') { $this->addJsFile('profile.js'); if (!$this->CanEditPhotos) { 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 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); $validation = new Gdn_Validation(); $configurationModel = new Gdn_ConfigurationModel($validation); $this->Form->setModel($configurationModel); $avatar = $this->User->Photo; if ($avatar === null) { $avatar = UserModel::getDefaultAvatarUrl(); } $source = ''; $crop = null; if ($this->isUploadedAvatar($avatar)) { // Get the image source so we can manipulate it in the crop module. $upload = new Gdn_UploadImage(); $thumbnailSize = c('Garden.Thumbnail.Size', 40); $basename = changeBasename($avatar, "p%s"); $source = $upload->copyLocal($basename); // Set up cropping. $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source); $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($avatar, "n%s"))); $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($avatar, "p%s"))); $this->setData('crop', $crop); } else { $this->setData('avatar', $avatar); } if (!$this->Form->authenticatedPostBack()) { $this->Form->setData($configurationModel->Data); } else { if ($this->Form->save() !== false) { $upload = new Gdn_UploadImage(); $newAvatar = false; if ($tmpAvatar = $upload->validateUpload('Avatar', false)) { // New upload $thumbOptions = array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif')); $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions, $upload); } else { if ($avatar && $crop && $crop->isCropped()) { // New thumbnail $tmpAvatar = $source; $thumbOptions = array('Crop' => true, 'SourceX' => $crop->getCropXValue(), 'SourceY' => $crop->getCropYValue(), 'SourceWidth' => $crop->getCropWidth(), 'SourceHeight' => $crop->getCropHeight()); $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions); } } if ($this->Form->errorCount() == 0) { if ($newAvatar !== false) { $thumbnailSize = c('Garden.Thumbnail.Size', 40); // Update crop properties. $basename = changeBasename($newAvatar, "p%s"); $source = $upload->copyLocal($basename); $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source); $crop->setSize($thumbnailSize, $thumbnailSize); $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "n%s"))); $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "p%s"))); $this->setData('crop', $crop); } } if ($this->deliveryType() === DELIVERY_TYPE_VIEW) { $this->jsonTarget('', '', 'Refresh'); $this->RedirectUrl = userUrl($this->User); } $this->informMessage(t("Your settings have been saved.")); } } if (val('SideMenuModule', val('Panel', val('Assets', $this)))) { /** @var SideMenuModule $sidemenu */ $sidemenu = $this->Assets['Panel']['SideMenuModule']; $sidemenu->highlightRoute('/profile/picture'); } $this->title(t('Change Picture')); $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture')); $this->render('picture', 'profile', 'dashboard'); }
/** * 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(); }
/** * 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(); }
/** * 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(); }
/** * Allows the configuration of basic setup information in Garden. This * should not be functional after the application has been set up. * * @since 2.0.0 * @access public * @param string $RedirectUrl Where to send user afterward. */ private function configure($RedirectUrl = '') { // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array('Garden.Locale', 'Garden.Title', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName')); // Set the models on the forms. $this->Form->setModel($ConfigurationModel); // If seeing the form for the first time... if (!$this->Form->isPostback()) { // Force the webroot using our best guesstimates $ConfigurationModel->Data['Database.Host'] = 'localhost'; $this->Form->setData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->applyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.'); // Let's make some user-friendly custom errors for database problems $DatabaseHost = $this->Form->getFormValue('Database.Host', '~~Invalid~~'); $DatabaseName = $this->Form->getFormValue('Database.Name', '~~Invalid~~'); $DatabaseUser = $this->Form->getFormValue('Database.User', '~~Invalid~~'); $DatabasePassword = $this->Form->getFormValue('Database.Password', '~~Invalid~~'); $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost); try { $Connection = new PDO($ConnectionString, $DatabaseUser, $DatabasePassword); } catch (PDOException $Exception) { switch ($Exception->getCode()) { case 1044: $this->Form->addError(t('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1045: $this->Form->addError(t('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1049: $this->Form->addError(t('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 2005: $this->Form->addError(t("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage())); break; default: $this->Form->addError(sprintf(t('ValidateConnection'), strip_tags($Exception->getMessage()))); break; } } $ConfigurationModel->Validation->applyRule('Garden.Title', 'Required'); $ConfigurationFormValues = $this->Form->formValues(); if ($ConfigurationModel->validate($ConfigurationFormValues) !== true || $this->Form->errorCount() > 0) { // Apply the validation results to the form(s) $this->Form->setValidationResults($ConfigurationModel->validationResults()); } else { $Host = array_shift(explode(':', Gdn::request()->requestHost())); $Domain = Gdn::request()->domain(); // Set up cookies now so that the user can be signed in. $ExistingSalt = c('Garden.Cookie.Salt', false); $ConfigurationFormValues['Garden.Cookie.Salt'] = $ExistingSalt ? $ExistingSalt : betterRandomString(16, 'Aa0'); $ConfigurationFormValues['Garden.Cookie.Domain'] = ''; // Don't set this to anything by default. # Tim - 2010-06-23 // Additional default setup values. $ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = true; $ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title']; $ConfigurationModel->save($ConfigurationFormValues, true); // If changing locale, redefine locale sources: $NewLocale = 'en-CA'; // $this->Form->getFormValue('Garden.Locale', false); if ($NewLocale !== false && Gdn::config('Garden.Locale') != $NewLocale) { $Locale = Gdn::locale(); $Locale->set($NewLocale); } // Install db structure & basic data. $Database = Gdn::database(); $Database->init(); $Drop = false; $Explicit = false; try { include PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php'; } catch (Exception $ex) { $this->Form->addError($ex); } if ($this->Form->errorCount() > 0) { return false; } // Create the administrative user $UserModel = Gdn::userModel(); $UserModel->defineSchema(); $UsernameError = t('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.'); $UserModel->Validation->applyRule('Name', 'Username', $UsernameError); $UserModel->Validation->applyRule('Name', 'Required', t('You must specify an admin username.')); $UserModel->Validation->applyRule('Password', 'Required', t('You must specify an admin password.')); $UserModel->Validation->applyRule('Password', 'Match'); $UserModel->Validation->applyRule('Email', 'Email'); if (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) { $this->Form->setValidationResults($UserModel->validationResults()); } else { // The user has been created successfully, so sign in now. saveToConfig('Garden.Installed', true, array('Save' => false)); Gdn::session()->start($AdminUserID, true); saveToConfig('Garden.Installed', false, array('Save' => false)); } if ($this->Form->errorCount() > 0) { return false; } // Assign some extra settings to the configuration file if everything succeeded. $ApplicationInfo = array(); include CombinePaths(array(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php')); // Detect Internet connection for CDNs $Disconnected = !(bool) @fsockopen('ajax.googleapis.com', 80); saveToConfig(array('Garden.Version' => val('Version', val('Dashboard', $ApplicationInfo, array()), 'Undefined'), 'Garden.Cdns.Disable' => $Disconnected, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.GettingStarted' => 'GettingStarted', 'EnabledPlugins.HtmLawed' => 'HtmLawed')); } } return $this->Form->errorCount() == 0 ? true : false; }
/** * * * @param bool $UserID * @throws Exception * @throws Gdn_UserException */ public function sso($UserID = false) { $this->permission('Garden.Users.Edit'); $ProviderModel = new Gdn_AuthenticationProviderModel(); $Form = new Gdn_Form(); if ($this->Request->isAuthenticatedPostBack()) { // Make sure everything has been posted. $Form->validateRule('ClientID', 'ValidateRequired'); $Form->validateRule('UniqueID', 'ValidateRequired'); if (!validateRequired($Form->getFormValue('Username')) && !validateRequired($Form->getFormValue('Email'))) { $Form->addError('Username or Email is required.'); } $Provider = $ProviderModel->getProviderByKey($Form->getFormValue('ClientID')); if (!$Provider) { $Form->addError(sprintf('%1$s "%2$s" not found.', t('Provider'), $Form->getFormValue('ClientID'))); } if ($Form->errorCount() > 0) { throw new Gdn_UserException($Form->errorString()); } // Grab the user. $User = false; if ($Email = $Form->getFormValue('Email')) { $User = Gdn::userModel()->GetByEmail($Email); } if (!$User && ($Username = $Form->getFormValue('Username'))) { $User = Gdn::userModel()->GetByUsername($Username); } if (!$User) { throw new Gdn_UserException(sprintf(t('User not found.'), strtolower(t(UserModel::SigninLabelCode()))), 404); } // Validate the user's password. $PasswordHash = new Gdn_PasswordHash(); $Password = $this->Form->getFormValue('Password', null); if ($Password !== null && !$PasswordHash->CheckPassword($Password, val('Password', $User), val('HashMethod', $User))) { throw new Gdn_UserException(t('Invalid password.'), 401); } // Okay. We've gotten this far. Let's save the authentication. $User = (array) $User; Gdn::userModel()->saveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $Form->getFormValue('ClientID'), 'UniqueID' => $Form->getFormValue('UniqueID'))); $Row = Gdn::userModel()->getAuthentication($Form->getFormValue('UniqueID'), $Form->getFormValue('ClientID')); if ($Row) { $this->setData('Result', $Row); } else { throw new Gdn_UserException(t('There was an error saving the data.')); } } else { $User = Gdn::userModel()->getID($UserID); if (!$User) { throw notFoundException('User'); } $Result = Gdn::sql()->select('ua.ProviderKey', '', 'ClientID')->select('ua.ForeignUserKey', '', 'UniqueID')->select('ua.UserID')->select('p.Name')->select('p.AuthenticationSchemeAlias', '', 'Type')->from('UserAuthentication ua')->join('UserAuthenticationProvider p', 'ua.ProviderKey = p.AuthenticationKey')->where('UserID', $UserID)->get()->resultArray(); $this->setData('Result', $Result); } $this->render('Blank', 'Utility', 'Dashboard'); }
/** * * * @throws Exception */ public function setHourOffset() { $Form = new Gdn_Form(); if ($Form->authenticatedPostBack()) { if (!Gdn::session()->isValid()) { throw permissionException('Garden.SignIn.Allow'); } $HourOffset = $Form->getFormValue('HourOffset'); Gdn::userModel()->setField(Gdn::session()->UserID, 'HourOffset', $HourOffset); // If we receive a time zone, only accept it if we can verify it as a valid identifier. $timeZone = $Form->getFormValue('TimeZone'); if (!empty($timeZone)) { try { $tz = new DateTimeZone($timeZone); Gdn::userModel()->saveAttribute(Gdn::session()->UserID, ['TimeZone' => $tz->getName(), 'SetTimeZone' => null]); } catch (\Exception $ex) { Logger::log(Logger::ERROR, $ex->getMessage(), ['timeZone' => $timeZone]); Gdn::userModel()->saveAttribute(Gdn::session()->UserID, ['TimeZone' => null, 'SetTimeZone' => $timeZone]); $timeZone = ''; } } elseif ($currentTimeZone = Gdn::session()->getAttribute('TimeZone')) { // Check to see if the current timezone agrees with the posted offset. try { $tz = new DateTimeZone($currentTimeZone); $currentHourOffset = $tz->getOffset(new DateTime()) / 3600; if ($currentHourOffset != $HourOffset) { // Clear out the current timezone or else it will override the browser's offset. Gdn::userModel()->saveAttribute(Gdn::session()->UserID, ['TimeZone' => null, 'SetTimeZone' => null]); } else { $timeZone = $tz->getName(); } } catch (Exception $ex) { Logger::log(Logger::ERROR, "Clearing out bad timezone: {timeZone}", ['timeZone' => $currentTimeZone]); // Clear out the bad timezone. Gdn::userModel()->saveAttribute(Gdn::session()->UserID, ['TimeZone' => null, 'SetTimeZone' => null]); } } $this->setData('Result', true); $this->setData('HourOffset', $HourOffset); $this->setData('TimeZone', $timeZone); $time = time(); $this->setData('UTCDateTime', gmdate('r', $time)); $this->setData('UserDateTime', gmdate('r', $time + $HourOffset * 3600)); } else { throw forbiddenException('GET'); } $this->render('Blank'); }