addError() public method

Adds an error to the errors collection and optionally relates it to the specified FieldName. Errors added with this method can be rendered with $this->Errors().
public addError ( $Error, string $FieldName = '' )
$FieldName string The name of the field to relate the error to.
コード例 #1
0
 /**
  * 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();
 }
コード例 #2
0
 /**
  * Run the database structure or /utility/structure.
  *
  * Note: Keep this method protected!
  *
  * @param string $appName Unique app name or 'all' (default).
  * @param bool $captureOnly Whether to list changes rather than execute (0 or 1).
  * @throws Exception
  */
 protected function runStructure($appName = 'all', $captureOnly = true)
 {
     // This permission is run again to be sure someone doesn't accidentally call this method incorrectly.
     $this->permission('Garden.Settings.Manage');
     $Files = array();
     $appName = $appName == '' ? 'all' : $appName;
     if ($appName == 'all') {
         // Load all application structure files.
         $ApplicationManager = new Gdn_ApplicationManager();
         $Apps = $ApplicationManager->enabledApplications();
         $AppNames = array_column($Apps, 'Folder');
         foreach ($AppNames as $appName) {
             $Files[] = combinePaths(array(PATH_APPLICATIONS, $appName, 'settings', 'structure.php'), DS);
         }
         $appName = 'all';
     } else {
         // Load that specific application structure file.
         $Files[] = combinePaths(array(PATH_APPLICATIONS, $appName, 'settings', 'structure.php'), DS);
     }
     $Drop = false;
     $Explicit = false;
     $captureOnly = !($captureOnly == '0');
     $Structure = Gdn::structure();
     $Structure->CaptureOnly = $captureOnly;
     $SQL = Gdn::sql();
     $SQL->CaptureModifications = $captureOnly;
     $this->setData('CaptureOnly', $Structure->CaptureOnly);
     $this->setData('Drop', $Drop);
     $this->setData('Explicit', $Explicit);
     $this->setData('ApplicationName', $appName);
     $this->setData('Status', '');
     $FoundStructureFile = false;
     foreach ($Files as $File) {
         if (file_exists($File)) {
             $FoundStructureFile = true;
             try {
                 include $File;
             } catch (Exception $Ex) {
                 $this->Form->addError($Ex);
             }
         }
     }
     // Run the structure of all of the plugins.
     $Plugins = Gdn::pluginManager()->enabledPlugins();
     foreach ($Plugins as $PluginKey => $Plugin) {
         $PluginInstance = Gdn::pluginManager()->getPluginInstance($PluginKey, Gdn_PluginManager::ACCESS_PLUGINNAME);
         if (method_exists($PluginInstance, 'Structure')) {
             $PluginInstance->structure();
         }
     }
     if (property_exists($Structure->Database, 'CapturedSql')) {
         $this->setData('CapturedSql', (array) $Structure->Database->CapturedSql);
     } else {
         $this->setData('CapturedSql', array());
     }
     if ($this->Form->errorCount() == 0 && !$captureOnly && $FoundStructureFile) {
         $this->setData('Status', 'The structure was successfully executed.');
     }
 }
コード例 #3
0
 /**
  * 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();
 }
コード例 #4
0
 /**
  * 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();
 }
コード例 #5
0
 /**
  * Restore logs.
  *
  * @since 2.0.?
  * @access public
  *
  * @param array $LogIDs List of log IDs.
  */
 public function restore($LogIDs)
 {
     $this->permission(array('Garden.Moderation.Manage', 'Moderation.Spam.Manage', 'Moderation.ModerationQueue.Manage'), false);
     // Grab the logs.
     $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->render('Blank', 'Utility');
 }
コード例 #6
0
 /**
  * Determine whether user can register with this username.
  *
  * @since 2.0.0
  * @access public
  * @param string $Name Username to be checked.
  */
 public function usernameAvailable($Name = '')
 {
     $this->_DeliveryType = DELIVERY_TYPE_BOOL;
     $Available = true;
     if (c('Garden.Registration.NameUnique', true) && $Name != '') {
         $UserModel = Gdn::userModel();
         if ($UserModel->getByUsername($Name)) {
             $Available = false;
         }
     }
     if (!$Available) {
         $this->Form->addError(sprintf(t('%s unavailable'), t('Name')));
     }
     $this->render();
 }
