/**
  * @return PermissionModel
  */
 public function GetPermissionModel()
 {
     if ($this->_PermissionModel === null) {
         $this->_PermissionModel = Gdn::PermissionModel();
     }
     return $this->_PermissionModel;
 }
Example #2
0
 public function DefinePermissions($UserID)
 {
     $Data = Gdn::PermissionModel()->CachePermissions($UserID);
     $Permissions = array();
     foreach ($Data as $i => $Row) {
         $JunctionTable = $Row['JunctionTable'];
         $JunctionColumn = $Row['JunctionColumn'];
         $JunctionID = $Row['JunctionID'];
         unset($Row['JunctionColumn'], $Row['JunctionColumn'], $Row['JunctionID'], $Row['RoleID'], $Row['PermissionID']);
         foreach ($Row as $PermissionName => $Value) {
             if ($Value == 0) {
                 continue;
             }
             if (is_numeric($JunctionID) && $JunctionID > 0) {
                 $Permissions[$PermissionName][] = $JunctionID;
             } else {
                 $Permissions[] = $PermissionName;
             }
         }
     }
     // Throw a fatal error if the user has no permissions
     // if (count($Permissions) == 0)
     //    trigger_error(ErrorMessage('The requested user ('.$this->UserID.') has no permissions.', 'Session', 'Start'), E_USER_ERROR);
     // Save the permissions to the user table
     $Permissions = Format::Serialize($Permissions);
     if ($UserID > 0) {
         $this->SQL->Put('User', array('Permissions' => $Permissions), array('UserID' => $UserID));
     }
     return $Permissions;
 }
Example #3
0
 public function Edit($RoleID = FALSE)
 {
     if ($this->Head && $this->Head->Title() == '') {
         $this->Head->Title(Translate('Edit Role'));
     }
     $this->Permission('Garden.Roles.Manage');
     $this->AddSideMenu('garden/role');
     $PermissionModel = Gdn::PermissionModel();
     $this->Role = $this->RoleModel->GetByRoleID($RoleID);
     // $this->EditablePermissions = is_object($this->Role) ? $this->Role->EditablePermissions : '1';
     $this->AddJsFile('/js/library/jquery.gardencheckboxgrid.js');
     // Set the model on the form.
     $this->Form->SetModel($this->RoleModel);
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('RoleID', $RoleID);
     $LimitToSuffix = !$this->Role || $this->Role->CanSession == '1' ? '' : 'View';
     // Load all permissions based on enabled applications and plugins
     //$this->SetData('PermissionData', $PermissionModel->GetPermissions($RoleID, $LimitToSuffix), TRUE);
     // If seeing the form for the first time...
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Get the role data for the requested $RoleID and put it into the form.
         $this->SetData('PermissionData', $PermissionModel->GetPermissionsEdit($RoleID ? $RoleID : 0, $LimitToSuffix), true);
         $this->Form->SetData($this->Role);
     } else {
         // If the form has been posted back...
         // 2. Save the data (validation occurs within):
         if ($RoleID = $this->Form->Save()) {
             $this->StatusMessage = Gdn::Translate('Your changes have been saved.');
             $this->RedirectUrl = Url('garden/role');
             // Reload the permission data.
             $this->SetData('PermissionData', $PermissionModel->GetPermissionsEdit($RoleID, $LimitToSuffix), true);
         }
     }
     $this->Render();
 }
 /**
  * Initialy set SystemUserID as config value Plugins.Incognito.UserID
  * and set up category permissions
  *
  */
 public function Setup()
 {
     // set config value
     if (!is_numeric(C('Plugins.Incognito.UserID'))) {
         $SystemUserID = Gdn::UserModel()->GetSystemUserID();
         SaveToConfig('Plugins.Incognito.UserID', $SystemUserID);
     }
     // add category permissions
     $PermissionModel = Gdn::PermissionModel();
     $PermissionModel->Define(array('Vanilla.Discussions.Incognito' => 0, 'Vanilla.Comments.Incognito' => 0), 'tinyint', 'Category', 'PermissionCategoryID');
 }
 /**
  * Loads default page view.
  *
  * @param string $PageUrlCode ; Unique page URL stub identifier.
  */
 public function Index($PageUrlCode = '')
 {
     $this->Page = $this->PageModel->GetByUrlCode($PageUrlCode);
     // Require the custom view permission if it exists.
     // Otherwise, the page is public by default.
     $ViewPermissionName = 'BasicPages.' . $PageUrlCode . '.View';
     if (array_key_exists($ViewPermissionName, Gdn::PermissionModel()->PermissionColumns())) {
         $this->Permission($ViewPermissionName);
     }
     // If page doesn't exist.
     if ($this->Page == null) {
         throw new Exception(sprintf(T('%s Not Found'), T('Page')), 404);
         return null;
     }
     $this->SetData('Page', $this->Page, false);
     // Add body CSS class.
     $this->CssClass = 'Page-' . $this->Page->UrlCode;
     if (IsMobile()) {
         $this->CssClass .= ' PageMobile';
     }
     // Set the canonical URL to have the proper page link.
     $this->CanonicalUrl(PageModel::PageUrl($this->Page));
     // Add modules
     $this->AddModule('GuestModule');
     $this->AddModule('SignedInModule');
     // Add CSS files
     $this->AddCssFile('page.css');
     $this->AddModule('NewDiscussionModule');
     $this->AddModule('DiscussionFilterModule');
     $this->AddModule('BookmarkedModule');
     $this->AddModule('DiscussionsModule');
     $this->AddModule('RecentActivityModule');
     // Setup head.
     if (!$this->Data('Title')) {
         $Title = C('Garden.HomepageTitle');
         $DefaultControllerDestination = Gdn::Router()->GetDestination('DefaultController');
         if ($Title != '' && strpos($DefaultControllerDestination, 'page/' . $this->Page->UrlCode) !== false) {
             // If the page is set as DefaultController.
             $this->Title($Title, '');
             // Add description meta tag.
             $this->Description(C('Garden.Description', null));
         } else {
             // If the page is NOT the DefaultController.
             $this->Title($this->Page->Name);
             // Add description meta tag.
             $this->Description(SliceParagraph(Gdn_Format::PlainText($this->Page->Body, $this->Page->Format), 160));
         }
     }
     $this->Render();
 }
