public function enablePlugin($pluginName, $filter = 'all') { if (!Gdn::request()->isAuthenticatedPostBack(true)) { throw new Exception('Requires POST', 405); } $this->permission('Garden.Settings.Manage'); $action = 'none'; if ($filter == 'disabled') { $action = 'SlideUp'; } $addon = Gdn::addonManager()->lookupAddon($pluginName); try { $validation = new Gdn_Validation(); if (!Gdn::pluginManager()->enablePlugin($pluginName, $validation)) { $this->Form->setValidationResults($validation->results()); } else { Gdn_LibraryMap::ClearCache(); $this->informMessage(sprintf(t('%s Enabled.'), val('name', $addon->getInfo(), t('Plugin')))); } $this->EventArguments['PluginName'] = $pluginName; $this->EventArguments['Validation'] = $validation; $this->fireEvent('AfterEnablePlugin'); } catch (Exception $e) { $this->Form->addError($e); } $this->handleAddonToggle($pluginName, $addon->getInfo(), 'plugins', true, $filter, $action); }
/** * Saves the avatar to /uploads in two sizes: * p* : The profile-sized image, which is constrained by Garden.Profile.MaxWidth and Garden.Profile.MaxHeight. * n* : The thumbnail-sized image, which is constrained and cropped according to Garden.Thumbnail.Size. * Also deletes the old avatars. * * @param string $source The path to the local copy of the image. * @param array $thumbOptions The options to save the thumbnail-sized avatar with. * @param Gdn_UploadImage|null $upload The upload object. * @return bool Whether the saves were successful. */ private function saveAvatars($source, $thumbOptions, $upload = null) { try { $ext = ''; if (!$upload) { $upload = new Gdn_UploadImage(); $ext = 'jpg'; } // Generate the target image name $targetImage = $upload->generateTargetName(PATH_UPLOADS, $ext, true); $imageBaseName = pathinfo($targetImage, PATHINFO_BASENAME); $subdir = stringBeginsWith(dirname($targetImage), PATH_UPLOADS . '/', false, true); // Save the profile size image. $parts = Gdn_UploadImage::saveImageAs($source, self::AVATAR_FOLDER . "/{$subdir}/p{$imageBaseName}", c('Garden.Profile.MaxHeight', 1000), c('Garden.Profile.MaxWidth', 250), array('SaveGif' => c('Garden.Thumbnail.SaveGif'))); $thumbnailSize = c('Garden.Thumbnail.Size', 40); // Save the thumbnail size image. Gdn_UploadImage::saveImageAs($source, self::AVATAR_FOLDER . "/{$subdir}/n{$imageBaseName}", $thumbnailSize, $thumbnailSize, $thumbOptions); } catch (Exception $ex) { $this->Form->addError($ex); return false; } $bak = $this->User->Photo; $userPhoto = sprintf($parts['SaveFormat'], self::AVATAR_FOLDER . "/{$subdir}/{$imageBaseName}"); 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; } $this->deleteAvatars($bak); return $userPhoto; }
/** * Send email confirmation message to user. * * @access public * @since 2.0.? * * @param int $UserID */ public function emailConfirmRequest($UserID = '') { if ($UserID && !Gdn::session()->checkPermission('Garden.Users.Edit')) { $UserID = ''; } try { $this->UserModel->sendEmailConfirmationEmail($UserID); } catch (Exception $Ex) { } $this->Form->setValidationResults($this->UserModel->validationResults()); $this->render(); }
/** * Do code checks on an uploaded addon. * * @param int $AddonID Addon to check. * @param bool|false $SaveVersionID Whether to save the version id. * @throws Exception Addon not found. */ public function check($AddonID, $SaveVersionID = false) { $this->permission('Addons.Addon.Manage'); if ($SaveVersionID !== false) { // Get the version data. $Version = $this->AddonModel->SQL->getWhere('AddonVersion', array('AddonVersionID' => $SaveVersionID))->firstRow(DATASET_TYPE_ARRAY); $this->AddonModel->save($Version); $this->Form->setValidationResults($this->AddonModel->validationResults()); } $Addon = $this->AddonModel->getID($AddonID, false, ['GetVersions' => true]); $AddonTypes = Gdn::sql()->get('AddonType')->resultArray(); $AddonTypes = Gdn_DataSet::index($AddonTypes, 'AddonTypeID'); if (!$Addon) { throw notFoundException('Addon'); } // Get the data for the most recent version of the addon. $upload = new Gdn_Upload(); // Also used per version below. $Path = $upload->copyLocal($Addon['File']); $AddonData = arrayTranslate((array) $Addon, array('AddonID', 'AddonKey', 'Name', 'Type', 'Description', 'Requirements', 'Checked')); try { $FileAddonData = UpdateModel::analyzeAddon($Path); if ($FileAddonData) { $AddonData = array_merge($AddonData, arrayTranslate($FileAddonData, array('AddonKey' => 'File_AddonKey', 'Name' => 'File_Name', 'File_Type', 'Description' => 'File_Description', 'Requirements' => 'File_Requirements', 'Checked' => 'File_Checked'))); $AddonData['File_Type'] = valr($FileAddonData['AddonTypeID'] . '.Label', $AddonTypes, 'Unknown'); } $upload->delete($Path); } catch (Exception $Ex) { $AddonData['File_Error'] = $Ex->getMessage(); } $this->setData('Addon', $AddonData); // Go through the versions and make sure we get the versions to check out. $Versions = array(); foreach ($Addon['Versions'] as $Version) { $Version = $Version; $Path = $upload->copyLocal($Version['File']); try { $VersionData = arrayTranslate((array) $Version, array('AddonVersionID', 'Version', 'AddonKey', 'Name', 'MD5', 'FileSize', 'Checked')); $FileVersionData = UpdateModel::analyzeAddon($Path); $FileVersionData = arrayTranslate($FileVersionData, array('Version' => 'File_Version', 'AddonKey' => 'File_AddonKey', 'Name' => 'File_Name', 'MD5' => 'File_MD5', 'FileSize' => 'File_FileSize', 'Checked' => 'File_Checked')); $upload->delete($Path); } catch (Exception $Ex) { $FileVersionData = array('File_Error' => $Ex->getMessage()); } $Versions[] = array_merge($VersionData, $FileVersionData); } $this->setData('Versions', $Versions); $this->addModule('AddonHelpModule'); $this->render(); }
/** * Manage list of plugins. * * @since 2.0.0 * @access public * @param string $Filter 'enabled', 'disabled', or 'all' (default) * @param string $PluginName Unique ID of plugin to be modified. * @param string $TransientKey Security token. */ public function plugins($Filter = '', $PluginName = '', $TransientKey = '') { $this->permission('Garden.Settings.Manage'); // Page setup $this->addJsFile('addons.js'); $this->title(t('Plugins')); $this->addSideMenu('dashboard/settings/plugins'); // Validate and set properties $Session = Gdn::session(); if ($PluginName && !$Session->validateTransientKey($TransientKey)) { $PluginName = ''; } if (!in_array($Filter, array('enabled', 'disabled'))) { $Filter = 'all'; } $this->Filter = $Filter; // Retrieve all available plugins from the plugins directory $this->EnabledPlugins = Gdn::pluginManager()->enabledPlugins(); self::sortAddons($this->EnabledPlugins); $this->AvailablePlugins = Gdn::pluginManager()->availablePlugins(); self::sortAddons($this->AvailablePlugins); if ($PluginName != '') { try { $this->EventArguments['PluginName'] = $PluginName; if (array_key_exists($PluginName, $this->EnabledPlugins) === true) { Gdn::pluginManager()->disablePlugin($PluginName); Gdn_LibraryMap::clearCache(); $this->fireEvent('AfterDisablePlugin'); } else { $Validation = new Gdn_Validation(); if (!Gdn::pluginManager()->enablePlugin($PluginName, $Validation)) { $this->Form->setValidationResults($Validation->results()); } else { Gdn_LibraryMap::ClearCache(); } $this->EventArguments['Validation'] = $Validation; $this->fireEvent('AfterEnablePlugin'); } } catch (Exception $e) { $this->Form->addError($e); } if ($this->Form->errorCount() == 0) { redirect('/settings/plugins/' . $this->Filter); } } $this->render(); }
/** * * * @throws Exception * @throws Gdn_UserException */ public function merge() { $this->permission('Garden.Settings.Manage'); // This must be a postback. if (!$this->Request->isAuthenticatedPostBack()) { throw forbiddenException('GET'); } $Validation = new Gdn_Validation(); $Validation->applyRule('OldUserID', 'ValidateRequired'); $Validation->applyRule('NewUserID', 'ValidateRequired'); if ($Validation->validate($this->Request->Post())) { $Result = Gdn::userModel()->merge($this->Request->post('OldUserID'), $this->Request->post('NewUserID')); $this->setData($Result); } else { $this->Form->setValidationResults($Validation->results()); } $this->render('Blank', 'Utility'); }
/** * 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; }
/** * Create or update a comment. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error. */ public function comment($DiscussionID = '') { // Get $DiscussionID from RequestArgs if valid if ($DiscussionID == '' && count($this->RequestArgs)) { if (is_numeric($this->RequestArgs[0])) { $DiscussionID = $this->RequestArgs[0]; } } // If invalid $DiscussionID, get from form. $this->Form->setModel($this->CommentModel); $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0); // Set discussion data $this->DiscussionID = $DiscussionID; $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID); // Is this an embedded comment being posted to a discussion that doesn't exist yet? $vanilla_type = $this->Form->getFormValue('vanilla_type', ''); $vanilla_url = $this->Form->getFormValue('vanilla_url', ''); $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', ''); $Attributes = array('ForeignUrl' => $vanilla_url); $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', ''); $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != ''; // Only allow vanilla identifiers of 32 chars or less - md5 if larger if (strlen($vanilla_identifier) > 32) { $Attributes['vanilla_identifier'] = $vanilla_identifier; $vanilla_identifier = md5($vanilla_identifier); } if (!$Discussion && $isEmbeddedComments) { $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type); if ($Discussion) { $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID; $this->Form->setValue('DiscussionID', $DiscussionID); } } // If so, create it! if (!$Discussion && $isEmbeddedComments) { // Add these values back to the form if they exist! $this->Form->addHidden('vanilla_identifier', $vanilla_identifier); $this->Form->addHidden('vanilla_type', $vanilla_type); $this->Form->addHidden('vanilla_url', $vanilla_url); $this->Form->addHidden('vanilla_category_id', $vanilla_category_id); $PageInfo = fetchPageInfo($vanilla_url); if (!($Title = $this->Form->getFormValue('Name'))) { $Title = val('Title', $PageInfo, ''); if ($Title == '') { $Title = t('Undefined discussion subject.'); if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") { $Title .= ' ' . t('Page timed out.'); } } } $Description = val('Description', $PageInfo, ''); $Images = val('Images', $PageInfo, array()); $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); if (!$Description && count($Images) == 0) { $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } else { $Body = formatString(' <div class="EmbeddedContent">{Image}<strong>{Title}</strong> <p>{Excerpt}</p> <p><a href="{Url}">{LinkText}</a></p> <div class="ClearFix"></div> </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText)); } if ($Body == '') { $Body = $vanilla_url; } if ($Body == '') { $Body = t('Undefined discussion body.'); } // Validate the CategoryID for inserting. $Category = CategoryModel::categories($vanilla_category_id); if (!$Category) { $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0); if ($vanilla_category_id <= 0) { // No default category defined, so grab the first non-root category and use that. $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID; // No categories in the db? default to 0 if (!$vanilla_category_id) { $vanilla_category_id = 0; } } } else { $vanilla_category_id = $Category['CategoryID']; } $EmbedUserID = c('Garden.Embed.UserID'); if ($EmbedUserID) { $EmbedUser = Gdn::userModel()->getID($EmbedUserID); } if (!$EmbedUserID || !$EmbedUser) { $EmbedUserID = Gdn::userModel()->getSystemUserID(); } $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes)); $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData; $this->fireEvent('BeforeEmbedDiscussion'); $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData); $ValidationResults = $this->DiscussionModel->validationResults(); if (count($ValidationResults) == 0 && $DiscussionID > 0) { $this->Form->addHidden('DiscussionID', $DiscussionID); // Put this in the form so reposts won't cause new discussions. $this->Form->setFormValue('DiscussionID', $DiscussionID); // Put this in the form values so it is used when saving comments. $this->setJson('DiscussionID', $DiscussionID); $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false)); // Update the category discussion count if ($vanilla_category_id > 0) { $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID); } } } // If no discussion was found, error out if (!$Discussion) { $this->Form->addError(t('Failed to find discussion for commenting.')); } /** * Special care is taken for embedded comments. Since we don't currently use an advanced editor for these * comments, we may need to apply certain filters and fixes to the data to maintain its intended display * with the input format (e.g. maintaining newlines). */ if ($isEmbeddedComments) { $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter')); switch ($inputFormatter) { case 'Wysiwyg': $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body'))); break; } } $PermissionCategoryID = val('PermissionCategoryID', $Discussion); // Setup head $this->addJsFile('jquery.autosize.min.js'); $this->addJsFile('autosave.js'); $this->addJsFile('post.js'); // Setup comment model, $CommentID, $DraftID $Session = Gdn::session(); $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : ''; $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : ''; $this->EventArguments['CommentID'] = $CommentID; $this->EventArguments['DraftID'] = $DraftID; // Determine whether we are editing $Editing = $CommentID > 0 || $DraftID > 0; $this->EventArguments['Editing'] = $Editing; // If closed, cancel & go to discussion if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) { redirect(DiscussionUrl($Discussion)); } // Add hidden IDs to form $this->Form->addHidden('DiscussionID', $DiscussionID); $this->Form->addHidden('CommentID', $CommentID); $this->Form->addHidden('DraftID', $DraftID, true); // Check permissions if ($Discussion && $Editing) { // Permission to edit if ($this->Comment->InsertUserID != $Session->UserID) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure that content can (still) be edited. $EditContentTimeout = c('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure only moderators can edit closed things if ($Discussion->Closed) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } $this->Form->setFormValue('CommentID', $CommentID); } elseif ($Discussion) { // Permission to add $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID); } if ($this->Form->authenticatedPostBack()) { // Save as a draft? $FormValues = $this->Form->formValues(); $FormValues = $this->CommentModel->filterForm($FormValues); if (!$Editing) { unset($FormValues['CommentID']); } if ($DraftID == 0) { $DraftID = $this->Form->getFormValue('DraftID', 0); } $Type = GetIncomingValue('Type'); $Draft = $Type == 'Draft'; $this->EventArguments['Draft'] = $Draft; $Preview = $Type == 'Preview'; if ($Draft) { $DraftID = $this->DraftModel->save($FormValues); $this->Form->addHidden('DraftID', $DraftID, true); $this->Form->setValidationResults($this->DraftModel->validationResults()); } elseif (!$Preview) { // Fix an undefined title if we can. if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) { $Set = array('Name' => $this->Form->getFormValue('Name')); if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) { $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set); } $Inserted = !$CommentID; $CommentID = $this->CommentModel->save($FormValues); // The comment is now half-saved. if (is_numeric($CommentID) && $CommentID > 0) { if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) { $this->CommentModel->save2($CommentID, $Inserted, true, true); } else { $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax'); } // $Discussion = $this->DiscussionModel->getID($DiscussionID); $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false)); $this->EventArguments['Discussion'] = $Discussion; $this->EventArguments['Comment'] = $Comment; $this->fireEvent('AfterCommentSave'); } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) { $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.'); } $this->Form->setValidationResults($this->CommentModel->validationResults()); if ($CommentID > 0 && $DraftID > 0) { $this->DraftModel->delete($DraftID); } } // Handle non-ajax requests first: if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { if ($this->Form->errorCount() == 0) { // Make sure that this form knows what comment we are editing. if ($CommentID > 0) { $this->Form->addHidden('CommentID', $CommentID); } // If the comment was not a draft if (!$Draft) { // Redirect to the new comment. if ($CommentID > 0) { redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}"); } elseif ($CommentID == SPAM) { $this->setData('DiscussionUrl', DiscussionUrl($Discussion)); $this->View = 'Spam'; } } elseif ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = val('Body', $FormValues, ''); $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter')); $this->addAsset('Content', $this->fetchView('preview')); } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } } } else { // Handle ajax-based requests if ($this->Form->errorCount() > 0) { // Return the form errors $this->errorMessage($this->Form->errors()); } else { // Make sure that the ajax request form knows about the newly created comment or draft id $this->setJson('CommentID', $CommentID); $this->setJson('DraftID', $DraftID); if ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = val('Body', $FormValues, ''); $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter')); $this->View = 'preview'; } elseif (!$Draft) { // If the comment was not a draft // If Editing a comment if ($Editing) { // Just reload the comment in question $this->Offset = 1; $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('Discussion', $Discussion); // Load the discussion $this->ControllerName = 'discussion'; $this->View = 'comments'; // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID); } else { // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments. $OrderBy = valr('0.0', $this->CommentModel->orderBy()); // $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID')); // $DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly'); // if (!$Redirect) { // // Otherwise load all new comments that the user hasn't seen yet // $LastCommentID = $this->Form->getFormValue('LastCommentID'); // if (!is_numeric($LastCommentID)) // $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly // // // Don't reload the first comment if this new comment is the first one. // $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID); // // Do not load more than a single page of data... // $Limit = c('Vanilla.Comments.PerPage', 30); // // // Redirect if the new new comment isn't on the same page. // $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit); // } // if ($Redirect) { // // The user posted a comment on a page other than the last one, so just redirect to the last page. // $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true); // } else { // // Make sure to load all new comments since the page was last loaded by this user // if ($DisplayNewCommentOnly) $this->Offset = $this->CommentModel->GetOffset($CommentID); $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('NewComments', true); $this->ClassName = 'DiscussionController'; $this->ControllerName = 'discussion'; $this->View = 'comments'; // } // Make sure to set the user's discussion watch records $CountComments = $this->CommentModel->getCount($DiscussionID); $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments; $Offset = $CountComments - $Limit; $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments); } } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } // And update the draft count $UserModel = Gdn::userModel(); $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0); $this->setJson('MyDrafts', t('My Drafts')); $this->setJson('CountDrafts', $CountDrafts); } } } elseif ($this->Request->isPostBack()) { throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401); } else { // Load form if (isset($this->Comment)) { $this->Form->setData((array) $this->Comment); } } // Include data for FireEvent if (property_exists($this, 'Discussion')) { $this->EventArguments['Discussion'] = $this->Discussion; } if (property_exists($this, 'Comment')) { $this->EventArguments['Comment'] = $this->Comment; } $this->fireEvent('BeforeCommentRender'); if ($this->deliveryType() == DELIVERY_TYPE_DATA) { if ($this->data('Comments') instanceof Gdn_DataSet) { $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY); if ($Comment) { $Photo = $Comment['InsertPhoto']; if (strpos($Photo, '//') === false) { $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s')); } $Comment['InsertPhoto'] = $Photo; } $this->Data = array('Comment' => $Comment); } $this->RenderData($this->Data); } else { require_once $this->fetchViewLocation('helper_functions', 'Discussion'); // Render default view. $this->render(); } }
/** * Set user's photo (avatar). * * @since 2.0.0 * @access public * @param mixed $UserReference Unique identifier, possible username or ID. * @param string $Username . */ public function picture($UserReference = '', $Username = '', $UserID = '') { if (!Gdn::session()->checkRankedPermission(c('Garden.Profile.EditPhotos', true))) { throw forbiddenException('@Editing user photos has been disabled.'); } // Permission checks $this->permission(array('Garden.Profiles.Edit', 'Moderation.Profiles.Edit', 'Garden.ProfilePicture.Edit'), false); $Session = Gdn::session(); if (!$Session->isValid()) { $this->Form->addError('You must be authenticated in order to use this form.'); } // Check ability to manipulate image $ImageManipOk = false; if (function_exists('gd_info')) { $GdInfo = gd_info(); $GdVersion = preg_replace('/[a-z ()]+/i', '', $GdInfo['GD Version']); if ($GdVersion < 2) { throw new Exception(sprintf(t("This installation of GD is too old (v%s). Vanilla requires at least version 2 or compatible."), $GdVersion)); } } else { throw new Exception(sprintf(t("Unable to detect PHP GD installed on this system. Vanilla requires GD version 2 or better."))); } // Get user data & prep form. if ($this->Form->authenticatedPostBack() && $this->Form->getFormValue('UserID')) { $UserID = $this->Form->getFormValue('UserID'); } $this->getUserInfo($UserReference, $Username, $UserID, true); $this->Form->setModel($this->UserModel); if ($this->Form->authenticatedPostBack() === true) { $this->Form->setFormValue('UserID', $this->User->UserID); // Set user's Photo attribute to a URL, provided the current user has proper permission to do so. $photoUrl = $this->Form->getFormValue('Url', false); if ($photoUrl && Gdn::session()->checkPermission('Garden.Settings.Manage')) { if (isUrl($photoUrl) && filter_var($photoUrl, FILTER_VALIDATE_URL)) { $UserPhoto = $photoUrl; } else { $this->Form->addError('Invalid photo URL'); } } else { $UploadImage = new Gdn_UploadImage(); try { // Validate the upload $TmpImage = $UploadImage->ValidateUpload('Picture'); // Generate the target image name. $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS, '', true); $Basename = pathinfo($TargetImage, PATHINFO_BASENAME); $Subdir = stringBeginsWith(dirname($TargetImage), PATH_UPLOADS . '/', false, true); // Delete any previously uploaded image. $UploadImage->delete(changeBasename($this->User->Photo, 'p%s')); // Save the uploaded image in profile size. $Props = $UploadImage->SaveImageAs($TmpImage, "userpics/{$Subdir}/p{$Basename}", c('Garden.Profile.MaxHeight', 1000), c('Garden.Profile.MaxWidth', 250), array('SaveGif' => c('Garden.Thumbnail.SaveGif'))); $UserPhoto = sprintf($Props['SaveFormat'], "userpics/{$Subdir}/{$Basename}"); // // Save the uploaded image in preview size // $UploadImage->SaveImageAs( // $TmpImage, // 'userpics/t'.$ImageBaseName, // Gdn::config('Garden.Preview.MaxHeight', 100), // Gdn::config('Garden.Preview.MaxWidth', 75) // ); // Save the uploaded image in thumbnail size $ThumbSize = Gdn::config('Garden.Thumbnail.Size', 40); $UploadImage->saveImageAs($TmpImage, "userpics/{$Subdir}/n{$Basename}", $ThumbSize, $ThumbSize, array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif'))); } catch (Exception $Ex) { // Throw the exception on API calls. if ($this->deliveryType() === DELIVERY_TYPE_DATA) { throw $Ex; } $this->Form->addError($Ex); } } // If there were no errors, associate the image with the user if ($this->Form->errorCount() == 0) { if (!$this->UserModel->save(array('UserID' => $this->User->UserID, 'Photo' => $UserPhoto), array('CheckExisting' => true))) { $this->Form->setValidationResults($this->UserModel->validationResults()); } else { $this->User->Photo = $UserPhoto; setValue('Photo', $this->Data['Profile'], $UserPhoto); setValue('PhotoUrl', $this->Data['Profile'], Gdn_Upload::url(changeBasename($UserPhoto, 'n%s'))); } } // If there were no problems, redirect back to the user account if ($this->Form->errorCount() == 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) { $this->informMessage(sprite('Check', 'InformSprite') . t('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite'); redirect($this->deliveryType() == DELIVERY_TYPE_VIEW ? userUrl($this->User) : userUrl($this->User, '', 'picture')); } } if ($this->Form->errorCount() > 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) { $this->deliveryType(DELIVERY_TYPE_ALL); } $this->title(t('Change Picture')); $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture')); $this->render(); }
/** * Start a new conversation. * * @since 2.0.0 * @access public * * @param string $Recipient Username of the recipient. * @param string $Subject Subject of the message. */ public function add($Recipient = '', $Subject = '') { $this->permission('Conversations.Conversations.Add'); $this->Form->setModel($this->ConversationModel); // Set recipient limit if (!checkPermission('Garden.Moderation.Manage') && c('Conversations.MaxRecipients')) { $this->addDefinition('MaxRecipients', c('Conversations.MaxRecipients')); $this->setData('MaxRecipients', c('Conversations.MaxRecipients')); } if ($this->Form->authenticatedPostBack()) { $RecipientUserIDs = array(); $To = explode(',', $this->Form->getFormValue('To', '')); $UserModel = new UserModel(); foreach ($To as $Name) { if (trim($Name) != '') { $User = $UserModel->getByUsername(trim($Name)); if (is_object($User)) { $RecipientUserIDs[] = $User->UserID; } } } // Enforce MaxRecipients if (!$this->ConversationModel->addUserAllowed(0, count($RecipientUserIDs))) { // Reuse the Info message now as an error. $this->Form->addError(sprintf(plural($this->data('MaxRecipients'), "You are limited to %s recipient.", "You are limited to %s recipients."), c('Conversations.MaxRecipients'))); } $this->EventArguments['Recipients'] = $RecipientUserIDs; $this->fireEvent('BeforeAddConversation'); $this->Form->setFormValue('RecipientUserID', $RecipientUserIDs); $ConversationID = $this->Form->save(); if ($ConversationID !== false) { $Target = $this->Form->getFormValue('Target', 'messages/' . $ConversationID); $this->RedirectUrl = url($Target); $Conversation = $this->ConversationModel->getID($ConversationID, false, ['viewingUserID' => Gdn::session()->UserID]); $NewMessageID = val('FirstMessageID', $Conversation); $this->EventArguments['MessageID'] = $NewMessageID; $this->fireEvent('AfterConversationSave'); } } else { // Check if valid user name has been passed. if ($Recipient != '') { if (!Gdn::userModel()->getByUsername($Recipient)) { $this->Form->setValidationResults(['RecipientUserID' => [sprintf('"%s" is an unknown username.', $Recipient)]]); $Recipient = ''; } else { $this->Form->setValue('To', $Recipient); } } if ($Subject != '') { $this->Form->setValue('Subject', $Subject); } } if ($Target = Gdn::request()->get('Target')) { $this->Form->addHidden('Target', $Target); } Gdn_Theme::section('PostConversation'); $this->title(t('New Conversation')); $this->setData('Breadcrumbs', array(array('Name' => t('Inbox'), 'Url' => '/messages/inbox'), array('Name' => $this->data('Title'), 'Url' => 'messages/add'))); $this->CssClass = 'NoPanel'; $this->render(); }