コード例 #7
0
 /**
  * Do password reset.
  *
  * @access public
  * @since 2.0.0
  *
  * @param int $UserID Unique.
  * @param string $PasswordResetKey Authenticate with unique, 1-time code sent via email.
  */
 public function passwordReset($UserID = '', $PasswordResetKey = '')
 {
     $PasswordResetKey = trim($PasswordResetKey);
     if (!is_numeric($UserID) || $PasswordResetKey == '' || $this->UserModel->getAttribute($UserID, 'PasswordResetKey', '') != $PasswordResetKey) {
         $this->Form->addError('Failed to authenticate your password reset request. Try using the reset request form again.');
         Logger::event('password_reset_failure', Logger::NOTICE, '{username} failed to authenticate password reset request.');
         $this->fireEvent('PasswordResetFailed', ['UserID' => $UserID]);
     }
     $Expires = $this->UserModel->getAttribute($UserID, 'PasswordResetExpires');
     if ($this->Form->errorCount() === 0 && $Expires < time()) {
         $this->Form->addError('@' . t('Your password reset token has expired.', 'Your password reset token has expired. Try using the reset request form again.'));
         Logger::event('password_reset_failure', Logger::NOTICE, '{username} has an expired reset token.');
         $this->fireEvent('PasswordResetFailed', ['UserID' => $UserID]);
     }
     if ($this->Form->errorCount() == 0) {
         $User = $this->UserModel->getID($UserID, DATASET_TYPE_ARRAY);
         if ($User) {
             $User = arrayTranslate($User, array('UserID', 'Name', 'Email'));
             $this->setData('User', $User);
         }
     } else {
         $this->setData('Fatal', true);
     }
     if ($this->Form->errorCount() == 0 && $this->Form->isPostBack() === true) {
         $Password = $this->Form->getFormValue('Password', '');
         $Confirm = $this->Form->getFormValue('Confirm', '');
         if ($Password == '') {
             $this->Form->addError('Your new password is invalid');
             Logger::event('password_reset_failure', Logger::NOTICE, 'Failed to reset the password for {username}. Password is invalid.');
         } elseif ($Password != $Confirm) {
             $this->Form->addError('Your passwords did not match.');
         }
         Logger::event('password_reset_failure', Logger::NOTICE, 'Failed to reset the password for {username}. Passwords did not match.');
         if ($this->Form->errorCount() == 0) {
             $User = $this->UserModel->passwordReset($UserID, $Password);
             Logger::event('password_reset', Logger::NOTICE, '{username} has reset their password.');
             Gdn::session()->start($User->UserID, true);
             //            $Authenticator = Gdn::authenticator()->AuthenticateWith('password');
             //            $Authenticator->FetchData($Authenticator, array('Email' => $User->Email, 'Password' => $Password, 'RememberMe' => FALSE));
             //            $AuthUserID = $Authenticator->Authenticate();
             redirect('/');
         }
     }
     $this->render();
 }
コード例 #8
0
 /**
  * Restore logs.
  *
  * @since 2.0.?
  * @access public
  *
  * @param array $LogIDs List of log IDs.
  */
 public function restore()
 {
     if (!Gdn::request()->isAuthenticatedPostBack(true)) {
         throw new Exception('Requires POST', 405);
     }
     $this->permission(array('Garden.Moderation.Manage', 'Moderation.Spam.Manage', 'Moderation.ModerationQueue.Manage'), false);
     $LogIDs = Gdn::request()->post('LogIDs');
     // Grab the logs.
     $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->render('Blank', 'Utility');
 }