Example #6
0
 public function Delete($RoleID, $ReplacementRoleID)
 {
     // First update users that will be orphaned
     if (is_numeric($ReplacementRoleID) && $ReplacementRoleID > 0) {
         $this->SQL->Update('UserRole')->Join('UserRole urs', 'UserRole.UserID = urs.UserID')->GroupBy('urs.UserID')->Having('count(urs.RoleID) =', '1', TRUE, FALSE)->Set('UserRole.RoleID', $ReplacementRoleID)->Where(array('UserRole.RoleID' => $RoleID))->Put();
     }
     // Remove permissions for this role.
     $PermissionModel = Gdn::PermissionModel();
     $PermissionModel->Delete($RoleID);
     // Remove the cached permissions for all users with this role.
     $this->SQL->Update('User')->Join('UserRole', 'User.UserID = UserRole.UserID')->Set('Permissions', '')->Set('CacheRoleID', NULL)->Where(array('UserRole.RoleID' => $RoleID))->Put();
     // Remove the role
     $this->SQL->Delete('Role', array('RoleID' => $RoleID));
 }
 /**
  * Editing a category.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be updated.
  */
 public function EditCategory($CategoryID = '')
 {
     // Check permission
     $this->Permission('Garden.Settings.Manage');
     // Set up models
     $RoleModel = new RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     if (!$CategoryID && $this->Form->IsPostBack()) {
         if ($ID = $this->Form->GetFormValue('CategoryID')) {
             $CategoryID = $ID;
         }
     }
     // Get category data
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID;
     // Set up head
     $this->AddJsFile('jquery.alphanumeric.js');
     $this->AddJsFile('categories.js');
     $this->AddJsFile('jquery.gardencheckboxgrid.js');
     $this->Title(T('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     $this->SetData('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     $this->FireEvent('AddEditCategory');
     if ($this->Form->IsPostBack() == FALSE) {
         $this->Form->SetData($this->Category);
         $this->SetupDiscussionTypes($this->Category);
         $this->Form->SetValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID);
     } else {
         $this->SetupDiscussionTypes($this->Category);
         $Upload = new Gdn_Upload();
         $TmpImage = $Upload->ValidateUpload('PhotoUpload', FALSE);
         if ($TmpImage) {
             // Generate the target image name
             $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS);
             $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
             // Save the uploaded image
             $Parts = $Upload->SaveAs($TmpImage, $ImageBaseName);
             $this->Form->SetFormValue('Photo', $Parts['SaveName']);
         }
         $this->Form->SetFormValue('CustomPoints', (bool) $this->Form->GetFormValue('CustomPoints'));
         if ($this->Form->Save()) {
             $Category = CategoryModel::Categories($CategoryID);
             $this->SetData('Category', $Category);
             if ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
                 Redirect('vanilla/settings/managecategories');
             }
         }
     }
     // Get all of the currently selected role/permission combinations for this junction.
     $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions));
     $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
     if ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
         $this->SetData('PermissionData', $Permissions, TRUE);
     }
     // Render default view
     $this->Render();
 }
Example #8
0
 /**
  * Joins the query to a permission junction table and limits the results accordingly.
  *
  * @param mixed $Permission The permission name (or array of names) to use when limiting the query.
  * @param string $ForeignAlias The alias of the table to join to (ie. Category).
  * @param string $ForeignColumn The primary key column name of $JunctionTable (ie. CategoryID).
  * @param string $JunctionTable
  * @param string $JunctionColumn
  */
 public function Permission($Permission, $ForeignAlias, $ForeignColumn, $JunctionTable = '', $JunctionColumn = '')
 {
     $PermissionModel = Gdn::PermissionModel();
     $PermissionModel->SQLPermission($this, $Permission, $ForeignAlias, $ForeignColumn, $JunctionTable, $JunctionColumn);
     return $this;
 }
