public function save($FormPostValues, $Settings = false)
{
// Define the primary key in this model's table.
$this->defineSchema();
$RoleID = val('RoleID', $FormPostValues);
$Insert = $RoleID > 0 ? false : true;
if ($Insert) {
// Figure out the next role ID.
$MaxRoleID = $this->SQL->select('r.RoleID', 'MAX')->from('Role r')->get()->value('RoleID', 0);
$RoleID = $MaxRoleID + 1;
$this->addInsertFields($FormPostValues);
$FormPostValues['RoleID'] = strval($RoleID);
// string for validation
} else {
$this->addUpdateFields($FormPostValues);
}
// Validate the form posted values
if ($this->validate($FormPostValues, $Insert)) {
$Fields = $this->Validation->schemaValidationFields();
$Fields = $this->coerceData($Fields);
if ($Insert === false) {
$this->update($Fields, array('RoleID' => $RoleID));
} else {
$this->insert($Fields);
}
// Now update the role permissions
$Role = $this->GetByRoleID($RoleID);
$PermissionModel = Gdn::permissionModel();
if (array_key_exists('Permissions', $FormPostValues)) {
$globalPermissions = $FormPostValues['Permissions'];
$categoryPermissions = val('Category', $globalPermissions, []);
// Massage the global permissions.
unset($globalPermissions['Category']);
$globalPermissions['RoleID'] = $RoleID;
$globalPermissions['JunctionTable'] = null;
$globalPermissions['JunctionColumn'] = null;
$globalPermissions['JunctionID'] = null;
$Permissions = [$globalPermissions];
// Massage the category permissions.
foreach ($categoryPermissions as $perm) {
$row = $perm;
$row['RoleID'] = $RoleID;
$row['JunctionTable'] = 'Category';
$row['JunctionColumn'] = 'PermissionCategoryID';
$row['JunctionID'] = $row['CategoryID'];
unset($row['CategoryID']);
$Permissions[] = $row;
}
} else {
$Permissions = val('Permission', $FormPostValues);
$Permissions = $PermissionModel->pivotPermissions($Permissions, array('RoleID' => $RoleID));
}
$permissionsWhere = ['RoleID' => $RoleID];
if (val('IgnoreCategoryPermissions', $FormPostValues)) {
// Include the default category permissions when ignoring the rest.
$permissionsWhere['JunctionID'] = [null, -1];
}
$PermissionModel->saveAll($Permissions, $permissionsWhere);
if (Gdn::cache()->activeEnabled()) {
// Don't update the user table if we are just using cached permissions.
$this->ClearCache();
Gdn::userModel()->clearPermissions();
} else {
// Remove the cached permissions for all users with this role.
$this->SQL->update('User')->join('UserRole', 'User.UserID = UserRole.UserID')->set('Permissions', '')->where(array('UserRole.RoleID' => $RoleID))->put();
}
} else {
$RoleID = false;
}
return $RoleID;
}