コード例 #9
0
 /**
  * Allows the setting of data into one of two serialized data columns on the
  * user table: Preferences and Attributes.
  *
  * The method expects "Name" & "Value" to be in the $_POST collection. This method always
  * saves to the row of the user id performing this action (ie. $Session->UserID). The
  * type of property column being saved should be specified in the url:
  * i.e. /dashboard/utility/set/preference/name/value/transientKey
  * or /dashboard/utility/set/attribute/name/value/transientKey
  *
  * @since 2.0.0
  * @access public
  * @param string $UserPropertyColumn The type of value being saved: preference or attribute.
  * @param string $Name The name of the property being saved.
  * @param string $Value The value of the property being saved.
  * @param string $TransientKey A unique transient key to authenticate that the user intended to perform this action.
  */
 public function set($UserPropertyColumn = '', $Name = '', $Value = '', $TransientKey = '')
 {
     $this->_DeliveryType = DELIVERY_TYPE_BOOL;
     $Session = Gdn::session();
     $Success = false;
     if (in_array($UserPropertyColumn, array('preference', 'attribute')) && $Name != '' && $Value != '' && $Session->UserID > 0 && $Session->validateTransientKey($TransientKey)) {
         $UserModel = Gdn::factory("UserModel");
         $Method = $UserPropertyColumn == 'preference' ? 'SavePreference' : 'SaveAttribute';
         $Success = $UserModel->{$Method}($Session->UserID, $Name, $Value) ? 'TRUE' : 'FALSE';
     }
     if (!$Success) {
         $this->Form->addError('ErrorBool');
     }
     // Redirect back where the user came from if necessary
     if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
         redirect($_SERVER['HTTP_REFERER']);
     } else {
         $this->render();
     }
 }
コード例 #10
0
 /**
  * Revoke an invitation.
  *
  * @since 2.0.0
  * @param int $InvitationID Unique identifier.
  * @throws Exception Throws an exception when the invitation isn't found or the user doesn't have permission to delete it.
  */
 public function uninvite($InvitationID)
 {
     $this->permission('Garden.SignIn.Allow');
     if (!$this->Form->authenticatedPostBack()) {
         throw forbiddenException('GET');
     }
     $InvitationModel = new InvitationModel();
     $Session = Gdn::session();
     try {
         $Valid = $InvitationModel->delete($InvitationID, $this->UserModel);
         if ($Valid) {
             $this->informMessage(t('The invitation was removed successfully.'));
             $this->jsonTarget(".js-invitation[data-id=\"{$InvitationID}\"]", '', 'SlideUp');
         }
     } catch (Exception $ex) {
         $this->Form->addError(strip_tags($ex->getMessage()));
     }
     if ($this->Form->errorCount() == 0) {
         $this->render('Blank', 'Utility');
     }
 }
コード例 #11
0
 /**
  * Allows users to bookmark conversations.
  *
  * @param int $ConversationID Unique ID of conversation to view.
  * @param string $TransientKey Single-use hash to prove intent.
  */
 public function bookmark($ConversationID = '', $TransientKey = '')
 {
     $Session = Gdn::session();
     $Bookmark = null;
     // Validate & do bookmarking.
     if (is_numeric($ConversationID) && $ConversationID > 0 && $Session->UserID > 0 && $Session->validateTransientKey($TransientKey)) {
         $Bookmark = $this->ConversationModel->bookmark($ConversationID, $Session->UserID);
     }
     // Report success or error
     if ($Bookmark === false) {
         $this->Form->addError('ErrorBool');
     } else {
         $this->setJson('Bookmark', $Bookmark);
     }
     // Redirect back where the user came from if necessary
     if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
         redirect($_SERVER['HTTP_REFERER']);
     } else {
         $this->render();
     }
 }
コード例 #12
0
 /**
  * Set the icon for an addon.
  *
  * @param int $AddonID Specified addon id.
  * @throws Exception Addon not found.
  */
 public function icon($AddonID = '')
 {
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     $Addon = $this->AddonModel->getID($AddonID);
     if (!$Addon) {
         throw notFoundException('Addon');
     }
     if ($Session->UserID != $Addon['InsertUserID']) {
         $this->permission('Addons.Addon.Manage');
     }
     $this->addModule('AddonHelpModule', 'Panel');
     $this->Form->setModel($this->AddonModel);
     $this->Form->addHidden('AddonID', $AddonID);
     if ($this->Form->authenticatedPostBack()) {
         $UploadImage = new Gdn_UploadImage();
         try {
             // Validate the upload
             $imageLocation = $UploadImage->validateUpload('Icon');
             $TargetImage = $this->saveIcon($imageLocation);
         } catch (Exception $ex) {
             $this->Form->addError($ex);
         }
         // If there were no errors, remove the old picture and insert the picture
         if ($this->Form->errorCount() == 0) {
             if ($Addon['Icon']) {
                 $UploadImage->delete($Addon['Icon']);
             }
             $this->AddonModel->save(array('AddonID' => $AddonID, 'Icon' => $TargetImage));
         }
         // If there were no problems, redirect back to the addon
         if ($this->Form->errorCount() == 0) {
             $this->RedirectUrl = Url('/addon/' . AddonModel::slug($Addon));
         }
     }
     $this->render();
 }