Example #9
0
 public function EditCategory($CategoryID = '')
 {
     $this->Permission('Vanilla.Categories.Manage');
     $RoleModel = new Gdn_RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->AddJsFile('/js/library/jquery.gardencheckboxgrid.js');
     $this->Title(Translate('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($this->Category);
     } else {
         if ($this->Form->Save()) {
             // Report success
             $this->StatusMessage = Gdn::Translate('The category was saved successfully.');
             $this->RedirectUrl = Url('vanilla/settings/managecategories');
         }
     }
     // Get all of the currently selected role/permission combinations for this junction
     $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category');
     $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
     $this->SetData('PermissionData', $Permissions, TRUE);
     $this->Render();
 }
Example #10
0
if ($SQL->GetWhere('ActivityType', array('Name' => 'DiscussionComment'))->NumRows() == 0) {
    $SQL->Insert('ActivityType', array('AllowComments' => '0', 'Name' => 'DiscussionComment', 'FullHeadline' => '%1$s commented on %4$s %8$s.', 'ProfileHeadline' => '%1$s commented on %4$s %8$s.', 'RouteCode' => 'discussion', 'Notify' => '1', 'Public' => '0'));
}
// People mentioning others in discussion topics
if ($SQL->GetWhere('ActivityType', array('Name' => 'DiscussionMention'))->NumRows() == 0) {
    $SQL->Insert('ActivityType', array('AllowComments' => '0', 'Name' => 'DiscussionMention', 'FullHeadline' => '%1$s mentioned %3$s in a %8$s.', 'ProfileHeadline' => '%1$s mentioned %3$s in a %8$s.', 'RouteCode' => 'discussion', 'Notify' => '1', 'Public' => '0'));
}
// People mentioning others in comments
if ($SQL->GetWhere('ActivityType', array('Name' => 'CommentMention'))->NumRows() == 0) {
    $SQL->Insert('ActivityType', array('AllowComments' => '0', 'Name' => 'CommentMention', 'FullHeadline' => '%1$s mentioned %3$s in a %8$s.', 'ProfileHeadline' => '%1$s mentioned %3$s in a %8$s.', 'RouteCode' => 'comment', 'Notify' => '1', 'Public' => '0'));
}
// People commenting on user's bookmarked discussions
if ($SQL->GetWhere('ActivityType', array('Name' => 'BookmarkComment'))->NumRows() == 0) {
    $SQL->Insert('ActivityType', array('AllowComments' => '0', 'Name' => 'BookmarkComment', 'FullHeadline' => '%1$s commented on your %8$s.', 'ProfileHeadline' => '%1$s commented on your %8$s.', 'RouteCode' => 'bookmarked discussion', 'Notify' => '1', 'Public' => '0'));
}
$PermissionModel = Gdn::PermissionModel();
$PermissionModel->Database = $Database;
$PermissionModel->SQL = $SQL;
// Define some global vanilla permissions.
$PermissionModel->Define(array('Vanilla.Settings.Manage', 'Vanilla.Categories.Manage', 'Vanilla.Spam.Manage'));
// Define some permissions for the Vanilla categories.
$PermissionModel->Define(array('Vanilla.Discussions.View' => 1, 'Vanilla.Discussions.Add' => 1, 'Vanilla.Discussions.Edit' => 0, 'Vanilla.Discussions.Announce' => 0, 'Vanilla.Discussions.Sink' => 0, 'Vanilla.Discussions.Close' => 0, 'Vanilla.Discussions.Delete' => 0, 'Vanilla.Comments.Add' => 1, 'Vanilla.Comments.Edit' => 0, 'Vanilla.Comments.Delete' => 0), 'tinyint', 'Category', 'CategoryID');
if ($Drop) {
    // Get the general category so we can assign permissions to it.
    $GeneralCategoryID = $SQL->GetWhere('Category', array('Name' => 'General'))->Value('CategoryID', 0);
    // Set the initial guest permissions.
    $PermissionModel->Save(array('RoleID' => 2, 'JunctionTable' => 'Category', 'JunctionColumn' => 'CategoryID', 'JunctionID' => $GeneralCategoryID, 'Vanilla.Discussions.View' => 1), TRUE);
    // Set the intial member permissions.
    $PermissionModel->Save(array('RoleID' => 8, 'JunctionTable' => 'Category', 'JunctionColumn' => 'CategoryID', 'JunctionID' => $GeneralCategoryID, 'Vanilla.Discussions.Add' => 1, 'Vanilla.Discussions.View' => 1, 'Vanilla.Comments.Add' => 1), TRUE);
    // Set the initial moderator permissions.
    $PermissionModel->Save(array('RoleID' => 32, 'Vanilla.Categories.Manage' => 1, 'Vanilla.Spam.Manage' => 1), TRUE);
Example #11
0
 /**
  * Joins the query to a permission junction table and limits the results
  * accordingly.
  *
  * @param string $JunctionTable The table to join to (ie. Category)
  * @param string $JunctionColumn The primary key column name of $JunctionTable (ie. CategoryID).
  * @param mixed $Permissions The permission name (or array of names) to use when limiting the query.
  */
 public function Permission($JunctionTableAlias, $JunctionColumn, $Permissions)
 {
     $PermissionModel = Gdn::PermissionModel();
     $PermissionModel->SQLPermission($this, $JunctionTableAlias, $JunctionColumn, $Permissions);
     return $this;
 }
Example #12
0
 public function EnablePlugin($PluginName, $Validation, $Setup = FALSE)
 {
     // 1. Make sure that the plugin's requirements are met
     // Required Plugins
     $AvailablePlugins = $this->AvailablePlugins();
     $RequiredPlugins = ArrayValue('RequiredPlugins', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredPlugins, $this->EnabledPlugins, 'plugin');
     // Required Themes
     $ThemeManager = new Gdn_ThemeManager();
     $EnabledThemes = $ThemeManager->EnabledThemeInfo();
     $RequiredThemes = ArrayValue('RequiredTheme', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredThemes, $EnabledThemes, 'theme');
     // Required Applications
     $ApplicationManager = new Gdn_ApplicationManager();
     $EnabledApplications = $ApplicationManager->EnabledApplications();
     $RequiredApplications = ArrayValue('RequiredApplications', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredApplications, $EnabledApplications, 'application');
     // 2. Include the plugin, instantiate it, and call it's setup method
     $PluginInfo = ArrayValue($PluginName, $AvailablePlugins, FALSE);
     $PluginFolder = ArrayValue('Folder', $PluginInfo, FALSE);
     if ($PluginFolder == '') {
         throw new Exception(Gdn::Translate('The plugin folder was not properly defined.'));
     }
     $PluginClassName = ArrayValue('ClassName', $PluginInfo, FALSE);
     if ($PluginFolder !== FALSE && $PluginClassName !== FALSE && class_exists($PluginClassName) === FALSE) {
         $this->IncludePlugins(array($PluginName => $PluginFolder));
         if (class_exists($PluginClassName)) {
             $Plugin = new $PluginClassName();
             $Plugin->Setup();
         }
     } elseif (class_exists($PluginClassName, FALSE) !== FALSE && $Setup === TRUE) {
         $Plugin = new $PluginClassName();
         $Plugin->Setup();
     }
     // 3. If setup succeeded, register any specified permissions
     $PermissionName = ArrayValue('RegisterPermissions', $PluginInfo, FALSE);
     if ($PermissionName != FALSE) {
         $PermissionModel = Gdn::PermissionModel();
         $PermissionModel->Define($PermissionName);
     }
     if (is_object($Validation) && count($Validation->Results()) > 0) {
         return FALSE;
     }
     // 4. If everything succeeded, add the plugin to the
     // $EnabledPlugins array in conf/plugins.php
     // $EnabledPlugins['PluginClassName'] = 'Plugin Folder Name';
     $Config = Gdn::Factory(Gdn::AliasConfig);
     $Config->Load(PATH_CONF . DS . 'config.php', 'Save');
     $Config->Set('EnabledPlugins' . '.' . $PluginName, $PluginFolder);
     $Config->Save();
     $ApplicationManager = new Gdn_ApplicationManager();
     $Locale = Gdn::Locale();
     $Locale->Set($Locale->Current(), $ApplicationManager->EnabledApplicationFolders(), $this->EnabledPluginFolders(), TRUE);
     return TRUE;
 }
 /**
  * Loads view for creating a new page.
  *
  * @param object $Page ; Not NULL when editing a valid page.
  */
 public function NewPage($Page = null)
 {
     // Check permission
     $this->Permission('Garden.Settings.Manage');
     // Add JavaScript files.
     $this->AddJsFile('jquery-ui.js');
     $this->AddJsFile('jquery.autogrow.js');
     $this->AddJsFile('pagessettings-newpage.js');
     // Prep Model
     $this->Form->SetModel($this->PageModel);
     // Set format data.
     $this->SetData('Formats', $this->GetFormats());
     $this->AddDefinition('DefaultFormat', C('BasicPages.DefaultFormatter', C('Garden.InputFormatter', 'Html')));
     // If form wasn't submitted.
     if ($this->Form->IsPostBack() == false) {
         // Prep form with current data for editing
         if (isset($Page)) {
             $this->SetData('Page', $Page);
             $this->Form->SetData($Page);
             // Send CurrentFormat value to the page to be used for
             // setting the selected value of the formats drop-down.
             $this->AddDefinition('CurrentFormat', $Page->Format);
             $this->Form->AddHidden('UrlCodeIsDefined', '1');
             if (Gdn::Router()->MatchRoute($Page->UrlCode . $this->PageModel->RouteExpressionSuffix)) {
                 $this->Form->SetValue('HidePageFromURL', '1');
                 $this->Form->SetFormValue('HidePageFromURL', '1');
             }
         } else {
             $this->Form->AddHidden('UrlCodeIsDefined', '0');
         }
     } else {
         // Form was submitted.
         $FormValues = $this->Form->FormValues();
         if (isset($Page)) {
             $FormValues['PageID'] = $Page->PageID;
             $this->Form->SetFormValue('PageID', $Page->PageID);
         }
         // Validate form values.
         if ($FormValues['Name'] == '') {
             $this->Form->AddError(T('BasicPages.Settings.NewPage.ErrorName', 'Page title is required.'), 'Name');
         }
         if ($FormValues['Body'] == '') {
             $this->Form->AddError(T('BasicPages.Settings.NewPage.ErrorBody', 'Page body is required.'), 'Body');
         }
         // Format Name
         $FormValues['Name'] = Gdn_Format::Text($FormValues['Name']);
         // Validate UrlCode.
         if ($FormValues['UrlCode'] == '') {
             $FormValues['UrlCode'] = $FormValues['Name'];
         }
         // Format the UrlCode.
         $FormValues['UrlCode'] = Gdn_Format::Url($FormValues['UrlCode']);
         $this->Form->SetFormValue('UrlCode', $FormValues['UrlCode']);
         $SQL = Gdn::Database()->SQL();
         // Make sure that the UrlCode is unique among pages.
         $SQL->Select('p.PageID')->From('Page p')->Where('p.UrlCode', $FormValues['UrlCode']);
         if (isset($Page)) {
             $SQL->Where('p.PageID <>', $Page->PageID);
         }
         $UrlCodeExists = isset($SQL->Get()->FirstRow()->PageID);
         if ($UrlCodeExists) {
             $this->Form->AddError(T('BasicPages.Settings.NewPage.ErrorUrlCode', 'The specified URL code is already in use by another page.'), 'UrlCode');
         }
         // Make sure sort is set if new page.
         if (!$Page) {
             $LastSort = $this->PageModel->GetLastSort();
             $FormValues['Sort'] = $LastSort + 1;
         }
         // Send CurrentFormat value to the page to be used for
         // setting the selected value of the formats drop-down.
         $this->AddDefinition('CurrentFormat', $FormValues['Format']);
         // Explicitly cast these values to an integer data type in case
         // they are equal to '' to be valid with MySQL strict mode, etc.
         $FormValues['SiteMenuLink'] = (int) $FormValues['SiteMenuLink'];
         // If all form values are validated.
         if ($this->Form->ErrorCount() == 0) {
             $PageID = $this->PageModel->Save($FormValues);
             $ValidationResults = $this->PageModel->ValidationResults();
             $this->Form->SetValidationResults($ValidationResults);
             // Create and clean up routes for UrlCode.
             if ($Page->UrlCode != $FormValues['UrlCode']) {
                 if (Gdn::Router()->MatchRoute($Page->UrlCode . $this->PageModel->RouteExpressionSuffix)) {
                     Gdn::Router()->DeleteRoute($Page->UrlCode . $this->PageModel->RouteExpressionSuffix);
                 }
             }
             if ($FormValues['HidePageFromURL'] == '1' && !Gdn::Router()->MatchRoute($FormValues['UrlCode'] . $this->PageModel->RouteExpressionSuffix)) {
                 Gdn::Router()->SetRoute($FormValues['UrlCode'] . $this->PageModel->RouteExpressionSuffix, 'page/' . $FormValues['UrlCode'] . $this->PageModel->RouteTargetSuffix, 'Internal');
             } elseif ($FormValues['HidePageFromURL'] == '0' && Gdn::Router()->MatchRoute($FormValues['UrlCode'] . $this->PageModel->RouteExpressionSuffix)) {
                 Gdn::Router()->DeleteRoute($FormValues['UrlCode'] . $this->PageModel->RouteExpressionSuffix);
             }
             // Set up a custom view permission.
             // The UrlCode must be unique and validated before this code.
             $ViewPermissionName = 'BasicPages.' . $FormValues['UrlCode'] . '.View';
             $PermissionTable = Gdn::Database()->Structure()->Table('Permission');
             $PermissionModel = Gdn::PermissionModel();
             // If a page is being edited, then check if UrlCode was changed by the user
             // and rename the custom view permission column for the page if it exists accordingly,
             // to keep the permission table clean.
             if (isset($Page) && $Page->UrlCode != $FormValues['UrlCode']) {
                 $OldViewPermissionName = 'BasicPages.' . $Page->UrlCode . '.View';
                 $PermissionModel->Undefine($OldViewPermissionName);
                 // The column must be dropped for now, because the RenameColumn method
                 // has a bug, which has been reported.
                 //$PermissionTable->RenameColumn($OldViewPermissionName, $ViewPermissionName);
             }
             $ViewPermissionExists = $PermissionTable->ColumnExists($ViewPermissionName);
             // Check if the user checked the setting to enable the custom view permission.
             if ((bool) $FormValues['ViewPermission']) {
                 // Check if the permission does not exist.
                 if (!$ViewPermissionExists) {
                     // Create the custom view permission.
                     $PermissionModel->Define($ViewPermissionName);
                     // Set initial permission for the Administrator role.
                     $PermissionModel->Save(array('Role' => 'Administrator', $ViewPermissionName => 1));
                 }
             } elseif ($ViewPermissionExists) {
                 // Delete the custom view permission if it exists.
                 $PermissionTable->DropColumn($ViewPermissionName);
             }
             if ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
                 if (strtolower($this->RequestMethod) == 'newpage') {
                     Redirect('pagessettings/allpages#Page_' . $PageID);
                 }
                 $this->InformMessage('<span class="InformSprite Check"></span>' . T('BasicPages.Settings.NewPage.Saved', 'The page has been saved successfully. <br />Go back to ') . Anchor(T('BasicPages.Settings.AllPages', 'all pages'), 'pagessettings/allpages') . T('BasicPages.Settings.NewPage.Saved2', ' or ') . Anchor(T('BasicPages.Settings.NewPage.ViewPage', 'view the page'), PageModel::PageUrl($FormValues['UrlCode'])) . '.', 'Dismissable AutoDismiss HasSprite');
             }
         }
     }
     // Setup head.
     if ($this->Data('Title')) {
         $this->AddSideMenu();
         $this->Title($this->Data('Title'));
     } else {
         $this->AddSideMenu('pagessettings/newpage');
         $this->Title(T('BasicPages.Settings.NewPage', 'New Page'));
     }
     $this->Render();
 }
 /**
  * Load and compile user permissions
  *
  * @param integer $UserID
  * @param boolean $Serialize
  * @return array
  */
 public function DefinePermissions($UserID, $Serialize = TRUE)
 {
     if (Gdn::Cache()->ActiveEnabled()) {
         $PermissionsIncrement = $this->GetPermissionsIncrement();
         $UserPermissionsKey = FormatString(self::USERPERMISSIONS_KEY, array('UserID' => $UserID, 'PermissionsIncrement' => $PermissionsIncrement));
         $CachePermissions = Gdn::Cache()->Get($UserPermissionsKey);
         if ($CachePermissions !== Gdn_Cache::CACHEOP_FAILURE) {
             return $CachePermissions;
         }
     }
     $Data = Gdn::PermissionModel()->CachePermissions($UserID);
     $Permissions = UserModel::CompilePermissions($Data);
     $PermissionsSerialized = NULL;
     if (Gdn::Cache()->ActiveEnabled()) {
         Gdn::Cache()->Store($UserPermissionsKey, $Permissions);
     } else {
         // Save the permissions to the user table
         $PermissionsSerialized = Gdn_Format::Serialize($Permissions);
         if ($UserID > 0) {
             $this->SQL->Put('User', array('Permissions' => $PermissionsSerialized), array('UserID' => $UserID));
         }
     }
     if ($Serialize && is_null($PermissionsSerialized)) {
         $PermissionsSerialized = Gdn_Format::Serialize($Permissions);
     }
     return $Serialize ? $PermissionsSerialized : $Permissions;
 }
Example #15
0
 /**
  * Saves the category.
  *
  * @param array $FormPostValue The values being posted back from the form.
  */
 public function Save($FormPostValues)
 {
     // Define the primary key in this model's table.
     $this->DefineSchema();
     $CategoryID = ArrayValue('CategoryID', $FormPostValues);
     $NewName = ArrayValue('Name', $FormPostValues, '');
     $Insert = $CategoryID > 0 ? FALSE : TRUE;
     if ($Insert) {
         $this->AddInsertFields($FormPostValues);
     }
     $this->AddUpdateFields($FormPostValues);
     // Validate the form posted values
     if ($this->Validate($FormPostValues, $Insert)) {
         $Fields = $this->Validation->SchemaValidationFields();
         $Fields = RemoveKeyFromArray($Fields, 'CategoryID');
         $AllowDiscussions = ArrayValue('AllowDiscussions', $Fields) == '1' ? TRUE : FALSE;
         $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
         if ($Insert === FALSE) {
             $OldCategory = $this->GetID($CategoryID);
             $AllowDiscussions = $OldCategory->AllowDiscussions;
             // Force the allowdiscussions property
             $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
             $this->Update($Fields, array('CategoryID' => $CategoryID));
         } else {
             // Make sure this category gets added to the end of the sort
             $SortData = $this->SQL->Select('Sort')->From('Category')->OrderBy('Sort', 'desc')->Limit(1)->Get()->FirstRow();
             $Fields['Sort'] = $SortData ? $SortData->Sort + 1 : 1;
             $CategoryID = $this->Insert($Fields);
             if ($AllowDiscussions) {
                 // If there are any parent categories, make this a child of the last one
                 $ParentData = $this->SQL->Select('CategoryID')->From('Category')->Where('AllowDiscussions', '0')->OrderBy('Sort', 'desc')->Limit(1)->Get();
                 if ($ParentData->NumRows() > 0) {
                     $this->SQL->Update('Category')->Set('ParentCategoryID', $ParentData->FirstRow()->CategoryID)->Where('CategoryID', $CategoryID)->Put();
                 }
             } else {
                 // If there are any categories without parents, make this one the parent
                 $this->SQL->Update('Category')->Set('ParentCategoryID', $CategoryID)->Where('ParentCategoryID is null')->Where('AllowDiscussions', '1')->Put();
             }
             $this->Organize();
         }
         // Save the permissions
         $PermissionModel = Gdn::PermissionModel();
         $Permissions = $PermissionModel->PivotPermissions($FormPostValues['Permission'], array('JunctionID' => $CategoryID));
         $PermissionModel->SaveAll($Permissions, array('JunctionID' => $CategoryID));
     } else {
         $CategoryID = FALSE;
     }
     return $CategoryID;
 }
Example #16
0
 public function Structure()
 {
     // Pocket class isn't autoloaded on Enable.
     require_once 'library/class.pocket.php';
     $St = Gdn::Structure();
     $St->Table('Pocket')->PrimaryKey('PocketID')->Column('Name', 'varchar(255)')->Column('Page', 'varchar(50)', NULL)->Column('Location', 'varchar(50)')->Column('Sort', 'smallint')->Column('Repeat', 'varchar(25)')->Column('Body', 'text')->Column('Format', 'varchar(20)')->Column('Condition', 'varchar(500)', NULL)->Column('Disabled', 'smallint', '0')->Column('Attributes', 'text', NULL)->Column('MobileOnly', 'tinyint', '0')->Column('MobileNever', 'tinyint', '0')->Column('EmbeddedNever', 'tinyint', '0')->Column('ShowInDashboard', 'tinyint', '0')->Column('Type', array(Pocket::TYPE_DEFAULT, Pocket::TYPE_AD), Pocket::TYPE_DEFAULT)->Set();
     $PermissionModel = Gdn::PermissionModel();
     $PermissionModel->Define(array('Garden.NoAds.Allow' => 0));
 }
 /**
  * Editing a category.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be updated.
  */
 public function EditCategory($CategoryID = '')
 {
     // Check permission
     $this->Permission('Vanilla.Categories.Manage');
     // Set up models
     $RoleModel = new RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     // Get category data
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID;
     // Set up head
     $this->AddJsFile('jquery.alphanumeric.js');
     $this->AddJsFile('categories.js');
     $this->AddJsFile('jquery.gardencheckboxgrid.js');
     $this->Title(T('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     $this->FireEvent('AddEditCategory');
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($this->Category);
     } else {
         if ($this->Form->Save()) {
             Redirect('vanilla/settings/managecategories');
         }
     }
     // 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);
     $this->SetData('PermissionData', $Permissions, TRUE);
     // Render default view
     $this->Render();
 }
Example #18
0
 public function EnablePlugin($PluginName, $Validation, $Setup = FALSE)
 {
     // 1. Make sure that the plugin's requirements are met
     // Required Plugins
     $AvailablePlugins = $this->AvailablePlugins();
     $RequiredPlugins = ArrayValue('RequiredPlugins', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredPlugins, $this->EnabledPlugins, 'plugin');
     // Required Themes
     $ThemeManager = new Gdn_ThemeManager();
     $EnabledThemes = $ThemeManager->EnabledThemeInfo();
     $RequiredThemes = ArrayValue('RequiredTheme', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredThemes, $EnabledThemes, 'theme');
     // Required Applications
     $ApplicationManager = new Gdn_ApplicationManager();
     $EnabledApplications = $ApplicationManager->EnabledApplications();
     $RequiredApplications = ArrayValue('RequiredApplications', ArrayValue($PluginName, $AvailablePlugins, array()), FALSE);
     CheckRequirements($PluginName, $RequiredApplications, $EnabledApplications, 'application');
     // 2. Include the plugin, instantiate it, and call its setup method
     $PluginInfo = ArrayValue($PluginName, $AvailablePlugins, FALSE);
     $PluginFolder = ArrayValue('Folder', $PluginInfo, FALSE);
     if ($PluginFolder == '') {
         throw new Exception(Gdn::Translate('The plugin folder was not properly defined.'));
     }
     $this->_PluginHook($PluginName, self::ACTION_ENABLE, $Setup);
     // 3. If setup succeeded, register any specified permissions
     $PermissionName = ArrayValue('RegisterPermissions', $PluginInfo, FALSE);
     if ($PermissionName != FALSE) {
         $PermissionModel = Gdn::PermissionModel();
         $PermissionModel->Define($PermissionName);
     }
     if (is_object($Validation) && count($Validation->Results()) > 0) {
         return FALSE;
     }
     // 4. If everything succeeded, add the plugin to the
     // $EnabledPlugins array in conf/plugins.php
     // $EnabledPlugins['PluginClassName'] = 'Plugin Folder Name';
     SaveToConfig('EnabledPlugins' . '.' . $PluginName, $PluginFolder);
     $ApplicationManager = new Gdn_ApplicationManager();
     $Locale = Gdn::Locale();
     $Locale->Set($Locale->Current(), $ApplicationManager->EnabledApplicationFolders(), $this->EnabledPluginFolders(), TRUE);
     return TRUE;
 }
 /**
  * Undocumented method.
  *
  * @param string $ApplicationName Undocumented variable.
  * @param string $Validation Undocumented variable.
  * @todo Document RegisterPermissions() method.
  */
 public function RegisterPermissions($ApplicationName, &$Validation)
 {
     $ApplicationInfo = ArrayValue($ApplicationName, $this->AvailableApplications(), array());
     $PermissionName = ArrayValue('RegisterPermissions', $ApplicationInfo, FALSE);
     if ($PermissionName != FALSE) {
         $PermissionModel = Gdn::PermissionModel();
         $PermissionModel->Define($PermissionName);
     }
 }
Example #20
0
 /**
  * Saves the category.
  *
  * @param array $FormPostValue The values being posted back from the form.
  */
 public function Save($FormPostValues)
 {
     // Define the primary key in this model's table.
     $this->DefineSchema();
     $CategoryID = ArrayValue('CategoryID', $FormPostValues);
     $NewName = ArrayValue('Name', $FormPostValues, '');
     $UrlCode = ArrayValue('UrlCode', $FormPostValues, '');
     $Insert = $CategoryID > 0 ? FALSE : TRUE;
     if ($Insert) {
         $this->AddInsertFields($FormPostValues);
     }
     $this->AddUpdateFields($FormPostValues);
     $this->Validation->ApplyRule('UrlCode', 'Required');
     $this->Validation->ApplyRule('UrlCode', 'UrlString', 'Url code can only contain letters, numbers, underscores and dashes.');
     // Make sure that the UrlCode is unique among categories.
     $this->SQL->Select('CategoryID')->From('Category')->Where('UrlCode', $UrlCode);
     if ($CategoryID) {
         $this->SQL->Where('CategoryID <>', $CategoryID);
     }
     if ($this->SQL->Get()->NumRows()) {
         $this->Validation->AddValidationResult('UrlCode', 'The specified url code is already in use by another category.');
     }
     // Validate the form posted values
     if ($this->Validate($FormPostValues, $Insert)) {
         $Fields = $this->Validation->SchemaValidationFields();
         $Fields = RemoveKeyFromArray($Fields, 'CategoryID');
         $AllowDiscussions = ArrayValue('AllowDiscussions', $Fields) == '1' ? TRUE : FALSE;
         $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
         if ($Insert === FALSE) {
             $OldCategory = $this->GetID($CategoryID);
             $AllowDiscussions = $OldCategory->AllowDiscussions;
             // Force the allowdiscussions property
             $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
             $this->Update($Fields, array('CategoryID' => $CategoryID));
         } else {
             // Make sure this category gets added to the end of the sort
             $SortData = $this->SQL->Select('Sort')->From('Category')->OrderBy('Sort', 'desc')->Limit(1)->Get()->FirstRow();
             $Fields['Sort'] = $SortData ? $SortData->Sort + 1 : 1;
             $CategoryID = $this->Insert($Fields);
             if ($AllowDiscussions) {
                 // If there are any parent categories, make this a child of the last one
                 $ParentData = $this->SQL->Select('CategoryID')->From('Category')->Where('AllowDiscussions', '0')->OrderBy('Sort', 'desc')->Limit(1)->Get();
                 if ($ParentData->NumRows() > 0) {
                     $this->SQL->Update('Category')->Set('ParentCategoryID', $ParentData->FirstRow()->CategoryID)->Where('CategoryID', $CategoryID)->Put();
                 }
             } else {
                 // If there are any categories without parents, make this one the parent
                 $this->SQL->Update('Category')->Set('ParentCategoryID', $CategoryID)->Where('ParentCategoryID is null')->Where('AllowDiscussions', '1')->Put();
             }
             $this->Organize();
         }
         // Save the permissions
         if ($AllowDiscussions) {
             $PermissionModel = Gdn::PermissionModel();
             $Permissions = $PermissionModel->PivotPermissions($FormPostValues['Permission'], array('JunctionID' => $CategoryID));
             $PermissionModel->SaveAll($Permissions, array('JunctionID' => $CategoryID));
         }
         // Force the user permissions to refresh.
         $this->SQL->Put('User', array('Permissions' => ''), array('Permissions <>' => ''));
     } else {
         $CategoryID = FALSE;
     }
     return $CategoryID;
 }
 /**
  * Test to see if a plugin throws fatal errors.
  */
 public function TestPlugin($PluginName, &$Validation, $Setup = FALSE)
 {
     // Make sure that the plugin's requirements are met
     // Required Plugins
     $PluginInfo = $this->GetPluginInfo($PluginName);
     $RequiredPlugins = GetValue('RequiredPlugins', $PluginInfo, FALSE);
     CheckRequirements($PluginName, $RequiredPlugins, $this->EnabledPlugins(), 'plugin');
     // Required Themes
     $EnabledThemes = Gdn::ThemeManager()->EnabledThemeInfo();
     $RequiredThemes = ArrayValue('RequiredTheme', $PluginInfo, FALSE);
     CheckRequirements($PluginName, $RequiredThemes, $EnabledThemes, 'theme');
     // Required Applications
     $EnabledApplications = Gdn::ApplicationManager()->EnabledApplications();
     $RequiredApplications = ArrayValue('RequiredApplications', $PluginInfo, FALSE);
     CheckRequirements($PluginName, $RequiredApplications, $EnabledApplications, 'application');
     // Include the plugin, instantiate it, and call its setup method
     $PluginClassName = ArrayValue('ClassName', $PluginInfo, FALSE);
     $PluginFolder = ArrayValue('Folder', $PluginInfo, FALSE);
     if ($PluginFolder == '') {
         throw new Exception(T('The plugin folder was not properly defined.'));
     }
     $this->_PluginHook($PluginName, self::ACTION_ENABLE, $Setup);
     // If setup succeeded, register any specified permissions
     $PermissionName = GetValue('RegisterPermissions', $PluginInfo, FALSE);
     if ($PermissionName != FALSE) {
         $PermissionModel = Gdn::PermissionModel();
         $PermissionModel->Define($PermissionName);
     }
     return TRUE;
 }
Example #22
0
 public function Structure()
 {
     $RegisterPermissions = GetValue('RegisterPermissions', Gdn::PluginManager()->GetPluginInfo('Morf'));
     if ($RegisterPermissions) {
         Gdn::PermissionModel()->Define($RegisterPermissions);
     }
 }
Example #23
0
 /**
  * Saves the category.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $FormPostValue The values being posted back from the form.
  * @return int ID of the saved category.
  */
 public function Save($FormPostValues)
 {
     // Define the primary key in this model's table.
     $this->DefineSchema();
     // Get data from form
     $CategoryID = ArrayValue('CategoryID', $FormPostValues);
     $NewName = ArrayValue('Name', $FormPostValues, '');
     $UrlCode = ArrayValue('UrlCode', $FormPostValues, '');
     $AllowDiscussions = ArrayValue('AllowDiscussions', $FormPostValues, '');
     $CustomPermissions = (bool) GetValue('CustomPermissions', $FormPostValues);
     // Is this a new category?
     $Insert = $CategoryID > 0 ? FALSE : TRUE;
     if ($Insert) {
         $this->AddInsertFields($FormPostValues);
     }
     $this->AddUpdateFields($FormPostValues);
     $this->Validation->ApplyRule('UrlCode', 'Required');
     $this->Validation->ApplyRule('UrlCode', 'UrlStringRelaxed');
     // Make sure that the UrlCode is unique among categories.
     $this->SQL->Select('CategoryID')->From('Category')->Where('UrlCode', $UrlCode);
     if ($CategoryID) {
         $this->SQL->Where('CategoryID <>', $CategoryID);
     }
     if ($this->SQL->Get()->NumRows()) {
         $this->Validation->AddValidationResult('UrlCode', 'The specified url code is already in use by another category.');
     }
     //	Prep and fire event.
     $this->EventArguments['FormPostValues'] =& $FormPostValues;
     $this->EventArguments['CategoryID'] = $CategoryID;
     $this->FireEvent('BeforeSaveCategory');
     // Validate the form posted values
     if ($this->Validate($FormPostValues, $Insert)) {
         $Fields = $this->Validation->SchemaValidationFields();
         $Fields = RemoveKeyFromArray($Fields, 'CategoryID');
         $AllowDiscussions = ArrayValue('AllowDiscussions', $Fields) == '1' ? TRUE : FALSE;
         $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
         if ($Insert === FALSE) {
             $OldCategory = $this->GetID($CategoryID, DATASET_TYPE_ARRAY);
             $AllowDiscussions = $OldCategory['AllowDiscussions'];
             // Force the allowdiscussions property
             $Fields['AllowDiscussions'] = $AllowDiscussions ? '1' : '0';
             $this->Update($Fields, array('CategoryID' => $CategoryID));
             // Check for a change in the parent category.
             if (isset($Fields['ParentCategoryID']) && $OldCategory['ParentCategoryID'] != $Fields['ParentCategoryID']) {
                 $this->RebuildTree();
             } else {
                 $this->SetCache($CategoryID, $Fields);
             }
         } else {
             $CategoryID = $this->Insert($Fields);
             if ($CustomPermissions && $CategoryID) {
                 $this->SQL->Put('Category', array('PermissionCategoryID' => $CategoryID), array('CategoryID' => $CategoryID));
             }
             $this->RebuildTree();
             // Safeguard to make sure that treeleft and treeright cols are added
         }
         // Save the permissions
         if ($AllowDiscussions && $CategoryID) {
             // Check to see if this category uses custom permissions.
             if ($CustomPermissions) {
                 $PermissionModel = Gdn::PermissionModel();
                 $Permissions = $PermissionModel->PivotPermissions(GetValue('Permission', $FormPostValues, array()), array('JunctionID' => $CategoryID));
                 $PermissionModel->SaveAll($Permissions, array('JunctionID' => $CategoryID, 'JunctionTable' => 'Category'));
                 if (!$Insert) {
                     // Figure out my last permission and tree info.
                     $Data = $this->SQL->Select('PermissionCategoryID, TreeLeft, TreeRight')->From('Category')->Where('CategoryID', $CategoryID)->Get()->FirstRow(DATASET_TYPE_ARRAY);
                     // Update this category's permission.
                     $this->SQL->Put('Category', array('PermissionCategoryID' => $CategoryID), array('CategoryID' => $CategoryID));
                     // Update all of my children that shared my last category permission.
                     $this->SQL->Put('Category', array('PermissionCategoryID' => $CategoryID), array('TreeLeft >' => $Data['TreeLeft'], 'TreeRight <' => $Data['TreeRight'], 'PermissionCategoryID' => $Data['PermissionCategoryID']));
                     self::ClearCache();
                 }
             } elseif (!$Insert) {
                 // Figure out my parent's permission.
                 $NewPermissionID = $this->SQL->Select('p.PermissionCategoryID')->From('Category c')->Join('Category p', 'c.ParentCategoryID = p.CategoryID')->Where('c.CategoryID', $CategoryID)->Get()->Value('PermissionCategoryID', 0);
                 if ($NewPermissionID != $CategoryID) {
                     // Update all of my children that shared my last permission.
                     $this->SQL->Put('Category', array('PermissionCategoryID' => $NewPermissionID), array('PermissionCategoryID' => $CategoryID));
                     self::ClearCache();
                 }
                 // Delete my custom permissions.
                 $this->SQL->Delete('Permission', array('JunctionTable' => 'Category', 'JunctionColumn' => 'PermissionCategoryID', 'JunctionID' => $CategoryID));
             }
         }
         // Force the user permissions to refresh.
         Gdn::UserModel()->ClearPermissions();
         // $this->RebuildTree();
     } else {
         $CategoryID = FALSE;
     }
     return $CategoryID;
 }
 public function DefinePermissions($UserID, $Serialize = TRUE)
 {
     if (Gdn::Cache()->ActiveEnabled()) {
         $PermissionsIncrement = $this->GetPermissionsIncrement();
         $UserPermissionsKey = FormatString(self::USERPERMISSIONS_KEY, array('UserID' => $UserID, 'PermissionsIncrement' => $PermissionsIncrement));
         $CachePermissions = Gdn::Cache()->Get($UserPermissionsKey);
         if ($CachePermissions !== Gdn_Cache::CACHEOP_FAILURE) {
             return $CachePermissions;
         }
     }
     $Data = Gdn::PermissionModel()->CachePermissions($UserID);
     $Permissions = array();
     foreach ($Data as $i => $Row) {
         $JunctionTable = $Row['JunctionTable'];
         $JunctionColumn = $Row['JunctionColumn'];
         $JunctionID = $Row['JunctionID'];
         unset($Row['JunctionColumn'], $Row['JunctionColumn'], $Row['JunctionID'], $Row['RoleID'], $Row['PermissionID']);
         foreach ($Row as $PermissionName => $Value) {
             if ($Value == 0) {
                 continue;
             }
             if (is_numeric($JunctionID) && $JunctionID !== NULL) {
                 if (!array_key_exists($PermissionName, $Permissions)) {
                     $Permissions[$PermissionName] = array();
                 }
                 if (!is_array($Permissions[$PermissionName])) {
                     $Permissions[$PermissionName] = array();
                 }
                 $Permissions[$PermissionName][] = $JunctionID;
             } else {
                 $Permissions[] = $PermissionName;
             }
         }
     }
     // Throw a fatal error if the user has no permissions
     // if (count($Permissions) == 0)
     //    trigger_error(ErrorMessage('The requested user ('.$this->UserID.') has no permissions.', 'Session', 'Start'), E_USER_ERROR);
     $PermissionsSerialized = NULL;
     if (Gdn::Cache()->ActiveEnabled()) {
         Gdn::Cache()->Store($UserPermissionsKey, $Permissions);
     } else {
         // Save the permissions to the user table
         $PermissionsSerialized = Gdn_Format::Serialize($Permissions);
         if ($UserID > 0) {
             $this->SQL->Put('User', array('Permissions' => $PermissionsSerialized), array('UserID' => $UserID));
         }
     }
     if ($Serialize && is_null($PermissionsSerialized)) {
         $PermissionsSerialized = Gdn_Format::Serialize($Permissions);
     }
     return $Serialize ? $PermissionsSerialized : $Permissions;
 }
 /**
  * Run when a plugin is disabled via dashboard
  * Right now it only removes permissions on 2.1b1+
  */
 public function OnDisable()
 {
     // Deregister permissions (only in 2.1+)
     if (version_compare(APPLICATION_VERSION, '2.1b1', '>=')) {
         $PermissionModel = Gdn::PermissionModel();
         $PermissionModel->Undefine(array('Plugins.DiscussionPolls.Add', 'Plugins.DiscussionPolls.View', 'Plugins.DiscussionPolls.Vote', 'Plugins.DiscussionPolls.Manage'));
     }
 }
Example #26
0
 /**
  * Settings screen for role and restriction choice.
  *
  * @param object $sender SettingsController.
  * @return void.
  * @package ReadOnly
  * @since 0.1
  */
 public function settingsController_readOnly_create($sender)
 {
     // Define general settings properties.
     $sender->permission('Garden.Settings.Manage');
     $sender->addSideMenu('/dashboard/settings/plugins');
     $sender->setData('Title', t('ReadOnly Settings'));
     $sender->setData('Description', t('ReadOnly Settings Description', 'Choose which roles and actions should be restricted.<br/>You
         should inform your users about the read only state by ' . anchor('adding a message', '/dashboard/message/add') . ' to the forum.'));
     // Consolidate/prepare permissions.
     $permissionModel = Gdn::PermissionModel();
     $perms = $permissionModel->PermissionColumns();
     unset($perms['PermissionID']);
     $permissions = array();
     foreach ($perms as $key => $value) {
         $action = substr($key, strrpos($key, '.') + 1);
         $permissions[$action] .= $key . ', ';
     }
     $permissionItems = array();
     foreach ($permissions as $key => $value) {
         $text = $key . '<span>' . trim($value, ', ') . '</span>';
         $permissionItems[$text] = $key;
     }
     // Consolidate/prepare roles.
     $roleModel = new RoleModel();
     $roles = $roleModel->roles();
     $roleItems = array();
     foreach ($roles as $role) {
         $roleItems[$role['Name']] = $role['RoleID'];
     }
     // Build form info.
     $configurationModule = new configurationModule($sender);
     $configurationModule->initialize(array('ReadOnly.Restrictions' => array('Control' => 'CheckBoxList', 'Description' => t('ReadOnly Settings Restrictions', 'Choose the actions that should be restricted. Below each action is a list of all the current permissions with that action."Add" and "Edit" is recommended.'), 'Items' => $permissionItems, 'LabelCode' => 'Restrictions'), 'ReadOnly.Roles' => array('Control' => 'CheckBoxList', 'Description' => t('Choose the roles that should <strong>not</strong> be restricted (Admin users will always have all permissions).'), 'Items' => $roleItems, 'LabelCode' => 'Roles'), 'ReadOnly.Message' => array('Control' => 'TextBox', 'LabelCode' => 'Message Text', 'Description' => 'It is a good idea to ' . anchor('inform your users', '/dashboard/message') . ' about the restrictions so that they now what\'s going on...', 'Options' => array('MultiLine' => true)), 'ReadOnly.ShowAlert' => array('Control' => 'Checkbox', 'Description' => 'You can choose show or deactivate the message, however.', 'LabelCode' => 'Show Message')));
     // Handle alert message.
     if ($sender->Request->isPostBack()) {
         $post = $sender->Request->getRequestArguments('post');
         $messageModel = new MessageModel();
         $messageID = c('ReadOnly.MessageID');
         $message = $messageModel->getID($messageID);
         if (!$post['ReadOnly-dot-Message']) {
             // Delete message when no text is given.
             if ($message) {
                 $messageModel->delete(array('MessageID' => $messageID));
                 removeFromConfig('ReadOnly.MessageID');
             }
         } else {
             // Check if message already exists.
             if ($message) {
                 // Set MessageID so that existing message gets updated
                 $formPostValues['MessageID'] = $messageID;
             }
             $formPostValues['Location'] = '[Base]';
             $formPostValues['AssetTarget'] = 'Content';
             $formPostValues['Content'] = $post['ReadOnly-dot-Message'];
             $formPostValues['CssClass'] = 'AlertMessage';
             $formPostValues['Enabled'] = $post['ReadOnly-dot-ShowAlert'];
             $formPostValues['AllowDismiss'] = false;
             $formPostValues['TransientKey'] = Gdn::session()->transientKey();
             saveToConfig('ReadOnly.MessageID', $messageModel->save($formPostValues));
         }
     }
     // Show form.
     $configurationModule->renderAll();
 }