コード例 #13
0
 /**
  * Check minimum requirements for Garden.
  *
  * @since 2.0.0
  * @access private
  * @return bool Whether platform passes requirement check.
  */
 private function _checkPrerequisites()
 {
     // Make sure we are running at least PHP 5.1
     if (version_compare(phpversion(), ENVIRONMENT_PHP_VERSION) < 0) {
         $this->Form->addError(sprintf(t('You are running PHP version %1$s. Vanilla requires PHP %2$s or greater. You must upgrade PHP before you can continue.'), phpversion(), ENVIRONMENT_PHP_VERSION));
     }
     // Make sure PDO is available
     if (!class_exists('PDO')) {
         $this->Form->addError(t('You must have the PDO module enabled in PHP in order for Vanilla to connect to your database.'));
     }
     if (!defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')) {
         $this->Form->addError(t('You must have the MySQL driver for PDO enabled in order for Vanilla to connect to your database.'));
     }
     // Make sure that the correct filesystem permissions are in place.
     $PermissionProblem = false;
     // Make sure the appropriate folders are writable.
     $ProblemDirectories = array();
     if (!is_readable(PATH_CONF) || !isWritable(PATH_CONF)) {
         $ProblemDirectories[] = PATH_CONF;
     }
     if (!is_readable(PATH_UPLOADS) || !isWritable(PATH_UPLOADS)) {
         $ProblemDirectories[] = PATH_UPLOADS;
     }
     if (!is_readable(PATH_CACHE) || !isWritable(PATH_CACHE)) {
         $ProblemDirectories[] = PATH_CACHE;
     }
     if (file_exists(PATH_CACHE . '/Smarty/compile') && (!is_readable(PATH_CACHE . '/Smarty/compile') || !isWritable(PATH_CACHE . '/Smarty/compile'))) {
         $ProblemDirectories[] = PATH_CACHE . '/Smarty/compile';
     }
     // Display our permission errors.
     if (count($ProblemDirectories) > 0) {
         $PermissionProblem = true;
         $PermissionError = t('Some folders don\'t have correct permissions.', '<p>These folders must be readable and writable by the web server:</p>');
         $PermissionHelp = '<pre>' . implode("\n", $ProblemDirectories) . '</pre>';
         $this->Form->addError($PermissionError . $PermissionHelp);
     }
     // Make sure the config folder is writable.
     if (!$PermissionProblem) {
         $ConfigFile = Gdn::config()->defaultPath();
         if (file_exists($ConfigFile)) {
             // Make sure the config file is writable.
             if (!is_readable($ConfigFile) || !isWritable($ConfigFile)) {
                 $this->Form->addError(sprintf(t('Your configuration file does not have the correct permissions. PHP needs to be able to read and write to this file: <code>%s</code>'), $ConfigFile));
                 $PermissionProblem = true;
             }
         } else {
             // Make sure the config file can be created.
             if (!is_writeable(dirname($ConfigFile))) {
                 $this->Form->addError(sprintf(t('Your configuration file cannot be created. PHP needs to be able to create this file: <code>%s</code>'), $ConfigFile));
                 $PermissionProblem = true;
             }
         }
     }
     // Make sure the cache folder is writable
     if (!$PermissionProblem) {
         if (!file_exists(PATH_CACHE . '/Smarty')) {
             mkdir(PATH_CACHE . '/Smarty');
         }
         if (!file_exists(PATH_CACHE . '/Smarty/cache')) {
             mkdir(PATH_CACHE . '/Smarty/cache');
         }
         if (!file_exists(PATH_CACHE . '/Smarty/compile')) {
             mkdir(PATH_CACHE . '/Smarty/compile');
         }
     }
     return $this->Form->errorCount() == 0 ? true : false;
 }
コード例 #14
0
 /**
  * Create or update a comment.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error.
  */
 public function comment($DiscussionID = '')
 {
     // Get $DiscussionID from RequestArgs if valid
     if ($DiscussionID == '' && count($this->RequestArgs)) {
         if (is_numeric($this->RequestArgs[0])) {
             $DiscussionID = $this->RequestArgs[0];
         }
     }
     // If invalid $DiscussionID, get from form.
     $this->Form->setModel($this->CommentModel);
     $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0);
     // Set discussion data
     $this->DiscussionID = $DiscussionID;
     $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID);
     // Is this an embedded comment being posted to a discussion that doesn't exist yet?
     $vanilla_type = $this->Form->getFormValue('vanilla_type', '');
     $vanilla_url = $this->Form->getFormValue('vanilla_url', '');
     $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', '');
     $Attributes = array('ForeignUrl' => $vanilla_url);
     $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', '');
     $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != '';
     // Only allow vanilla identifiers of 32 chars or less - md5 if larger
     if (strlen($vanilla_identifier) > 32) {
         $Attributes['vanilla_identifier'] = $vanilla_identifier;
         $vanilla_identifier = md5($vanilla_identifier);
     }
     if (!$Discussion && $isEmbeddedComments) {
         $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type);
         if ($Discussion) {
             $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID;
             $this->Form->setValue('DiscussionID', $DiscussionID);
         }
     }
     // If so, create it!
     if (!$Discussion && $isEmbeddedComments) {
         // Add these values back to the form if they exist!
         $this->Form->addHidden('vanilla_identifier', $vanilla_identifier);
         $this->Form->addHidden('vanilla_type', $vanilla_type);
         $this->Form->addHidden('vanilla_url', $vanilla_url);
         $this->Form->addHidden('vanilla_category_id', $vanilla_category_id);
         $PageInfo = fetchPageInfo($vanilla_url);
         if (!($Title = $this->Form->getFormValue('Name'))) {
             $Title = val('Title', $PageInfo, '');
             if ($Title == '') {
                 $Title = t('Undefined discussion subject.');
                 if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") {
                     $Title .= ' ' . t('Page timed out.');
                 }
             }
         }
         $Description = val('Description', $PageInfo, '');
         $Images = val('Images', $PageInfo, array());
         $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
         if (!$Description && count($Images) == 0) {
             $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
         } else {
             $Body = formatString('
         <div class="EmbeddedContent">{Image}<strong>{Title}</strong>
            <p>{Excerpt}</p>
            <p><a href="{Url}">{LinkText}</a></p>
            <div class="ClearFix"></div>
         </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText));
         }
         if ($Body == '') {
             $Body = $vanilla_url;
         }
         if ($Body == '') {
             $Body = t('Undefined discussion body.');
         }
         // Validate the CategoryID for inserting.
         $Category = CategoryModel::categories($vanilla_category_id);
         if (!$Category) {
             $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0);
             if ($vanilla_category_id <= 0) {
                 // No default category defined, so grab the first non-root category and use that.
                 $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID;
                 // No categories in the db? default to 0
                 if (!$vanilla_category_id) {
                     $vanilla_category_id = 0;
                 }
             }
         } else {
             $vanilla_category_id = $Category['CategoryID'];
         }
         $EmbedUserID = c('Garden.Embed.UserID');
         if ($EmbedUserID) {
             $EmbedUser = Gdn::userModel()->getID($EmbedUserID);
         }
         if (!$EmbedUserID || !$EmbedUser) {
             $EmbedUserID = Gdn::userModel()->getSystemUserID();
         }
         $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes));
         $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData;
         $this->fireEvent('BeforeEmbedDiscussion');
         $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData);
         $ValidationResults = $this->DiscussionModel->validationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0) {
             $this->Form->addHidden('DiscussionID', $DiscussionID);
             // Put this in the form so reposts won't cause new discussions.
             $this->Form->setFormValue('DiscussionID', $DiscussionID);
             // Put this in the form values so it is used when saving comments.
             $this->setJson('DiscussionID', $DiscussionID);
             $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
             // Update the category discussion count
             if ($vanilla_category_id > 0) {
                 $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID);
             }
         }
     }
     // If no discussion was found, error out
     if (!$Discussion) {
         $this->Form->addError(t('Failed to find discussion for commenting.'));
     }
     /**
      * Special care is taken for embedded comments.  Since we don't currently use an advanced editor for these
      * comments, we may need to apply certain filters and fixes to the data to maintain its intended display
      * with the input format (e.g. maintaining newlines).
      */
     if ($isEmbeddedComments) {
         $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter'));
         switch ($inputFormatter) {
             case 'Wysiwyg':
                 $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body')));
                 break;
         }
     }
     $PermissionCategoryID = val('PermissionCategoryID', $Discussion);
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     // Setup comment model, $CommentID, $DraftID
     $Session = Gdn::session();
     $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : '';
     $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : '';
     $this->EventArguments['CommentID'] = $CommentID;
     $this->EventArguments['DraftID'] = $DraftID;
     // Determine whether we are editing
     $Editing = $CommentID > 0 || $DraftID > 0;
     $this->EventArguments['Editing'] = $Editing;
     // If closed, cancel & go to discussion
     if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) {
         redirect(DiscussionUrl($Discussion));
     }
     // Add hidden IDs to form
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('CommentID', $CommentID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     // Check permissions
     if ($Discussion && $Editing) {
         // Permission to edit
         if ($this->Comment->InsertUserID != $Session->UserID) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = c('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($Discussion->Closed) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         $this->Form->setFormValue('CommentID', $CommentID);
     } elseif ($Discussion) {
         // Permission to add
         $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID);
     }
     if ($this->Form->authenticatedPostBack()) {
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->CommentModel->filterForm($FormValues);
         if (!$Editing) {
             unset($FormValues['CommentID']);
         }
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Type = GetIncomingValue('Type');
         $Draft = $Type == 'Draft';
         $this->EventArguments['Draft'] = $Draft;
         $Preview = $Type == 'Preview';
         if ($Draft) {
             $DraftID = $this->DraftModel->save($FormValues);
             $this->Form->addHidden('DraftID', $DraftID, true);
             $this->Form->setValidationResults($this->DraftModel->validationResults());
         } elseif (!$Preview) {
             // Fix an undefined title if we can.
             if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) {
                 $Set = array('Name' => $this->Form->getFormValue('Name'));
                 if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) {
                     $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
                     $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
                 }
                 $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set);
             }
             $Inserted = !$CommentID;
             $CommentID = $this->CommentModel->save($FormValues);
             // The comment is now half-saved.
             if (is_numeric($CommentID) && $CommentID > 0) {
                 if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) {
                     $this->CommentModel->save2($CommentID, $Inserted, true, true);
                 } else {
                     $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax');
                 }
                 // $Discussion = $this->DiscussionModel->getID($DiscussionID);
                 $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false));
                 $this->EventArguments['Discussion'] = $Discussion;
                 $this->EventArguments['Comment'] = $Comment;
                 $this->fireEvent('AfterCommentSave');
             } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) {
                 $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.');
             }
             $this->Form->setValidationResults($this->CommentModel->validationResults());
             if ($CommentID > 0 && $DraftID > 0) {
                 $this->DraftModel->delete($DraftID);
             }
         }
         // Handle non-ajax requests first:
         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
             if ($this->Form->errorCount() == 0) {
                 // Make sure that this form knows what comment we are editing.
                 if ($CommentID > 0) {
                     $this->Form->addHidden('CommentID', $CommentID);
                 }
                 // If the comment was not a draft
                 if (!$Draft) {
                     // Redirect to the new comment.
                     if ($CommentID > 0) {
                         redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}");
                     } elseif ($CommentID == SPAM) {
                         $this->setData('DiscussionUrl', DiscussionUrl($Discussion));
                         $this->View = 'Spam';
                     }
                 } elseif ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->addAsset('Content', $this->fetchView('preview'));
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         } else {
             // Handle ajax-based requests
             if ($this->Form->errorCount() > 0) {
                 // Return the form errors
                 $this->errorMessage($this->Form->errors());
             } else {
                 // Make sure that the ajax request form knows about the newly created comment or draft id
                 $this->setJson('CommentID', $CommentID);
                 $this->setJson('DraftID', $DraftID);
                 if ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->View = 'preview';
                 } elseif (!$Draft) {
                     // If the comment was not a draft
                     // If Editing a comment
                     if ($Editing) {
                         // Just reload the comment in question
                         $this->Offset = 1;
                         $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('Discussion', $Discussion);
                         // Load the discussion
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion
                         $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID);
                     } else {
                         // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments.
                         $OrderBy = valr('0.0', $this->CommentModel->orderBy());
                         //                     $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID'));
                         //							$DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly');
                         //                     if (!$Redirect) {
                         //                        // Otherwise load all new comments that the user hasn't seen yet
                         //                        $LastCommentID = $this->Form->getFormValue('LastCommentID');
                         //                        if (!is_numeric($LastCommentID))
                         //                           $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly
                         //
                         //                        // Don't reload the first comment if this new comment is the first one.
                         //                        $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID);
                         //                        // Do not load more than a single page of data...
                         //                        $Limit = c('Vanilla.Comments.PerPage', 30);
                         //
                         //                        // Redirect if the new new comment isn't on the same page.
                         //                        $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit);
                         //                     }
                         //                     if ($Redirect) {
                         //                        // The user posted a comment on a page other than the last one, so just redirect to the last page.
                         //                        $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true);
                         //                     } else {
                         //                        // Make sure to load all new comments since the page was last loaded by this user
                         //								if ($DisplayNewCommentOnly)
                         $this->Offset = $this->CommentModel->GetOffset($CommentID);
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('NewComments', true);
                         $this->ClassName = 'DiscussionController';
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         //                     }
                         // Make sure to set the user's discussion watch records
                         $CountComments = $this->CommentModel->getCount($DiscussionID);
                         $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments;
                         $Offset = $CountComments - $Limit;
                         $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments);
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
                 // And update the draft count
                 $UserModel = Gdn::userModel();
                 $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0);
                 $this->setJson('MyDrafts', t('My Drafts'));
                 $this->setJson('CountDrafts', $CountDrafts);
             }
         }
     } elseif ($this->Request->isPostBack()) {
         throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401);
     } else {
         // Load form
         if (isset($this->Comment)) {
             $this->Form->setData((array) $this->Comment);
         }
     }
     // Include data for FireEvent
     if (property_exists($this, 'Discussion')) {
         $this->EventArguments['Discussion'] = $this->Discussion;
     }
     if (property_exists($this, 'Comment')) {
         $this->EventArguments['Comment'] = $this->Comment;
     }
     $this->fireEvent('BeforeCommentRender');
     if ($this->deliveryType() == DELIVERY_TYPE_DATA) {
         if ($this->data('Comments') instanceof Gdn_DataSet) {
             $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY);
             if ($Comment) {
                 $Photo = $Comment['InsertPhoto'];
                 if (strpos($Photo, '//') === false) {
                     $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                 }
                 $Comment['InsertPhoto'] = $Photo;
             }
             $this->Data = array('Comment' => $Comment);
         }
         $this->RenderData($this->Data);
     } else {
         require_once $this->fetchViewLocation('helper_functions', 'Discussion');
         // Render default view.
         $this->render();
     }
 }
コード例 #15
0
 /**
  * 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();
 }
コード例 #16
0
 /**
  * Deleting a category.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be deleted.
  */
 public function deleteCategory($CategoryID = false)
 {
     // Check permission
     $this->permission('Garden.Settings.Manage');
     // Set up head
     $this->addJsFile('categories.js');
     $this->title(t('Delete Category'));
     $this->addSideMenu('vanilla/settings/managecategories');
     // Get category data
     $this->Category = $this->CategoryModel->getID($CategoryID);
     if (!$this->Category) {
         $this->Form->addError('The specified category could not be found.');
     } else {
         // Make sure the form knows which item we are deleting.
         $this->Form->addHidden('CategoryID', $CategoryID);
         // Get a list of categories other than this one that can act as a replacement
         $this->OtherCategories = $this->CategoryModel->getWhere(array('CategoryID <>' => $CategoryID, 'AllowDiscussions' => $this->Category->AllowDiscussions, 'CategoryID >' => 0), 'Sort');
         if (!$this->Form->authenticatedPostBack()) {
             $this->Form->setFormValue('DeleteDiscussions', '1');
             // Checked by default
         } else {
             $ReplacementCategoryID = $this->Form->getValue('ReplacementCategoryID');
             $ReplacementCategory = $this->CategoryModel->getID($ReplacementCategoryID);
             // Error if:
             // 1. The category being deleted is the last remaining category that
             // allows discussions.
             if ($this->Category->AllowDiscussions == '1' && $this->OtherCategories->numRows() == 0) {
                 $this->Form->addError('You cannot remove the only remaining category that allows discussions');
             }
             /*
             // 2. The category being deleted allows discussions, and it contains
             // discussions, and there is no replacement category specified.
             if ($this->Form->errorCount() == 0
                && $this->Category->AllowDiscussions == '1'
                && $this->Category->CountDiscussions > 0
                && ($ReplacementCategory == FALSE || $ReplacementCategory->AllowDiscussions != '1'))
                $this->Form->addError('You must select a replacement category in order to remove this category.');
             */
             // 3. The category being deleted does not allow discussions, and it
             // does contain other categories, and there are replacement parent
             // categories available, and one is not selected.
             /*
             if ($this->Category->AllowDiscussions == '0'
                && $this->OtherCategories->numRows() > 0
                && !$ReplacementCategory) {
                if ($this->CategoryModel->getWhere(array('ParentCategoryID' => $CategoryID))->numRows() > 0)
                   $this->Form->addError('You must select a replacement category in order to remove this category.');
             }
             */
             if ($this->Form->errorCount() == 0) {
                 // Go ahead and delete the category
                 try {
                     $this->CategoryModel->delete($this->Category, $this->Form->getValue('ReplacementCategoryID'));
                 } catch (Exception $ex) {
                     $this->Form->addError($ex);
                 }
                 if ($this->Form->errorCount() == 0) {
                     $this->RedirectUrl = url('vanilla/settings/managecategories');
                     $this->informMessage(t('Deleting category...'));
                 }
             }
         }
     }
     // Render default view
     $this->render();
 }
コード例 #17
0
 /**
  * Mobile Themes management screen.
  *
  * @since 2.2.10.3
  * @access public
  * @param string $ThemeName Unique ID.
  * @param string $TransientKey Security token.
  */
 public function mobileThemes($ThemeName = '', $TransientKey = '')
 {
     $IsMobile = true;
     $this->addJsFile('addons.js');
     $this->addJsFile('addons.js');
     $this->setData('Title', t('Mobile Themes'));
     $this->permission('Garden.Settings.Manage');
     $this->setHighlightRoute('dashboard/settings/themes');
     // Get currently enabled theme.
     $EnabledThemeName = Gdn::ThemeManager()->MobileTheme();
     $ThemeInfo = Gdn::themeManager()->getThemeInfo($EnabledThemeName);
     $this->setData('EnabledThemeInfo', $ThemeInfo);
     $this->setData('EnabledThemeFolder', val('Folder', $ThemeInfo));
     $this->setData('EnabledTheme', $ThemeInfo);
     $this->setData('EnabledThemeScreenshotUrl', val('ScreenshotUrl', $ThemeInfo));
     $this->setData('EnabledThemeName', val('Name', $ThemeInfo, val('Index', $ThemeInfo)));
     // Get all themes.
     $Themes = Gdn::themeManager()->availableThemes();
     // Filter themes.
     foreach ($Themes as $ThemeKey => $ThemeData) {
         // Only show mobile themes.
         if (empty($ThemeData['IsMobile'])) {
             unset($Themes[$ThemeKey]);
         }
         // Remove themes that are archived
         if (!empty($ThemeData['Archived'])) {
             unset($Themes[$ThemeKey]);
         }
     }
     uasort($Themes, array('SettingsController', '_NameSort'));
     $this->setData('AvailableThemes', $Themes);
     // Process self-post.
     if ($ThemeName != '' && Gdn::session()->validateTransientKey($TransientKey)) {
         try {
             $ThemeInfo = Gdn::themeManager()->getThemeInfo($ThemeName);
             if ($ThemeInfo === false) {
                 throw new Exception(sprintf(t("Could not find a theme identified by '%s'"), $ThemeName));
             }
             Gdn::session()->setPreference(array('PreviewMobileThemeName' => '', 'PreviewMobileThemeFolder' => ''));
             // Clear out the preview
             Gdn::themeManager()->enableTheme($ThemeName, $IsMobile);
             $this->EventArguments['ThemeName'] = $ThemeName;
             $this->EventArguments['ThemeInfo'] = $ThemeInfo;
             $this->fireEvent('AfterEnableTheme');
         } catch (Exception $Ex) {
             $this->Form->addError($Ex);
         }
         $AsyncRequest = $this->deliveryType() === DELIVERY_TYPE_VIEW ? true : false;
         if ($this->Form->errorCount() == 0) {
             if ($AsyncRequest) {
                 echo 'Success';
                 $this->render('Blank', 'Utility', 'Dashboard');
                 exit;
             } else {
                 redirect('/settings/mobilethemes');
             }
         } else {
             if ($AsyncRequest) {
                 echo $this->Form->errorString();
                 $this->render('Blank', 'Utility', 'Dashboard');
                 exit;
             }
         }
     }
     $this->render();
 }