
/***********************************************
* Generated at 11/6/2008 2:57
***********************************************/


/***********************************************
* Patch: cs_Schema_Patch_2.1.00
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Update Apple release databases to Johnny... Use the 01 patch as a template this
--one has special prerequisite handling

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=2 and Minor=0 and Patch<58

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = 57)
	BEGIN
--## Schema Patch ##

--All we are doing is updating the schema revision

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.01
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.01'

-- Add index date field to post table to support re-indexing posts after a
-- specified period of time

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_executesql N'ALTER TABLE [dbo].[cs_Posts] ADD [IndexDate] [smalldatetime]' 

--note the following line needs to be in sp_executesql because the referenced column does not exist when SQL initally
--evaluates the SQL patch and will cause an error IndexDate does not exist...

--note - due to the potential that this update will take a very long time so we will allow the column to be null
--and account for it in the corrisponding job
--exec sp_executesql N'UPDATE [dbo].[cs_Posts] SET [IndexDate] = [PostDate] WHERE IsIndexed = 1'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.02
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_executesql N'ALTER TABLE dbo.cs_Sections ADD DefaultLanguage nvarchar(32) NULL' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.03
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
CREATE TABLE [dbo].[cs_PageViews](
	[URL] [nvarchar](512) NOT NULL,
	[VisitCount] [int] NOT NULL,
	[DateTimeStamp] [datetime] NOT NULL
) ON [PRIMARY]

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.04
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_executesql N'ALTER TABLE dbo.cs_statistics_Site ADD ViewCount int NOT NULL DEFAULT 0'
exec sp_executesql N'ALTER TABLE dbo.cs_statistics_Site ADD ReplyCount int NOT NULL DEFAULT 0' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.05
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

--This sql patch updates are no longer required, the API has been updated to accept nulls
--The patch takes too long on large databases
	
--update cs_Posts Set UserTime = PostDate where UserTime is null
--ALTER TABLE cs_posts ALTER COLUMN UserTime DateTime NOT NULL 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.06
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_MailingLists]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[csm_MailingLists] (
		[SectionID] [int] NOT NULL ,
		[EmailAddress] [nvarchar] (100) NOT NULL ,
		[IsMailingList] [bit] NOT NULL ,
		[SettingsID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[csm_MailingLists] WITH NOCHECK ADD 
		CONSTRAINT [PK_le_MailingList] PRIMARY KEY  CLUSTERED 
		(
			[SectionID],
			[SettingsID]
		)  ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_EmailIds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[csm_EmailIds] (
		[EmailID] [bigint] NOT NULL ,
		[UserID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[csm_EmailIds] WITH NOCHECK ADD 
		CONSTRAINT [PK_csm_EmailIds] PRIMARY KEY  CLUSTERED 
		(
			[EmailID]
		)  ON [PRIMARY]'
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.07
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogPost_cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] DROP CONSTRAINT FK_cs_RollerBlogPost_cs_RollerBlogFeeds'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogFeeds_cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] DROP CONSTRAINT FK_cs_RollerBlogFeeds_cs_RollerBlogUrls'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogFeeds]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogPost]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogUrls]'


exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogFeeds] (
	[SectionID] [int] NOT NULL ,
	[SettingsID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[IntervalMinutes] [int] NOT NULL ,
	[Title] [nvarchar] (256) NULL ,
	[PostFullArticle] [bit] NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
) ON [PRIMARY]'


exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogPost] (
	[SectionID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[PostID] [int] NOT NULL ,
	[PermaLink] [nvarchar] (512) NOT NULL ,
	[CommentUrl] [nvarchar] (512)  NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [DF_cs_RollerBlogFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RollerBlogFeeds_IntervalMinutes] DEFAULT (5) FOR [IntervalMinutes],
	CONSTRAINT [DF_cs_RollerBlogFeeds_PostFullArticle] DEFAULT (0) FOR [PostFullArticle],
	CONSTRAINT [DF_cs_RollerBlogFeeds_ExerptSize] DEFAULT (256) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RollerBlogFeeds_State] DEFAULT (0) FOR [State],
	CONSTRAINT [PK_cs_RollerBlogFeeds] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [PK_cs_RollerBlogPost] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlID],
		[PostID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogUrls] ADD 
	CONSTRAINT [PK_cs_RollerBlogUrls] PRIMARY KEY  CLUSTERED 
	(
		[UrlID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_RollerBlogUrls] FOREIGN KEY 
	(
		[UrlID]
	) REFERENCES [dbo].[cs_RollerBlogUrls] (
		[UrlID]
	),
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_Sections] FOREIGN KEY 
	(
		[SettingsID],
		[SectionID]
	) REFERENCES [dbo].[cs_Sections] (
		[SettingsID],
		[SectionID]
	)'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [FK_cs_RollerBlogPost_cs_RollerBlogFeeds] FOREIGN KEY 
	(
		[SectionID],
		[UrlID]
	) REFERENCES [dbo].[cs_RollerBlogFeeds] (
		[SectionID],
		[UrlID]
	)'



--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.08
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

alter table cs_PostMetadata alter column MetaKey nvarchar(100) not null
alter table cs_PostMetadata alter column MetaType nvarchar(100) not null
alter table cs_PostMetadata alter column MetaValue nvarchar(100) not null

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.09
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserAvatar]
Add [Length] [int] NULL,
[ContentType] [nvarchar] (64) NULL,
[Content] [image] NULL,
[DateLastUpdated] [datetime] NOT NULL CONSTRAINT [DF_cs_UserAvatar_DateLastUpdated] DEFAULT (getdate())'

exec sp_executesql N'UPDATE [dbo].[cs_UserAvatar] SET Length = i.Length, ContentType = i.ContentType, [Content] = i.[Content], [DateLastUpdated] = i.[DateLastUpdated] 
	FROM [dbo].[cs_UserAvatar] a JOIN [dbo].[cs_Images] i on i.ImageID = a.ImageID'
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_UserAvatar_cs_Images]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_UserAvatar] DROP CONSTRAINT [FK_cs_UserAvatar_cs_Images]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserAvatar] DROP COLUMN [ImageID]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Images]') and OBJECTPROPERTY(id, N'IsTable') = 1)
exec sp_executesql N'DROP TABLE [dbo].[cs_Images]'

--SQL 2000 cant handle altering an image col
--exec sp_executesql N'ALTER TABLE [dbo].[cs_UserAvatar]
--ALTER COLUMN [Content] [image] NOT NULL'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.10
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_executesql N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsBlogAggregated bit NOT NULL DEFAULT 1'
exec sp_executesql N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsBlogRollAggregated bit NOT NULL DEFAULT 1'
exec sp_executesql N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsRollerBlogAggregated bit NOT NULL DEFAULT 1'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.11
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'ALTER TABLE cs_Posts ADD
	PostMedia int NOT NULL CONSTRAINT DF_cs_Posts_PostMedia DEFAULT 0'

-- Video
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 2, PostType = 1 WHERE PostType = 4'

-- Polls (within forums)
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

-- Image
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 1, PostType = 1 WHERE PostType = 3'

-- Set PostMedia to Image for all Photo Gallery posts
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 1 WHERE PostMedia=0
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 2))'

-- Reset all Forum PostTypes to Post (1)
exec sp_executesql N'UPDATE cs_Posts SET ApplicationPostType = 1 WHERE ApplicationPostType <> 1
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.12
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

update cs_Posts Set PostName = Replace(PostName,'_',' ') where PostName is not null

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.13
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_UserInvitation] (
	[InvitationKey]  uniqueidentifier ROWGUIDCOL  NOT NULL ,
	[UserID] [int] NOT NULL ,
	[Email] [nvarchar] (255) NOT NULL ,
	[DateInvited] [datetime] NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserInvitation] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_UserInvitation] PRIMARY KEY  CLUSTERED 
	(
		[InvitationKey]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserInvitation] ADD 
	CONSTRAINT [DF_cs_UserInvitation_InvitationKey] DEFAULT (newid()) FOR [InvitationKey],
	CONSTRAINT [DF_cs_UserInvitation_DateInvited] DEFAULT (getdate()) FOR [DateInvited]'

exec sp_executesql N'ALTER TABLE dbo.cs_UserInvitation ADD
	PropertyNames ntext NULL,
	PropertyValues ntext NULL'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.14
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_Sections_MailingLists_Delete]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
begin
	exec sp_executesql N'CREATE TRIGGER csm_Sections_MailingLists_Delete ON cs_Sections
	FOR DELETE
	AS
	BEGIN
		DELETE FROM csm_MailingLists WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE FROM csm_EmailIds WHERE SectionID IN (SELECT SectionID FROM DELETED)
	END'
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.15
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrl]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrl] (
	[CtrlID] [int] NOT NULL ,
	[Title] [varchar] (256) NOT NULL ,
	[Name] [varchar] (256) NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[PostCount] [int] NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ADD 
	CONSTRAINT [DF_RssCtrl_ExerptSize] DEFAULT (125) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RssCtrl_PostCount] DEFAULT (3) FOR [PostCount]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrl] ON [dbo].[cs_RssCtrl]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlFeeds] (
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[Title] [nvarchar] (256) NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD 
	CONSTRAINT [DF_cs_RssCtrlFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RssCtrlFeeds_State] DEFAULT (0) FOR [State]'

	exec sp_executesql N'CREATE  INDEX [IX_cs_RssCtrlFeeds] ON [dbo].[cs_RssCtrlFeeds]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlPost] (
	[PostID] [int] IDENTITY (1, 1) NOT NULL ,
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Author] [nvarchar] (256) NOT NULL ,
	[Subject] [nvarchar] (256) NULL ,
	[Body] [ntext] NULL ,
	[PostDate] [datetime] NOT NULL ,
	[PermaLink] [nvarchar] (312) NOT NULL ,
	[CommentUrl] [nvarchar] (512) NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost] ON [dbo].[cs_RssCtrlPost]([PostID]) ON [PRIMARY]'

	exec sp_executesql N'CREATE  INDEX [IX_cs_RssCtrlPost_1] ON [dbo].[cs_RssCtrlPost]([CtrlID]) ON [PRIMARY]'

	-- Index is too big for SQL2000 
	--exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost_2] ON [dbo].[cs_RssCtrlPost]([PermaLink]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlUrls] ON [dbo].[cs_RssCtrlUrls]([UrlID]) ON [PRIMARY]'
end
***********************************************************************************************************************************/

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_2.1.16
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

DECLARE @TABLE_SCHEMA NVARCHAR(50),@TABLE_NAME NVARCHAR(50),@COLUMN_NAME NVARCHAR(50),@CONSTRAINT_NAME NVARCHAR(50)

SET @TABLE_SCHEMA = 'dbo'
SET @TABLE_NAME = 'cs_RollerBlogFeeds'
SET @COLUMN_NAME = 'IsRollerBlogAggregated'

SELECT
	@CONSTRAINT_NAME = OBJECT_NAME(c1.cdefault)
FROM syscolumns AS c1 
		JOIN syscomments AS c2 
			ON c1.cdefault = c2.id 
WHERE 	OBJECT_NAME(c1.id) = @TABLE_NAME AND c1.name = @COLUMN_NAME 

/* the following does the same thing but is SQL 2005 only
select 
	@CONSTRAINT_NAME = d.name
  from sys.default_constraints as d
  join sys.objects as o
    on o.object_id = d.parent_object_id
  join sys.columns as c
    on c.object_id = o.object_id and c.column_id = d.parent_column_id
  join sys.schemas as s
    on s.schema_id = o.schema_id
WHERE s.name = @TABLE_SCHEMA and o.name = @TABLE_NAME and c.name = @COLUMN_NAME
*/

DECLARE @STRSQL NVARCHAR(4000);
if @CONSTRAINT_NAME is not null
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP CONSTRAINT ['+@CONSTRAINT_NAME+']'
	exec sp_executesql @STRSQL
END
if exists (select * from dbo.sysobjects where id = object_id(N'[' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP COLUMN ['+@COLUMN_NAME+']'
	exec sp_executesql @STRSQL
END
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.17
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- patch sql removed, but left in so versions won't cause errors

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.18
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.18'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 18;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************

IF  EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_RssCtrlPost]') AND name = N'IX_cs_RssCtrlPost_2')
	exec sp_executesql N'DROP INDEX [dbo].[cs_RssCtrlPost].[IX_cs_RssCtrlPost_2]'
	
*****************************************  This has been moved to an addon ********************************************/
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.19
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.19'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 19;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- Polls (within forums)
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.20
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.20'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 20;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PK_cs_PostReindexQueue]') and OBJECTPROPERTY(id, N'IsPrimaryKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_PostReindexQueue] DROP CONSTRAINT [PK_cs_PostReindexQueue]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostReindexQueue]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'DROP TABLE [dbo].[cs_PostReindexQueue]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.21
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.21'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 21;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserProfile] ADD AllowSiteToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSiteToContact DEFAULT 0'
exec sp_executesql N'ALTER TABLE [dbo].[cs_UserProfile] ADD AllowSitePartnersToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSitePartnersToContact DEFAULT 0'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_2.1.22
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.22'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 22;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RollerBlogFeeds] Set SiteUrl = '''''

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) NOT NULL'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.23
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.23'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 23;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'Update cs_Posts set PostConfiguration = 55 from cs_Posts join cs_RollerBlogPost on cs_Posts.PostID  = cs_RollerBlogPost.PostID where PostConfiguration & 16 <> 16'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.24
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.24'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 24;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrlFeeds] Set SiteUrl = '''''

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) NOT NULL'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ADD [SettingsID] [int] NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrl] Set [SettingsID] = (select min(SettingsID) from cs_SiteSettings)'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ALTER COLUMN [SettingsID] [int] NOT NULL'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [IntervalMinutes] [int] NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrlFeeds] Set [IntervalMinutes] = 5'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [IntervalMinutes] [int] NOT NULL'

*****************************************  This has been moved to an addon ********************************************/
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.25
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.25'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 25;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'Alter Table cs_Posts Add  SpamScore [int] Not Null Constraint cs_Posts_DefaultSpamScore default(0)'

exec sp_executesql N'Alter Table cs_Posts Add  PostStatus [int] Not Null Constraint cs_Posts_DefaultPostStatus default(0)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.26
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.26'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 26;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'update cs_Posts set PostMedia = 2 where SectionID in (select SectionID from cs_Sections where ApplicationType = 1) and ApplicationPostType in (1, 2) and PropertyNames like ''%VideoUrl%'''

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.27
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.27'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 27;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


UPDATE	PP
SET		PP.AllowMask = CONVERT(bigint, PP.AllowMask) | CONVERT(bigint, 0x0000000000000100)
FROM	cs_ProductPermissions PP INNER JOIN aspnet_Roles R ON PP.RoleID = R.RoleId
WHERE	ApplicationType = 0 AND R.LoweredRoleName IN ('moderator', 'forumsadministrator', 'systemadministrator')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.28
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.28'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 28;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'Alter Table cs_posts_deleted_archive Add PropertyNames [ntext] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add PropertyValues [ntext] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add SpamScore [int] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add PostStatus [int] NULL'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.29
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.29'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 29;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql
	N'CREATE TABLE dbo.Tmp_cs_PageViews
	(
	URL nvarchar(440) NOT NULL,
	VisitCount int NOT NULL,
	DateTimeStamp datetime NOT NULL
	)  ON [PRIMARY]'

IF EXISTS(SELECT * FROM dbo.cs_PageViews)
	 EXECUTE sp_executesql
		N'INSERT INTO dbo.Tmp_cs_PageViews (URL, VisitCount, DateTimeStamp)
		SELECT CONVERT(nvarchar(440), URL), VisitCount, DateTimeStamp FROM dbo.cs_PageViews (HOLDLOCK TABLOCKX)'

EXECUTE sp_executesql
	N'DROP TABLE dbo.cs_PageViews'

EXECUTE sp_executesql
	N'EXECUTE sp_rename N''dbo.Tmp_cs_PageViews'', N''cs_PageViews'', ''OBJECT'''

EXECUTE sp_executesql
	N'CREATE CLUSTERED INDEX IX_cs_PageViews ON dbo.cs_PageViews
	(
	URL,
	DateTimeStamp
	) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.00
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'DROP TABLE dbo.cs_EmailQueue'

exec sp_executesql N'CREATE TABLE [dbo].[mg_EmailQueue](
	[EmailID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_cs_EmailQueue_EmailID]  DEFAULT (newid()),
	[NextTryTime] [datetime] NOT NULL CONSTRAINT [DF_cs_EmailQueue_createdTimestamp]  DEFAULT (''1/1/1979 12:00:00''),
	[NumberOfTries] [int] NOT NULL CONSTRAINT [DF_cs_EmailQueue_NumberOfTries]  DEFAULT (0),
	[SettingsID] [int] NULL,
	[EmailXml] [ntext] NOT NULL DEFAULT ('''')
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.01
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.01'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

Insert [cs_EventDescriptions] Values(320,'Blog File Storage Upload')
Insert [cs_EventDescriptions] Values(321,'Blog File Storage Delete')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.02
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[csm_MessageIDs](
	[MessageID] [nvarchar](100) NOT NULL,
	[SettingsID] [int] NOT NULL,
	[PostID] [int] NOT NULL
) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.03
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- Patch removed due to issue with upgrading existing versions that have messages still in the email queue

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.04
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_ThemeConfigurationData] (
		[ThemeName] [nvarchar] (255) NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL ,
		[PropertyNames] [ntext] NULL ,
		[PropertyValues] [ntext] NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_ThemeConfigurationData] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_ThemeConfigurationData] PRIMARY KEY  CLUSTERED 
	(
		[ThemeName],
		[SettingsID],
		[SectionID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TRIGGER cs_Section_Delete ON cs_Sections 
	FOR DELETE 
	AS
	BEGIN
		DELETE cs_SectionPermissions WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE cs_Threads WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE cs_ThemeConfigurationData WHERE SectionID IN (SELECT SectionID FROM DELETED)
	END'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.05
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_SectionSubscriptions](
	[SubscriptionID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_SubscriptionID]  DEFAULT (newid()),
	[SectionID] [int] NOT NULL,
	[Email] [nvarchar](256),
	[SubscriptionType] [int] NOT NULL,
	[UserID] [int] NULL CONSTRAINT [DF_cs_SectionSubscriptions_UserID]  DEFAULT ((-1)),
	[SettingsID] [int] NULL CONSTRAINT [DF_cs_SectionSubscriptions_SettingsID]  DEFAULT ((-1)),
	[DateSubscribed] [datetime] NOT NULL,
	[DateUnsubscribed] [datetime] NULL,
	[SubscriptionFrequency] [int] NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_SubscriptionFrequency]  DEFAULT ((1)),
	[IsConfirmed] [bit] NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_IsConfirmed]  DEFAULT ((0)),
		 CONSTRAINT [PK_cs_SectionSubscriptions] PRIMARY KEY CLUSTERED 
		(
			[SubscriptionID] ASC
		) ON [PRIMARY]
		) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.06
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_ThemeConfigurationData_TEMP] (
		[ThemeConfigurationDataTempID] [uniqueidentifier] NOT NULL ,
		[ThemeName] [nvarchar] (255) NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL ,
		[PropertyNames] [ntext]  NULL ,
		[PropertyValues] [ntext] NULL ,
		[LastModified] [datetime] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'


exec sp_executesql N'ALTER TABLE [dbo].[cs_ThemeConfigurationData_TEMP] ADD 
	CONSTRAINT [DF_cs_ThemeConfigurationData_TEMP_LastModified] DEFAULT (getdate()) FOR [LastModified],
	CONSTRAINT [PK_cs_ThemeConfigurationData_TEMP] PRIMARY KEY  CLUSTERED 
	(
		[ThemeConfigurationDataTempID],
		[ThemeName],
		[SettingsID],
		[SectionID]
	)  ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.07
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- BEGIN cs_Users
EXECUTE sp_executesql
N'ALTER TABLE [dbo].[cs_Users] ADD
	[UserName] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Users_UserName] DEFAULT '''',
	[Email] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Users_Email] DEFAULT '''',
	[IsApproved] [bit] NULL, 
	[IsAnonymous] [bit] NOT NULL CONSTRAINT [DF_cs_Users_IsAnonymous] DEFAULT 0,
	[CreateDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Users_CreateDate] DEFAULT (getdate())'

EXECUTE sp_executesql
N'UPDATE	CU
SET
	CU.[UserName] = AU.[UserName],
	CU.[Email] = ISNULL(AM.[Email], ''''),
	CU.[IsApproved] = AM.[IsApproved],
	CU.[IsAnonymous] = AU.[IsAnonymous],
	CU.[CreateDate] = AM.[CreateDate]
FROM
	[dbo].[cs_Users] CU INNER JOIN [dbo].[aspnet_Users] AU ON CU.[MembershipID] = AU.[UserId]
	INNER JOIN [dbo].[aspnet_Membership] AM ON CU.[MembershipID] = AM.[UserId]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_UserName]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_Email]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_IsAnonymous]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_CreateDate]'

DECLARE	@ConstraintName nvarchar(255)
SELECT	@ConstraintName = CONSTRAINT_NAME
FROM	INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE	TABLE_NAME = 'cs_Users' AND CONSTRAINT_TYPE = 'FOREIGN KEY'

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = @ConstraintName AND TABLE_NAME = 'cs_Users' AND COLUMN_NAME = 'MembershipID')
BEGIN
	DECLARE	@sql nvarchar(4000)
	SET		@sql = 'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [' + @ConstraintName + ']'
	EXECUTE sp_executesql @sql
END
-- END cs_Users

EXECUTE sp_executesql N'ALTER TABLE [cs_ProductPermissions] DROP [FK_cs_ProductPermissions_RoleID]'

EXECUTE sp_executesql N'ALTER TABLE [cs_SectionPermissions] DROP [FK_cs_SectionPermissions_RoleID]'

EXECUTE sp_executesql N'ALTER TABLE [cs_RoleQuotas] DROP [FK_cs_GalleryRoleQuotas_aspnet_Roles]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.08
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql
	N'INSERT INTO [dbo].[cs_SectionSubscriptions]
		([SectionID],[Email],[SubscriptionType],[UserID],[SettingsID],[DateSubscribed],[SubscriptionFrequency],[IsConfirmed])
	SELECT TS.[SectionID], U.[Email], MIN(TS.[SubscriptionType]) as [SubscriptionType], U.[UserID], TS.[SettingsID],
			MAX(TS.[DateCreated]) as [DateSubscribed], 1 as [SubscriptionFrequency], 1 as [IsConfirmed]
	FROM	[dbo].[cs_TrackedSections] TS
			INNER JOIN [dbo].[cs_Users] U ON TS.[UserID] = U.[UserID]
			INNER JOIN [dbo].[cs_Sections] Sec ON Sec.[SectionID] = TS.[SectionID]
			INNER JOIN [dbo].[cs_ApplicationType] A ON A.[ApplicationType] = Sec.[ApplicationType]
	WHERE TS.[SubscriptionType] = 3 AND A.[ApplicationName] = ''Weblog''
	GROUP BY U.[UserID], TS.[SectionID], U.[Email], TS.[SettingsID]
	Having count(*) = 1'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.09
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''cs_Licenses'', ''cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''PK_cs_Licenses'', ''PK_cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''IX_cs_Licenses'', ''IX_cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'CREATE TABLE [dbo].[cs_Licenses] (
		[LicenseID] [uniqueidentifier] NOT NULL ,
		[LicenseValue] [ntext] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXECUTE sp_executesql
	N'ALTER TABLE [dbo].[cs_Licenses] WITH NOCHECK ADD 
		CONSTRAINT [PK_cs_Licenses] PRIMARY KEY  CLUSTERED 
		(
			[LicenseID]
		)  ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.10
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- This patch has been removed

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.11
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql
N'ALTER TABLE [dbo].[cs_Licenses] ADD
	[InstallDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Licenses_InstallDate] DEFAULT (getdate())'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.12
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.13
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

DECLARE @ApplicationType INT
SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Forum'

DECLARE @Parent CURSOR
SET @Parent = CURSOR LOCAL FAST_FORWARD FOR 
	SELECT DISTINCT ParentID FROM cs_Sections WHERE ApplicationType = @ApplicationType and ParentID > 0

OPEN @Parent
DECLARE @ParentID INT

FETCH NEXT FROM @Parent INTO @ParentID
WHILE (@@FETCH_STATUS = 0)
	BEGIN
		DECLARE @SortOrder INT
		SET @SortOrder = 0

		DECLARE @Section CURSOR
		SET @Section = CURSOR LOCAL FAST_FORWARD FOR
			SELECT SectionID FROM cs_Sections WHERE ParentID = @ParentID Order By [Name]

		Open @Section
		DECLARE @SectionID INT
		FETCH NEXT FROM @Section INTO @SectionID

		WHILE (@@FETCH_STATUS = 0)
			BEGIN
				UPDATE cs_Sections 
				SET SortOrder = @SortOrder
				WHERE SectionID = @SectionID

				SET @SortOrder = @SortOrder + 1
				FETCH NEXT FROM @Section INTO @SectionID
			END
		CLOSE @Section
		DEALLOCATE @Section
	
		FETCH NEXT FROM @Parent INTO @ParentID
	END

CLOSE @Parent
DEALLOCATE @Parent

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.14
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE name = N'IX_cs_Users')
	EXECUTE sp_executesql N'DROP INDEX [dbo].[cs_Users].[IX_cs_Users]'

CREATE NONCLUSTERED INDEX IX_cs_Users_UserName ON dbo.cs_Users (UserName) ON [PRIMARY]
CREATE UNIQUE NONCLUSTERED INDEX IX_cs_Users_MembershipID ON dbo.cs_Users (MembershipID) ON [PRIMARY]

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.15
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'ALTER TABLE [cs_Censorship] ALTER COLUMN [Word]  nvarchar(256)'
EXECUTE sp_executesql N'ALTER TABLE [cs_Censorship] ALTER COLUMN [Replacement]  nvarchar(256)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.16
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

delete from cs_Licenses where LicenseID in ('B3B02D98-A87D-4AE4-9786-4A98CA0D282E', '956bfd20-e904-4059-9a92-6afc433b9349')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.17
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- This patch has been removed

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.18
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.18'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 18;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.19
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.19'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 19;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- create tables for post year/month/day queries
if object_id(N'dbo.cs_weblog_PostByYearMonth_tbl01') IS NULL
	exec sp_executesql N'create table dbo.cs_weblog_PostByYearMonth_tbl01 (
	[SectionID] int not null
	, [Year] smallint not null
	, [Month] tinyint not null
	, [Day] tinyint not null
	, [PostCount] int not null
	, constraint PK_cs_weblog_PostByYearMonth_tbl01 primary key clustered (
		[SectionID] asc
		, [Year] desc
		, [Month] desc
		, [Day] desc
	)
	)'

if object_id(N'dbo.cs_weblog_PostByYearMonth_tbl02') IS NULL
	exec sp_executesql N'create table dbo.cs_weblog_PostByYearMonth_tbl02 (
	[SectionID] int not null
	, [Year] smallint not null
	, [Month] tinyint not null
	, [Day] tinyint not null
	, [PostCount] int not null
	, constraint PK_cs_weblog_PostByYearMonth_tbl02 primary key clustered (
		[SectionID] asc
		, [Year] desc
		, [Month] desc
		, [Day] desc
	)
	)'

-- adjust the fill factor on the index for cs_Posts_InCategories
if exists (select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
	where tc.TABLE_NAME = N'cs_Posts_InCategories' and tc.CONSTRAINT_NAME = 'PK_cs_PostsInCategories')
	exec sp_executesql N'alter table cs_Posts_InCategories drop constraint PK_cs_PostsInCategories'

exec sp_executesql N'ALTER TABLE [dbo].[cs_Posts_InCategories]
	ADD CONSTRAINT [PK_cs_PostsInCategories] PRIMARY KEY CLUSTERED (
		[CategoryID]
		, [PostID]
	) with fillfactor = 90'

-- for cs_Referral
-- drop cs_Referral PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Referrals'
	and CONSTRAINT_NAME = N'PK_cs_Referrals' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Referrals] DROP CONSTRAINT [PK_cs_Referrals]'

-- add cs_Referral PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Referrals] ADD CONSTRAINT [PK_cs_Referrals] PRIMARY KEY  CLUSTERED 
	(
		[SettingsID],
		[SectionID],
		[PostID],
		[UrlID]
	) with fillfactor = 90 ON [PRIMARY] 
'

-- for cs_Urls
-- drop cs_Urls.UrlID foreign constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Referrals'
	and CONSTRAINT_NAME = N'FK_cs_Referrals_cs_Urls' and CONSTRAINT_TYPE = N'FOREIGN KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Referrals] DROP CONSTRAINT [FK_cs_Referrals_cs_Urls]'

-- drop cs_Referrals PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Urls'
	and CONSTRAINT_NAME = N'PK_cs_Urls' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Urls] DROP CONSTRAINT [PK_cs_Urls]'

-- add cs_Urls PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Urls] ADD CONSTRAINT [PK_cs_Urls] PRIMARY KEY  CLUSTERED 
	(
		[UrlID]
	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
'

-- add cs_Referrals FK constraint to cs_Urls.UrlID
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Referrals] ADD CONSTRAINT [FK_cs_Referrals_cs_Urls] FOREIGN KEY 
	(
		[UrlID]
	) REFERENCES [cs_Urls] (
		[UrlID]
	)
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.20
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.20'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 20;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- updating UsernameRegex to updated pattern
exec('
declare
	@UsernameRegexOriginalEscaped nvarchar(128), @UsernameRegexNew nvarchar(128), @UsernameRegexNodeName nvarchar(128)
	, @id int, @ptrSettingsXML binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettingsXML binary(16) not null
	, UsernameRegexStart int not null, UsernameRegexEnd int not null, UsernameRegexNodeLength int not null
	, insert_offset AS UsernameRegexStart + UsernameRegexNodeLength - 1
	, delete_length AS UsernameRegexEnd - (UsernameRegexStart + UsernameRegexNodeLength)
)

set nocount on

select
	-- actual pattern: N''[a-zA-Z]+[^\<\>]*''
	@UsernameRegexOriginalEscaped = N''[[]a-zA-Z]+[[][^]\&lt;\&gt;]*''
	, @UsernameRegexNew = N''^[a-zA-Z0-9_\- @\.]+$''
	, @UsernameRegexNodeName = N''UsernameRegex''

select
	db_name() DatabaseName, s.SettingsID, s.SettingsXML
	, case when patindex(
		N''%<'' + @UsernameRegexNodeName + N''>''
		+ @UsernameRegexOriginalEscaped
		+ N''</'' + @UsernameRegexNodeName + N''>%''
		, s.SettingsXML )<>0 then ''Updating'' else ''No Update'' end
from
	cs_SiteSettings s

insert into @t (ptrSettingsXML, UsernameRegexStart, UsernameRegexEnd, UsernameRegexNodeLength)
select
	TEXTPTR( s.SettingsXML )
	, patindex( N''%<'' + @UsernameRegexNodeName + N''>%'', s.SettingsXML )
	, patindex( N''%</'' + @UsernameRegexNodeName + N''>%'', s.SettingsXML )
	, 2 + LEN( @UsernameRegexNodeName )
from
	cs_SiteSettings s
where
	s.SettingsXML IS NOT NULL
	and patindex(
		N''%<'' + @UsernameRegexNodeName + N''>''
		+ @UsernameRegexOriginalEscaped
		+ N''</'' + @UsernameRegexNodeName + N''>%''
		, s.SettingsXML ) <> 0

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break
	
	select @ptrSettingsXML = t.ptrSettingsXML, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id
	
	UPDATETEXT cs_SiteSettings.SettingsXML @ptrSettingsXML @insert_offset @delete_length @UsernameRegexNew

	delete from @t where id = @id
end
')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.0.21
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.21'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 21;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

update aspnet_Roles set LoweredRoleName = LOWER(LoweredRoleName) where LoweredRoleName IN ( N'Registered Users', N'Trusted Users' )

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.00
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'alter table [dbo].[cs_Sections] add IsPublic BIT NULL'

exec sp_executesql N'create index IX_cs_Sections_Public on [dbo].[cs_Sections](SectionID,IsPublic)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.01
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.01'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_Users_OpenID] (
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[OpenID] [nvarchar] (440) NOT NULL ,
	[SettingsID] [int] NOT NULL ,
	[UserID] [int] NOT NULL ,
	[LastAccessed] [datetime] NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[Email] [nvarchar] (128) NOT NULL ,
CONSTRAINT [PK_cs_Users_OpenID] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_Users_OpenID] ON [dbo].[cs_Users_OpenID] 
(
	[OpenID] ASC,
	[SettingsID] ASC
) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.02
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'alter table [dbo].[cs_Sections] add HubSectionID INT NOT NULL DEFAULT -1'

exec sp_executesql N'create index IX_cs_Sections_Hub on [dbo].[cs_Sections](HubSectionID,SectionID)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.03
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionMembers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_SectionMembers] (
		[SectionID] [int] NOT NULL ,
		[UserID] [int] NOT NULL ,
		[MembershipType] [int] NOT NULL,
		[DateAdded] [datetime] NOT NULL CONSTRAINT [DF_cs_SectionMembers_DateAdded] DEFAULT (getdate())
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_SectionMembers] WITH NOCHECK ADD 
		CONSTRAINT [PK_cs_SectionMembers] PRIMARY KEY  CLUSTERED 
		(
			[UserID],
			[SectionID],
			[MembershipType]
		)  ON [PRIMARY]'

	--DROP TABLE cs_SectionMembers
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.04
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

	exec sp_executesql N'DECLARE @PropertyString		NVARCHAR(50)
DECLARE @PropertyDelimiter	NVARCHAR(50)
DECLARE @ValueDelimiter		NVARCHAR(50)

SET @PropertyString = ''%SectionOwners:S:%''
SET @PropertyDelimiter = ''%:%''
SET @ValueDelimiter = ''%;%''

SELECT LEN(@PropertyString)-2

CREATE TABLE #SectionOwners 
(
	SectionID int  NOT NULL,
	OwnerName nvarchar(256) collate database_default NOT NULL
)

CREATE TABLE #SectionOwnerProperty 
(
	SectionID int  NOT NULL,
	Owners nvarchar(4000) collate database_default NOT NULL
)

INSERT INTO #SectionOwnerProperty(SectionID, Owners)
SELECT
SectionID,
 
SUBSTRING(PropertyValues,
CONVERT(int, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),0,PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))))+1,
CONVERT(int, SUBSTRING(SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100),0, PATINDEX(@PropertyDelimiter, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100)))-1)
+1
) as Owners from cs_Sections WHERE (ApplicationType <> 0) AND (PATINDEX(@PropertyString, PropertyNames) > 0)

WHILE EXISTS (SELECT SectionID FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0)
BEGIN
	INSERT INTO #SectionOwners (SectionID, OwnerName) SELECT SectionID, LOWER(SUBSTRING(Owners,0,PATINDEX(@ValueDelimiter, Owners)))  FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0 
	UPDATE #SectionOwnerProperty SET Owners = SUBSTRING(Owners,PATINDEX(@ValueDelimiter, Owners)+1, DATALENGTH(Owners) - PATINDEX(@ValueDelimiter, Owners))  FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0 
END

INSERT INTO #SectionOwners (SectionID, OwnerName) SELECT SectionID, LOWER(Owners) FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) = 0 

DROP TABLE #SectionOwnerProperty

SELECT * FROM #SectionOwners
INSERT INTO cs_SectionMembers(SectionID, UserID, MembershipType) SELECT DISTINCT SO.SectionID, U.UserID, 1 FROM  #SectionOwners SO JOIN cs_Users U on U.UserName = SO.OwnerName JOIN cs_UserProfile P on U.UserID = P.UserID JOIN cs_Sections S on SO.SectionID = S.SectionID and P.SettingsID = S.SettingsID LEFT OUTER JOIN cs_SectionMembers SM on SM.SectionID = SO.SectionID and SM.UserID = U.UserID and SM.MembershipType = 1 WHERE SM.MembershipType is null 

DROP TABLE #SectionOwners' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.05
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[cs_Sections]') and Name = 'IsCommunityAggregated')
begin

exec sp_executesql N'alter table [dbo].[cs_Sections] add IsCommunityAggregated BIT NOT NULL DEFAULT -1'

exec sp_executesql N'DECLARE @PropertyString		NVARCHAR(50)
DECLARE @PropertyDelimiter	NVARCHAR(50)
DECLARE @ValueDelimiter		NVARCHAR(50)

SET @PropertyString = ''%IsCommunityAggregated:S:%''
SET @PropertyDelimiter = ''%:%''
SET @ValueDelimiter = ''%;%''

UPDATE cs_Sections set IsCommunityAggregated = CA.IsCommunityAggregatedProperty FROM cs_Sections S join (
SELECT
SectionID, 0 as IsCommunityAggregatedProperty
from cs_Sections WHERE PATINDEX(@PropertyString, PropertyNames) > 0 AND
LOWER(SUBSTRING(PropertyValues,
CONVERT(int, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),0,PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))))+1,
CONVERT(int, SUBSTRING(SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100),0, PATINDEX(@PropertyDelimiter, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100)))-1)
+1
)) = ''false'' 
) CA on S.SectionID = CA.SectionID
'
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.06
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

declare @propertyValuesPtr binary(16),
	@index int,
	@sectionID int

set nocount on

declare section_cursor cursor for
select SectionID
from cs_Sections
where ApplicationType = 1
	and PropertyValues like '%poisonivy%'

open section_cursor

fetch next from section_cursor into @sectionID
while @@fetch_status = 0
begin

	select @propertyValuesPtr = textptr(PropertyValues), @index = PATINDEX('%poisonivy%', PropertyValues)
	from cs_Sections
	where SectionID = @sectionID
	
	set @index = @index - 1

	if @index >= 0 begin
		print 'Updating theme for blog with ID ' + convert(varchar(20), @sectionID) + ' ...'
		updatetext cs_Sections.PropertyValues @propertyValuesPtr @index 9 'elemental'
	end

	fetch next from section_cursor into @sectionID
end

close section_cursor
deallocate section_cursor

set nocount off

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 
/***********************************************
* Patch: cs_Schema_Patch_3.1.07
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_Thread_Daily_Stats](
	[SectionID] [int] NOT NULL,
	[ThreadID] [int] NOT NULL,
	[Day] [datetime] NOT NULL,
	[ViewCount] [int] NOT NULL,
	CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED (
		[SectionID] ASC,
		[ThreadID] ASC
	) 
) ON [PRIMARY]


/****** Object:  Index [PK_cs_Thread_Daily_Stats]    Script Date: 06/27/2007 12:29:38 ******/
CREATE INDEX [IX_cs_Thread_Daily_Stats_Day] ON [dbo].[cs_Thread_Daily_Stats] 
(
	[Day] DESC
) ON [PRIMARY]'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.08
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- *****************************************
--
-- MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.09
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

/* was just local database corruption
exec sp_executesql N'Update cs_Users set UserName = ''Anonymous'' where IsAnonymous = 1 and UserName = '''''
*/

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.10
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

exec sp_executesql N'Update cs_Sections set HubSectionID = SectionID where HubSectionID = 0 and ApplicationType = 11'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.11
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

declare @ConstraintName sysname

Select @ConstraintName = o.name from  sysobjects o join syscolumns c on c.cdefault = o.id where c.name = 'HubSectionID' and parent_obj = OBJECT_ID('[dbo].[cs_Sections]')

EXEC('ALTER TABLE cs_Sections DROP CONSTRAINT ' + @ConstraintName)

exec sp_executesql N'ALTER TABLE cs_Sections ADD CONSTRAINT DF_cs_Sections_HubSectionID DEFAULT 0 FOR HubSectionID'

exec sp_executesql N'Update cs_Sections set HubSectionID = 0 where HubSectionID = -1'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.12
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_Thread_Daily_Stats]') AND name = N'PK_cs_Thread_Daily_Stats')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Thread_Daily_Stats] DROP CONSTRAINT [PK_cs_Thread_Daily_Stats]'

IF EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_Thread_Daily_Stats]') AND name = N'IX_cs_Thread_Daily_Stats_Day')
	exec sp_executesql N'DROP INDEX [dbo].[cs_Thread_Daily_Stats].[IX_cs_Thread_Daily_Stats_Day]'

exec sp_executesql N'
ALTER TABLE [dbo].[cs_Thread_Daily_Stats] ADD CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED
(
	[SectionID] ASC
	, [ThreadID] ASC
	, [Day] DESC
) ON [PRIMARY]
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.13
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DF_cs_Sections_EnableAutoDelete]'))
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP CONSTRAINT [DF_cs_Sections_EnableAutoDelete]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DF_cs_Sections_AutoDeleteThreshold]'))
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP CONSTRAINT [DF_cs_Sections_AutoDeleteThreshold]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP COLUMN [EnableAutoDelete]'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP COLUMN [AutoDeleteThreshold]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.14
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- *****************************************
--
-- MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.15
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

insert into [dbo].[cs_Groups] (SettingsID, Name, SortOrder, ApplicationType, Description)
select SettingsID, 'Hubs', 1, 11, ''
from [dbo].[cs_SiteSettings]
where SettingsID not in (select SettingsID from [dbo].[cs_Groups] where Name = 'Hubs' and ApplicationType = 11)

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.16
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- *****************************************
--
-- OTHER PARTS OF THIS PATCH MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

-- for cs_Thread_Daily_Stats
-- drop cs_Thread_Daily_Stats PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Thread_Daily_Stats'
	and CONSTRAINT_NAME = N'PK_cs_Thread_Daily_Stats' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Thread_Daily_Stats] DROP CONSTRAINT [PK_cs_Thread_Daily_Stats]'

-- add cs_Thread_Daily_Stats PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Thread_Daily_Stats] ADD CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED
(
	[SectionID] ASC
	, [ThreadID] ASC
	, [Day] DESC
) with fillfactor = 90 ON [PRIMARY]
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.17
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

update [dbo].[cs_SectionMembers]
set MembershipType = 8
where MembershipType = 4

update [dbo].[cs_SectionMembers]
set MembershipType = 4
where MembershipType = 3

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.18
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.18'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 18;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.19
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.19'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 19;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- *****************************************
--
-- Clearing the patch; table cs_User_ApplicationToken no longer needed.
-- It's been renamed to cs_User_ApiKeys (with a different schema), which
-- can be found in patch 3.1.24.
--
-- *****************************************

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_3.1.20
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.20'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 20;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FriendRequests]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_FriendRequests](
	[FriendshipRequestID] [int] IDENTITY(1,1) NOT NULL,
	[RequestorUserID] [int] NOT NULL,
	[RequesteeUserID] [int] NOT NULL,
	[Message] [varchar](2000) NULL,
	[FriendshipState] [tinyint] NOT NULL,
	[CreatedDate] [datetime] NOT NULL CONSTRAINT [DF_cs_FriendRequests_CreatedDate]  DEFAULT (getdate()),
	[LastModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_cs_FriendRequests_LastModifiedDate]  DEFAULT (getdate()),
PRIMARY KEY CLUSTERED 
(
	[FriendshipRequestID] ASC
)WITH FILLFACTOR = 90
)'
	
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Friends_xref]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_Friends_xref](
	[UserID] [int] NOT NULL,
	[FriendUserID] [int] NOT NULL)'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Friends_xref]  
	WITH CHECK ADD  CONSTRAINT [FK_cs_Friends_xref_cs_Users] 
	FOREIGN KEY([UserID])
	REFERENCES [dbo].[cs_Users] ([UserID])'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Friends_xref] 
	CHECK CONSTRAINT [FK_cs_Friends_xref_cs_Users]'

	
end


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.21
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.21'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 21;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'ALTER TABLE [dbo].[cs_Groups] ADD ParentGroupID int NOT NULL DEFAULT((0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.22
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.22'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 22;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder]'))
	exec sp_rename cs_Folder, cs_Folder_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost]'))
	exec sp_rename cs_FeedPost, cs_FeedPost_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed]'))
	exec sp_rename cs_Feed, cs_Feed_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FolderFeed]'))
	exec sp_rename cs_FolderFeed, cs_FolderFeed_deprecated

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.23
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.23'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 23;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_GroupPermissions](
	[SettingsID] [int] NOT NULL,
	[GroupID] [int] NOT NULL,
	[RoleID] [uniqueidentifier] NOT NULL,
	[AllowMask] [binary](8) NOT NULL,
	[DenyMask] [binary](8) NOT NULL
CONSTRAINT [PK_cs_GroupPermissions] PRIMARY KEY CLUSTERED 
(
	[SettingsID] ASC,
	[GroupID] ASC,
	[RoleID] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_GroupPermissions] ADD CONSTRAINT [FK_cs_GroupPermissions_SettingsID] FOREIGN KEY([SettingsID]) 
	REFERENCES [dbo].[cs_SiteSettings] ([SettingsID])'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.24
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.24'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 24;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_ApiKeys](
	[ApiKeyID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [int] NOT NULL,
	[Value] [char](8) NOT NULL,
	[Name] [varchar](50) NOT NULL,
	[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_cs_ApiKeys_DateCreated]  DEFAULT (getdate()),
	[Enabled] [bit] NOT NULL CONSTRAINT [DF_cs_ApiKeys_Enabled]  DEFAULT ((1)),
 CONSTRAINT [PK_cs_ApiKeys] PRIMARY KEY CLUSTERED 
(
	[ApiKeyID] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_ApiKeys_UserID] ON [dbo].[cs_ApiKeys] ([UserID]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_ApiKeys_Value] ON [dbo].[cs_ApiKeys] ([Value])'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.25
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.25'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 25;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_ApiKeys]') and OBJECTPROPERTY(id, N'IsTable') = 1)
BEGIN
	if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys]') and OBJECTPROPERTY(id, N'IsTable') = 1)
BEGIN
	EXECUTE sp_Rename N'cs_User_ApiKeys', 'cs_ApiKeys'
	EXECUTE sp_Rename N'PK_cs_User_ApiKeys', 'PK_cs_ApiKeys'

	IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_User_ApiKeys_Value')
	BEGIN
		EXECUTE sp_executesql N'DROP INDEX [IX_cs_User_ApiKeys_Value] ON [dbo].[cs_ApiKeys]'
		IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_ApiKeys_Value')
			EXECUTE sp_executesql N'CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_ApiKeys_Value] ON [dbo].[cs_ApiKeys] ([Value])'
	END
	IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_User_ApiKeys_UserID')
	BEGIN
		EXECUTE sp_executesql N'DROP INDEX [IX_cs_User_ApiKeys_UserID] ON [dbo].[cs_ApiKeys]'
		IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_ApiKeys_UserID')
			EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_ApiKeys_UserID] ON [dbo].[cs_ApiKeys] ([UserID]) WITH FILLFACTOR = 90 ON [PRIMARY]'
	END
END
END

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.26
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.26'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 26;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- The table created is no longer required.  Empty schema patch.

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.27
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.27'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 27;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[cs_FavoriteUsers]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	EXECUTE sp_executesql N'
	INSERT INTO cs_FriendRequests
		([RequestorUserID], [RequesteeUserID], [Message], [FriendshipState], [CreatedDate], [LastModifiedDate])
	SELECT U.UserID, FU.UserID, ''A friendship request has been initiated.  Please either accept or reject this request.'' as [Message], 2 as [FriendshipState], getdate() as [CreatedDate], getdate() as [LastModifiedDate]
		FROM cs_Users U
		INNER JOIN cs_FavoriteUsers FU ON FU.OwnerID = U.UserID AND FU.UserID IN 
			(SELECT OwnerID FROM cs_FavoriteUsers FUs WHERE FUs.UserID = U.UserID)
	WHERE NOT EXISTS (SELECT * FROM cs_FriendRequests FR WHERE FR.RequestorUserID = U.UserID AND FR.RequesteeUserID = FU.UserID)'

	EXECUTE sp_executesql N'
	DELETE FROM cs_FriendRequests WHERE FriendshipRequestID in
	(SELECT FR.FriendshipRequestID FROM cs_FriendRequests FR
		INNER JOIN cs_FriendRequests FRS ON FR.[RequesteeUserID] = FRS.[RequestorUserID] AND FRS.[RequesteeUserID] = FR.[RequestorUserID] AND FR.[RequesteeUserID] < FRS.[RequesteeUserID]
	 WHERE FR.FriendshipState = 2 AND FR.[RequesteeUserID] <> FR.[RequestorUserID])'

	EXECUTE sp_executesql N'
	INSERT INTO cs_Friends_xref (UserID, FriendUserID)
	SELECT FR.RequestorUserID, FR.RequesteeUserID
		FROM cs_FriendRequests FR
		WHERE FR.FriendshipState = 2 AND NOT EXISTS (Select * FROM cs_Friends_xref F WHERE F.UserID = FR.RequestorUserID AND F.FriendUserID = FR.RequesteeUserID)'

	EXECUTE sp_executesql N'
	INSERT INTO cs_Friends_xref (UserID, FriendUserID)
	SELECT FR.RequesteeUserID, FR.RequestorUserID
		FROM cs_FriendRequests FR
		WHERE FR.FriendshipState = 2 AND NOT EXISTS (Select * FROM cs_Friends_xref F WHERE F.FriendUserID = FR.RequestorUserID AND F.UserID = FR.RequesteeUserID)'

	EXECUTE sp_executesql N'
	INSERT INTO cs_FriendRequests
		([RequestorUserID], [RequesteeUserID], [Message], [FriendshipState], [CreatedDate], [LastModifiedDate])
	SELECT U.UserID, FU.UserID, ''A friendship request has been initiated.  Please either accept or reject this request.'' as [Message], 1 as [FriendshipState], getdate() as [CreatedDate], getdate() as [LastModifiedDate]
		FROM cs_Users U
		INNER JOIN cs_FavoriteUsers FU ON FU.OwnerID = U.UserID AND FU.UserID NOT IN 
			(SELECT OwnerID FROM cs_FavoriteUsers FUs WHERE FUs.UserID = U.UserID)
	WHERE NOT EXISTS (SELECT * FROM cs_FriendRequests FR WHERE FR.RequestorUserID = U.UserID AND FR.RequesteeUserID = FU.UserID)'


	EXECUTE sp_executesql N'
	INSERT INTO mg_EmailQueue (SettingsID, EmailXml) 
	SELECT S.SettingsID, 
		N''<?xml version="1.0" encoding="utf-16"?><MailMessage><Revision>0</Revision><Headers /><DeliveryNotificationOptions>None</DeliveryNotificationOptions><Priority>Normal</Priority><From><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml><Revision>0</Revision><Name>''
		+ S.[SiteName]
		+ N'' - Automated Email</Name><Address>info@notset.com</Address></Telligent.MailGateway.Common.Components.MailAddressXml></MailAddress></From><To><MailAddress><Revision>0</Revision><Name /><Address>''
		+ U.Email
		+ N''</Address></MailAddress></To><Cc /><Bcc /><Sender><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml /></MailAddress></Sender><ReplyTo><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml /></MailAddress></ReplyTo><Subject>New Friend Request(s) on ''
		+ S.[SiteName]
		+ N''</Subject><SubjectEncoding /><Body>You have friendships that are awaiting confirmation at &lt;a href=''
		+ S.[SiteUrl]
		+ N''/&gt;''
		+ S.[SiteName]
		+ N''&lt;/a&gt;&lt;p&gt;Please visit the &lt;a href=''
		+ S.[SiteUrl]
		+ N''/members/''
		+ U.UserName
		+ N''/friends/default.aspx&gt;My Friends&lt;/a&gt; page of your profile to approve these requests.&lt;/p&gt;</Body><BodyEncoding>65001</BodyEncoding><BodyFormat /><IsBodyHtml>True</IsBodyHtml><Attachments><Attachment /></Attachments><AttachmentHandles /><AlternateViews></AlternateViews></MailMessage>''
	FROM (
		SELECT DISTINCT UP.[SettingsID], UX.[Email], UX.UserName
		FROM cs_Users UX
		INNER JOIN cs_UserProfile UP on UX.UserID = UP.UserID AND UP.EnableEmail = 1
		WHERE EXISTS (
			SELECT 1 FROM [cs_FriendRequests] FR
			WHERE UX.UserID = FR.RequesteeUserID AND FR.FriendshipState = 1
		)
	) AS U
	INNER JOIN (
		select SX.SettingsID
			, coalesce( convert( nvarchar(512), substring(SX.SettingsXML, len(''SiteName'')+2+NULLIF(patindex(N''%<SiteName>%</SiteName>%'', SX.SettingsXML), 0),NULLIF(patindex(N''%</SiteName>%'', SX.SettingsXML), 0) - len(''SiteName'') - 2 - NULLIF(patindex(N''%<SiteName>%</SiteName>%'', SX.SettingsXML), 0)) ), N''NO_SITE''	) AS [SiteName]
			, coalesce( convert( nvarchar(512), substring(SX.SettingsXML, len(''SiteUrl'' )+2+NULLIF(patindex(N''%<SiteUrl>%</SiteUrl>%''  , SX.SettingsXML), 0),NULLIF(patindex(N''%</SiteUrl>%'' , SX.SettingsXML), 0) - len(''SiteUrl'' ) - 2 - NULLIF(patindex(N''%<SiteUrl>%</SiteUrl>%''  , SX.SettingsXML), 0)) ), N''NO SITE URL'') AS [SiteUrl]
		FROM cs_SiteSettings SX
		WHERE
			''true'' = convert( nvarchar(4), substring(SX.SettingsXML, len(''EnableEmail'')+2+NULLIF(patindex(N''%<EnableEmail>%</EnableEmail>%'', SX.SettingsXML), 0),NULLIF(patindex(N''%</EnableEmail>%'', SX.SettingsXML), 0) - len(''EnableEmail'') - 2 - NULLIF(patindex(N''%<EnableEmail>%</EnableEmail>%'', SX.SettingsXML), 0)) )
	) S on S.SettingsID = U.SettingsID
	'

END

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.28
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.28'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 28;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- Create cs_Messaging_Messages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_Messages](
	[MessageId] [uniqueidentifier] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[Subject] [nvarchar](100) NOT NULL,
	[Body] [nvarchar](1000) NOT NULL,
	[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_cs_Messaging_Messages_DateCreated]  DEFAULT (getdate()),
 CONSTRAINT [PK_cs_Messaging_Messages] PRIMARY KEY CLUSTERED 
(
	[MessageId] ASC
)) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_Messages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_Messages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_Messages_cs_Users] FOREIGN KEY([AuthorId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_Messages] CHECK CONSTRAINT [FK_cs_Messaging_Messages_cs_Users]'

-- Create indexes for cs_Messaging_Messages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_Messages_AuthorId] ON [dbo].[cs_Messaging_Messages] ([AuthorId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_Conversations table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_Conversations](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[ParticipantCount] [int] NOT NULL,
	[MessageCount] [int] NOT NULL,
 CONSTRAINT [PK_cs_Messaging_Conversations] PRIMARY KEY CLUSTERED 
(
	[ConversationId] ASC
)) ON [PRIMARY]'

-- Create cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ConversationMessages](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Conversations] FOREIGN KEY([ConversationId]) REFERENCES [dbo].[cs_Messaging_Conversations] ([ConversationId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages] CHECK CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Conversations]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages] CHECK CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Messages]'

-- Create indexes for cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationMessages_ConversationId] ON [dbo].[cs_Messaging_ConversationMessages] ([ConversationId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationMessages_MessageId] ON [dbo].[cs_Messaging_ConversationMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ConversationParticipants](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[ParticipantId] [int] NOT NULL,
	[Active] [bit] NOT NULL CONSTRAINT [DF_cs_Messaging_ConversationParticipants_Active]  DEFAULT ((1))
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Messaging_Conversations] FOREIGN KEY([ConversationId]) REFERENCES [dbo].[cs_Messaging_Conversations] ([ConversationId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants] CHECK CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Messaging_Conversations]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Users] FOREIGN KEY([ParticipantId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants] CHECK CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Users]'

-- Create indexes for cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationParticipants_ConversationId] ON [dbo].[cs_Messaging_ConversationParticipants] ([ConversationId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationParticipants_ParticipantId] ON [dbo].[cs_Messaging_ConversationParticipants] ([ParticipantId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ProfileMessages](
	[UserId] [int] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages] CHECK CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Messaging_Messages]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Users] FOREIGN KEY([UserId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages] CHECK CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Users]'

-- Create indexes for cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ProfileMessages_MessageId] ON [dbo].[cs_Messaging_ProfileMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ProfileMessages_UserId] ON [dbo].[cs_Messaging_ProfileMessages] ([UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_GroupMessages](
	[GroupId] [int] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_GroupMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_GroupMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_GroupMessages] CHECK CONSTRAINT [FK_cs_Messaging_GroupMessages_cs_Messaging_Messages]'

-- Create indexes for cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_GroupMessages_GroupId] ON [dbo].[cs_Messaging_GroupMessages] ([GroupId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_GroupMessages_MessageId] ON [dbo].[cs_Messaging_GroupMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ActivityMessages](
	[MessageId] [uniqueidentifier] NOT NULL,
	[UserId] [int] NOT NULL,
	[GroupId] [int] NULL,
    [Type] [nvarchar](50) NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages] CHECK CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Messaging_Messages]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Users] FOREIGN KEY([UserId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages] CHECK CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Users]'

-- Create indexes for cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_MessageId] ON [dbo].[cs_Messaging_ActivityMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_UserId] ON [dbo].[cs_Messaging_ActivityMessages] ([UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_GroupId] ON [dbo].[cs_Messaging_ActivityMessages] ([GroupId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_Type] ON [dbo].[cs_Messaging_ActivityMessages] ([Type]) WITH FILLFACTOR = 90 ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.29
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.29'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 29;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='cs_PostAttachments' and COLUMN_NAME='Content' )
	EXECUTE sp_executesql N'ALTER TABLE cs_PostAttachments ADD CONSTRAINT [DF_cs_PostAttachments_Content] DEFAULT 0x FOR [Content]'

if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='cs_PostAttachments_TEMP' and COLUMN_NAME='Content' )
	EXECUTE sp_executesql N'ALTER TABLE cs_PostAttachments_TEMP ADD CONSTRAINT [DF_cs_PostAttachments_TEMP_Content] DEFAULT 0x FOR [Content]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.30
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.30'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 30;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_AddonConfigurationData] (
		[AddonName] [nvarchar] (255) NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[AddonID] [uniqueidentifier] NOT NULL ,
		[PropertyNames] [ntext] NULL ,
		[PropertyValues] [ntext] NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_AddonConfigurationData] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_AddonConfigurationData] PRIMARY KEY  CLUSTERED 
	(
		[SettingsID],
		[AddonID]
	)  ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.31
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.31'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 31;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF NOT EXISTS (
		select 1 from INFORMATION_SCHEMA.TABLES t
		where t.TABLE_SCHEMA = N'dbo' AND t.TABLE_NAME = N'cs_SpamPosts'
	)
	exec sp_executesql N'CREATE TABLE [dbo].[cs_SpamPosts]
(
	SpamPostID bigint identity(1, 1) not null,
	SourceProcedure nvarchar(128) not null,
	SectionID int not null,
	ParentID int not null,
	AllowDuplicatePosts bit,
	DuplicateIntervalInMinutes int,
	Subject nvarchar(256),
	UserID int not null,
	PostAuthor nvarchar(64),
	Body ntext,
	FormattedBody ntext,
	EmoticonID int,
	IsLocked bit,
	IsSticky bit,
	IsApproved bit,
	StickyDate datetime,
	PostType int,
	PostMedia int,
	PostDate datetime not null, /* ensuring that this is never null */
	UserHostAddress nvarchar(32),
	PropertyNames ntext,
	PropertyValues ntext,
	SettingsID int not null,
	IsTracked bit,
	--PostID int not null, /* leaving this one out on purpose */
	ThreadID int, /* this could possibly be null if a thread starter is ever marked as definite spam */
	PostConfiguration int,
	UpdateSectionStatistics bit,
	UserTime datetime not null, /* if for some reason this value comes in a NULL, I will use PostDate and then finally GETDATE() */
	ApplicationPostType int,
	PostName nvarchar(256),
	ThreadStatus int,
	Points int,
	PostDisplayName nvarchar(64),
	AutoApprove bit,

	/* from cs_weblog_Post_Create */
	TitleUrl nvarchar(256),
	PostConfig int,
	BlogPostType tinyint,
	Categories nvarchar(4000),
	SpamScore int,
	PostStatus int
)'

IF NOT EXISTS (
		select 1 from INFORMATION_SCHEMA.TABLES t
		where t.TABLE_SCHEMA = N'dbo' AND t.TABLE_NAME = N'cs_SpamPosts'
	)
	exec sp_executesql N'ALTER TABLE [dbo].[cs_SpamPosts] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_SpamPosts] PRIMARY KEY CLUSTERED
	(
		[SpamPostID]
	) ON [PRIMARY]'

IF indexproperty( object_id(N'[dbo].[cs_SpamPosts]'), N'IX_cs_SpamPosts_SettingsID_SectionID', N'IndexID') IS NULL
	exec sp_executesql N'CREATE INDEX [IX_cs_SpamPosts_SettingsID_SectionID] ON [dbo].[cs_SpamPosts]
	(
		[SettingsID]
		, [SectionID]
		, [ThreadID]
	) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.32
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.32'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 32;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
if not exists( select * from cs_ApplicationType where ApplicationType = 13 )
	insert into cs_ApplicationType values( 13, ''MediaGallery'')

DECLARE @ApplicationID uniqueidentifier
DECLARE @SettingsID int
DECLARE @Perm_RoleID uniqueidentifier

DECLARE settingsCursor CURSOR FOR
select ss.SettingsID, aa.ApplicationId
from cs_SiteSettings ss
inner join aspnet_Applications aa on ss.ApplicationName = aa.ApplicationName

OPEN settingsCursor

FETCH NEXT FROM settingsCursor
INTO @SettingsID, @ApplicationID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''mediagalleryadministrator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''MediaGalleryAdministrator'', N''mediagalleryadministrator'', N''Administration role for Media Galleries'')
	END

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Everyone''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Registered Users''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Editor''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Moderator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''MediaGalleryAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''SystemAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x41001008000002FF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Owners''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 )

	FETCH NEXT FROM settingsCursor
	INTO @SettingsID, @ApplicationID
END

CLOSE settingsCursor
DEALLOCATE settingsCursor
')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.33
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.33'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 33;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_rename @objname='files_Downloads', @newname='cs_Posts_Downloads', @objtype='OBJECT'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_3.1.34
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.34'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 1;
Set @Patch = 34;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(14, ''Rest'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(1000, ''Newsletter'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(1001, ''Games'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(53, ''Wiki'')'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.00
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.01
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.01'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN

--## Schema Patch ##

exec sp_executesql N'DELETE FROM cs_TrackedSections WHERE SectionID = 0'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.02
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN

--## Schema Patch ##


if object_id('cs_TEMP_FoldSpamConfiguration', 'P') IS NOT NULL
	exec ('drop procedure cs_TEMP_FoldSpamConfiguration')

/* create temp stored proc */
exec('
create procedure cs_TEMP_FoldSpamConfiguration
	@SettingsID int
	, @xml ntext = null
as

declare @ret int, @iXml int, @node nvarchar(128)

select @node = N''/SpamConfiguration/RuleSettings/RuleSetting''

EXECUTE @ret = [master].[dbo].[sp_xml_preparedocument] @iXml OUTPUT, @xml

declare @t table (
	[parentid] int not null
	, [id] int not null
	, [RuleID] uniqueidentifier not null
	, [Key] nvarchar(128) collate database_default not null
	, [Value] nvarchar(3875) collate database_default not null
	, [ValueLength] int not null
)

insert into @t
SELECT
	n.[parentid]
	, n.[id]
	, r.[RuleID]
    , n.[localname] [Key]
    , d.[text] [value]
    , datalength(d.[text]) / 2 [value_len] FROM (
	SELECT * FROM OPENXML(@iXml, @node, 2)
	with (
		[RuleID] uniqueidentifier ''RuleID/text()''
		, [id] int ''@mp:id''
	)
) AS r
inner join (
	SELECT [id], [parentid], [localname] FROM OPENXML(@iXml, @node, 2)
) as n on n.[parentid] = r.[id]
inner join (
	SELECT [parentid], [text] FROM OPENXML(@iXml, @node, 2)
) as d on d.[parentid] = n.[id]
where
	n.[localname] <> N''RuleID'' and n.[localname] <> ''Description'' and 
	n.[localname] <> ''MaxValueLength'' and n.[localname] <> ''DefaultValue''
order by
	n.[parentid], n.[id]

/* release the XML document now that we are done */
EXECUTE [master].[dbo].[sp_xml_removedocument] @iXml

declare @p table (
	[id] int identity(1, 1) not null
	, [AddonID] uniqueidentifier not null
	, [PropertyName] nvarchar(128) collate database_default null
	, [PropertyValue] nvarchar(3875) collate database_default null
)

insert into @p (AddonID, PropertyName, PropertyValue)
select RuleID [AddonID]
	, [Value] + N'':S:'' + coalesce((
		select cast(sum(tx.[ValueLength]) as nvarchar) from @t tx
		where tx.[Key] = ''Value'' and tx.[id] < t.[id] and tx.[RuleID] = t.[RuleID]
	), N''0'') + N'':'' + coalesce((select cast(sum(tx.[ValueLength]) as nvarchar) from @t tx 
		where tx.[parentid] = t.[parentid] and tx.[Key] = ''Value''), N''0'') + N'':'' [PropertyName]
	, (select tx.[Value] from @t tx where tx.[parentid] = t.[parentid] and tx.[Key] = ''Value'') [PropertyValue]
from @t t
where t.[Key] = ''Key''
order by
	t.[RuleID]

if object_id(''tempdb..#flat'') IS NOT NULL exec (''drop table #flat'')

create table #flat (
	[AddonID] uniqueidentifier not null
	, [PropertyNames] ntext collate database_default null
	, [PropertyValues] ntext collate database_default null
)

declare @id int, @AddonID uniqueidentifier
	, @PropertyName nvarchar(128), @PropertyValue nvarchar(3875)
	, @pnPTR binary(16), @pvPTR binary(16)

select @id = 1

while 1=1
begin
	select
		@AddonID = p.[AddonID], @PropertyName = p.[PropertyName], @PropertyValue = p.[PropertyValue]
	from @p p
	where p.[id] = @id
	
	if @@ROWCOUNT = 0 break
	
	if not exists (select 1 from #flat where [AddonID] = @AddonID)
		insert into #flat ([AddonID], [PropertyNames], [PropertyValues]) values (@AddonID, '''', '''')
	
	select @pnPTR = TEXTPTR(f.[PropertyNames]), @pvPTR = TEXTPTR(f.[PropertyValues])
	from #flat f
	where f.[AddonID] = @AddonID
	
	updatetext #flat.[PropertyNames]  @pnPTR null 0 @PropertyName
	updatetext #flat.[PropertyValues] @pvPTR null 0 @PropertyValue
	
	select @id = @id + 1
end

/* showing what was migrated */
select
	cast( f.AddonID as nvarchar(255) )
	, @SettingsID
	, f.AddonID, f.PropertyNames, f.PropertyValues
from
	#flat f
where
	not exists (
		select 1 from [cs_AddonConfigurationData] fx
		where fx.[SettingsID] = @SettingsID AND cast( f.AddonID as nvarchar(255) ) = fx.[AddonName]
	)

/* actually setting it */
INSERT INTO [cs_AddonConfigurationData]( [AddonName], [SettingsID], [AddonID], [PropertyNames], [PropertyValues] )
select
	cast( f.AddonID as nvarchar(255) )
	, @SettingsID
	, f.AddonID, f.PropertyNames, f.PropertyValues
from
	#flat f
where
	not exists (
		select 1 from [cs_AddonConfigurationData] fx
		where fx.[SettingsID] = @SettingsID AND cast( f.AddonID as nvarchar(255) ) = fx.[AddonName]
	)

drop table #flat
')

/* execute rehash - designed to work with sql 2k and 2k5 */
exec (N'
	set nocount on

	declare @qPosition int,
		@qValue nvarchar(4000),
		@hasErrorOccured bit

	/* declare 250 nvarchar(4000) (nearly 1MB worth of space) */
	declare @q1 nvarchar(4000), @q2 nvarchar(4000), @q3 nvarchar(4000), @q4 nvarchar(4000), @q5 nvarchar(4000), @q6 nvarchar(4000), @q7 nvarchar(4000), @q8 nvarchar(4000), @q9 nvarchar(4000), @q10 nvarchar(4000), 
		@q11 nvarchar(4000), @q12 nvarchar(4000), @q13 nvarchar(4000), @q14 nvarchar(4000), @q15 nvarchar(4000), @q16 nvarchar(4000), @q17 nvarchar(4000), @q18 nvarchar(4000), @q19 nvarchar(4000), @q20 nvarchar(4000), 
		@q21 nvarchar(4000), @q22 nvarchar(4000), @q23 nvarchar(4000), @q24 nvarchar(4000), @q25 nvarchar(4000), @q26 nvarchar(4000), @q27 nvarchar(4000), @q28 nvarchar(4000), @q29 nvarchar(4000), @q30 nvarchar(4000), 
		@q31 nvarchar(4000), @q32 nvarchar(4000), @q33 nvarchar(4000), @q34 nvarchar(4000), @q35 nvarchar(4000), @q36 nvarchar(4000), @q37 nvarchar(4000), @q38 nvarchar(4000), @q39 nvarchar(4000), @q40 nvarchar(4000), 
		@q41 nvarchar(4000), @q42 nvarchar(4000), @q43 nvarchar(4000), @q44 nvarchar(4000), @q45 nvarchar(4000), @q46 nvarchar(4000), @q47 nvarchar(4000), @q48 nvarchar(4000), @q49 nvarchar(4000), @q50 nvarchar(4000), 
		@q51 nvarchar(4000), @q52 nvarchar(4000), @q53 nvarchar(4000), @q54 nvarchar(4000), @q55 nvarchar(4000), @q56 nvarchar(4000), @q57 nvarchar(4000), @q58 nvarchar(4000), @q59 nvarchar(4000), @q60 nvarchar(4000), 
		@q61 nvarchar(4000), @q62 nvarchar(4000), @q63 nvarchar(4000), @q64 nvarchar(4000), @q65 nvarchar(4000), @q66 nvarchar(4000), @q67 nvarchar(4000), @q68 nvarchar(4000), @q69 nvarchar(4000), @q70 nvarchar(4000), 
		@q71 nvarchar(4000), @q72 nvarchar(4000), @q73 nvarchar(4000), @q74 nvarchar(4000), @q75 nvarchar(4000), @q76 nvarchar(4000), @q77 nvarchar(4000), @q78 nvarchar(4000), @q79 nvarchar(4000), @q80 nvarchar(4000), 
		@q81 nvarchar(4000), @q82 nvarchar(4000), @q83 nvarchar(4000), @q84 nvarchar(4000), @q85 nvarchar(4000), @q86 nvarchar(4000), @q87 nvarchar(4000), @q88 nvarchar(4000), @q89 nvarchar(4000), @q90 nvarchar(4000), 
		@q91 nvarchar(4000), @q92 nvarchar(4000), @q93 nvarchar(4000), @q94 nvarchar(4000), @q95 nvarchar(4000), @q96 nvarchar(4000), @q97 nvarchar(4000), @q98 nvarchar(4000), @q99 nvarchar(4000), @q100 nvarchar(4000), 
		@q101 nvarchar(4000), @q102 nvarchar(4000), @q103 nvarchar(4000), @q104 nvarchar(4000), @q105 nvarchar(4000), @q106 nvarchar(4000), @q107 nvarchar(4000), @q108 nvarchar(4000), @q109 nvarchar(4000), @q110 nvarchar(4000), 
		@q111 nvarchar(4000), @q112 nvarchar(4000), @q113 nvarchar(4000), @q114 nvarchar(4000), @q115 nvarchar(4000), @q116 nvarchar(4000), @q117 nvarchar(4000), @q118 nvarchar(4000), @q119 nvarchar(4000), @q120 nvarchar(4000), 
		@q121 nvarchar(4000), @q122 nvarchar(4000), @q123 nvarchar(4000), @q124 nvarchar(4000), @q125 nvarchar(4000), @q126 nvarchar(4000), @q127 nvarchar(4000), @q128 nvarchar(4000), @q129 nvarchar(4000), @q130 nvarchar(4000), 
		@q131 nvarchar(4000), @q132 nvarchar(4000), @q133 nvarchar(4000), @q134 nvarchar(4000), @q135 nvarchar(4000), @q136 nvarchar(4000), @q137 nvarchar(4000), @q138 nvarchar(4000), @q139 nvarchar(4000), @q140 nvarchar(4000), 
		@q141 nvarchar(4000), @q142 nvarchar(4000), @q143 nvarchar(4000), @q144 nvarchar(4000), @q145 nvarchar(4000), @q146 nvarchar(4000), @q147 nvarchar(4000), @q148 nvarchar(4000), @q149 nvarchar(4000), @q150 nvarchar(4000), 
		@q151 nvarchar(4000), @q152 nvarchar(4000), @q153 nvarchar(4000), @q154 nvarchar(4000), @q155 nvarchar(4000), @q156 nvarchar(4000), @q157 nvarchar(4000), @q158 nvarchar(4000), @q159 nvarchar(4000), @q160 nvarchar(4000), 
		@q161 nvarchar(4000), @q162 nvarchar(4000), @q163 nvarchar(4000), @q164 nvarchar(4000), @q165 nvarchar(4000), @q166 nvarchar(4000), @q167 nvarchar(4000), @q168 nvarchar(4000), @q169 nvarchar(4000), @q170 nvarchar(4000), 
		@q171 nvarchar(4000), @q172 nvarchar(4000), @q173 nvarchar(4000), @q174 nvarchar(4000), @q175 nvarchar(4000), @q176 nvarchar(4000), @q177 nvarchar(4000), @q178 nvarchar(4000), @q179 nvarchar(4000), @q180 nvarchar(4000), 
		@q181 nvarchar(4000), @q182 nvarchar(4000), @q183 nvarchar(4000), @q184 nvarchar(4000), @q185 nvarchar(4000), @q186 nvarchar(4000), @q187 nvarchar(4000), @q188 nvarchar(4000), @q189 nvarchar(4000), @q190 nvarchar(4000), 
		@q191 nvarchar(4000), @q192 nvarchar(4000), @q193 nvarchar(4000), @q194 nvarchar(4000), @q195 nvarchar(4000), @q196 nvarchar(4000), @q197 nvarchar(4000), @q198 nvarchar(4000), @q199 nvarchar(4000), @q200 nvarchar(4000), 
		@q201 nvarchar(4000), @q202 nvarchar(4000), @q203 nvarchar(4000), @q204 nvarchar(4000), @q205 nvarchar(4000), @q206 nvarchar(4000), @q207 nvarchar(4000), @q208 nvarchar(4000), @q209 nvarchar(4000), @q210 nvarchar(4000), 
		@q211 nvarchar(4000), @q212 nvarchar(4000), @q213 nvarchar(4000), @q214 nvarchar(4000), @q215 nvarchar(4000), @q216 nvarchar(4000), @q217 nvarchar(4000), @q218 nvarchar(4000), @q219 nvarchar(4000), @q220 nvarchar(4000), 
		@q221 nvarchar(4000), @q222 nvarchar(4000), @q223 nvarchar(4000), @q224 nvarchar(4000), @q225 nvarchar(4000), @q226 nvarchar(4000), @q227 nvarchar(4000), @q228 nvarchar(4000), @q229 nvarchar(4000), @q230 nvarchar(4000), 
		@q231 nvarchar(4000), @q232 nvarchar(4000), @q233 nvarchar(4000), @q234 nvarchar(4000), @q235 nvarchar(4000), @q236 nvarchar(4000), @q237 nvarchar(4000), @q238 nvarchar(4000), @q239 nvarchar(4000), @q240 nvarchar(4000), 
		@q241 nvarchar(4000), @q242 nvarchar(4000), @q243 nvarchar(4000), @q244 nvarchar(4000), @q245 nvarchar(4000), @q246 nvarchar(4000), @q247 nvarchar(4000), @q248 nvarchar(4000), @q249 nvarchar(4000), @q250 nvarchar(3999),
		@q251 nvarchar(1)

	/* initialize all vars */
	select @q1 = N'''', @q2 = N'''', @q3 = N'''', @q4 = N'''', @q5 = N'''', @q6 = N'''', @q7 = N'''', @q8 = N'''', @q9 = N'''', @q10 = N'''', 
		@q11 = N'''', @q12 = N'''', @q13 = N'''', @q14 = N'''', @q15 = N'''', @q16 = N'''', @q17 = N'''', @q18 = N'''', @q19 = N'''', @q20 = N'''', 
		@q21 = N'''', @q22 = N'''', @q23 = N'''', @q24 = N'''', @q25 = N'''', @q26 = N'''', @q27 = N'''', @q28 = N'''', @q29 = N'''', @q30 = N'''', 
		@q31 = N'''', @q32 = N'''', @q33 = N'''', @q34 = N'''', @q35 = N'''', @q36 = N'''', @q37 = N'''', @q38 = N'''', @q39 = N'''', @q40 = N'''', 
		@q41 = N'''', @q42 = N'''', @q43 = N'''', @q44 = N'''', @q45 = N'''', @q46 = N'''', @q47 = N'''', @q48 = N'''', @q49 = N'''', @q50 = N'''', 
		@q51 = N'''', @q52 = N'''', @q53 = N'''', @q54 = N'''', @q55 = N'''', @q56 = N'''', @q57 = N'''', @q58 = N'''', @q59 = N'''', @q60 = N'''', 
		@q61 = N'''', @q62 = N'''', @q63 = N'''', @q64 = N'''', @q65 = N'''', @q66 = N'''', @q67 = N'''', @q68 = N'''', @q69 = N'''', @q70 = N'''', 
		@q71 = N'''', @q72 = N'''', @q73 = N'''', @q74 = N'''', @q75 = N'''', @q76 = N'''', @q77 = N'''', @q78 = N'''', @q79 = N'''', @q80 = N'''', 
		@q81 = N'''', @q82 = N'''', @q83 = N'''', @q84 = N'''', @q85 = N'''', @q86 = N'''', @q87 = N'''', @q88 = N'''', @q89 = N'''', @q90 = N'''', 
		@q91 = N'''', @q92 = N'''', @q93 = N'''', @q94 = N'''', @q95 = N'''', @q96 = N'''', @q97 = N'''', @q98 = N'''', @q99 = N'''', @q100 = N'''', 
		@q101 = N'''', @q102 = N'''', @q103 = N'''', @q104 = N'''', @q105 = N'''', @q106 = N'''', @q107 = N'''', @q108 = N'''', @q109 = N'''', @q110 = N'''', 
		@q111 = N'''', @q112 = N'''', @q113 = N'''', @q114 = N'''', @q115 = N'''', @q116 = N'''', @q117 = N'''', @q118 = N'''', @q119 = N'''', @q120 = N'''', 
		@q121 = N'''', @q122 = N'''', @q123 = N'''', @q124 = N'''', @q125 = N'''', @q126 = N'''', @q127 = N'''', @q128 = N'''', @q129 = N'''', @q130 = N'''', 
		@q131 = N'''', @q132 = N'''', @q133 = N'''', @q134 = N'''', @q135 = N'''', @q136 = N'''', @q137 = N'''', @q138 = N'''', @q139 = N'''', @q140 = N'''', 
		@q141 = N'''', @q142 = N'''', @q143 = N'''', @q144 = N'''', @q145 = N'''', @q146 = N'''', @q147 = N'''', @q148 = N'''', @q149 = N'''', @q150 = N'''', 
		@q151 = N'''', @q152 = N'''', @q153 = N'''', @q154 = N'''', @q155 = N'''', @q156 = N'''', @q157 = N'''', @q158 = N'''', @q159 = N'''', @q160 = N'''', 
		@q161 = N'''', @q162 = N'''', @q163 = N'''', @q164 = N'''', @q165 = N'''', @q166 = N'''', @q167 = N'''', @q168 = N'''', @q169 = N'''', @q170 = N'''', 
		@q171 = N'''', @q172 = N'''', @q173 = N'''', @q174 = N'''', @q175 = N'''', @q176 = N'''', @q177 = N'''', @q178 = N'''', @q179 = N'''', @q180 = N'''', 
		@q181 = N'''', @q182 = N'''', @q183 = N'''', @q184 = N'''', @q185 = N'''', @q186 = N'''', @q187 = N'''', @q188 = N'''', @q189 = N'''', @q190 = N'''', 
		@q191 = N'''', @q192 = N'''', @q193 = N'''', @q194 = N'''', @q195 = N'''', @q196 = N'''', @q197 = N'''', @q198 = N'''', @q199 = N'''', @q200 = N'''', 
		@q201 = N'''', @q202 = N'''', @q203 = N'''', @q204 = N'''', @q205 = N'''', @q206 = N'''', @q207 = N'''', @q208 = N'''', @q209 = N'''', @q210 = N'''', 
		@q211 = N'''', @q212 = N'''', @q213 = N'''', @q214 = N'''', @q215 = N'''', @q216 = N'''', @q217 = N'''', @q218 = N'''', @q219 = N'''', @q220 = N'''', 
		@q221 = N'''', @q222 = N'''', @q223 = N'''', @q224 = N'''', @q225 = N'''', @q226 = N'''', @q227 = N'''', @q228 = N'''', @q229 = N'''', @q230 = N'''', 
		@q231 = N'''', @q232 = N'''', @q233 = N'''', @q234 = N'''', @q235 = N'''', @q236 = N'''', @q237 = N'''', @q238 = N'''', @q239 = N'''', @q240 = N'''', 
		@q241 = N'''', @q242 = N'''', @q243 = N'''', @q244 = N'''', @q245 = N'''', @q246 = N'''', @q247 = N'''', @q248 = N'''', @q249 = N'''', @q250 = N'''',
		@q251 = N'''''''' /* special ending for this process */

	select @qPosition = 1, @qValue = N'''', @hasErrorOccured = 0

	declare @SettingsID int, @sqlPTR binary(16), @sqlstring nvarchar(100), @index int
	select @index = 1
	DECLARE cSettingIDs CURSOR FOR
		SELECT acs.SettingsID from cs_ApplicationConfigurationSettings acs where acs.ApplicationType = 10

	open cSettingIDs
	fetch next from cSettingIDs into @SettingsID
	while @@fetch_status = 0
	begin
		set @q1 = N''exec cs_TEMP_FoldSpamConfiguration '' + cast(@SettingsID as nvarchar(10)) + N'', N''''''

		while @index <= 0x7ffffff
		begin
			select @qPosition = @qPosition + 1
			SELECT @qValue = (select replace( substring(acs.Settings, @index, 2000), N'''''''', N'''''''''''' )
				from cs_ApplicationConfigurationSettings acs where acs.SettingsID = @SettingsID AND acs.ApplicationType = 10)

			if @qValue is null OR datalength(@qValue) = 0 begin break end

			if @qPosition <= 100
			begin
				if @qPosition = 1 select @q1 = @qValue else if @qPosition = 2 select @q2 = @qValue else if @qPosition = 3 select @q3 = @qValue else if @qPosition = 4 select @q4 = @qValue else if @qPosition = 5 select @q5 = @qValue else if @qPosition = 6 select @q6 = @qValue else if @qPosition = 7 select @q7 = @qValue else if @qPosition = 8 select @q8 = @qValue else if @qPosition = 9 select @q9 = @qValue else if @qPosition = 10 select @q10 = @qValue 
				else if @qPosition = 11 select @q11 = @qValue else if @qPosition = 12 select @q12 = @qValue else if @qPosition = 13 select @q13 = @qValue else if @qPosition = 14 select @q14 = @qValue else if @qPosition = 15 select @q15 = @qValue else if @qPosition = 16 select @q16 = @qValue else if @qPosition = 17 select @q17 = @qValue else if @qPosition = 18 select @q18 = @qValue else if @qPosition = 19 select @q19 = @qValue else if @qPosition = 20 select @q20 = @qValue 
				else if @qPosition = 21 select @q21 = @qValue else if @qPosition = 22 select @q22 = @qValue else if @qPosition = 23 select @q23 = @qValue else if @qPosition = 24 select @q24 = @qValue else if @qPosition = 25 select @q25 = @qValue else if @qPosition = 26 select @q26 = @qValue else if @qPosition = 27 select @q27 = @qValue else if @qPosition = 28 select @q28 = @qValue else if @qPosition = 29 select @q29 = @qValue else if @qPosition = 30 select @q30 = @qValue 
				else if @qPosition = 31 select @q31 = @qValue else if @qPosition = 32 select @q32 = @qValue else if @qPosition = 33 select @q33 = @qValue else if @qPosition = 34 select @q34 = @qValue else if @qPosition = 35 select @q35 = @qValue else if @qPosition = 36 select @q36 = @qValue else if @qPosition = 37 select @q37 = @qValue else if @qPosition = 38 select @q38 = @qValue else if @qPosition = 39 select @q39 = @qValue else if @qPosition = 40 select @q40 = @qValue 
				else if @qPosition = 41 select @q41 = @qValue else if @qPosition = 42 select @q42 = @qValue else if @qPosition = 43 select @q43 = @qValue else if @qPosition = 44 select @q44 = @qValue else if @qPosition = 45 select @q45 = @qValue else if @qPosition = 46 select @q46 = @qValue else if @qPosition = 47 select @q47 = @qValue else if @qPosition = 48 select @q48 = @qValue else if @qPosition = 49 select @q49 = @qValue else if @qPosition = 50 select @q50 = @qValue 
				else if @qPosition = 51 select @q51 = @qValue else if @qPosition = 52 select @q52 = @qValue else if @qPosition = 53 select @q53 = @qValue else if @qPosition = 54 select @q54 = @qValue else if @qPosition = 55 select @q55 = @qValue else if @qPosition = 56 select @q56 = @qValue else if @qPosition = 57 select @q57 = @qValue else if @qPosition = 58 select @q58 = @qValue else if @qPosition = 59 select @q59 = @qValue else if @qPosition = 60 select @q60 = @qValue 
				else if @qPosition = 61 select @q61 = @qValue else if @qPosition = 62 select @q62 = @qValue else if @qPosition = 63 select @q63 = @qValue else if @qPosition = 64 select @q64 = @qValue else if @qPosition = 65 select @q65 = @qValue else if @qPosition = 66 select @q66 = @qValue else if @qPosition = 67 select @q67 = @qValue else if @qPosition = 68 select @q68 = @qValue else if @qPosition = 69 select @q69 = @qValue else if @qPosition = 70 select @q70 = @qValue 
				else if @qPosition = 71 select @q71 = @qValue else if @qPosition = 72 select @q72 = @qValue else if @qPosition = 73 select @q73 = @qValue else if @qPosition = 74 select @q74 = @qValue else if @qPosition = 75 select @q75 = @qValue else if @qPosition = 76 select @q76 = @qValue else if @qPosition = 77 select @q77 = @qValue else if @qPosition = 78 select @q78 = @qValue else if @qPosition = 79 select @q79 = @qValue else if @qPosition = 80 select @q80 = @qValue 
				else if @qPosition = 81 select @q81 = @qValue else if @qPosition = 82 select @q82 = @qValue else if @qPosition = 83 select @q83 = @qValue else if @qPosition = 84 select @q84 = @qValue else if @qPosition = 85 select @q85 = @qValue else if @qPosition = 86 select @q86 = @qValue else if @qPosition = 87 select @q87 = @qValue else if @qPosition = 88 select @q88 = @qValue else if @qPosition = 89 select @q89 = @qValue else if @qPosition = 90 select @q90 = @qValue 
				else if @qPosition = 91 select @q91 = @qValue else if @qPosition = 92 select @q92 = @qValue else if @qPosition = 93 select @q93 = @qValue else if @qPosition = 94 select @q94 = @qValue else if @qPosition = 95 select @q95 = @qValue else if @qPosition = 96 select @q96 = @qValue else if @qPosition = 97 select @q97 = @qValue else if @qPosition = 98 select @q98 = @qValue else if @qPosition = 99 select @q99 = @qValue else if @qPosition = 100 select @q100 = @qValue
			end
			else if @qPosition <= 200
			begin
				if @qPosition = 101 select @q101 = @qValue else if @qPosition = 102 select @q102 = @qValue else if @qPosition = 103 select @q103 = @qValue else if @qPosition = 104 select @q104 = @qValue else if @qPosition = 105 select @q105 = @qValue else if @qPosition = 106 select @q106 = @qValue else if @qPosition = 107 select @q107 = @qValue else if @qPosition = 108 select @q108 = @qValue else if @qPosition = 109 select @q109 = @qValue else if @qPosition = 110 select @q110 = @qValue
				else if @qPosition = 111 select @q111 = @qValue else if @qPosition = 112 select @q112 = @qValue else if @qPosition = 113 select @q113 = @qValue else if @qPosition = 114 select @q114 = @qValue else if @qPosition = 115 select @q115 = @qValue else if @qPosition = 116 select @q116 = @qValue else if @qPosition = 117 select @q117 = @qValue else if @qPosition = 118 select @q118 = @qValue else if @qPosition = 119 select @q119 = @qValue else if @qPosition = 120 select @q120 = @qValue
				else if @qPosition = 121 select @q121 = @qValue else if @qPosition = 122 select @q122 = @qValue else if @qPosition = 123 select @q123 = @qValue else if @qPosition = 124 select @q124 = @qValue else if @qPosition = 125 select @q125 = @qValue else if @qPosition = 126 select @q126 = @qValue else if @qPosition = 127 select @q127 = @qValue else if @qPosition = 128 select @q128 = @qValue else if @qPosition = 129 select @q129 = @qValue else if @qPosition = 130 select @q130 = @qValue 
				else if @qPosition = 131 select @q131 = @qValue else if @qPosition = 132 select @q132 = @qValue else if @qPosition = 133 select @q133 = @qValue else if @qPosition = 134 select @q134 = @qValue else if @qPosition = 135 select @q135 = @qValue else if @qPosition = 136 select @q136 = @qValue else if @qPosition = 137 select @q137 = @qValue else if @qPosition = 138 select @q138 = @qValue else if @qPosition = 139 select @q139 = @qValue else if @qPosition = 140 select @q140 = @qValue 
				else if @qPosition = 141 select @q141 = @qValue else if @qPosition = 142 select @q142 = @qValue else if @qPosition = 143 select @q143 = @qValue else if @qPosition = 144 select @q144 = @qValue else if @qPosition = 145 select @q145 = @qValue else if @qPosition = 146 select @q146 = @qValue else if @qPosition = 147 select @q147 = @qValue else if @qPosition = 148 select @q148 = @qValue else if @qPosition = 149 select @q149 = @qValue else if @qPosition = 150 select @q150 = @qValue 
				else if @qPosition = 151 select @q151 = @qValue else if @qPosition = 152 select @q152 = @qValue else if @qPosition = 153 select @q153 = @qValue else if @qPosition = 154 select @q154 = @qValue else if @qPosition = 155 select @q155 = @qValue else if @qPosition = 156 select @q156 = @qValue else if @qPosition = 157 select @q157 = @qValue else if @qPosition = 158 select @q158 = @qValue else if @qPosition = 159 select @q159 = @qValue else if @qPosition = 160 select @q160 = @qValue 
				else if @qPosition = 161 select @q161 = @qValue else if @qPosition = 162 select @q162 = @qValue else if @qPosition = 163 select @q163 = @qValue else if @qPosition = 164 select @q164 = @qValue else if @qPosition = 165 select @q165 = @qValue else if @qPosition = 166 select @q166 = @qValue else if @qPosition = 167 select @q167 = @qValue else if @qPosition = 168 select @q168 = @qValue else if @qPosition = 169 select @q169 = @qValue else if @qPosition = 170 select @q170 = @qValue 
				else if @qPosition = 171 select @q171 = @qValue else if @qPosition = 172 select @q172 = @qValue else if @qPosition = 173 select @q173 = @qValue else if @qPosition = 174 select @q174 = @qValue else if @qPosition = 175 select @q175 = @qValue else if @qPosition = 176 select @q176 = @qValue else if @qPosition = 177 select @q177 = @qValue else if @qPosition = 178 select @q178 = @qValue else if @qPosition = 179 select @q179 = @qValue else if @qPosition = 180 select @q180 = @qValue 
				else if @qPosition = 181 select @q181 = @qValue else if @qPosition = 182 select @q182 = @qValue else if @qPosition = 183 select @q183 = @qValue else if @qPosition = 184 select @q184 = @qValue else if @qPosition = 185 select @q185 = @qValue else if @qPosition = 186 select @q186 = @qValue else if @qPosition = 187 select @q187 = @qValue else if @qPosition = 188 select @q188 = @qValue else if @qPosition = 189 select @q189 = @qValue else if @qPosition = 190 select @q190 = @qValue 
				else if @qPosition = 191 select @q191 = @qValue else if @qPosition = 192 select @q192 = @qValue else if @qPosition = 193 select @q193 = @qValue else if @qPosition = 194 select @q194 = @qValue else if @qPosition = 195 select @q195 = @qValue else if @qPosition = 196 select @q196 = @qValue else if @qPosition = 197 select @q197 = @qValue else if @qPosition = 198 select @q198 = @qValue else if @qPosition = 199 select @q199 = @qValue else if @qPosition = 200 select @q200 = @qValue
			end else begin
				if @qPosition = 201 select @q201 = @qValue else if @qPosition = 202 select @q202 = @qValue else if @qPosition = 203 select @q203 = @qValue else if @qPosition = 204 select @q204 = @qValue else if @qPosition = 205 select @q205 = @qValue else if @qPosition = 206 select @q206 = @qValue else if @qPosition = 207 select @q207 = @qValue else if @qPosition = 208 select @q208 = @qValue else if @qPosition = 209 select @q209 = @qValue else if @qPosition = 210 select @q210 = @qValue 
				else if @qPosition = 211 select @q211 = @qValue else if @qPosition = 212 select @q212 = @qValue else if @qPosition = 213 select @q213 = @qValue else if @qPosition = 214 select @q214 = @qValue else if @qPosition = 215 select @q215 = @qValue else if @qPosition = 216 select @q216 = @qValue else if @qPosition = 217 select @q217 = @qValue else if @qPosition = 218 select @q218 = @qValue else if @qPosition = 219 select @q219 = @qValue else if @qPosition = 220 select @q220 = @qValue 
				else if @qPosition = 221 select @q221 = @qValue else if @qPosition = 222 select @q222 = @qValue else if @qPosition = 223 select @q223 = @qValue else if @qPosition = 224 select @q224 = @qValue else if @qPosition = 225 select @q225 = @qValue else if @qPosition = 226 select @q226 = @qValue else if @qPosition = 227 select @q227 = @qValue else if @qPosition = 228 select @q228 = @qValue else if @qPosition = 229 select @q229 = @qValue else if @qPosition = 230 select @q230 = @qValue 
				else if @qPosition = 231 select @q231 = @qValue else if @qPosition = 232 select @q232 = @qValue else if @qPosition = 233 select @q233 = @qValue else if @qPosition = 234 select @q234 = @qValue else if @qPosition = 235 select @q235 = @qValue else if @qPosition = 236 select @q236 = @qValue else if @qPosition = 237 select @q237 = @qValue else if @qPosition = 238 select @q238 = @qValue else if @qPosition = 239 select @q239 = @qValue else if @qPosition = 240 select @q240 = @qValue 
				else if @qPosition = 241 select @q241 = @qValue else if @qPosition = 242 select @q242 = @qValue else if @qPosition = 243 select @q243 = @qValue else if @qPosition = 244 select @q244 = @qValue else if @qPosition = 245 select @q245 = @qValue else if @qPosition = 246 select @q246 = @qValue else if @qPosition = 247 select @q247 = @qValue else if @qPosition = 248 select @q248 = @qValue else if @qPosition = 249 select @q249 = @qValue else if @qPosition = 250 select @q250 = @qValue
				
				if @qPosition > 250
				begin
					raiserror(''Internal Error : Command buffer limit of ~1MB has been reached! Resultset will not be executed.'', 16, -1)
					select @hasErrorOccured = 1
				end
			end

			if @hasErrorOccured = 1 begin break end

			select @index = @index + 2000, @qValue = null
		end

		if @hasErrorOccured = 1 begin break end

		/* concat all buffers and execute */
		exec(@q1+@q2+@q3+@q4+@q5+@q6+@q7+@q8+@q9+@q10+
			@q11+@q12+@q13+@q14+@q15+@q16+@q17+@q18+@q19+@q20+
			@q21+@q22+@q23+@q24+@q25+@q26+@q27+@q28+@q29+@q30+
			@q31+@q32+@q33+@q34+@q35+@q36+@q37+@q38+@q39+@q40+
			@q41+@q42+@q43+@q44+@q45+@q46+@q47+@q48+@q49+@q50+
			@q51+@q52+@q53+@q54+@q55+@q56+@q57+@q58+@q59+@q60+
			@q61+@q62+@q63+@q64+@q65+@q66+@q67+@q68+@q69+@q70+
			@q71+@q72+@q73+@q74+@q75+@q76+@q77+@q78+@q79+@q80+
			@q81+@q82+@q83+@q84+@q85+@q86+@q87+@q88+@q89+@q90+
			@q91+@q92+@q93+@q94+@q95+@q96+@q97+@q98+@q99+@q100+
			@q101+@q102+@q103+@q104+@q105+@q106+@q107+@q108+@q109+@q110+
			@q111+@q112+@q113+@q114+@q115+@q116+@q117+@q118+@q119+@q120+
			@q121+@q122+@q123+@q124+@q125+@q126+@q127+@q128+@q129+@q130+
			@q131+@q132+@q133+@q134+@q135+@q136+@q137+@q138+@q139+@q140+
			@q141+@q142+@q143+@q144+@q145+@q146+@q147+@q148+@q149+@q150+
			@q151+@q152+@q153+@q154+@q155+@q156+@q157+@q158+@q159+@q160+
			@q161+@q162+@q163+@q164+@q165+@q166+@q167+@q168+@q169+@q170+
			@q171+@q172+@q173+@q174+@q175+@q176+@q177+@q178+@q179+@q180+
			@q181+@q182+@q183+@q184+@q185+@q186+@q187+@q188+@q189+@q190+
			@q191+@q192+@q193+@q194+@q195+@q196+@q197+@q198+@q199+@q200+
			@q201+@q202+@q203+@q204+@q205+@q206+@q207+@q208+@q209+@q210+
			@q211+@q212+@q213+@q214+@q215+@q216+@q217+@q218+@q219+@q220+
			@q221+@q222+@q223+@q224+@q225+@q226+@q227+@q228+@q229+@q230+
			@q231+@q232+@q233+@q234+@q235+@q236+@q237+@q238+@q239+@q240+
			@q241+@q242+@q243+@q244+@q245+@q246+@q247+@q248+@q249+@q250+
			@q251)

		select @index = 1

		select @q1 = N'''', @q2 = N'''', @q3 = N'''', @q4 = N'''', @q5 = N'''', @q6 = N'''', @q7 = N'''', @q8 = N'''', @q9 = N'''', @q10 = N'''', 
			@q11 = N'''', @q12 = N'''', @q13 = N'''', @q14 = N'''', @q15 = N'''', @q16 = N'''', @q17 = N'''', @q18 = N'''', @q19 = N'''', @q20 = N'''', 
			@q21 = N'''', @q22 = N'''', @q23 = N'''', @q24 = N'''', @q25 = N'''', @q26 = N'''', @q27 = N'''', @q28 = N'''', @q29 = N'''', @q30 = N'''', 
			@q31 = N'''', @q32 = N'''', @q33 = N'''', @q34 = N'''', @q35 = N'''', @q36 = N'''', @q37 = N'''', @q38 = N'''', @q39 = N'''', @q40 = N'''', 
			@q41 = N'''', @q42 = N'''', @q43 = N'''', @q44 = N'''', @q45 = N'''', @q46 = N'''', @q47 = N'''', @q48 = N'''', @q49 = N'''', @q50 = N'''', 
			@q51 = N'''', @q52 = N'''', @q53 = N'''', @q54 = N'''', @q55 = N'''', @q56 = N'''', @q57 = N'''', @q58 = N'''', @q59 = N'''', @q60 = N'''', 
			@q61 = N'''', @q62 = N'''', @q63 = N'''', @q64 = N'''', @q65 = N'''', @q66 = N'''', @q67 = N'''', @q68 = N'''', @q69 = N'''', @q70 = N'''', 
			@q71 = N'''', @q72 = N'''', @q73 = N'''', @q74 = N'''', @q75 = N'''', @q76 = N'''', @q77 = N'''', @q78 = N'''', @q79 = N'''', @q80 = N'''', 
			@q81 = N'''', @q82 = N'''', @q83 = N'''', @q84 = N'''', @q85 = N'''', @q86 = N'''', @q87 = N'''', @q88 = N'''', @q89 = N'''', @q90 = N'''', 
			@q91 = N'''', @q92 = N'''', @q93 = N'''', @q94 = N'''', @q95 = N'''', @q96 = N'''', @q97 = N'''', @q98 = N'''', @q99 = N'''', @q100 = N'''', 
			@q101 = N'''', @q102 = N'''', @q103 = N'''', @q104 = N'''', @q105 = N'''', @q106 = N'''', @q107 = N'''', @q108 = N'''', @q109 = N'''', @q110 = N'''', 
			@q111 = N'''', @q112 = N'''', @q113 = N'''', @q114 = N'''', @q115 = N'''', @q116 = N'''', @q117 = N'''', @q118 = N'''', @q119 = N'''', @q120 = N'''', 
			@q121 = N'''', @q122 = N'''', @q123 = N'''', @q124 = N'''', @q125 = N'''', @q126 = N'''', @q127 = N'''', @q128 = N'''', @q129 = N'''', @q130 = N'''', 
			@q131 = N'''', @q132 = N'''', @q133 = N'''', @q134 = N'''', @q135 = N'''', @q136 = N'''', @q137 = N'''', @q138 = N'''', @q139 = N'''', @q140 = N'''', 
			@q141 = N'''', @q142 = N'''', @q143 = N'''', @q144 = N'''', @q145 = N'''', @q146 = N'''', @q147 = N'''', @q148 = N'''', @q149 = N'''', @q150 = N'''', 
			@q151 = N'''', @q152 = N'''', @q153 = N'''', @q154 = N'''', @q155 = N'''', @q156 = N'''', @q157 = N'''', @q158 = N'''', @q159 = N'''', @q160 = N'''', 
			@q161 = N'''', @q162 = N'''', @q163 = N'''', @q164 = N'''', @q165 = N'''', @q166 = N'''', @q167 = N'''', @q168 = N'''', @q169 = N'''', @q170 = N'''', 
			@q171 = N'''', @q172 = N'''', @q173 = N'''', @q174 = N'''', @q175 = N'''', @q176 = N'''', @q177 = N'''', @q178 = N'''', @q179 = N'''', @q180 = N'''', 
			@q181 = N'''', @q182 = N'''', @q183 = N'''', @q184 = N'''', @q185 = N'''', @q186 = N'''', @q187 = N'''', @q188 = N'''', @q189 = N'''', @q190 = N'''', 
			@q191 = N'''', @q192 = N'''', @q193 = N'''', @q194 = N'''', @q195 = N'''', @q196 = N'''', @q197 = N'''', @q198 = N'''', @q199 = N'''', @q200 = N'''', 
			@q201 = N'''', @q202 = N'''', @q203 = N'''', @q204 = N'''', @q205 = N'''', @q206 = N'''', @q207 = N'''', @q208 = N'''', @q209 = N'''', @q210 = N'''', 
			@q211 = N'''', @q212 = N'''', @q213 = N'''', @q214 = N'''', @q215 = N'''', @q216 = N'''', @q217 = N'''', @q218 = N'''', @q219 = N'''', @q220 = N'''', 
			@q221 = N'''', @q222 = N'''', @q223 = N'''', @q224 = N'''', @q225 = N'''', @q226 = N'''', @q227 = N'''', @q228 = N'''', @q229 = N'''', @q230 = N'''', 
			@q231 = N'''', @q232 = N'''', @q233 = N'''', @q234 = N'''', @q235 = N'''', @q236 = N'''', @q237 = N'''', @q238 = N'''', @q239 = N'''', @q240 = N'''', 
			@q241 = N'''', @q242 = N'''', @q243 = N'''', @q244 = N'''', @q245 = N'''', @q246 = N'''', @q247 = N'''', @q248 = N'''', @q249 = N'''', @q250 = N'''',
			@q251 = N'''''''' /* special ending for this process */

		fetch next from cSettingIDs into @SettingsID
	end
	close cSettingIDs
	deallocate cSettingIDs

	if @hasErrorOccured = 1
	begin
		print ''An error occured - too much data to execute!''
	end
')

/* remove temp stored proc */
if object_id('cs_TEMP_FoldSpamConfiguration', 'P') IS NOT NULL
	exec ('drop procedure cs_TEMP_FoldSpamConfiguration')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.03
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN

--## Schema Patch ##

exec sp_executesql N'ALTER TABLE cs_Messaging_Messages ALTER COLUMN Body ntext not null'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.04
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if object_id('cs_TemporaryUserTokens') IS NULL
	EXECUTE sp_executesql N'
	CREATE TABLE [dbo].[cs_TemporaryUserTokens] (
		[TemporaryUserTokenID] [int] IDENTITY (1, 1) NOT NULL ,
		[UserID] [int] NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[Token] [uniqueidentifier] NOT NULL ,
		[ExpirationDate] [datetime] NOT NULL 
	) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.05
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
	UPDATE cs_Censorship 
	SET Word = ''expression\(.*\);''
	WHERE Word = ''expression\(*.\);''

	UPDATE cs_Censorship 
	SET Word = ''expression\(.*\)''
	WHERE Word = ''expression\(*.\)''
')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.06
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
	insert into cs_ThemeConfigurationData (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues)
	select ''calypso'', SettingsID, SectionID, PropertyNames, PropertyValues
	from cs_ThemeConfigurationData
	where ThemeName = ''default''
	and SectionID not in (
		select T.SectionID from cs_ThemeConfigurationData T where T.ThemeName = ''calypso''
		)
')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.07
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_ModerationAudit]') AND [name] = N'IX_cs_ModerationAudit_UserID_ModerationAction')
	exec sp_executesql N'DROP INDEX [cs_ModerationAudit].[IX_cs_ModerationAudit_UserID_ModerationAction]'

exec sp_executesql N'create index IX_cs_ModerationAudit_UserID_ModerationAction on cs_ModerationAudit ( UserID, ModerationAction ) on [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.08
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.09
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

/* Manage updates to cs_Friends_xref */
IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_Friends_xrefId')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_Friends_xrefId]'

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'cs_Friends_xref' AND COLUMN_NAME = N'Friends_xrefId')
	exec sp_executesql N'alter table [cs_Friends_xref] drop column [Friends_xrefId]'

/* this is a temporary identity */
exec sp_executesql N'alter table [cs_Friends_xref] add [Friends_xrefId] int identity(1, 1) not null'

exec sp_executesql N'CREATE INDEX [IX_cs_Friends_xref_Friends_xrefId] ON [cs_Friends_xref]
(
	[Friends_xrefId]
)
ON [PRIMARY]'

set nocount on
exec sp_executesql N'delete from [cs_Friends_xref]
where exists (
	select 1 from [cs_Friends_xref] b
	where
		b.[UserID] = [cs_Friends_xref].[UserID]
		and b.[FriendUserID] = [cs_Friends_xref].[FriendUserID]
	group by
		b.[UserID], b.[FriendUserID]
	having
		min(b.[Friends_xrefId]) < [cs_Friends_xref].[Friends_xrefId]
)'
set nocount off

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_Friends_xrefId')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_Friends_xrefId]'

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'cs_Friends_xref' AND COLUMN_NAME = N'Friends_xrefId')
	exec sp_executesql N'alter table [cs_Friends_xref] drop column [Friends_xrefId]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IXUC_cs_Friends_xref_UserID_FriendUserID')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IXUC_cs_Friends_xref_UserID_FriendUserID]'

exec sp_executesql N'CREATE UNIQUE CLUSTERED INDEX [IXUC_cs_Friends_xref_UserID_FriendUserID] ON [cs_Friends_xref]
(
	[UserID]
	, [FriendUserID]
) WITH FILLFACTOR = 90
ON [PRIMARY]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_FriendUserID')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_FriendUserID]'

exec sp_executesql N'CREATE INDEX [IX_cs_Friends_xref_FriendUserID] ON [cs_Friends_xref]
(
	[FriendUserID]
) WITH FILLFACTOR = 90
ON [PRIMARY]'

exec sp_executesql N'dbcc dbreindex(''cs_Friends_xref'')'


/* Now manage updates to cs_SearchBarrel */
if exists (select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
	where tc.TABLE_NAME = N'cs_SearchBarrel' and tc.CONSTRAINT_NAME = 'IX_cs_SearchBarrel')
	exec sp_executesql N'ALTER TABLE [cs_SearchBarrel] DROP CONSTRAINT [IX_cs_SearchBarrel]'

exec sp_executesql N'ALTER TABLE [cs_SearchBarrel] ADD CONSTRAINT [IX_cs_SearchBarrel] UNIQUE NONCLUSTERED
(
	[WordHash] ASC,
	[PostID] ASC
) WITH FILLFACTOR = 90
ON [PRIMARY]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_SearchBarrel]') AND [name] = N'WordHash_SectionID_CLX_IDX')
	exec sp_executesql N'DROP INDEX [cs_SearchBarrel].[WordHash_SectionID_CLX_IDX]'

exec sp_executesql N'CREATE CLUSTERED INDEX [WordHash_SectionID_CLX_IDX] ON [cs_SearchBarrel] 
(
	[WordHash] ASC,
	[SectionID] ASC
) WITH FILLFACTOR = 90 ON [PRIMARY]'

exec sp_executesql N'dbcc dbreindex(''cs_SearchBarrel'')'



--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.10
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if object_id(N'cs_Visits', N'U') IS NOT NULL
	exec sp_executesql N'drop table [cs_Visits]'

if object_id(N'cs_VisitsDaily', N'U') IS NOT NULL
	exec sp_executesql N'drop table [cs_VisitsDaily]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.11
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
DECLARE @ApplicationID uniqueidentifier
DECLARE @Perm_RoleID uniqueidentifier

DECLARE settingsCursor CURSOR FOR
select aa.ApplicationId
from cs_SiteSettings ss
inner join aspnet_Applications aa on ss.ApplicationName = aa.ApplicationName

OPEN settingsCursor

FETCH NEXT FROM settingsCursor
INTO @ApplicationID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''groupadministrator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''GroupAdministrator'', N''groupadministrator'', N''Administration role for Groups'')
	END
	
	FETCH NEXT FROM settingsCursor
	INTO @ApplicationID
END

CLOSE settingsCursor
DEALLOCATE settingsCursor
')	

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.12
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
DELETE FROM cs_PrivateMessages WHERE UserID NOT IN (SELECT U.UserID FROM cs_Users U)
')	

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.0.13
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

delete from [dbo].[cs_Licenses] where LicenseID = '01B84EF8-EA06-42D5-9634-AD716B8445FB'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.14
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_RollerBlogPost' and convert(varbinary(12), COLUMN_NAME) = 0x550072006C0049006400)
begin
	print N'Renaming cs_RollerBlogPost.UrlId to UrlID'
	exec sp_rename N'cs_RollerBlogPost.UrlId', N'UrlID_TEMP'
	exec sp_rename N'cs_RollerBlogPost.UrlID_TEMP', N'UrlID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(10), COLUMN_NAME) = 0x750072006C0049004400)
begin
	print N'Renaming cs_UrlRedirects.urlID to UrlID'
	exec sp_rename N'cs_UrlRedirects.urlID', N'UrlID_TEMP'
	exec sp_rename N'cs_UrlRedirects.UrlID_TEMP', N'UrlID'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(6), COLUMN_NAME) = 0x750072006C00)
begin
	print N'Renaming cs_UrlRedirects.url to Url'
	exec sp_rename N'cs_UrlRedirects.url', N'Url_TEMP'
	exec sp_rename N'cs_UrlRedirects.Url_TEMP', N'Url'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(22), COLUMN_NAME) = 0x69006D007000720065007300730069006F006E007300)
begin
	print N'Renaming cs_UrlRedirects.impressions to Impressions'
	exec sp_rename N'cs_UrlRedirects.impressions', N'Impressions_TEMP'
	exec sp_rename N'cs_UrlRedirects.Impressions_TEMP', N'Impressions'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(22), COLUMN_NAME) = 0x6400650073006300720069007000740069006F006E00)
begin
	print N'Renaming cs_UrlRedirects.description to Description'
	exec sp_rename N'cs_UrlRedirects.description', N'Description_TEMP'
	exec sp_rename N'cs_UrlRedirects.Description_TEMP', N'Description'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UserReadPost' and convert(varbinary(12), COLUMN_NAME) = 0x550073006500720049006400)
begin
	print N'Renaming cs_UserReadPost.UserId to UserID'
	exec sp_rename N'cs_UserReadPost.UserId', N'UserID_TEMP'
	exec sp_rename N'cs_UserReadPost.UserID_TEMP', N'UserID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Users_OpenID' and convert(varbinary(12), COLUMN_NAME) = 0x550073006500720049006400)
begin
	print N'Renaming cs_Users_OpenID.UserId to UserID'
	exec sp_rename N'cs_Users_OpenID.UserId', N'UserID_TEMP'
	exec sp_rename N'cs_Users_OpenID.UserID_TEMP', N'UserID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Thread_Daily_Stats' and convert(varbinary(18), COLUMN_NAME) = 0x530065006300740069006F006E0049006400)
begin
	print N'Renaming cs_Thread_Daily_Stats.SectionId to SectionID'
	exec sp_rename N'cs_Thread_Daily_Stats.SectionId', N'SectionID_TEMP'
	exec sp_rename N'cs_Thread_Daily_Stats.SectionID_TEMP', N'SectionID'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Thread_Daily_Stats' and convert(varbinary(16), COLUMN_NAME) = 0x54006800720065006100640049006400)
begin
	print N'Renaming cs_Thread_Daily_Stats.ThreadId to ThreadID'
	exec sp_rename N'cs_Thread_Daily_Stats.ThreadId', N'ThreadID_TEMP'
	exec sp_rename N'cs_Thread_Daily_Stats.ThreadID_TEMP', N'ThreadID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_AddonConfigurationData' and convert(varbinary(14), COLUMN_NAME) = 0x4100640064006F006E0049006400)
begin
	print N'Renaming cs_AddonConfigurationData.AddonId to AddonID'
	exec sp_rename N'cs_AddonConfigurationData.AddonId', N'AddonID_TEMP'
	exec sp_rename N'cs_AddonConfigurationData.AddonID_TEMP', N'AddonID'
end


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.15
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


exec('
declare
	@NodeOriginalEscaped nvarchar(128), @NodeNew nvarchar(128), @NodeName nvarchar(128)
	, @id int, @ptrSettings binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettings binary(16) not null
	, NodeStart int not null, NodeEnd int not null, NodeLength int not null
	, insert_offset AS NodeStart + NodeLength - 1
	, delete_length AS NodeEnd - (NodeStart + NodeLength)
)

set nocount on

select
	@NodeOriginalEscaped = N''default''
	, @NodeNew = N''hawaii''
	, @NodeName = N''DefaultTheme''

select
	db_name() DatabaseName, s.SettingsID, s.Settings
	, case when patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.Settings )<>0 then ''Updating'' else ''No Update'' end
from
	cs_ApplicationConfigurationSettings s
where
	s.ApplicationType in (1, 11)

insert into @t (ptrSettings, NodeStart, NodeEnd, NodeLength)
select
	TEXTPTR( s.Settings )
	, patindex( N''%<'' + @NodeName + N''>%'', s.Settings )
	, patindex( N''%</'' + @NodeName + N''>%'', s.Settings )
	, 2 + LEN( @NodeName )
from
	cs_ApplicationConfigurationSettings s
where
	s.Settings IS NOT NULL
	and patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.Settings ) <> 0
	and s.ApplicationType in (1, 11)

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break

	select @ptrSettings = t.ptrSettings, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id

	UPDATETEXT cs_ApplicationConfigurationSettings.Settings @ptrSettings @insert_offset @delete_length @NodeNew

	delete from @t where id = @id
end
')

exec('
declare
	@NodeOriginalEscaped nvarchar(128), @NodeNew nvarchar(128), @NodeName nvarchar(128)
	, @id int, @ptrSettingsXML binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettingsXML binary(16) not null
	, NodeStart int not null, NodeEnd int not null, NodeLength int not null
	, insert_offset AS NodeStart + NodeLength - 1
	, delete_length AS NodeEnd - (NodeStart + NodeLength)
)

set nocount on

select
	@NodeOriginalEscaped = N''default''
	, @NodeNew = N''hawaii''
	, @NodeName = N''DefaultTheme''

select
	db_name() DatabaseName, s.SettingsID, s.SettingsXML
	, case when patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.SettingsXML )<>0 then ''Updating'' else ''No Update'' end
from
	cs_SiteSettings s

insert into @t (ptrSettingsXML, NodeStart, NodeEnd, NodeLength)
select
	TEXTPTR( s.SettingsXML )
	, patindex( N''%<'' + @NodeName + N''>%'', s.SettingsXML )
	, patindex( N''%</'' + @NodeName + N''>%'', s.SettingsXML )
	, 2 + LEN( @NodeName )
from
	cs_SiteSettings s
where
	s.SettingsXML IS NOT NULL
	and patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.SettingsXML ) <> 0

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break

	select @ptrSettingsXML = t.ptrSettingsXML, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id
	
	UPDATETEXT cs_SiteSettings.SettingsXML @ptrSettingsXML @insert_offset @delete_length @NodeNew

	delete from @t where id = @id
end
')

exec(N'
declare @myTable table (id int not null, idx int not null, Item nvarchar(500) collate database_default)

declare @t table(
	id int identity(1, 1) not null
	, SectionID int not null
	, PName nvarchar(1000) collate database_default not null
	, PType nchar(1) collate database_default not null
	, PStart int not null, PLength int not null
	, PValue nvarchar(1000) collate database_default not null
	, PValueLen as ( len(PValue) )
	)

declare @s table(
	id int identity(1, 1) not null
	, SectionID int not null
	, ptrPNames binary(16) not null
	, PNamesLength int not null
	, ptrPValues binary(16) not null
	)

declare @frommarker int, @tomarker int, @strlen int, @item nvarchar(500)
	, @PName nvarchar(1000), @PValue nvarchar(1000)
	, @OriginalTheme nvarchar(100), @NewTheme nvarchar(100)
	, @id int, @mtId int, @mtx int
	, @SectionID int, @ptrvalPN binary(16), @ptrvalPV binary(16)

set nocount on
set ansi_warnings off

select
	@OriginalTheme = N''default''
	, @NewTheme = N''hawaii''
	, @id = 1

insert into @s (SectionID, ptrPNames, PNamesLength, ptrPValues)
select
	s.SectionID, TEXTPTR(s.PropertyNames), DATALENGTH(s.PropertyNames), TEXTPTR(s.PropertyValues)
from
	cs_Sections s
where
	s.PropertyNames is not null and DATALENGTH(s.PropertyNames) > 0
	and s.PropertyValues is not null and DATALENGTH(s.PropertyValues) > 0
	and s.PropertyNames like ''%Theme:S:%''
	and s.PropertyValues like ''%'' + @OriginalTheme + ''%''
	and s.ApplicationType in (1, 11)

print ''Possibly changing themes on ('' + cast(@@ROWCOUNT as varchar) + '') sections from '' + @OriginalTheme + '' to '' + @NewTheme

while (1 = 1)
begin
	select @SectionID = SectionID, @ptrvalPN = ptrPNames, @ptrvalPV = ptrPValues from @s where id = @id

	if @@rowcount = 0 begin break end

	select @frommarker=1, @tomarker=1, @mtId = 1, @mtx = 1
	delete from @myTable
	while (@tomarker > 0)
	begin
		select @tomarker = CHARINDEX (N'':'', PropertyNames, @frommarker)
			, @strlen = case when @tomarker > 0 then @tomarker - @frommarker else DATALENGTH(PropertyNames) - @frommarker + 1 end
			, @item = ltrim(rtrim(SUBSTRING (PropertyNames, @frommarker, @strlen)))
		from cs_Sections where SectionID = @SectionID
		insert into @myTable values(@mtId, @mtx, @item)
		select @mtId = case when @mtx % 4 = 0 then @mtId + 1 else @mtId end, @mtx = case @mtx when 4 then 1 else @mtx + 1 end, @frommarker = @tomarker + 1
	end

	insert into @t (SectionID, PName, PType, PStart, PLength, PValue)
	select
		@SectionID
		, min(case when idx = 1 then Item end), min(case when idx = 2 then Item end)
		, convert(int, min(case when idx = 3 then Item end)), convert(int, min(case when idx = 4 then Item end))
		, N''''
	from @myTable
	where coalesce(Item, N'''') <> N''''
	group by id

	update t set t.PValue = substring(s.PropertyValues, t.PStart + 1, t.PLength)
	from @t t inner join cs_Sections s on t.SectionID = s.SectionID

	update @t set PValue = @NewTheme where PName = N''Theme'' and PValue = @OriginalTheme and SectionID = @SectionID

	if @@ROWCOUNT > 0
	begin
		print ''Editing theme on SectionID '' + cast(@SectionID as varchar)
		DECLARE sectionCursor CURSOR FOR
		select t1.PName + N'':'' + t1.PType + N'':'' + convert(nvarchar, coalesce(sum(t2.PValueLen), 0)) + N'':'' + convert(nvarchar, t1.PValueLen) + N'':'', t1.PValue
		from @t t1 left outer join @t t2 on t1.SectionID = t2.SectionID and t1.id > t2.id
		where t1.SectionID = @SectionID
		group by t1.id, t1.SectionID, t1.PName, t1.PType, t1.PValueLen, t1.PValue
		order by t1.id

		updatetext cs_Sections.PropertyNames  @ptrvalPN 0 null N''''
		updatetext cs_Sections.PropertyValues @ptrvalPV 0 null N''''

		open sectionCursor
		fetch next from sectionCursor into @PName, @PValue
		while @@fetch_status = 0
		begin
			updatetext cs_Sections.PropertyNames  @ptrvalPN null 0 @PName
			updatetext cs_Sections.PropertyValues @ptrvalPV null 0 @PValue
			fetch next from sectionCursor into @PName, @PValue
		end
		close sectionCursor
		deallocate sectionCursor
	end else begin
		print ''No change for SectionID '' + cast(@SectionID as varchar)
	end

	set @id = @id + 1
end
set ansi_warnings on
set nocount off
')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.16
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


exec(N'
DELETE FROM cs_SectionMembers FROM cs_SectionMembers sm join cs_Sections s on sm.SectionID = s.SectionID  left outer join cs_UserProfile p on sm.UserID = p.UserID and s.SettingsID = p.SettingsID WHERE p.SettingsID is null
')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.0.17
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 0;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'alter table [cs_Messaging_ConversationParticipants] add [IsRead] [bit] NOT NULL CONSTRAINT [DF_cs_Messaging_ConversationParticipants_Read]  DEFAULT ((0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_4.1.00
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_Wikis]
(
	[WikiId] [int] IDENTITY (1, 1) NOT NULL,
	[HubId] [int] NULL,
	[Name] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_Wikis_Name] DEFAULT (''''),
	[Description] [nvarchar] (1000) NOT NULL CONSTRAINT [DF_cs_Wiki_Wikis_Description] DEFAULT (''''),
	[ApplicationKey] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_Wikis_ApplicationKey] DEFAULT (''''),
	[IsEnabled] [bit] NOT NULL CONSTRAINT [DF_cs_Wiki_Wikis_IsEnabled] DEFAULT (1),
	CONSTRAINT [PK_cs_Wiki_Wikis] PRIMARY KEY CLUSTERED ([WikiId]) ON [PRIMARY]
)
ON [PRIMARY]'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_Pages]
(
	[PageId] [int] IDENTITY (1, 1) NOT NULL,
	[WikiId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[ParentPageId] [int] NULL,
	[Title] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_Title] DEFAULT (''''),
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_Body] DEFAULT (''''),
	[FormattedBody] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_FormattedBody] DEFAULT (''''),
	[IsPublished] [bit] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_IsPublished] DEFAULT (1),
	[RatingCount] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_RatingCount] DEFAULT (0),
	[RatingSum] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_RatingSum] DEFAULT (0),
	[LastModifiedUtcDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_LastModifiedDate] DEFAULT (getdate()),
	CONSTRAINT [PK_cs_Wiki_Pages] PRIMARY KEY CLUSTERED ([PageId]) ON [PRIMARY]
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages] ADD
	CONSTRAINT [FK_cs_Wiki_Pages_cs_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[cs_Users] ([UserID]),
	CONSTRAINT [FK_cs_Wiki_Pages_cs_Wiki_Wikis] FOREIGN KEY ([WikiId]) REFERENCES [dbo].[cs_Wiki_Wikis] ([WikiId]) ON DELETE CASCADE,
	CONSTRAINT [FK_cs_Wiki_Pages_cs_Wiki_Pages] FOREIGN KEY ([ParentPageId]) REFERENCES [dbo].[cs_Wiki_Pages] ([PageId])'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageRatings]
(
	[PageId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Rating] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_PageRatings_Rating] DEFAULT (3),
	CONSTRAINT [PK_cs_Wiki_PageRatings] PRIMARY KEY CLUSTERED ([PageId], [UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]
)
ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRatings] ADD
	CONSTRAINT [FK_cs_Wiki_PageRatings_cs_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[cs_Users] ([UserID]),
	CONSTRAINT [FK_cs_Wiki_PageRatings_cs_Wiki_Pages] FOREIGN KEY ([PageId]) REFERENCES [dbo].[cs_Wiki_Pages] ([PageId]) ON DELETE CASCADE'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageComments]
(
	[PageCommentId] [int] IDENTITY (1, 1) NOT NULL,
	[PageId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_PageComments_Body] DEFAULT (''''),
	[FormattedBody] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_PageComments_FormattedBody] DEFAULT (''''),
	[RatingCount] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_PageComments_RatingCount] DEFAULT (0),
	[RatingSum] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_PageComments_RatingSum] DEFAULT (0),
	[PublishedUtcDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Wiki_PageComments_PublishedDate] DEFAULT (getdate()),
	CONSTRAINT [PK_cs_Wiki_PageComments] PRIMARY KEY CLUSTERED ([PageCommentId]) ON [PRIMARY]
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageComments] ADD
	CONSTRAINT [FK_cs_Wiki_PageComments_cs_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[cs_Users] ([UserID]),
	CONSTRAINT [FK_cs_Wiki_PageComments_cs_Wiki_Pages] FOREIGN KEY ([PageId]) REFERENCES [dbo].[cs_Wiki_Pages] ([PageId]) ON DELETE CASCADE'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageCommentRatings]
(
	[PageCommentId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Rating] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_PageCommentRatings_Rating] DEFAULT (3),
	CONSTRAINT [PK_cs_Wiki_PageCommentRatings] PRIMARY KEY CLUSTERED ([PageCommentId], [UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]
)
ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageCommentRatings] ADD
	CONSTRAINT [FK_cs_Wiki_PageCommentRatings_cs_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[cs_Users] ([UserID]),
	CONSTRAINT [FK_cs_Wiki_PageCommentRatings_cs_Wiki_PageComments] FOREIGN KEY ([PageCommentId]) REFERENCES [dbo].[cs_Wiki_PageComments] ([PageCommentId]) ON DELETE CASCADE'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageRevisions]
(
	[PageRevisionId] [int] IDENTITY (1, 1) NOT NULL,
	[PageId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Title] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_Title] DEFAULT (''''),
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_Body] DEFAULT (''''),
	[FormattedBody] [ntext] NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_FormattedBody] DEFAULT (''''),
	[LastModifiedUtcDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_LastModifiedDate] DEFAULT (getdate()),
	CONSTRAINT [PK_cs_Wiki_PageRevisions] PRIMARY KEY CLUSTERED ([PageRevisionId]) ON [PRIMARY]
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRevisions] ADD
	CONSTRAINT [FK_cs_Wiki_PageRevisions_cs_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[cs_Users] ([UserID]),
	CONSTRAINT [FK_cs_Wiki_PageRevisions_cs_Wiki_Pages] FOREIGN KEY ([PageId]) REFERENCES [dbo].[cs_Wiki_Pages] ([PageId]) ON DELETE CASCADE'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.01
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.01'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE cs_UserProfile
	ADD EnableFavoriteSharing bit DEFAULT 1 NOT NULL
'

EXECUTE sp_executesql N'
UPDATE cs_UserProfile
	SET EnableFavoriteSharing = 1
	WHERE FavoritesShared & 5 = 5
'

EXECUTE sp_executesql N'
ALTER TABLE dbo.cs_UserProfile
	DROP CONSTRAINT DF_cs_UserProfile_FavoritesShared
'

EXECUTE sp_executesql N'
ALTER TABLE dbo.cs_UserProfile
	DROP COLUMN FavoritesShared
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.02
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_Tags]
(
	[TagId] [int] IDENTITY (1, 1) NOT NULL,
	[Name] [nvarchar] (256) NOT NULL,
	[NameLowerCase] AS LOWER([Name]),
	CONSTRAINT [PK_cs_Wiki_Tags] PRIMARY KEY CLUSTERED ([TagId]) ON [PRIMARY]
)
ON [PRIMARY]'


EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageTags]
(
	[PageId] [int] NOT NULL,
	[TagId] [int] NOT NULL,
	CONSTRAINT [PK_cs_Wiki_PageTags] PRIMARY KEY CLUSTERED ([PageId], [TagId]) ON [PRIMARY]
)
ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageTags] ADD
	CONSTRAINT [FK_cs_Wiki_PageTags_cs_Wiki_Pages] FOREIGN KEY ([PageId]) REFERENCES [dbo].[cs_Wiki_Pages] ([PageId]) ON DELETE CASCADE'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageTags] ADD
	CONSTRAINT [FK_cs_Wiki_PageTags_cs_Wiki_Tags] FOREIGN KEY ([TagId]) REFERENCES [dbo].[cs_Wiki_Tags] ([TagId]) ON DELETE CASCADE'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.03
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
	ADD [PageKey] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_PageKey] DEFAULT ('''')'

EXECUTE sp_executesql N'
UPDATE [cs_Wiki_Pages]
SET [PageKey] = CONVERT(nvarchar, [PageId])'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
	DROP CONSTRAINT [DF_cs_Wiki_Pages_PageKey]'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.04
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
	ADD [RevisionCount] [int] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_RevisionCount]  DEFAULT ((1))'

EXECUTE sp_executesql N'
UPDATE [cs_Wiki_Pages] SET RevisionCount = 0'

EXECUTE sp_executesql N'
UPDATE [cs_Wiki_Pages] SET RevisionCount =
	(SELECT     COALESCE (COUNT(r.PageRevisionId), 0) AS cnt
	FROM          cs_Wiki_PageRevisions r
	WHERE r.PageId = [cs_Wiki_Pages].PageId)'
	
EXECUTE sp_executesql N'
UPDATE [cs_Wiki_Pages] SET RevisionCount = RevisionCount + 1'



--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.05
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec('
DECLARE @ApplicationID uniqueidentifier
DECLARE @SettingsID int
DECLARE @Perm_RoleID uniqueidentifier

DECLARE settingsCursor CURSOR FOR
select ss.SettingsID, aa.ApplicationId
from cs_SiteSettings ss
inner join aspnet_Applications aa on ss.ApplicationName = aa.ApplicationName

OPEN settingsCursor

FETCH NEXT FROM settingsCursor
INTO @SettingsID, @ApplicationID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''wikiadministrator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''WikiAdministrator'', N''wikiadministrator'', N''Administration role for Wikis'')
	END
	
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''wikimoderator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''WikiModerator'', N''wikimoderator'', N''Moderator role for Wikis'')
	END
	
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''wikicontributor'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''WikiContributor'', N''wikicontributor'', N''Contributor role for Wikis'')
	END

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Everyone''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000000000000000B, 0x0000700000000034 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Registered Users''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000020000000001F, 0xFFFFDFFFFFFFFFE0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''WikiContributor''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000020000000001F, 0xFFFFDFFFFFFFFFE0 )
	
	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''WikiModerator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000070000000003F, 0xFFFF8FFFFFFFFFC0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''WikiAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x010070000000003F, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''SystemAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x010070000000003F, 0 )

	FETCH NEXT FROM settingsCursor
	INTO @SettingsID, @ApplicationID
END

CLOSE settingsCursor
DEALLOCATE settingsCursor
')

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.06
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_Permissions](
	[WikiId] [int] NOT NULL,
	[RoleId] [uniqueidentifier] NOT NULL,
	[AllowMask] [binary](8) NOT NULL,
	[DenyMask] [binary](8) NOT NULL
CONSTRAINT [PK_cs_Wiki_Permissions] PRIMARY KEY CLUSTERED 
(
	[WikiId] ASC,
	[RoleId] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Permissions] ADD CONSTRAINT [FK_cs_Wiki_Permissions_WikiId] FOREIGN KEY([WikiId]) 
	REFERENCES [dbo].[cs_Wiki_Wikis] ([WikiId])'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.07
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
	ADD [IsLocked] [bit] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_IsLocked]  DEFAULT ((0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.08
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
	ADD [IsIndexed] [bit] NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_IsIndexed]  DEFAULT ((0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.09
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

/* temp identity */
EXECUTE sp_executesql N'
	ALTER TABLE [dbo].[cs_es_Search_RemoveQueue] ADD [TEMP_ID] [int] identity(1, 1) NOT NULL
'

/* remove any duplicates */
EXECUTE sp_executesql N'
	delete from [dbo].[cs_es_Search_RemoveQueue]
	where exists (
		select 1 from [dbo].[cs_es_Search_RemoveQueue] b
		where
			b.[PostID] = [dbo].[cs_es_Search_RemoveQueue].[PostID]
		group by
			b.[PostID]
		having
			[dbo].[cs_es_Search_RemoveQueue].[TEMP_ID] < max( b.[TEMP_ID] )
	)
'

/* remove the temp identity */
EXECUTE sp_executesql N'
	ALTER TABLE [dbo].[cs_es_Search_RemoveQueue] drop column [TEMP_ID]
'

/* add new column with constraint */
EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_es_Search_RemoveQueue]
	ADD [ApplicationType] [varchar] (50) NOT NULL CONSTRAINT [DF_cs_es_Search_RemoveQueue_ApplicationType] DEFAULT('''')'

/* update items with appropriate application type */
EXECUTE sp_executesql N'
	UPDATE [cs_es_Search_RemoveQueue] SET ApplicationType = 
		A.ApplicationName FROM [cs_es_Search_RemoveQueue] SR
		INNER JOIN [cs_Posts] P ON P.PostID = SR.PostID
		INNER JOIN [cs_Sections] S ON P.SectionID = S.SectionID 
		INNER JOIN [cs_ApplicationType] A ON A.ApplicationType = S.ApplicationType'

/* add new constraint */
EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_es_Search_RemoveQueue]
	ADD CONSTRAINT [PK_es_Search_RemoveQueue] PRIMARY KEY CLUSTERED 
(
	[PostID] ASC,
	[ApplicationType] ASC
) WITH FILLFACTOR = 90 ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.10
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Wiki_PageFollowers](
	[PageId] [int] NOT NULL,
	[UserId] [int] NOT NULL
CONSTRAINT [PK_cs_Wiki_PageFollowers] PRIMARY KEY CLUSTERED 
(
	[PageId] ASC,
	[UserId] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageFollowers] ADD CONSTRAINT [FK_cs_Wiki_PageFollowers_PageId] FOREIGN KEY([PageId]) 
	REFERENCES [dbo].[cs_Wiki_Pages] ([PageId])'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.11
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRevisions]
	ADD [RevisionNumber] [int] NOT NULL CONSTRAINT DF_cs_Wiki_PageRevisions_RevisionNumber DEFAULT 0'

EXECUTE sp_executesql N'
UPDATE cs_Wiki_PageRevisions
SET RevisionNumber = PageRevisionId'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.12
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Weblog_ContactRequests](
	[Id] [int] IDENTITY (1, 1) NOT NULL,
	[WeblogId] [int] NOT NULL,
	[Subject] [nvarchar] (256) NULL,
	[Name] [nvarchar] (256) NULL,
	[EmailAddress] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Weblog_ContactRequests_EmailAddress] DEFAULT (''''),
	[CreationDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Weblog_ContactRequests_CreationDate] DEFAULT (getdate()),
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Weblog_ContactRequests_Body] DEFAULT (''''),
	[IsModerated] [bit] NOT NULL CONSTRAINT [DF_cs_Weblog_ContactRequests_IsModerated] DEFAULT (0),
CONSTRAINT [PK_cs_Weblog_ContactRequests] PRIMARY KEY CLUSTERED 
(
	[Id] ASC,
	[WeblogId] ASC
)) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.13
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Hub_ContactRequests](
	[Id] [int] IDENTITY (1, 1) NOT NULL,
	[HubId] [int] NOT NULL,
	[Subject] [nvarchar] (256) NULL,
	[Name] [nvarchar] (256) NULL,
	[EmailAddress] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_EmailAddress] DEFAULT (''''),
	[CreationDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_CreationDate] DEFAULT (getdate()),
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_Body] DEFAULT (''''),
	[IsModerated] [bit] NOT NULL CONSTRAINT [DFcs_Hub_ContactRequests_IsModerated] DEFAULT (0),
CONSTRAINT [PK_cs_Hub_ContactRequests] PRIMARY KEY CLUSTERED 
(
	[Id] ASC,
	[HubId] ASC
)) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.14
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRevisions]
	ADD [PageKey] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_PageKey] DEFAULT ('''')'

EXECUTE sp_executesql N'
UPDATE [cs_Wiki_PageRevisions]
SET [PageKey] = p.[PageKey]
FROM [cs_Wiki_Pages] p
WHERE [cs_Wiki_PageRevisions].[PageId] = p.[PageId]'


EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRevisions]
	DROP CONSTRAINT [DF_cs_Wiki_PageRevisions_PageKey]'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.15
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_rename N'[dbo].[cs_Posts_Downloads].[IX_files_Downloads_PostID]', N'IX_cs_Posts_Downloads_PostID'

EXECUTE sp_rename N'[dbo].[cs_Posts_Downloads].[IX_files_Downloads_UserID]', N'IX_cs_Posts_Downloads_UserID'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.16
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'DECLARE @count int, @themeName nvarchar(255)

DECLARE @HubIds TABLE (
	/* this process depends on the IDENTITY value here starting on 1 and incrementing by 1 */
	IndexId int IDENTITY(1, 1) NOT NULL,
	HubId int NOT NULL
)

set @themeName = N''hawaii''

INSERT INTO @HubIds (HubId)
	SELECT T.SectionID as HubId
	FROM [cs_ThemeConfigurationData] T
	INNER JOIN cs_Sections S ON S.SectionID = T.SectionID AND S.ApplicationType = 11
	WHERE T.ThemeName = @themeName AND T.SectionID > -1

SET @count = @@ROWCOUNT

IF @count <> 0
begin
	DECLARE @widgetValue nvarchar(2000), @updatedWidgetValue nvarchar(2100), @valuesLength int, @widgetsValueLength int
	SET @widgetValue = N''<contentFragment type="CommunityServer.Wikis.Controls.PageFilesContentFragment, CommunityServer.Wikis" id="c383f66a-9c76-4b03-b940-c4717e608afb" configuration="fragmentTitle=Attachments&amp;listCssClass=CommonSidebarList" /><contentFragment type="CommunityServer.Wikis.Controls.PageDetailsContentFragment, CommunityServer.Wikis" id="b5920911-a4e3-4c3b-bd1d-fbabbb9a6278" configuration="fragmentTitle=Page+Details" />''
	SELECT @widgetsValueLength = (datalength(@widgetValue) / 2) + 2
	
	DECLARE @startIndex int, @lengthIndex int, @startValue int, @valuesOffset int, @valuesDeleteLength int, @oldLengthValue int
	DECLARE @lengthValue int, @sectionId int, @lengthDeleteLength int, @lengthValueVarchar nvarchar(256)
	DECLARE @valuesPtr varbinary(16), @namesPtr varbinary(16)
	
	DECLARE @otherStartIndexOld int, @otherStartIndex int, @otherStartLength int
	DECLARE @otherStartValue int, @otherStartDeleteLength int, @otherNewStartValue int
	DECLARE @otherNewStartValueVarchar nvarchar(200)
	
	while @count > 0
	begin
		SELECT @sectionId = HubId FROM @HubIds WHERE IndexId = @count
		SELECT @startIndex = CHARINDEX(N''DefaultGroupWidgets'', PropertyNames, 0) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		
		SELECT @startIndex = @startIndex + (datalength(N''DefaultGroupWidgets:S:'')/2)
		SELECT @lengthIndex = CHARINDEX(N'':'', PropertyNames, @startIndex) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		SELECT @startValue = CONVERT(int, SUBSTRING(PropertyNames, @startIndex, @lengthIndex - @startIndex)) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		
		SELECT @startIndex = CHARINDEX(N'':'', PropertyNames, @startIndex) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		SET @startIndex = @startIndex + 1
		
		SELECT @lengthIndex = CHARINDEX(N'':'', PropertyNames, @startIndex) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		SELECT @lengthValue = CONVERT(int, SUBSTRING(PropertyNames, @startIndex, @lengthIndex - @startIndex)) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		
		SELECT @valuesPtr = TEXTPTR([PropertyValues]), @namesPtr = TEXTPTR([PropertyNames]) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
		SET @lengthValueVarchar = CONVERT(nvarchar, @lengthValue)
		SELECT @lengthDeleteLength = datalength(@lengthValueVarchar) / 2
		SET @oldLengthValue = @lengthValue
		SET @lengthValue = @lengthValue + @widgetsValueLength - 2
		SET @lengthValueVarchar = CONVERT(nvarchar, @lengthValue)
		SET @startIndex = @startIndex - 1
		UPDATETEXT [cs_ThemeConfigurationData].[PropertyNames] @namesPtr @startIndex @lengthDeleteLength @lengthValueVarchar
		
		SELECT @valuesOffset = (@startValue + @oldLengthValue) - (datalength(N''</contentFragments>'')/2)
		SELECT @valuesDeleteLength = datalength(N''</contentFragments>'')/2
		SET @updatedWidgetValue = @widgetValue + N''</contentFragments>''
		
		UPDATETEXT [cs_ThemeConfigurationData].[PropertyValues] @valuesPtr @valuesOffset @valuesDeleteLength @updatedWidgetValue
		
		SET @otherStartIndex = @startIndex
		
		while 1 = 1
		begin
			SET @otherStartIndexOld = @otherStartIndex
			SELECT @otherStartIndex = CHARINDEX(N'':S:'', PropertyNames, @startIndex) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
			
			if @otherStartIndex IS NULL OR (@otherStartIndex <= @otherStartIndexOld + 3)
			    break;
			
			SET @otherStartIndex = @otherStartIndex + 3
			
			SELECT @otherStartLength = CHARINDEX(N'':'', PropertyNames, @otherStartIndex) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
			SELECT @otherStartValue = CONVERT(int, SUBSTRING(PropertyNames, @otherStartIndex, @otherStartLength - @otherStartIndex)) FROM [cs_ThemeConfigurationData] WHERE SectionID = @sectionId AND ThemeName = @themeName
			
			SELECT @otherStartDeleteLength = datalength(CONVERT(nvarchar, @otherStartValue)) / 2
			SELECT @otherNewStartValue = @otherStartValue + @widgetsValueLength - 2
			
			SET @otherNewStartValueVarchar = CONVERT(nvarchar, @otherNewStartValue)
			
			SET @otherStartIndex = @otherStartIndex - 1
			UPDATETEXT [cs_ThemeConfigurationData].[PropertyNames] @namesPtr @otherStartIndex @otherStartDeleteLength @otherNewStartValueVarchar
		end
		
		SET @count = @count - 1
	end
end'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.17
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'CREATE INDEX [IX_cs_Wiki_PageComments] ON [dbo].[cs_Wiki_PageComments]([PageId]) ON [PRIMARY]'

EXECUTE sp_executesql N'CREATE INDEX [IX_cs_Wiki_Tags_Name] ON [dbo].[cs_Wiki_Tags]([Name]) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.18
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.18'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 18;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


if object_id('FK_cs_Wiki_PageFollowers_PageId', 'F') is not null
	EXECUTE sp_executesql N'ALTER TABLE cs_Wiki_PageFollowers DROP CONSTRAINT FK_cs_Wiki_PageFollowers_PageId'

EXECUTE sp_executesql N'ALTER TABLE cs_Wiki_PageFollowers ADD CONSTRAINT
	FK_cs_Wiki_PageFollowers_PageId FOREIGN KEY
	(
	PageId
	) REFERENCES cs_Wiki_Pages
	(
	PageId
	)ON DELETE  CASCADE'

if object_id('FK_cs_Wiki_Permissions_WikiId', 'F') is not null
	EXECUTE sp_executesql N'ALTER TABLE cs_Wiki_Permissions DROP CONSTRAINT FK_cs_Wiki_Permissions_WikiId'

EXECUTE sp_executesql N'ALTER TABLE cs_Wiki_Permissions ADD CONSTRAINT
	FK_cs_Wiki_Permissions_WikiId FOREIGN KEY
	(
	WikiId
	) REFERENCES cs_Wiki_Wikis
	(
	WikiId
	)ON DELETE  CASCADE'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.19
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.19'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 19;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


EXECUTE sp_executesql N'drop index [dbo].[cs_ThreadsRead].[IX_PostsRead]'

EXECUTE sp_executesql N'CREATE CLUSTERED INDEX [IX_PostsRead] ON [dbo].[cs_ThreadsRead]
(
	[UserID] ASC
	, [ThreadID] ASC
)WITH FILLFACTOR = 90 ON [PRIMARY]'

execute sp_executesql N'dbcc dbreindex (''dbo.cs_ThreadsRead'')'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.20
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.20'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 20;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
	DECLARE @SectionIds TABLE (
		SectionId int NOT NULL
	)
	
	INSERT INTO @SectionIds (SectionId)
	SELECT S.SectionID as SectionId
	FROM [cs_Sections] S
	WHERE S.HubSectionID > 0 and S.HubSectionID not in (select sx.SectionID from cs_Sections AS sx)

	DELETE FROM cs_SectionTokens WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_InkData WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	
	DELETE FROM cs_Links WHERE LinkCategoryID in (SELECT L.LinkCategoryID FROM cs_LinkCategories L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)
	DELETE FROM cs_LinkCategories WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_Moderators WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_TrackedSections WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_weblog_Weblogs WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_SectionsRead WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_ForumPingback WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_PostAttachments_TEMP WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	
	DELETE FROM cs_Posts_InCategories WHERE CategoryID in (SELECT L.CategoryID FROM cs_Post_Categories L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)
	DELETE FROM cs_Posts_InCategories WHERE PostID in (SELECT L.PostID FROM cs_Posts L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)
	DELETE FROM cs_Post_Categories_Parents WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_Post_Categories WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_ThreadsRead WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	
	DELETE FROM cs_nntp_Posts WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_nntp_Newsgroups WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_PostsArchive WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_SectionPermissions WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_FavoriteSections WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_SearchBarrel WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_PostEditNotes WHERE PostID in (SELECT L.PostID FROM cs_Posts L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)

	DELETE FROM cs_Posts WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	DELETE FROM cs_ThreadRating WHERE ThreadID in (SELECT L.ThreadID FROM cs_Threads L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)
	DELETE FROM cs_TrackedThreads WHERE ThreadID in (SELECT L.ThreadID FROM cs_Threads L INNER JOIN @SectionIds S on L.SectionID = S.SectionId)
	DELETE FROM cs_Threads WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
	
	DELETE FROM cs_Sections WHERE SectionID in (SELECT sx.SectionId FROM @SectionIds AS sx)
'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_4.1.21
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.21'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 21;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Wikis]
ADD [LastModifiedUtcDate] [datetime] NOT NULL CONSTRAINT DF_cs_Wiki_Wikis_LastModifiedDate DEFAULT GetUtcDate()'

EXECUTE sp_executesql N'
CREATE INDEX [IX_LastModified]
ON [dbo].[cs_Wiki_Wikis]
([WikiId] ASC, [LastModifiedUtcDate] ASC)
ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.22
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.22'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 22;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_PageRevisions]
ADD [Tags] [nvarchar](max) NOT NULL CONSTRAINT [DF_cs_Wiki_PageRevisions_Tags]  DEFAULT ('''')'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.23
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.23'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 23;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Threads]
ADD [ThreadType] int NOT NULL CONSTRAINT [DF_cs_Threads_ThreadType] DEFAULT (0)'

EXECUTE sp_executesql N'
set nocount on
set ansi_warnings off
declare @myTable table(id int not null,idx int not null,Item nvarchar(500) collate database_default)
declare @p table(Id int identity(1,1) not null,PostID int not null,ThreadID int not null,namesPtr binary(16) not null,valuesPtr binary(16) not null)
declare @t table(id int identity(1, 1) not null primary key
	,PostID int not null,ThreadID int not null
	,PName nvarchar(1000) collate database_default not null,PType nchar(1) collate database_default not null
	,PStart int not null, PLength int not null
	,PValue nvarchar(1000) collate database_default not null
	,PValueLen as (len(PValue))
)
declare
	@frommarker int,@tomarker int,@strlen int,@item nvarchar(500),@PName nvarchar(1000),@PValue nvarchar(1000)
	,@mtId int,@mtx int,@Id int,@PostID int,@ThreadID int,@namesPtr binary(16),@valuesPtr binary(16)

insert into @p(PostID,ThreadID,namesPtr,valuesPtr)
select p.PostID,p.ThreadID,textptr(p.PropertyNames),textptr(p.PropertyValues) from cs_Posts as p
where EXISTS(select 1 from cs_Sections as s where s.SettingsID=p.SettingsID and s.SectionID=p.SectionID AND s.ApplicationType=0)
	AND p.PostID=p.ParentID	AND p.PropertyNames like N''%ThreadType:%''

select @Id=1

while 1=1
begin
	select @PostID=p.PostID,@ThreadID=p.ThreadID from @p as p where p.Id=@Id
	if @@ROWCOUNT=0 begin break end
	select @frommarker=1,@tomarker=1,@mtId=1,@mtx=1
	delete from @myTable
	while(@tomarker > 0)
	begin
		select @tomarker=CHARINDEX(N'':'',PropertyNames,@frommarker)
			,@strlen=case when @tomarker>0 then @tomarker-@frommarker else DATALENGTH(PropertyNames)-@frommarker+1 end
			,@item=ltrim(rtrim(SUBSTRING(PropertyNames,@frommarker,@strlen)))
		from cs_Posts where PostID=@PostID
		insert into @myTable values(@mtId,@mtx,@item)
		select @mtId=case when @mtx%4=0 then @mtId+1 else @mtId end, @mtx=case @mtx when 4 then 1 else @mtx+1 end,@frommarker=@tomarker+1
	end
	insert into @t(PostID,ThreadID,PName,PType,PStart,PLength,PValue)
	select
		@PostID,@ThreadID,min(case when idx=1 then Item end),min(case when idx=2 then Item end)
		,convert(int,min(case when idx=3 then Item end)),convert(int,min(case when idx=4 then Item end))
		,N''''
	from @myTable where coalesce(Item,N'''')<>N'''' group by id
	set @Id=@Id+1
end

update t set t.PValue=substring(p.PropertyValues,t.PStart+1,t.PLength)
from @t t inner join cs_Posts p on t.PostID=p.PostID

update csT set csT.ThreadType=convert(int,t.ThreadTypeS)
from cs_Threads csT inner join(
	select tx.ThreadID,tx.PValue ThreadTypeS from @t as tx
	where tx.PName=N''ThreadType'' AND tx.PValue IS NOT NULL AND datalength(ltrim(rtrim(tx.PValue)))>0 AND ISNUMERIC(ltrim(rtrim(tx.PValue)))=1
) as t on csT.ThreadID=t.ThreadID

delete t from @t t where t.PName=N''ThreadType''

select @Id=1

while 1=1
begin
	select @PostID=p.PostID,@namesPtr=p.namesPtr,@valuesPtr=p.valuesPtr from @p as p where p.Id=@Id
	if @@ROWCOUNT=0 begin break end
	updatetext cs_Posts.PropertyNames  @namesPtr 0 null N''''
	updatetext cs_Posts.PropertyValues @valuesPtr 0 null N''''
	if exists(select 1 from @t t where t.PostID=@PostID)
	begin
		DECLARE pCursor CURSOR FOR
		select t1.PName+N'':''+t1.PType+N'':''+convert(nvarchar,coalesce(sum(t2.PValueLen),0))+N'':''+convert(nvarchar,t1.PValueLen)+N'':'',t1.PValue
		from @t t1 left outer join @t t2 on t1.PostID=t2.PostID and t1.id>t2.id
		where t1.PostID=@PostID
		group by t1.id,t1.PostID,t1.PName,t1.PType,t1.PValueLen,t1.PValue
		order by t1.id

		open pCursor
		fetch next from pCursor into @PName,@PValue
		while @@fetch_status = 0
		begin
			updatetext cs_Posts.PropertyNames  @namesPtr null 0 @PName
			updatetext cs_Posts.PropertyValues @valuesPtr null 0 @PValue
			select @PostID,@PName,@PValue
			fetch next from pCursor into @PName,@PValue
		end
		close pCursor
		deallocate pCursor
	end
	set @Id=@Id+1
end

set nocount off
set ansi_warnings on
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.24
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.24'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 24;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Forum_EmbeddedThreadUrl](
	[Url] [nvarchar](425) NOT NULL,
	[SectionID] [int] NOT NULL,
	[ThreadID] [int] NOT NULL,
 CONSTRAINT [PK_cs_EmbeddedThreadUrl] PRIMARY KEY CLUSTERED 
(
	[Url] ASC,
	[SectionID] ASC
)
) ON [PRIMARY]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.25
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.25'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 25;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_Wiki_Pages]
ADD [TotalViews] int NOT NULL CONSTRAINT [DF_cs_Wiki_Pages_TotalViews] DEFAULT (0)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.26
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.26'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 26;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[cs_Threads_Delete]''))
DROP TRIGGER [dbo].[cs_Threads_Delete]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.27
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.27'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 27;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

IF OBJECT_ID('[dbo].[aspnet_AnyDataInTables]') IS NOT NULL
	EXECUTE sp_executesql N'GRANT EXECUTE ON [dbo].[aspnet_AnyDataInTables] TO [public]'

IF OBJECT_ID('[dbo].[aspnet_Applications_CreateApplication]') IS NOT NULL
	EXECUTE sp_executesql N'GRANT EXECUTE ON [dbo].[aspnet_Applications_CreateApplication] TO [public]'

IF OBJECT_ID('[dbo].[aspnet_Setup_RemoveAllRoleMembers]') IS NOT NULL
	EXECUTE sp_executesql N'GRANT EXECUTE ON [dbo].[aspnet_Setup_RemoveAllRoleMembers] TO [public]'

IF OBJECT_ID('[dbo].[aspnet_Setup_RestorePermissions]') IS NOT NULL
	EXECUTE sp_executesql N'GRANT EXECUTE ON [dbo].[aspnet_Setup_RestorePermissions] TO [public]'

IF OBJECT_ID('[dbo].[aspnet_Users_CreateUser]') IS NOT NULL
	EXECUTE sp_executesql N'GRANT EXECUTE ON [dbo].[aspnet_Users_CreateUser] TO [public]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.28
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.28'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 28;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
DELETE FROM [dbo].[cs_SectionMembers] WHERE SectionID IN (SELECT SectionID FROM [dbo].[cs_Sections] WHERE ApplicationType = 0)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_4.1.29
* File Date: 11/6/2008 2:36
***********************************************/
Print 'Creating...cs_Schema_Patch_4.1.29'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 29;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

EXECUTE sp_executesql N'
declare @HubWikis table ( HubId int NOT NULL, WikiId int NOT NULL )

declare @Pages table ( NewWikiId int NOT NULL, PageId int NOT NULL, PageKey nvarchar(256) NOT NULL, ShouldChangePageKey bit NOT NULL)

set ansi_warnings off

/* determine which Hubs have duplicate Wikis and when the latest enabled Wiki for each Hub, taking the preference for latest */
insert into @HubWikis (HubId, WikiId)
select w.HubId, coalesce(max(case when w.IsEnabled = 1 then w.WikiId else null end), max(w.WikiId))
	from cs_Wiki_Wikis w
	where exists (
		select 1 from cs_Wiki_Wikis w2
		where w.HubId = w2.HubId and w2.HubId is not null
		group by w2.HubId
		having count(*) > 1
	)
	group by w.HubId

set ansi_warnings on

/* determine the pages that are affected by this scenario */
insert into @Pages (NewWikiId, PageId, PageKey, ShouldChangePageKey)
select hw.WikiId, p.PageId, p.PageKey, 0
from cs_Wiki_Wikis w
inner join cs_Wiki_Pages p on w.WikiId = p.WikiId
inner join @HubWikis hw on hw.HubId = w.HubId and w.WikiId <> hw.WikiId
where
	exists (
		select 1 from cs_Wiki_Wikis w2
		inner join cs_Wiki_Pages p2 on w2.WikiId = p2.WikiId
		where w.HubId = w2.HubId
			and w.WikiId <> w2.WikiId
			and p.PageKey = p2.PageKey
	)

/* decide which pagekeys should be updated */
update p set
	p.ShouldChangePageKey = 1
from @Pages p
inner join cs_Wiki_Wikis w1 on w1.WikiId = p.NewWikiId
inner join cs_Wiki_Wikis w2 on w1.HubId = w2.HubId
inner join cs_Wiki_Pages wp on w2.WikiId = wp.WikiId and wp.PageKey = p.PageKey

/* update page keys for pages in duplicated wikis with duplicated page keys to include the PageId */
update wp set
	wp.PageKey = wp.PageKey + nchar(32) + convert(nvarchar, wp.PageId)
from cs_Wiki_Pages wp
inner join @Pages p on wp.PageId = p.PageId and p.ShouldChangePageKey = 1

/* update page keys for page revisions in duplicated wikis with duplicated page keys to include the PageId */
update wpr set
	wpr.PageKey = wpr.PageKey + nchar(32) + convert(nvarchar, wpr.PageId)
from cs_Wiki_PageRevisions wpr
inner join @Pages p on wpr.PageId = p.PageId and p.ShouldChangePageKey = 1

/* update all pages in duplicated wikis to use the latest WikiID and set IsPublished to 0 */
update p set
	p.WikiId = hw.WikiId
	, p.IsPublished = 0
from cs_Wiki_Pages p
inner join cs_Wiki_Wikis w on p.WikiId = w.WikiId
inner join @HubWikis hw on w.HubId = hw.HubId and w.WikiId <> hw.WikiId

/* delete duplicated wikis */
delete cs_Wiki_Wikis
where WikiId in
(
	SELECT w.WikiId
	FROM cs_Wiki_Wikis w
	INNER JOIN @HubWikis hw on w.HubId = hw.HubId and w.WikiId <> hw.WikiId
)
'

exec sp_executesql N'
declare @Pages table (PageId int NOT NULL)

/* determine the pages that are affected by this scenario */
insert into @Pages (PageId)
select p.PageId
from cs_Wiki_Pages p
where
	exists (
		select 1 from cs_Wiki_Pages p2
		where p.WikiId = p2.WikiId
			and p.PageKey = p2.PageKey
		group by
			p2.WikiId, p2.PageKey
		having
			p.PageId > min(p2.PageId)
	)

/* update page keys for pages in duplicated wikis with duplicated page keys to include the PageId */
update wp set
	wp.PageKey = wp.PageKey + nchar(32) + convert(nvarchar, wp.PageId)
from cs_Wiki_Pages wp
inner join @Pages p on wp.PageId = p.PageId

/* update page keys for page revisions in duplicated wikis with duplicated page keys to include the PageId */
update wpr set
	wpr.PageKey = wpr.PageKey + nchar(32) + convert(nvarchar, wpr.PageId)
from cs_Wiki_PageRevisions wpr
inner join @Pages p on wpr.PageId = p.PageId
'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* View: cs_vw_EveryOne_Role
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_EveryOne_Role'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_EveryOne_Role]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_EveryOne_Role]
GO


/***********************************************
* View: cs_vw_HasReadForum
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_HasReadForum'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_HasReadForum]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_HasReadForum]
GO

Create View [dbo].[cs_vw_HasReadForum]

as
Select UserID, SectionID, MarkReadAfter, null as ThreadID, LastActivity FROM cs_SectionsRead
Union all
Select UserID, SectionID, null, ThreadID, null FROM cs_ThreadsRead

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_HasReadForum] to public
/***********************************************
* View: cs_vw_PostsWithAttachmentDetails
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_PostsWithAttachmentDetails'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_PostsWithAttachmentDetails]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_PostsWithAttachmentDetails]
GO

Create View [dbo].cs_vw_PostsWithAttachmentDetails
as

SELECT 
	p.[PostID], p.[ThreadID], p.[ParentID], p.[PostAuthor], p.[UserID], p.[SectionID], 
	p.[PostLevel], p.[SortOrder], p.[Subject], p.[PostDate], p.[IsApproved], p.[IsLocked], 
	p.[TotalViews], p.[Body], p.[FormattedBody], p.[IPAddress], p.[PostType], p.[PostMedia], p.[EmoticonID], 
	p.[PropertyNames] as PostPropertyNames, p.[PropertyValues] as PostPropertyValues, p.[SettingsID], p.[AggViews], p.[PostConfiguration], 
	p.[IsIndexed], p.[PostName], p.[UserTime], p.[ApplicationPostType], p.[Points], p.[RatingSum], 
	p.[TotalRatings], pa.[FileName] as AttachmentFilename, pa.[FileName], pa.[ContentType], pa.[ContentSize], pa.[Height], pa.[Width], pa.[IsRemote], pa.[FriendlyFileName], pa.Created,
	p.PostStatus, p.SpamScore

FROM cs_Posts p (nolock)
LEFT JOIN cs_PostAttachments pa (nolock) on p.PostID = pa.PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--Select * FROM cs_vw_PostsWithAttachmentDetails

grant select on [dbo].[cs_vw_PostsWithAttachmentDetails] to public



/***********************************************
* View: cs_vw_UsersInRoles
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_UsersInRoles'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_UsersInRoles]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_UsersInRoles]
GO


/***********************************************
* View: cs_vw_Users_FullUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_Users_FullUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_Users_FullUser]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_Users_FullUser]
GO

Create View [dbo].cs_vw_Users_FullUser
as

SELECT
	U.AppUserToken,
	U.Email,
	U.ForceLogin,
	U.IsAnonymous,
	U.LastAction,
	U.LastActivity,
	U.MembershipID,
	U.UserAccountStatus,
	U.UserID,
	U.UserName,
	U.CreateDate,
	UP.AllowSitePartnersToContact,
	UP.AllowSiteToContact,
	UP.EnableAvatar,
	UP.EnableDisplayInMemberList,
	UP.EnableDisplayUnreadThreadsOnly,
	UP.EnableEmail,
	UP.EnableHtmlEmail,
	UP.EnableOnlineStatus,
	UP.EnablePrivateMessages,
	UP.EnableThreadTracking,
	UP.EnableFavoriteSharing,
	UP.IsAvatarApproved,
	UP.IsIgnored,
	UP.ModerationLevel,
	UP.Points as UserPoints,
	UP.PostRank,
	UP.PostSortOrder,
	UP.PropertyNames as UserPropertyNames,
	UP.PropertyValues as UserPropertyValues,
	UP.PublicToken,
	UP.SettingsID,
	UP.TimeZone,
	UP.TotalPosts
FROM
	cs_Users U (nolock)
	INNER JOIN cs_UserProfile UP (nolock) ON U.UserID = UP.UserID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_Users_FullUser] to public

/***********************************************
* View: cs_vw_weblog_PostByYearMonth
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_vw_weblog_PostByYearMonth'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_weblog_PostByYearMonth]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_weblog_PostByYearMonth]
GO
create view dbo.cs_vw_weblog_PostByYearMonth
as
	select * from cs_weblog_PostByYearMonth_tbl01
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_weblog_PostByYearMonth] to public
go

-- now to attempt to populate the table initially
if object_id('dbo.cs_system_GenerateWeblogYearMonthDayList') IS NOT NULL
	exec dbo.cs_system_GenerateWeblogYearMonthDayList

go

/***********************************************
* Sproc: csm_EmailIDs_FindUserEmailID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_EmailIDs_FindUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_FindUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_FindUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_FindUserEmailID
	@EmailID bigint
AS

select E.UserID, E.SectionID, S.SettingsID
 from csm_EmailIDs E
 left join cs_Sections S on (S.SectionID = E.SectionID)
 where EmailID = @EmailID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_FindUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_GetUserEmailID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_EmailIDs_GetUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_GetUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_GetUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_GetUserEmailID
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

select EmailID from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_GetUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_UpdateUserEmailID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_EmailIDs_UpdateUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_UpdateUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_UpdateUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_UpdateUserEmailID
	@EmailID bigint,
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

delete from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID

insert into csm_EmailIDs (EmailID, UserID, SectionID) values (@EmailID, @UserID, @SectionID)
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_UpdateUserEmailID] to public
go
/***********************************************
* Sproc: csm_MailingLists_CreateUpdate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_MailingLists_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_CreateUpdate]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_CreateUpdate
(
	@SectionID		int,
	@EmailAddress		nvarchar(100),
	@IsMailingList		bit,
	@SettingsID		int
)
AS

if exists(select [SectionID] from csm_MailingLists where SectionID = @SectionID and SettingsID = @SettingsID)
begin
	update csm_MailingLists set EmailAddress = @EmailAddress, IsMailingList = @IsMailingList where SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	insert into csm_MailingLists (SectionID, EmailAddress, IsMailingList, SettingsID) values (@SectionID, @EmailAddress, @IsMailingList, @SettingsID)
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_CreateUpdate] to public
go
/***********************************************
* Sproc: csm_MailingLists_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_MailingLists_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_Get]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_Get
(
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Return all the sections that are mailing lists
SELECT
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnableAnonymousPosting,
	F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues,
	M.EmailAddress, M.IsMailingList, F.HubSectionID
FROM
	csm_MailingLists M
LEFT OUTER JOIN
	cs_Sections F ON F.SettingsID = M.SettingsID AND F.SectionID = M.SectionID
WHERE
	M.SettingsID = @SettingsID

exec csm_MailingList_Permissions_Get @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_Get] to public
go
/***********************************************
* Sproc: csm_MailingList_Permissions_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_MailingList_Permissions_Get'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[csm_MailingList_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[csm_MailingList_Permissions_Get]
GO

create procedure [dbo].[csm_MailingList_Permissions_Get]
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1,
		EmailAddress = null,
		ApplicationKey = null,
		P.RoleID, 
		P.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))
	FROM
		cs_ProductPermissions P
	WHERE 
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		M.EmailAddress,
		F.ApplicationKey,
		P.RoleID, 
		F.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_SectionPermissions P
	INNER JOIN
		csm_MailingLists M on P.SettingsID = M.SettingsID and P.SectionID = M.SectionID
	INNER JOIN
		cs_Sections F on P.SettingsID = F.SettingsID and P.SectionID = F.SectionID
	WHERE
		F.SettingsID = @SettingsID AND
		M.IsMailingList = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[csm_MailingList_Permissions_Get] to public
go
/***********************************************
* Sproc: csm_MessageID_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_MessageID_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MessageID_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MessageID_Add]
GO

CREATE PROCEDURE [dbo].csm_MessageID_Add
(
	@MessageID		nvarchar(100),
	@SettingsID		int,
	@PostID			int
)
AS

insert into csm_MessageIDs (MessageID, SettingsID, PostID) values (@MessageID, @SettingsID, @PostID)
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MessageID_Add] to public
go
/***********************************************
* Sproc: csm_MessageID_Check
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_MessageID_Check'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MessageID_Check]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MessageID_Check]
GO

CREATE PROCEDURE [dbo].csm_MessageID_Check
(
	@MessageID		nvarchar(100),
	@SettingsID		int
)
AS

declare @Check int
set @Check = (select 1 from csm_MessageIDs where MessageID = @MessageID and SettingsID = @SettingsID)
select isnull(@Check, 0) as 'Check'
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MessageID_Check] to public
go
/***********************************************
* Sproc: csm_Post_FindPostParent
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...csm_Post_FindPostParent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_Post_FindPostParent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_Post_FindPostParent]
GO

CREATE PROCEDURE [dbo].csm_Post_FindPostParent
(
	@PostID int=-1,
	@Subject nvarchar(256)=null,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @PostID <> -1
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.PostID = @PostID)
		select @PostID as PostID
	else	select -1 as PostID
end
else
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject)
		SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject
	else
		select -1 as PostID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_Post_FindPostParent] to public
go
/***********************************************
* Sproc: cs_ApiKeys_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApiKeys_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Create]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Create]
(
    @userId int,
    @value char(8),
    @name varchar(50)
)
AS

INSERT INTO cs_ApiKeys (UserID, [Value], [Name]) VALUES (@userId, @value, @name)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Create to public
go

/***********************************************
* Sproc: cs_ApiKeys_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApiKeys_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Delete]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Delete]
(
	@apiKeyId int
)
AS

DELETE FROM cs_ApiKeys WHERE ApiKeyID = @apiKeyId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Delete to public
go
/***********************************************
* Sproc: cs_ApiKeys_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApiKeys_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Get]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Get]
(
  @userId int
)
AS

SELECT * FROM cs_ApiKeys where UserID = @userId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Get to public
go
/***********************************************
* Sproc: cs_ApiKeys_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApiKeys_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Update]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Update]
(
    @apiKeyId int,
    @name varchar(50),
    @enabled bit
)
AS

UPDATE cs_ApiKeys SET
    [Name] = @name,
    [Enabled] = @enabled
WHERE ApiKeyID = @apiKeyId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Update to public
go

/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_CreateUpdate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_CreateUpdate --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint,
	@Settings NText = null
)

as

if exists(Select SettingsID FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType)
Begin
	Update cs_ApplicationConfigurationSettings
	Set Settings = @Settings
	where SettingsID = @SettingsID and ApplicationType = @ApplicationType
End
Else
Begin
	Insert cs_ApplicationConfigurationSettings (SettingsID, ApplicationType, Settings) 
	Values(@SettingsID, @ApplicationType, @Settings) 
End


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate] to public
go
/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_Get]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_Get --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint
)
as
Select Settings FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_Get] to public
go
/***********************************************
* Sproc: cs_Audit_Post
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Audit_Post'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Audit_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Audit_Post]
GO


CREATE proc [dbo].cs_Audit_Post
(
	@PostID		int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- Get the Post
	exec cs_forums_Post @PostID, null, 0, @SettingsID

	SELECT
		B.Description,
		U.UserName,
		A.*
	FROM
		cs_ModerationAudit A,
		cs_ModerationAction B,
		cs_vw_Users_FullUser U
	WHERE
		A.ModerationAction = B.ModerationAction AND
		A.SettingsID = B.SettingsID AND
		U.UserID = A.ModeratorID AND
		A.PostID = @PostID AND
		A.SettingsID = @SettingsID
	ORDER BY
		ModeratedOn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_Audit_Post to public
GO
/***********************************************
* Sproc: cs_BannedAddresses_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BannedAddresses_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddresses_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddresses_Get]
GO

CREATE Procedure [dbo].[cs_BannedAddresses_Get]
	@SettingsID	int
AS

	SELECT
		SettingsID
		, NetworkAddress
		, BannedDate
	FROM cs_BannedAddresses 
	WHERE SettingsID = @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddresses_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedAddress_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BannedAddress_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddress_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
GO

CREATE Procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
	  @SettingsID		INT
	, @NetworkAddress	NVARCHAR(50) 
	, @BannedDate		DATETIME
	, @ActionType		INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedAddresses where SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 1 
		else
		BEGIN
		
			INSERT INTO cs_BannedAddresses VALUES( @SettingsID, @NetworkAddress, @BannedDate )

			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedAddress record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedAddresses WHERE SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedAddresses SET
				SettingsID = @SettingsID,
				NetworkAddress = @NetworkAddress,
				BannedDate = @BannedDate
			WHERE
					SettingsID = @SettingsID 
				AND NetworkAddress = @NetworkAddress
				
			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedAddress record for SettingsID %d and NetworkAddress of %d', 16, 1, @SettingsID, @NetworkAddress )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedAddresses
		WHERE SettingsID = @SettingsID
			AND NetworkAddress = @NetworkAddress
			
		SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddress_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetworks_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BannedNetworks_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetworks_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetworks_Get]
GO

CREATE Procedure [dbo].[cs_BannedNetworks_Get]
	@SettingsID int
AS
	SELECT	SettingsID
		, BannedNetworkID
		, StartingAddress
		, EndingAddress
		, BannedDate
	FROM cs_BannedNetworks 
	WHERE SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_BannedNetworks_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetwork_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BannedNetwork_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetwork_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
GO


CREATE Procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
	@BannedNetworkID	INT = 0 OUTPUT,
	@SettingsID			INT,
	@StartingAddress	NVARCHAR(50)=  null,
	@EndingAddress		NVARCHAR(50) = null,
	@BannedDate			DATETIME,
	@ActionType			INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedNetworks where SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 1 
		ELSE
		BEGIN
		
			INSERT INTO cs_BannedNetworks (
				SettingsID,
				StartingAddress,
				EndingAddress,
				BannedDate
			) VALUES( 
				@SettingsID,
				@StartingAddress,
				@EndingAddress,
				@BannedDate
			)

			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedNetwork record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				SET @BannedNetworkID = @ID
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedNetworks WHERE SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedNetworks SET
				SettingsID		= @SettingsID,
				StartingAddress	= @StartingAddress,
				EndingAddress	= @EndingAddress,
				BannedDate		= @BannedDate
			WHERE
					SettingsID		= @SettingsID 
				AND BannedNetworkID = @BannedNetworkID
				
			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedNetworks record for SettingsID %d and BannedNetworkID of %d', 16, 1, @SettingsID, @BannedNetworkID )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedNetworks
		WHERE SettingsID		= @SettingsID
			AND BannedNetworkID = @BannedNetworkID
			
		SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedNetwork_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BlogActivityNightlyJob
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BlogActivityNightlyJob'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityNightlyJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityNightlyJob]
GO

CREATE    PROCEDURE [dbo].cs_BlogActivityNightlyJob

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	declare @RunDate datetime
	declare @JobRunDate datetime
	set @JobRunDate = getdate()
	set @RunDate = dateadd(d, -1, convert(datetime, (convert(varchar(10), @JobRunDate, 101))))
	 
        insert into [cs_BlogActivityReport] 
	select t.SectionID, t.ThreadID, @RunDate as CoverageDate
	 ,TotalViews  = (select t1.TotalViews from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayViews = (select coalesce((t1.TotalViews - yesterdays.TotalViews), t1.TotalViews) from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayComments  = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 4 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayTrackBacks = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 8 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
         ,IsPost   = (select case when p1.ApplicationPostType = 1 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,IsArticle  = (select case when p1.ApplicationPostType = 2 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,JobExecutionTimeStamp = @JobRunDate
         ,DayPosts = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 1 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayArticles = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 2 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	from dbo.cs_Threads t 
	-- Some existing CS databases have orphaned thread records that should have been deleted, so check to make sure at least one top-level post exists for the thread
	where exists(select PostID from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)

END






GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_BlogActivityNightlyJob to public
go

/***********************************************
* Sproc: cs_BlogActivityReportAggregate_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BlogActivityReportAggregate_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportAggregate_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportAggregate_Get]
GO
/***********************************************
* Sproc: cs_BlogActivityReportRecords_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_BlogActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_Censorships_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Censorships_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorships_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorships_Get]
GO


CREATE proc [dbo].cs_Censorships_Get
(
	@Word	nvarchar(256) = '',
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Censorship
	WHERE
		SettingsID = @SettingsID and (Word = @Word or (@Word = '' AND 1=1))


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Censorships_Get to public
go

/***********************************************
* Sproc: cs_Censorship_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Censorship_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorship_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorship_CreateUpdateDelete]
GO


CREATE proc [dbo].cs_Censorship_CreateUpdateDelete
(
	  @Word			nvarchar(256)
	, @DeleteWord 	bit = 0
	, @Replacement	nvarchar(256)
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteWord > 0 )
BEGIN
	DELETE FROM
		cs_Censorship
	WHERE
		Word = @Word and SettingsID = @SettingsID
	RETURN
END
ELSE
BEGIN
	UPDATE cs_Censorship SET
		Replacement	= @Replacement
	WHERE
		Word	= @Word and SettingsID = @SettingsID

	IF( @@rowcount = 0 )
	BEGIN
	INSERT INTO cs_Censorship (
		Word, Replacement, SettingsID
	) VALUES (
		@Word, @Replacement, @SettingsID
	)
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_Censorship_CreateUpdateDelete to public
GO
/***********************************************
* Sproc: cs_ConfigurableAddonData_CreateUpdate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ConfigurableAddonData_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ConfigurableAddonData_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ConfigurableAddonData_CreateUpdate]
GO

CREATE PROCEDURE dbo.cs_ConfigurableAddonData_CreateUpdate
	@AddonID uniqueidentifier,
	@SettingsID int,
	@AddonName varchar(255) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null
AS

if exists(select AddonID from cs_AddonConfigurationData where AddonID = @AddonID and SettingsID = @SettingsID)
	begin
		update cs_AddonConfigurationData
		set 	AddonName = @AddonName,
			PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues
		where AddonID = @AddonID and SettingsID = @SettingsID
	end else begin
		insert into cs_AddonConfigurationData (AddonID, AddonName, SettingsID, PropertyNames, PropertyValues) 
		values (@AddonID, @AddonName, @SettingsID, @PropertyNames, @PropertyValues)
	end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ConfigurableAddonData_CreateUpdate]  TO [public]
GO


/***********************************************
* Sproc: cs_ConfigurableAddonData_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ConfigurableAddonData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ConfigurableAddonData_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ConfigurableAddonData_Get]
GO

CREATE PROCEDURE dbo.cs_ConfigurableAddonData_Get
	@AddonID uniqueidentifier,
	@SettingsID int
AS
	select *
	from cs_AddonConfigurationData
	where AddonID = @AddonID and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ConfigurableAddonData_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Content_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Content_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_CreateUpdateDelete]
GO

CREATE PROCEDURE [dbo].cs_Content_CreateUpdateDelete
(
	@ContentID	int out,
	@Action 	int,
	@Name		nvarchar(256),
	@Title		nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@Hidden		bit,
	@UpdateDate 	bit,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	-- first check that content name is not already in use
	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content
		WHERE
			Name = @Name and SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	DECLARE @SortOrder int

	SELECT @SortOrder = coalesce(MAX(SortOrder) + 1, 1) FROM cs_Content where SettingsID = @SettingsID

	-- Create a new content
	INSERT INTO 
		cs_Content 
		(
			Name,
			Title,
			Body,
			FormattedBody,
			Hidden,
			SortOrder,
			SettingsID
		)
	VALUES 
		(
			@Name,
			@Title,
			@Body,
			@FormattedBody,
			@Hidden,
			@SortOrder,
			@SettingsID
		)
	
	SET @ContentID = SCOPE_IDENTITY()
END


-- UPDATE
ELSE IF @Action = 1
BEGIN

	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content c
		WHERE
			c.Name = @Name
			AND c.ContentID <> @ContentID and c.SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	IF EXISTS(SELECT NULL FROM cs_Content WHERE ContentID = @ContentID)
	BEGIN
		UPDATE
			cs_Content
		SET
			Name = @Name,
			Title = @Title,
			Body = @Body,
			FormattedBody = @FormattedBody
		WHERE
			ContentID = @ContentID and SettingsID = @SettingsID

		IF @UpdateDate = 1 
			EXEC cs_Content_UpdateDate @ContentID
	END

END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE cs_Content WHERE ContentID = @ContentID and SettingsID = @SettingsID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Content_GetIDFromName
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Content_GetIDFromName'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetIDFromName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetIDFromName]
GO
/***********************************************
* Sproc: cs_Content_GetList
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Content_GetList'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_Content_GetList]
(
	@SettingsID int
)
AS
	SELECT  
		*
	FROM 
		cs_Content c
	WHERE 
		c.Hidden = 0 and c.SettingsID = @SettingsID
	ORDER BY 
		LastModified DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Content_GetList] to public
go

/***********************************************
* Sproc: cs_Content_Load
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Content_Load'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_Load]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_Load]
GO

CREATE PROCEDURE [dbo].[cs_Content_Load]
(
	@ContentID int,
	@SettingsID int,
	@Name nvarchar(256) = null
)
AS
IF(@ContentID > 0)
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		ContentID = @ContentID and SettingsID = @SettingsID
END
ELSE
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		[Name] = @Name and SettingsID = @SettingsID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_Load to public
go



/***********************************************
* Sproc: cs_Content_UpdateDate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Content_UpdateDate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_UpdateDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_UpdateDate]
GO

CREATE PROCEDURE [dbo].[cs_Content_UpdateDate]
(
	@ContentID int
)
AS
	UPDATE
		cs_Content
	SET
		LastModified = getdate()
	WHERE
		ContentID = @ContentID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_UpdateDate to public
go
/***********************************************
* Sproc: cs_DisallowedNames_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_DisallowedNames_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedNames_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedNames_Get]
GO


CREATE PROCEDURE [dbo].cs_DisallowedNames_Get
(
	@SettingsID int
)
AS 
SET Transaction Isolation Level Read UNCOMMITTED

	SELECT 
		DisallowedName 
	FROM 
		cs_DisallowedNames
	WHERE
		SettingsID = @SettingsID 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedNames_Get to public
go
/***********************************************
* Sproc: cs_DisallowedName_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_DisallowedName_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedName_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedName_CreateUpdateDelete]
GO


CREATE PROCEDURE [dbo].cs_DisallowedName_CreateUpdateDelete
(
	@Name		nvarchar(64),
	@Replacement 	nvarchar(64),
	@DeleteName	bit = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteName > 0 )
BEGIN
	DELETE FROM
		cs_DisallowedNames
	WHERE
		DisallowedName = @Name and SettingsID = @SettingsID
END
ELSE 
BEGIN
		UPDATE cs_DisallowedNames SET
			DisallowedName = @Replacement
		WHERE
			DisallowedName = @Name and SettingsID = @SettingsID

	if( @@rowcount = 0 )
	BEGIN
		INSERT INTO cs_DisallowedNames (
			DisallowedName, SettingsID
		) VALUES (
			@Name, @SettingsID
		)
		
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedName_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Emails_SubscribedSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Emails_SubscribedSection'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_SubscribedSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_SubscribedSection]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_Emails_SubscribedSection]
(
	@PostID    int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Check if its a new thread or not
IF (@PostLevel = 1 AND @SectionID <> 0)
	BEGIN
		SELECT
			SubscriptionID, SectionID, Email, SubscriptionType, UserID, 
			SettingsID, DateSubscribed, SubscriptionFrequency, 1 as EnableHtmlEmail
		FROM 
			cs_SectionSubscriptions
		WHERE
			SectionID = @SectionID AND 
			SettingsID = @SettingsID AND
			DateUnsubscribed IS NULL AND
			IsConfirmed = 1 AND
			SubscriptionType & 3 <> 0
	END
ELSE IF (@SectionID <> 0)
	BEGIN
	-- this is a reply to an existing post (2)

		SELECT
			SubscriptionID, SectionID, Email, SubscriptionType, UserID, 
			SettingsID, DateSubscribed, SubscriptionFrequency, 1 as EnableHtmlEmail
		FROM 
			cs_SectionSubscriptions
		WHERE
			SectionID = @SectionID AND 
			SettingsID = @SettingsID AND
			DateUnsubscribed IS NULL AND
			IsConfirmed = 1 AND
			SubscriptionType & 3 = 3
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Emails_SubscribedSection] to public
go

/***********************************************
* Sproc: cs_Emails_TrackingSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Emails_TrackingSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingForum]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingSection]
GO


CREATE PROCEDURE [dbo].cs_Emails_TrackingSection
(
	@PostID    INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @HubSectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Get the hub SectionID
SELECT
  @HubSectionID = HubSectionID
FROM
  cs_Sections (nolock)
WHERE
  SectionID = @SectionID and SettingsID = @SettingsID

-- Check if its a new thread or not
IF (@PostLevel = 1)
BEGIN
	-- this is a new thread (1 & 2)
	
	IF (@SectionID <> 0) 
	BEGIN

		SELECT
			U.UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = F.UserID
		WHERE
			(F.SectionID = @SectionID or F.SectionID = @HubSectionID) AND
      F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
			U.EnableThreadTracking = 1 and
			U.EnableEmail = 1 and
			U.UserAccountStatus = 1 and
			F.SubscriptionType & 3 <> 0
	END
END
ELSE BEGIN
	-- this is a reply to an existing post (2)

	IF (@SectionID <> 0)
	BEGIN

		SELECT
			U.UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = F.UserID
		WHERE
			(F.SectionID = @SectionID or F.SectionID = @HubSectionID) AND
			U.SettingsID = @SettingsID and F.SettingsID = @SettingsID and 
			U.EnableThreadTracking = 1 and
			U.EnableEmail = 1 and
			U.UserAccountStatus = 1 and
			F.SubscriptionType & 3 = 3
	END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingSection to public
go
/***********************************************
* Sproc: cs_Emails_TrackingThread
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Emails_TrackingThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingThread]
GO



CREATE PROCEDURE [dbo].cs_Emails_TrackingThread
(
	@PostID INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

IF (@SectionID <> 0)
BEGIN

	SELECT
		U.UserID,
		U.Email, 
		U.EnableHtmlEmail,
		U.[PublicToken],
		U.[UserName]
	FROM 
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = T.UserID			
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
		U.EnableEmail = 1 and
		U.UserAccountStatus = 1 and
		U.EnableThreadTracking = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingThread to public
go
/***********************************************
* Sproc: cs_es_sprocs
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_es_sprocs'


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_QueueManager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_QueueManager]
GO


Create Proc [dbo].cs_es_Search_QueueManager
(
	@PostID int,
	@SettingsID int,
	@ApplicationType varchar(50) = NULL,
	@Add bit
)

as

if @Add = 1
Begin

	IF NOT EXISTS (SELECT PostID FROM [cs_es_Search_RemoveQueue] WHERE @PostID = PostID AND @SettingsID = SettingsID AND @ApplicationType = ApplicationType)
		INSERT INTO [cs_es_Search_RemoveQueue] (PostID, SettingsID, ApplicationType) VALUES (@PostID, @SettingsID, @ApplicationType)

End
ELSE
BEGIN
	DELETE FROM [cs_es_Search_RemoveQueue] WHERE PostID = @PostID and SettingsID = @SettingsID and (@ApplicationType IS NULL OR ApplicationType = @ApplicationType)
END


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_QueueManager to public
go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_Queue_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_Queue_Get]
GO


Create Proc [dbo].cs_es_Search_Queue_Get
(
	@SettingsID int
)

as

SELECT [PostID], [ApplicationType] FROM [cs_es_Search_RemoveQueue] WHERE SettingsID = @SettingsID


SET QUOTED_IDENTIFIER OFF 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_Queue_Get to public
go
/***********************************************
* Sproc: cs_EventLog_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_EventLog_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Add]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Add
(
	@EventType int,
	@Message ntext,
	@Category nvarchar(256),
	@MachineName nvarchar(256) = null,
	@EventID int,
	@SettingsID int
) AS

INSERT INTO [cs_EventLog]([Message], [Category], [SettingsID], [EventID], [EventType], [MachineName])
VALUES(  @Message, @Category, @SettingsID, @EventID, @EventType, @MachineName)


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Add to public
go
/***********************************************
* Sproc: cs_EventLog_Clear
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_EventLog_Clear'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Clear]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Clear]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Clear
(
	@Date datetime
) AS

Delete FROM cs_EventLog where  EventDate <= @Date

SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Clear to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntries
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_EventLog_GetEntries'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntries]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntries
(
	@SettingsID int = -1
)
AS
	SELECT TOP 1000
				EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.SettingsID = @SettingsID
		OR		EL.SettingsID = -1
	ORDER BY	EventLogID DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntries to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntry
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_EventLog_GetEntry'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntry]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntry
(
	@EntryID int
)
AS
	SELECT		EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.EventLogID = @EntryID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntry to public
go
/***********************************************
* Sproc: cs_Exceptions_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Exceptions_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Get]
GO




CREATE  procedure [dbo].cs_Exceptions_Get
(
	@SettingsID int,
	@ExceptionType int = 0,
	@MinFrequency int = 10,
	@SortOrder int = 1,
	@IncludeUnknown bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF @SortOrder = 1
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		DateLastOccurred DESC, Frequency DESC
ELSE
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		Frequency DESC, DateLastOccurred DESC
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Get to public
go
/***********************************************
* Sproc: cs_Exceptions_Log
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Exceptions_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Log]
GO




CREATE procedure [dbo].cs_Exceptions_Log
(
	@SettingsID int,
	@ExceptionHash varchar(128),
	@Category int,
	@Exception nvarchar(2000),
	@ExceptionMessage nvarchar(500),
	@UserAgent nvarchar(64),
	@IPAddress varchar(15),
	@HttpReferrer nvarchar (256),
	@HttpVerb nvarchar(24),
	@PathAndQuery nvarchar(512)
)
AS
BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

IF EXISTS (SELECT ExceptionID FROM cs_Exceptions WHERE ExceptionHash = @ExceptionHash and SettingsID = @SettingsID)

	UPDATE
		cs_Exceptions
	SET
		DateLastOccurred = GetDate(),
		Frequency = Frequency + 1
	WHERE
		ExceptionHash = @ExceptionHash and SettingsID = @SettingsID
ELSE
	INSERT INTO 
		cs_Exceptions
	(
		ExceptionHash,
		SettingsID,
		Category,
		Exception,
		ExceptionMessage,
		UserAgent,
		IPAddress,
		HttpReferrer,
		HttpVerb,
		PathAndQuery,
		DateCreated,
		DateLastOccurred,
		Frequency
	)
	VALUES
	(
		@ExceptionHash,
		@SettingsID,
		@Category,
		@Exception,
		@ExceptionMessage,
		@UserAgent,
		@IPAddress,
		@HttpReferrer,
		@HttpVerb,
		@PathAndQuery,
		GetDate(),
		GetDate(),
		1
	)

END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Log to public
go
/***********************************************
* Sproc: cs_Favorites_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorites_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_Get]
GO

CREATE procedure dbo.cs_Favorites_Get
(
	@FavoriteType	int,
	@UserID			int,
	@SettingsID		int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_Get] to public

/***********************************************
* Sproc: cs_Favorites_GetPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorites_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetPosts]
GO

CREATE procedure dbo.cs_Favorites_GetPosts
(
	@UserID		int,
	@ApplicationType int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	FP.ApplicationType,
	U.*,
	jP.TotalRatings AS PostTotalRatings,
	jP.RatingSum AS PostRatingSum,
	jP.PostID, 
	jP.ThreadID, 
	jP.ParentID, 
	jP.PostAuthor, 
	jP.UserID, 
	jP.SectionID, 
	jP.PostLevel, 
	jP.SortOrder, 
	jP.Subject, 
	jP.PostDate, 
	jP.IsApproved,
	jP.IsLocked as IsLocked,
	jP.IsIndexed, 
	jP.TotalViews as PostTotalViews,  --Conflicts with the Threads table which has precidence
	jP.Body, 
	jP.FormattedBody, 
	jP.IPAddress, 
	jP.PostType, 
	jP.PostMedia, 
	jP.EmoticonID, 
	jP.SettingsID, 
	jP.AggViews,
	jP.PostPropertyNames, 
	jP.PostPropertyValues,
	jP.PostConfiguration,
	jP.Points AS PostPoints,
	jP.PostStatus,
	jP.SpamScore,
	
	jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created, jP.Height, jP.Width,
	jP.PostName, 
	jP.ApplicationPostType, 
	jP.UserTime, 
	HasRead = 1,
	EditNotes = null, --(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),

	jT.PostAuthor as UserName,
	jT.TotalReplies as Replies, -- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1)

        jT.UserID as ThreadUserID,
        jT.PostAuthor as ThreadPostAuthor,
        jT.PostDate as ThreadPostDate,
        jT.ThreadDate,
        jT.LastViewedDate,
        jT.StickyDate,
        jT.TotalViews as TotalViews,
        jT.TotalReplies,
        jT.MostRecentPostAuthorID,
        jT.MostRecentPostAuthor,
        jT.MostRecentPostID,
        jT.IsLocked as ThreadIsLocked,
        jT.IsSticky,
        jT.IsApproved as ThreadIsApproved,
        jT.RatingSum,
        jT.TotalRatings,
        jT.ThreadEmoticonID,
        jT.ThreadStatus,
        jT.SettingsID
FROM
	cs_FavoritePosts FP
	JOIN cs_vw_PostsWithAttachmentDetails jP ON FP.PostID = jP.PostID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.UserID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE
	FP.OwnerID = @UserID
	AND FP.ApplicationType = @ApplicationType 
	AND jP.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID AND U.SettingsID = @SettingsID
ORDER BY
	Subject

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetPosts] to public

/***********************************************
* Sproc: cs_Favorites_GetSections
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorites_GetSections'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetSections]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetSections]
GO

CREATE procedure dbo.cs_Favorites_GetSections
(
	@UserID		int,
	@ApplicationType int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		F.SectionID,
		F.ApplicationType
	FROM
		cs_FavoriteSections F
	WHERE
		F.OwnerID = @UserID AND
		F.ApplicationType = @ApplicationType AND
		F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetSections] to public

/***********************************************
* Sproc: cs_Favorite_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorite_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Add]
GO

CREATE PROCEDURE dbo.cs_Favorite_Add
(
	@SettingsID			int,
	@UserID				int,
	@ItemID				int,
	@FavoriteType		int,
	@ApplicationType	int,
	@FavoriteID			int OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	IF @FavoriteType = 1		-- Section
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteSections F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	SectionID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteSections
				(OwnerID, SettingsID, SectionID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 4	-- Post
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoritePosts F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	PostID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoritePosts
				(OwnerID, SettingsID, PostID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Add] to public

/***********************************************
* Sproc: cs_Favorite_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorite_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Delete]
GO

CREATE PROCEDURE dbo.cs_Favorite_Delete
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	IF @FavoriteType = 1		-- Section

		DELETE
		FROM	cs_FavoriteSections
		WHERE	FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		DELETE
		FROM	cs_FavoritePosts
		WHERE	FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Delete] to public

/***********************************************
* Sproc: cs_Favorite_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorite_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Get]
GO

CREATE procedure dbo.cs_Favorite_Get
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Get] to public

/***********************************************
* Sproc: cs_Favorite_GetByUserItem
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Favorite_GetByUserItem'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_GetByUserItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_GetByUserItem]
GO

CREATE procedure dbo.cs_Favorite_GetByUserItem
(
	@SettingsID		int,
	@FavoriteType	int,
	@UserID			int,
	@ItemID			int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SectionID = @ItemID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.PostID = @ItemID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_GetByUserItem] to public

/***********************************************
* Sproc: cs_FeedPost_GetPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FeedPost_GetPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPost]
GO

/***********************************************
* Sproc: cs_FeedPost_GetPostFullDetails
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FeedPost_GetPostFullDetails'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPostFullDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPostFullDetails]
GO

/***********************************************
* Sproc: cs_FeedPost_UpdatePosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FeedPost_UpdatePosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_UpdatePosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_UpdatePosts]
GO
/***********************************************
* Sproc: cs_Feed_AddFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_AddFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_AddFeed]
GO

/***********************************************
* Sproc: cs_Feed_GetAll
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetAll'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetAll]
GO

/***********************************************
* Sproc: cs_Feed_GetAll_ModifiedSince
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetAll_ModifiedSince'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll_ModifiedSince]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[cs_Feed_GetAll_ModifiedSince]
GO
/***********************************************
* Sproc: cs_Feed_GetFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeed]
GO

/***********************************************
* Sproc: cs_Feed_GetFeedPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetFeedPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeedPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeedPosts]
GO

/***********************************************
* Sproc: cs_Feed_GetProperties
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetProperties'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetProperties]
GO

/***********************************************
* Sproc: cs_Feed_GetUsers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetUsers]
GO


/***********************************************
* Sproc: cs_Feed_MoveFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_MoveFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_MoveFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_MoveFeed]
GO

/***********************************************
* Sproc: cs_Feed_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_Update]
GO
/***********************************************
* Sproc: cs_Feed_UpdateFeedStatus
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Feed_UpdateFeedStatus'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_UpdateFeedStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_UpdateFeedStatus]
GO
/***********************************************
* Sproc: cs_Folder_AddFolder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_AddFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_AddFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_AddFolder]
GO


/***********************************************
* Sproc: cs_Folder_DeleteFolder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_DeleteFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_DeleteFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_DeleteFolder]
GO

/***********************************************
* Sproc: cs_Folder_GetFeeds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_GetFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFeeds]
GO

/***********************************************
* Sproc: cs_Folder_GetFolders
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_GetFolders'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFolders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFolders]
GO

/***********************************************
* Sproc: cs_Folder_GetSummary
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_GetSummary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetSummary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetSummary]
GO

/***********************************************
* Sproc: cs_Folder_MoveFolder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_MoveFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_MoveFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_MoveFolder]
GO

/***********************************************
* Sproc: cs_Folder_RenameFolder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Folder_RenameFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_RenameFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_RenameFolder]
GO

/***********************************************
* Sproc: cs_ForumPostActivityReportRecords_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ForumPostActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ForumPostActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ForumPostActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_forums_GetForumMessages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_GetForumMessages'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumMessages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumMessages]
GO


CREATE procedure [dbo].cs_forums_GetForumMessages
(
	@MessageID int = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @MessageID = 0
	SELECT 
		*
	FROM
		cs_Messages where SettingsID = @SettingsID
ELSE
	SELECT 
		*
	FROM
		cs_Messages
	WHERE
		MessageID = @MessageID and SettingsID = @SettingsID






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumMessages to public
go
/***********************************************
* Sproc: cs_forums_GetForumModerators
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_GetForumModerators'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumModerators]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumModerators]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumModerators
(
	@SectionID	int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- get a list of forum moderators
	SELECT 
		UserName, EmailNotification, DateCreated
	FROM 
		Moderators (nolock)
	WHERE 
		(SectionID = @SectionID OR SectionID = 0) and SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumModerators to public
go
/***********************************************
* Sproc: cs_forums_GetForumsModeratedByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_GetForumsModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsModeratedByUser]
GO






create procedure [dbo].cs_forums_GetForumsModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		SELECT SectionID, ForumName = 'All Forums', EmailNotification, DateCreated FROM Moderators (nolock)
		WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID
	ELSE
		-- get all of the forums moderated by this particular user
		SELECT
			M.SectionID,
			EmailNotification,
			ForumName = F.Name,
			M.DateCreated
		FROM Moderators M (nolock)
			INNER JOIN Forums F (nolock) ON
				F.SectionID = M.SectionID
		WHERE Username = @UserName and M.SettingsID = @SettingsID  and F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumsModeratedByUser to public
go
/***********************************************
* Sproc: cs_forums_GetForumsNotModeratedByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_GetForumsNotModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsNotModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsNotModeratedByUser]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumsNotModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF NOT EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		-- get all of the forums NOT moderated by this particular user
		SELECT SectionID =  0, ForumName =  'All Forums'
		UNION
		SELECT
			SectionID,
			ForumName = F.Name
		FROM Forums F (nolock) 
		WHERE SettingsID = @SettingsID and  SectionID NOT IN (SELECT SectionID FROM Moderators (nolock) WHERE Username = @UserName and SettingsID = @SettingsID)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetForumsNotModeratedByUser] to public
go
/***********************************************
* Sproc: cs_forums_GetUnmoderatedPostStatus
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_GetUnmoderatedPostStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetUnmoderatedPostStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetUnmoderatedPostStatus]
GO

CREATE PROCEDURE [dbo].cs_forums_GetUnmoderatedPostStatus
(
  @SectionID int = null,
  @UserName varchar,
  @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF(@SectionID = 0)
     SET @SectionID  = null

IF(@SectionID IS Null)
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
END
ELSE
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
     AND P.SectionID = @SectionID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetUnmoderatedPostStatus] to public
go
/***********************************************
* Sproc: cs_forums_Moderate_PostSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Moderate_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Moderate_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Moderate_PostSet]
GO
CREATE PROCEDURE dbo.cs_forums_Moderate_PostSet
(
	@SectionID		int,
	@PageIndex 		int,
	@PageSize 		int,
	@SortBy 		int,
	@SortOrder 		bit,
	@UserID 		int,
	@ReturnRecordCount 	bit,
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostDate DESC

-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration,P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = (SELECT count(UserID) from cs_Moderators where UserID = @UserID),
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Moderate_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Post
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Post'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Post]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE dbo.cs_forums_Post
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int,
	@MarkRead bit = 0,
	@IncludeCategories bit = 0
) 
AS

/* Procedure for getting basic information on a single post. */

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @NextThreadID int
DECLARE @PrevThreadID int
DECLARE @ThreadID int 
DECLARE @SectionID int
DECLARE @SortOrder int
DECLARE @IsApproved bit
DECLARE @IsAnonymousUser bit

SELECT 
	@ThreadID = ThreadID, 
	@SectionID = SectionID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Do we have an anonymous user?
SET @IsAnonymousUser = (SELECT IsAnonymous FROM cs_vw_Users_FullUser WHERE UserID = @UserID and SettingsID = @SettingsID)

DECLARE @TrackingThread bit

IF @TrackViews = 1
BEGIN
	-- Update the counter for the number of times this post is viewed
	UPDATE cs_Posts SET TotalViews = (TotalViews + 1) WHERE PostID = @PostID and SettingsID = @SettingsID
	UPDATE cs_Threads SET TotalViews = (TotalViews + 1) WHERE ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- Mark the post as read if this user is not anonymous
IF @MarkRead = 1 AND @IsAnonymousUser = 0 AND @IsApproved = 1
	EXECUTE cs_MarkThreadAsRead @ThreadID, @SectionID, @UserID, @SettingsID

---- get the anonymous user id for this site
--if( @UserID = 0 ) 
--BEGIN
--	exec cs_GetAnonymousUserID @SettingsID, @UserID output
--END
--
--
--IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID)
--	SELECT @TrackingThread = 1
--ELSE
--	SELECT @TrackingThread = 0

-- Get tracking thread information
IF (@IsAnonymousUser = 0) AND EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SET @TrackingThread = 1
ELSE
	SET @TrackingThread = 0

SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames as PostPropertyNames, P.PostPropertyValues as PostPropertyValues,
	P.PostConfiguration,P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	U.*, P.PostAuthor as [Username],
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	T.RatingSum,
	T.TotalRatings,
	HasRead = 0,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],P.Created, Height, Width,
--	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID),
	Replies = (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	--cs_Posts P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.UserID and P.SettingsID = @SettingsID and U.SettingsID = @SettingsID


IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name]
	FROM 
		cs_Posts_InCategories PIC
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		PIC.PostID = @PostID
End
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Post]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Posts_PostSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Posts_PostSet'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Posts_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Posts_PostSet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE dbo.cs_forums_Posts_PostSet
(
	@PostID	int,
	@PageIndex int,
	@PageSize int,
	@SortBy int,
	@SortOrder bit,
	@UserID int,
	@ReturnRecordCount bit,
	@AllowUnapproved bit = 0,
	@SettingsID int,
	@IncludeCategories bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int
DECLARE @SectionID int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Get the ThreadID
SELECT
	@ThreadID = ThreadID,
	@SectionID = SectionID
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY PostDate DESC

-- Sort by Author
IF @SortBy = 1 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID

ELSE IF @SortBy = 1 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID DESC

-- Sort by SortOrder
IF @SortBy = 2 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder

ELSE IF @SortBy = 2 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder DESC

-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration, P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	ThreadStarterAuthor = T.PostAuthor,
	ThreadStartDate = T.PostDate,	
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	Replies = 0, --not used(SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = 0, -- not used
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	AND (U.IsIgnored = 0 OR U.UserID = @UserID)	-- Ensure that you are not getting threads by ignored users unless the ignored user is requesting them
ORDER BY
	IndexID
END

IF @IncludeCategories = 1
BEGIN
	SET ROWCOUNT 0
	SELECT 
		Cats.[Name], jPI.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts_InCategories PIC ON jPI.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND  PIC.SettingsID = @SettingsID
End

IF @ReturnRecordCount = 1
  SELECT count(PostID) FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID  and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Posts_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Search
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Search]
GO
/***********************************************
* Sproc: cs_forums_Threads_ThreadsRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Threads_ThreadsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_threads_ThreadsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_threads_ThreadsRead]
GO



CREATE procedure [dbo].cs_forums_threads_ThreadsRead (
	@SectionID as int,
	@UserID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ReadAfter int

SELECT 
	@ReadAfter = MarkReadAfter 
FROM 
	cs_SectionsRead 
WHERE 
	UserID = @UserID AND 
	SectionID = @SectionID AND
	SettingsID = @SettingsID

IF @ReadAfter IS NOT NULL
	SELECT ThreadID = @ReadAfter
ELSE
	SELECT ThreadID = 0

IF @SectionID = -1
BEGIN
SELECT DISTINCT
	ThreadID
FROM
	cs_ThreadsRead
WHERE
	SettingsID = @SettingsID
	AND UserID = @UserID
END
ELSE
BEGIN
SELECT DISTINCT
	ThreadID
FROM
	cs_ThreadsRead
WHERE
	UserID = @UserID AND
	SectionID = @SectionID AND
	SettingsID = @SettingsID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_threads_ThreadsRead]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Thread_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_forums_Thread_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Thread_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Thread_Get]
GO



CREATE PROCEDURE [dbo].cs_forums_Thread_Get
/* Procedure for getting basic information on a single thread. */
(
	@ThreadID int,
	@UserID int,
	@SettingsID int
) AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	T.*,
	P.PostID,
	P.Subject,
	P.Body,P.FormattedBody,
	P.PostMedia,
	P.PostType,
	P.PostConfiguration,
	P.PropertyNames as PostPropertyNames,
	P.PropertyValues as PostPropertyValues,
	UserName = T.PostAuthor,
	HasRead =  CASE
		WHEN @UserID = 0 THEN 0
		WHEN @UserID > 0 THEN (Select Convert(bit,Count(*)) FROM cs_vw_HasReadForum where ((ThreadID is null and MarkReadAfter > P.ThreadID) or (MarkReadAfter is null and ThreadID = P.ThreadID)) and UserID = @UserID and SectionID = P.SectionID)
		END
FROM 
	cs_Posts P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = P.ParentID AND
	P.ThreadID = @ThreadID AND
	T.ThreadID = P.ThreadID AND
	P.UserID = U.UserID and P.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_Thread_Get to public
go
/***********************************************
* Sproc: cs_Forum_CreateEmbeddedThreadUrl
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Forum_CreateEmbeddedThreadUrl'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Forum_CreateEmbeddedThreadUrl]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Forum_CreateEmbeddedThreadUrl]
GO

CREATE PROCEDURE [dbo].[cs_Forum_CreateEmbeddedThreadUrl]
(
    @SectionID int,
    @Url nvarchar(425),
    @ThreadID int
)
AS
BEGIN

	INSERT INTO cs_Forum_EmbeddedThreadUrl (SectionID, Url, ThreadID)
	VALUES (@SectionID, @Url, @ThreadID)	

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Forum_CreateEmbeddedThreadUrl] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Forum_GetEmbeddedThreadUrl_ThreadID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Forum_GetEmbeddedThreadUrl_ThreadID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Forum_GetEmbeddedThreadUrl_ThreadID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Forum_GetEmbeddedThreadUrl_ThreadID]
GO

CREATE PROCEDURE [dbo].[cs_Forum_GetEmbeddedThreadUrl_ThreadID]
(
    @SectionID int,
    @Url nvarchar(425),
    @ThreadID int out
)
AS
BEGIN

	SET @ThreadID = -1

	SELECT @ThreadID = ThreadID
	FROM cs_Forum_EmbeddedThreadUrl
	WHERE SectionID = @SectionID
		AND Url = @Url

	SELECT ThreadID = @ThreadID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Forum_GetEmbeddedThreadUrl_ThreadID] TO PUBLIC
GO

/***********************************************
* Sproc: cs_fourm_Feedback_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_fourm_Feedback_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_fourm_Feedback_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_fourm_Feedback_Get]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_FriendRequest_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_Delete'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_Delete]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_Delete]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_Delete]
( 
	@UserID int,
	@FriendID int  
)

AS

SET NOCOUNT ON;

BEGIN
	DELETE FROM	[dbo].[cs_FriendRequests]
	WHERE		(RequestorUserID = @UserID AND RequesteeUserID = @FriendID)
	OR			(RequestorUserID = @FriendID AND RequesteeUserID = @UserID)

	
	DELETE FROM	[dbo].[cs_Friends_xref] 
	WHERE		UserID = @UserID AND FriendUserID = @FriendID
	
	
	DELETE FROM	[dbo].[cs_Friends_xref] 
	WHERE		UserID = @FriendID AND FriendUserID = @UserID
	
	RETURN 0;

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_Delete] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_DeleteByID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_DeleteByID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_DeleteByID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_DeleteByID]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_DeleteByID]
( 
	@FriendshipRequestID int 
)

AS

SET NOCOUNT ON;

BEGIN
	DECLARE @UserID int, @FriendID int 	
	
	SELECT @UserID = RequestorUserID FROM [dbo].[cs_FriendRequests] WHERE FriendshipRequestID = @FriendshipRequestID
	SELECT @FriendID = RequesteeUserID FROM [dbo].[cs_FriendRequests] WHERE FriendshipRequestID = @FriendshipRequestID
	
	DELETE FROM	[dbo].[cs_FriendRequests]
	WHERE		FriendshipRequestID = @FriendshipRequestID

	DELETE FROM	[dbo].[cs_Friends_xref] 
	WHERE		UserID = @UserID AND FriendUserID = @FriendID
	
	DELETE FROM	[dbo].[cs_Friends_xref] 
	WHERE		UserID = @FriendID AND FriendUserID = @UserID	

	RETURN 0;

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_DeleteByID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_Insert
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_Insert'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_Insert]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_Insert]

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_Insert]
(
	@RequestorUserID	int,
	@RequesteeUserID	int,
	@Message	varchar(2000),
	@FriendshipState			tinyint,
	@FriendshipRequestID				int out
)

AS
BEGIN

	SET Transaction Isolation Level Read UNCOMMITTED
	SET NOCOUNT ON;

	IF NOT EXISTS
	(
		SELECT 1 FROM [dbo].[cs_FriendRequests]
		WHERE	(RequestorUserID = @RequestorUserID	OR RequesteeUserID = @RequestorUserID)
			AND (RequestorUserID = @RequesteeUserID OR RequesteeUserID = @RequesteeUserID)
	)
	BEGIN

		INSERT INTO		[dbo].[cs_FriendRequests]
		(
			RequestorUserID,
			RequesteeUserID,
			Message,
			FriendshipState
		)
		VALUES
		(
			@RequestorUserID,
			@RequesteeUserID,
			@Message,
			@FriendshipState
		)

		SET @FriendshipRequestID = SCOPE_IDENTITY();

		EXECUTE [cs_FriendRequest_xref_Insert] @RequestorUserID, @RequesteeUserID, @FriendshipState

		RETURN 0;

	END ELSE BEGIN

		RETURN 1;

	END

END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_FriendRequest_Insert] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_Save
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_Save'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_Save]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_Save]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_Save]
(
	@ID int,
	@RequestorUserID	int, 
	@RequesteeUserID	int, 
	@Message	varchar(2000), 
	@FriendshipState			tinyint,
	@FriendshipRequestID				int out
)

AS

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;

BEGIN
IF @ID = 0
	BEGIN

	SELECT	@ID = ISNULL(FriendshipRequestID,0)
	FROM	[dbo].[cs_FriendRequests]
	WHERE	(RequestorUserID = @RequestorUserID OR RequesteeUserID = @RequestorUserID)
	AND		(RequestorUserID = @RequesteeUserID OR RequesteeUserID = @RequesteeUserID)
	
	END
	
	IF @ID = 0
	BEGIN
		EXEC cs_FriendRequest_Insert @RequestorUserID, @RequesteeUserID, @Message, @FriendshipState, @FriendshipRequestID out
	END
	ELSE
	BEGIN
		EXEC cs_FriendRequest_UpdateByID @ID, @RequestorUserID, @RequesteeUserID, @Message, @FriendshipState
		SET @FriendshipRequestID = @ID
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_Save] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_SelectBetweenUsers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_SelectBetweenUsers'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_SelectBetweenUsers]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_SelectBetweenUsers]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_SelectBetweenUsers]
(
	@UserID1 int, 
	@UserID2 int
)

AS

SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON;

BEGIN
	SELECT		
		FR.FriendshipRequestID, 
		FR.RequestorUserID, 
		FR.RequesteeUserID, 
		FR.FriendshipState, 
		FR.[Message], 
		FR.CreatedDate, 
		FR.LastModifiedDate
	FROM [dbo].[cs_FriendRequests] FR
	WHERE (FR.RequestorUserID = @UserID1 AND FR.RequesteeUserID = @UserID2)
	   OR (FR.RequesteeUserID = @UserID1 AND FR.RequestorUserID = @UserID2)
	
	RETURN 0;			
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_SelectBetweenUsers] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_SelectByID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_SelectByID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_SelectByID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_SelectByID]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_SelectByID]
(
	@FriendshipRequestID int
)

AS

SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON;

BEGIN
	SELECT		
		FriendshipRequestID, 
		RequestorUserID, 
		RequesteeUserID, 
		FriendshipState, 
		Message, 
		CreatedDate, 
		LastModifiedDate
	FROM		[dbo].[cs_FriendRequests]
	WHERE		FriendshipRequestID = @FriendshipRequestID
	
	RETURN 0;			
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_SelectByID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_SelectByRequesteeUserID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_SelectByRequesteeUserID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_SelectByRequesteeUserID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_SelectByRequesteeUserID]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_SelectByRequesteeUserID]
(
	@UserID int, 
	@FriendshipState tinyint = NULL,
	@sortOrder int,
	@sortBy int,
	@pageIndex int,
        @pageSize int,
        @totalCount int output
)

AS


DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
    IndexId int identity (1, 1) NOT NULL,
    FriendshipRequestID int NOT NULL,
    RequestorUserID int NOT NULL,
    RequesteeUserID int NOT NULL,
    FriendshipState tinyint NULL,
    [Message] nvarchar(2000) collate database_default NULL,
    CreatedDate datetime NULL,
    LastModifiedDate datetime NULL
)

IF (@sortBy = 0)
BEGIN

	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequesteeUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequesteeUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END ELSE BEGIN

	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequesteeUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequesteeUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_SelectByRequesteeUserID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_SelectByRequestorUserID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_SelectByRequestorUserID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_SelectByRequestorUserID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_SelectByRequestorUserID]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE [dbo].[cs_FriendRequest_SelectByRequestorUserID]
(
	@UserID int, 
	@FriendshipState tinyint = NULL,
	@sortOrder int,
	@sortBy int,
	@pageIndex int,
    	@pageSize int,
    	@totalCount int output
)

AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	FriendshipRequestID int NOT NULL,
    RequestorUserID int NOT NULL,
	RequesteeUserID int NOT NULL,
    FriendshipState tinyint NULL,
    [Message] nvarchar(2000) collate database_default NULL,
    CreatedDate datetime NULL,
    LastModifiedDate datetime NULL
)

IF (@sortBy = 0)
BEGIN

	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequestorUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequestorUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END ELSE BEGIN

	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequestorUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY LastModifiedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE RequestorUserID = @UserID
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY LastModifiedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_SelectByRequestorUserID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_SelectByUserID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_SelectByUserID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_SelectByUserID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_SelectByUserID]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE [dbo].[cs_FriendRequest_SelectByUserID]
(
	@UserID int, 
	@FriendshipState tinyint = NULL,
	@sortOrder int,
	@sortBy int,
	@pageIndex int,
    @pageSize int,
    @totalCount int output
)
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	FriendshipRequestID int NOT NULL,
    RequestorUserID int NOT NULL,
	RequesteeUserID int NOT NULL,
    FriendshipState tinyint NULL,
    [Message] nvarchar(2000) collate database_default NULL,
    CreatedDate datetime NULL,
    LastModifiedDate datetime NULL
)

IF (@sortBy = 0)
BEGIN
	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE 
			(RequesteeUserID = @UserID OR RequestorUserID = @UserID)
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE 
			(RequesteeUserID = @UserID OR RequestorUserID = @UserID)
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY CreatedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END ELSE BEGIN

	IF (@sortOrder = 0)
	BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE 
			(RequesteeUserID = @UserID OR RequestorUserID = @UserID)
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY LastModifiedDate ASC

		SET @totalCount = @@ROWCOUNT

	END ELSE BEGIN

		INSERT INTO #Temp
			(FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate)
		SELECT		
			FriendshipRequestID, 
			RequestorUserID, 
			RequesteeUserID, 
			FriendshipState, 
			[Message], 
			CreatedDate, 
			LastModifiedDate
		FROM [dbo].[cs_FriendRequests]
		WHERE 
			(RequesteeUserID = @UserID OR RequestorUserID = @UserID)
			AND	(@FriendshipState IS NULL OR FriendshipState = @FriendshipState)
		ORDER BY LastModifiedDate DESC

		SET @totalCount = @@ROWCOUNT

	END

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT FriendshipRequestID, RequestorUserID, RequesteeUserID, FriendshipState, [Message], CreatedDate, LastModifiedDate
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_SelectByUserID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_Update'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_Update]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_Update]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE [dbo].[cs_FriendRequest_Update]
(
	@RequestorUserID	int, 
	@RequesteeUserID	int, 
	@Message	varchar(2000), 
	@FriendshipState			tinyint 
)

AS

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;

DECLARE @FriendshipRequestID int

BEGIN
	SELECT	@FriendshipRequestID = FriendshipRequestID
	FROM	[dbo].[cs_FriendRequests]
	WHERE	(RequestorUserID = @RequestorUserID OR RequesteeUserID = @RequestorUserID)
	AND		(RequestorUserID = @RequesteeUserID OR RequesteeUserID = @RequesteeUserID)
	
	
	IF @FriendshipRequestID IS NOT NULL
	BEGIN
	
		EXEC cs_FriendRequest_UpdateByID @FriendshipRequestID, @RequestorUserID, @RequesteeUserID, @Message, @FriendshipState
		RETURN 0;
	END
	ELSE
		RETURN 1;
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_Update] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_UpdateByID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_UpdateByID'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_UpdateByID]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_UpdateByID]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE [dbo].[cs_FriendRequest_UpdateByID]
(
	@FriendshipRequestID int, 
	@RequestorUserID int, 
	@RequesteeUserID int, 
	@Message varchar(2000), 
	@FriendshipState tinyint 
)

AS

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;

BEGIN
	
	UPDATE	[dbo].[cs_FriendRequests]
	SET		RequestorUserID = @RequestorUserID, 
			RequesteeUserID = @RequesteeUserID, 
			Message  = @Message, 
			FriendshipState			  = @FriendshipState, 
			LastModifiedDate		  = GETDATE()
	WHERE	FriendshipRequestID			  = @FriendshipRequestID

	EXECUTE [cs_FriendRequest_xref_Insert] @RequestorUserID, @RequesteeUserID, @FriendshipState

	RETURN 0;

END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_FriendRequest_UpdateByID] to [public]
go

/***********************************************
* Sproc: cs_FriendRequest_xref_Insert
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_FriendRequest_xref_Insert'

IF OBJECT_ID(N'[dbo].[cs_FriendRequest_xref_Insert]') IS NOT NULL
	DROP PROCEDURE [dbo].[cs_FriendRequest_xref_Insert]

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[cs_FriendRequest_xref_Insert]
(
	@RequestorUserID int
	, @RequesteeUserID int
	, @FriendshipState tinyint
)

AS

SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON;

BEGIN

	IF (@FriendshipState = 2)
	BEGIN

		IF NOT EXISTS (SELECT 1 FROM cs_Friends_xref WHERE UserID = @RequestorUserID AND FriendUserID = @RequesteeUserID)
			INSERT INTO [dbo].[cs_Friends_xref]
			(
				UserID,
				FriendUserID
			)
			VALUES
			(
				@RequestorUserID,
				@RequesteeUserID
			)

		IF NOT EXISTS (SELECT 1 FROM cs_Friends_xref WHERE UserID = @RequesteeUserID AND FriendUserID = @RequestorUserID)
			INSERT INTO [dbo].[cs_Friends_xref]
			(
				UserID,
				FriendUserID
			)
			VALUES
			(
				@RequesteeUserID,
				@RequestorUserID
			)

	END
	RETURN 0;

END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_FriendRequest_xref_Insert] to [public]
go

/***********************************************
* Sproc: cs_GetAnonymousUserID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetAnonymousUserID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetAnonymousUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetAnonymousUserID]
GO

/* This sproc is no longer needed, the user can just be looked up by name */
--as "Anonymous"
--
--Create Proc [dbo].cs_GetAnonymousUserID
--(
--	@SettingsID int,
--	@UserID int output
--)
--as
--SET Transaction Isolation Level Read UNCOMMITTED
--SELECT	@UserID = U.UserID
--FROM	cs_Users U
--WHERE	U.IsAnonymous = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

GO

--grant execute on [dbo].cs_GetAnonymousUserID to public
go
/***********************************************
* Sproc: cs_GetSectionsForUserSubscriptions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetSectionsForUserSubscriptions'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetSectionsForUserSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetSectionsForUserSubscriptions]
GO

CREATE procedure dbo.cs_GetSectionsForUserSubscriptions
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		COALESCE(S.SectionID, T.SectionID) AS SectionID,
		S.ApplicationType
	FROM
		cs_Sections S
		LEFT JOIN cs_TrackedSections TS ON S.SectionID = TS.SectionID
		LEFT JOIN (cs_TrackedThreads TT INNER JOIN cs_Threads T ON TT.ThreadID = T.ThreadID) ON S.SectionID = T.SectionID
	WHERE
		(TS.UserID IS NULL OR TS.UserID = @UserID)
		AND (TT.UserID IS NULL OR TT.UserID = @UserID)
		AND TS.SettingsID = @SettingsID
		AND S.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_GetSectionsForUserSubscriptions] to public

/***********************************************
* Sproc: cs_GetSectionSubscriptionType
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetSectionSubscriptionType'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetSectionSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetSectionSubscriptionType]
GO


CREATE  procedure [dbo].cs_GetSectionSubscriptionType
(
	@UserID int,
	@SectionID int,
	@SettingsID int,
	@SubType int OUTPUT
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT SubscriptionType FROM cs_TrackedSections WHERE SectionID=@SectionID AND UserID=@UserID and SettingsID = @SettingsID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_GetSectionSubscriptionType to public
go
/***********************************************
* Sproc: cs_GetSectionSubscriptionTypes
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetSectionSubscriptionTypes'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetSectionSubscriptionTypes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetSectionSubscriptionTypes]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  procedure [dbo].cs_GetSectionSubscriptionTypes
(
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT SubscriptionType, SectionID FROM cs_TrackedSections WHERE UserID=@UserID and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_GetSectionSubscriptionTypes]  TO [public]
GO


/***********************************************
* Sproc: cs_GetTotalPostCount
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetTotalPostCount'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetTotalPostCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetTotalPostCount]
GO



CREATE   PROCEDURE [dbo].cs_GetTotalPostCount
(
	@SettingsID int
)

 AS
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT TOP 1 
		TotalPosts 
	FROM 
		forums_Statistics where SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_GetTotalPostCount] to public
go
/***********************************************
* Sproc: cs_GetUserIDByAppToken
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetUserIDByAppToken'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetUserIDByAppToken]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetUserIDByAppToken]
GO




CREATE         PROCEDURE [dbo].cs_GetUserIDByAppToken
(
	@AppUserToken varchar(128),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	U.UserID
FROM 
	cs_vw_Users_FullUser U (nolock)
WHERE 
	U.AppUserToken = @AppUserToken and SettingsID = @SettingsID






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_GetUserIDByAppToken] to public
go
/***********************************************
* Sproc: cs_GetUsersForSectionSubscriptions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_GetUsersForSectionSubscriptions'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetUsersForSectionSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetUsersForSectionSubscriptions]
GO

CREATE procedure dbo.cs_GetUsersForSectionSubscriptions
(
	@SectionID	int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_vw_Users_FullUser U
		LEFT JOIN cs_TrackedSections TS ON U.UserID = TS.UserID
		LEFT JOIN (cs_TrackedThreads TT INNER JOIN cs_Threads T ON TT.ThreadID = T.ThreadID) ON U.UserID = TT.UserID
	WHERE
		(TS.SectionID IS NULL OR TS.SectionID = @SectionID)
		AND (T.SectionID IS NULL OR T.SectionID = @SectionID)
		AND TS.SettingsID = @SettingsID
		AND U.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_GetUsersForSectionSubscriptions] to public

/***********************************************
* Sproc: cs_Groups_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Groups_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_Get]
GO

CREATE  PROCEDURE [dbo].cs_Groups_Get
(
	@SettingsID int,
	@ApplicationType smallint = 0,
	@RequireModeration bit = 0

)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF (@RequireModeration = 0)
		SELECT
			*
		FROM
			cs_Groups
		WHERE
			(SettingsID = @SettingsID) and ApplicationType = @ApplicationType
	ELSE
		SELECT DISTINCT
			FG.*
		FROM
			cs_Sections S,
			cs_Groups FG
		WHERE
			S.GroupID = FG.GroupID AND
			S.IsActive = 1 AND
			(SELECT Count(PostID) FROM cs_Posts P WHERE SectionID = S.SectionID AND P.IsApproved = 0) > 0 AND
			(FG.SettingsID = @SettingsID) AND
			FG.ApplicationType = @ApplicationType

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_Get] to public
go
/***********************************************
* Sproc: cs_Groups_ReOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Groups_ReOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_ReOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_ReOrder]
GO


Create Proc [dbo].cs_Groups_ReOrder 
(
	@GroupID int,
	@Index int,
	@SettingsID int
	
)

as

Set NoCount On

Declare @ApplicationType int
Select @ApplicationType = ApplicationType From cs_Groups where GroupID = @GroupID and SettingsID = @SettingsID

exec cs_Groups_ResetOrder @ApplicationType, @SettingsID

update cs_Groups
Set SortOrder = SortOrder + 1 where SortOrder >= @Index and SettingsID = @SettingsID and ApplicationType = @ApplicationType

update cs_Groups
Set SortOrder = @Index where GroupID = @GroupID and SettingsID = @SettingsID and ApplicationType = @ApplicationType

exec cs_Groups_ResetOrder @ApplicationType, @SettingsID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_ReOrder] to public
go
/***********************************************
* Sproc: cs_Groups_ResetOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Groups_ResetOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_ResetOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_ResetOrder]
GO

Create Proc [dbo].cs_Groups_ResetOrder
(
	@ApplicationType int,
	@SettingsID int
)
as

Declare @Sort int
Set @Sort = 0
Declare @GroupID int
DECLARE group_Cursor CURSOR FOR
SELECT GroupID FROM cs_Groups where ApplicationType = @ApplicationType and SettingsID = @SettingsID order by SortOrder

OPEN group_Cursor

FETCH NEXT FROM group_Cursor Into @GroupID
WHILE (@@FETCH_STATUS = 0)
Begin
	Update cs_Groups Set SortOrder = @Sort where GroupID = @GroupID
	Set @Sort = @Sort + 1
   FETCH NEXT FROM group_Cursor Into @GroupID
End

CLOSE group_Cursor
DEALLOCATE group_Cursor



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_ResetOrder] to public
go
/***********************************************
* Sproc: cs_Group_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Group_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Group_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Group_CreateUpdateDelete]
GO


CREATE       PROCEDURE [dbo].cs_Group_CreateUpdateDelete
(
	@GroupID	int out,
	@ParentGroupID  int = 0,
	@Name		nvarchar(256),
	@Description	nvarchar(1000) = '',
	@ApplicationType smallint = 0,
	@Action 	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	DECLARE @SortOrder int

	SELECT @SortOrder = coalesce(MAX(SortOrder) + 1, 1) FROM cs_Groups where SettingsID = @SettingsID

	-- Create a new forum group
	INSERT INTO 
		cs_Groups 
		(
			Name,
			Description,
			SortOrder,
			ApplicationType,
			SettingsID,
			ParentGroupID
		)
	VALUES 
		(
			@Name,
			@Description,
			@SortOrder,
			@ApplicationType,
			@SettingsID,
			@ParentGroupID
		)
	
	SET @GroupID = SCOPE_IDENTITY()
END


-- UPDATE
ELSE IF @Action = 1
BEGIN

	IF EXISTS(SELECT GroupID FROM cs_Groups WHERE GroupID = @GroupID)
	BEGIN
		UPDATE
			cs_Groups
		SET
			Name = @Name,
			Description = @Description,
			ParentGroupID = @ParentGroupID
		WHERE
			GroupID = @GroupID and SettingsID = @SettingsID
	END

END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE cs_Groups WHERE GroupID = @GroupID and SettingsID = @SettingsID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Group_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Group_Permissions_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Group_Permissions_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[cs_Group_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Group_Permissions_Get]
GO

create procedure [dbo].[cs_Group_Permissions_Get]
(
	@SettingsID int,
	@GroupID int = 0,
	@ApplicationType smallint
)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	IF (@GroupID > 0)
	BEGIN
		
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID

		UNION ALL
		
		-- Return the group permissions unioned
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 0), 
			SectionID = -1,
			P.GroupID,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			ApplicationType = @ApplicationType
		FROM
			cs_GroupPermissions P
		WHERE 
			P.SettingsID = @SettingsID AND 
			P.GroupID = @GroupID
		order by Implied asc
	END
	ELSE -- Return Product Permissions
	BEGIN
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = @GroupID,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID	
	END	

end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Group_Permissions_Get] to public
go
/***********************************************
* Sproc: cs_guestbook_GetPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_guestbook_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_GetPosts]
GO



CREATE PROCEDURE dbo.cs_guestbook_GetPosts
(
	@PageIndex int,
	@PageSize int,
	@SortOrder bit,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1


-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF  @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostID

ELSE 
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostID DESC


-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = '',
	Replies = 0,
	IsModerator = 0,
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END


  SELECT Count(PostID) FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID

DROP Table #PageIndex



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_guestbook_GetPosts]  TO [public]
GO


/***********************************************
* Sproc: cs_guestbook_Post_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_guestbook_Post_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_Post_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_Post_Create]
GO



CREATE   PROCEDURE [dbo].cs_guestbook_Post_Create
(
	@SectionID int,
	@Subject nvarchar(256),
	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@PostType int = 0,
	@PostDate datetime = null,
	@UserHostAddress nvarchar(32),
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@PostID int out
) 
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
SET NOCOUNT ON
DECLARE @ThreadID int

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		UserID = @UserID

-- Do we care about duplicates?

Select @ThreadID = ThreadID FROM cs_Threads Where SectionID = @SectionID


SET NOCOUNT ON
BEGIN TRAN


IF @ThreadID is null
BEGIN


	INSERT cs_Threads 	
	( 
		SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID, 
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID 
	)
	VALUES
	( 
		@SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@PostAuthor,
		@UserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		0,
		1,
		0,
		@PostDate,
		-1,
		@SettingsID 
	)

	-- Get the new ThreadID
	SELECT 
		@ThreadID = SCOPE_IDENTITY()
--	FROM
--		cs_Threads
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 

		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID
	        )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		1, 
		0, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostDate, 
		@UserHostAddress, 
		-1,
		@PropertyNames,
		@PropertyValues,
		@SettingsID )
		

	-- Get the new PostID
	SELECT 
		@PostID = SCOPE_IDENTITY()

	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 
		1, 
		0,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		1, 
		0, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostDate, 
		@UserHostAddress, 
		-1,
		@PropertyNames,
		@PropertyValues,
		@SettingsID  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = SCOPE_IDENTITY() 




		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID)
		WHERE
			ThreadID = @ThreadID
	END
END


COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_guestbook_Post_Create] to public
go
/***********************************************
* Sproc: cs_guestbook_Post_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_guestbook_Post_Delete'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_Post_Delete]
GO

CREATE   PROCEDURE [dbo].cs_guestbook_Post_Delete
(
	@SectionID int,
	@PostID int
)

as
SET Transaction Isolation Level Read UNCOMMITTED

Declare @ThreadID int
Select @ThreadID = ThreadID FROM cs_Posts where PostID = @PostID and SectionID = @SectionID

if(@ThreadID is null)
RETURN

Delete FROM cs_Posts where PostID = @PostID and SectionID = @SectionID

UPDATE
	cs_Threads 	
SET 
	TotalReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID)
WHERE
	ThreadID = @ThreadID
	
GO

grant execute on [dbo].[cs_guestbook_Post_Delete] to public
go
/***********************************************
* Sproc: cs_HubContactRequests_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_HubContactRequests_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_HubContactRequests_Add]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_HubContactRequests_Add]
GO

CREATE PROCEDURE [dbo].[cs_HubContactRequests_Add]
(
    @Id int OUTPUT,
    @HubId int,
    @Subject nvarchar(256) = '',
    @Name nvarchar(256) = '',
    @EmailAddress nvarchar(256) = '',
    @Body ntext,
    @IsModerated bit,
    @CreationDate datetime
)
AS
BEGIN

	INSERT INTO [cs_Hub_ContactRequests]
	(
		HubId,
		Subject,
		Name,
		EmailAddress,
		CreationDate,
		Body,
		IsModerated
	)
	VALUES
	(
		@HubId,
		@Subject,
		@Name,
		@EmailAddress,
		@CreationDate,
		@Body,
		@IsModerated
	)

	SET @Id = scope_identity()
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_HubContactRequests_Add] TO PUBLIC
GO

/***********************************************
* Sproc: cs_HubContactRequests_Approve
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_HubContactRequests_Approve'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_HubContactRequests_Approve]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_HubContactRequests_Approve]
GO

CREATE PROCEDURE [dbo].[cs_HubContactRequests_Approve]
(
    @Id int,
    @HubId int
)
AS
BEGIN
	UPDATE [cs_Hub_ContactRequests] 
	SET IsModerated = 0	
	WHERE Id = @Id AND HubId = @HubId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_HubContactRequests_Approve] TO PUBLIC
GO

/***********************************************
* Sproc: cs_HubContactRequests_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_HubContactRequests_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_HubContactRequests_Delete]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_HubContactRequests_Delete]
GO

CREATE PROCEDURE [dbo].[cs_HubContactRequests_Delete]
(
    @Id int,
    @HubId int
)
AS
BEGIN
	DELETE FROM [cs_Hub_ContactRequests] WHERE Id = @Id AND HubId = @HubId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_HubContactRequests_Delete] TO PUBLIC
GO

/***********************************************
* Sproc: cs_HubContactRequests_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_HubContactRequests_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_HubContactRequests_Get]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_HubContactRequests_Get]
GO

CREATE PROCEDURE [dbo].[cs_HubContactRequests_Get]
(
    @HubId int,
    @IsModerated bit = NULL,
    @PageIndex int,
    @PageSize int,
    @TotalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	CREATE TABLE #Results
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		Id int NOT NULL
	)

	INSERT INTO #Results
		(Id)
	SELECT
		CR.Id
	FROM
		[dbo].[cs_Hub_ContactRequests] CR
	WHERE
		CR.HubId = @HubId
		AND (@IsModerated IS NULL OR CR.IsModerated = @IsModerated)
	ORDER BY
		CR.CreationDate DESC

	SET @TotalCount = @@ROWCOUNT

	SET @rowsToReturn = @PageSize * (@PageIndex + 1)
	SET @pageLowerBound = @PageSize * @PageIndex
	SET @pageUpperBound = @pageLowerBound + @PageSize + 1

	SET ROWCOUNT @rowsToReturn

	SELECT
		CR.Id,
		CR.HubId,
		CR.Subject,
		CR.Name,
		CR.EmailAddress,
		CR.CreationDate,
		CR.Body,
		CR.IsModerated
	FROM
		[dbo].[cs_Hub_ContactRequests] CR
		INNER JOIN #Results R ON CR.Id = R.Id
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

	DROP TABLE #Results
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_HubContactRequests_Get] TO PUBLIC
GO
/***********************************************
* Sproc: cs_HubContactRequest_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_HubContactRequest_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_HubContactRequest_Get]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_HubContactRequest_Get]
GO

CREATE PROCEDURE [dbo].[cs_HubContactRequest_Get]
(
    @Id int
)
AS
BEGIN

	SELECT
		CR.Id,
		CR.HubId,
		CR.Subject,
		CR.Name,
		CR.EmailAddress,
		CR.CreationDate,
		CR.Body,
		CR.IsModerated
	FROM
		[dbo].[cs_Hub_ContactRequests] CR
	WHERE
		CR.Id = @Id

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_HubContactRequest_Get] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Image_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Image_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Image_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Image_CreateUpdateDelete]
GO


/***********************************************
* Sproc: cs_InkData_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_InkData_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Add]
GO


Create Proc [dbo].[cs_InkData_Add]
(	
	@SectionID int,
	@SettingsID int,
	@UserID int,
	@ApplicationType smallint,
	@Ink NTEXT,
	@DateUpdated datetime,
	@InkID int output
)
as

Insert cs_InkData (UserID, SettingsID, SectionID, Ink, DateUpdated, ApplicationType)
Values (@UserID, @SettingsID, @SectionID, @Ink, @DateUpdated, @ApplicationType)

Select @InkID = SCOPE_IDENTITY()



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Add] to public
go
/***********************************************
* Sproc: cs_InkData_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_InkData_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Delete]
GO

Create Proc [dbo].[cs_InkData_Delete]
(
	@InkID int,
	@SectionID int,
	@SettingsID int
)

as

Delete FROM cs_InkData Where SettingsID = @SettingsID and SectionID = @SectionID and InkID = @InkID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Delete] to public
go
/***********************************************
* Sproc: cs_InkData_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_InkData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Get]
GO

Create Proc [dbo].[cs_InkData_Get]
(
	@InkID int,
	@SettingsID int
)
as
Select InkID, Ink, UserID, SectionID, SettingsID, DateUpdated, ApplicationType FROM cs_InkData where InkID = @InkID and SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Get] to public
go
/***********************************************
* Sproc: cs_InkData_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_InkData_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Update]
GO

Create Proc [dbo].[cs_InkData_Update]
(	
	@SectionID int,
	@SettingsID int,
	@Ink NTEXT,
	@DateUpdated datetime,
	@InkID int
)
as

update cs_InkData 
SET
	Ink = @Ink, 
	DateUpdated = @DateUpdated
where
	SettingsID = @SettingsID and SectionID = @SectionID and InkID = @InkID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Update] to public
go
/***********************************************
* Sproc: cs_Licenses_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Licenses_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_Delete]
GO

CREATE PROCEDURE dbo.cs_Licenses_Delete
	@LicenseID uniqueidentifier
AS

delete from cs_Licenses where LicenseID = @LicenseID
GO


grant execute on [dbo].[cs_Licenses_Delete] to public
go
/***********************************************
* Sproc: cs_Licenses_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Licenses_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_Get]
GO

CREATE PROCEDURE dbo.cs_Licenses_Get AS

SELECT * FROM cs_Licenses
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Licenses_Get] to public
go
/***********************************************
* Sproc: cs_Licenses_GetUsage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Licenses_GetUsage'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_GetUsage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_GetUsage]
GO

CREATE PROCEDURE dbo.cs_Licenses_GetUsage
AS
begin

	set ansi_warnings off

	declare @NumberOfBlogs int
		, @NumberOfForums int
		, @NumberOfGalleries int
		, @NumberOfGroups int
		, @NumberOfContentMirrors int
		, @NumberOfAddresses int
		, @NumberOfUsers int
		, @NumberOfBlogPosts int
		, @NumberOfBlogComments int
		, @NumberOfForumPosts int
		, @NumberOfForumReplies int
		, @NumberOfMediaGalleryPosts int
		, @NumberOfMediaGalleryComments int
		, @NumberOfFriendRelationships int
		, @NumberOfMessages int

	select
		@NumberOfBlogPosts = NumberOfBlogPosts
		, @NumberOfBlogComments = NumberOfBlogComments
		, @NumberOfForumPosts = NumberOfForumPosts
		, @NumberOfForumReplies = NumberOfForumReplies
		, @NumberOfMediaGalleryPosts = NumberOfMediaGalleryPosts
		, @NumberOfMediaGalleryComments = NumberOfMediaGalleryComments
	from (
		select
			count(case when s.ApplicationType = 1 and p.PostLevel = 1 then p.PostID end) NumberOfBlogPosts
			, count(case when s.ApplicationType = 1 and p.PostLevel > 1 then p.PostID end) NumberOfBlogComments
			, count(case when s.ApplicationType = 0 and ForumType = 0 and p.PostLevel = 1 then p.PostID end) NumberOfForumPosts
			, count(case when s.ApplicationType = 0 and ForumType = 0 and p.PostLevel > 1 then p.PostID end) NumberOfForumReplies
			, count(case when s.ApplicationType = 13 and p.PostLevel = 1 then p.PostID end) NumberOfMediaGalleryPosts
			, count(case when s.ApplicationType = 13 and p.PostLevel > 1 then p.PostID end) NumberOfMediaGalleryComments
		from
			cs_Posts p
		inner join
			cs_Sections s on p.SettingsID = s.SettingsID and p.SectionID = s.SectionID
		where
			s.ApplicationType in (0, 1, 13)
			and s.IsActive = 1
	) as x

	select
		@NumberOfBlogs = NumberOfBlogs
		, @NumberOfForums = NumberOfForums
		, @NumberOfGalleries = NumberOfGalleries
		, @NumberOfGroups = NumberOfGroups
	from (
		select
			count(case when ApplicationType = 11 then SectionID end) as NumberOfGroups
			, count(case when ApplicationType = 0 and ForumType = 0 and HubSectionID = 0 then SectionID end) as NumberOfForums
			, count(case when ApplicationType = 1 and HubSectionID = 0 then SectionID end) as NumberOfBlogs
			, count(case when ApplicationType = 13 and HubSectionID = 0 then SectionID end) as NumberOfGalleries
		from cs_Sections
		where
			ApplicationType in (0, 1, 11, 13)
			and IsActive = 1
	) as x

	set @NumberOfContentMirrors = (select count(UrlID) from cs_RollerBlogFeeds where Enabled = 1)
	set @NumberOfAddresses = (select count(M.SectionID) from csm_MailingLists M left join cs_Sections S on (S.SectionID = M.SectionID) where S.IsActive = 1 and M.IsMailingList = 1)
	set @NumberOfUsers = (select count(UserID) from cs_Users)
	set @NumberOfFriendRelationships = (select count(UserID) from cs_Friends_xref)
	set @NumberOfMessages = (select count(*) from cs_Messaging_Messages)

	set ansi_warnings on

	select
		coalesce(@NumberOfBlogs, 0) NumberOfBlogs
		, coalesce(@NumberOfForums, 0) NumberOfForums
		, coalesce(@NumberOfGalleries, 0) NumberOfGalleries
		, coalesce(@NumberOfGroups, 0) NumberOfGroups
		, coalesce(@NumberOfContentMirrors, 0) NumberOfContentMirrors
		, coalesce(@NumberOfAddresses, 0) NumberOfAddresses
		, coalesce(@NumberOfBlogPosts, 0) NumberOfBlogPosts
		, coalesce(@NumberOfBlogComments, 0) NumberOfBlogComments
		, coalesce(@NumberOfForumPosts, 0) NumberOfForumPosts
		, coalesce(@NumberOfForumReplies, 0) NumberOfForumReplies
		, coalesce(@NumberOfMediaGalleryPosts, 0) NumberOfMediaGalleryPosts
		, coalesce(@NumberOfMediaGalleryComments, 0) NumberOfMediaGalleryComments
		, coalesce(@NumberOfFriendRelationships, 0) NumberOfFriendRelationships
		, coalesce(@NumberOfMessages, 0) NumberOfMessages
		, coalesce(@NumberOfUsers, 0) NumberOfUsers

end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Licenses_GetUsage] to public
go
/***********************************************
* Sproc: cs_Licenses_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Licenses_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_Update]
GO

CREATE PROCEDURE dbo.cs_Licenses_Update
	@LicenseID uniqueidentifier,
	@LicenseValue ntext
AS

if exists(select LicenseID from cs_Licenses where LicenseID = @LicenseID)
begin
	delete from cs_Licenses where LicenseID = @LicenseID
end

insert into cs_Licenses (LicenseID, LicenseValue, InstallDate) values (@LicenseID, @LicenseValue, getdate())
GO


grant execute on [dbo].[cs_Licenses_Update] to public
go
/***********************************************
* Sproc: cs_LinkCategories_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_LinkCategories_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategories_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategories_Get]
GO



CREATE PROCEDURE dbo.cs_LinkCategories_Get
(
	@SectionID int,
	@SettingsID int,
	@PreLoadLinks bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Categories
SELECT  [LinkCategoryID], [SectionID], [Name], [Description], [IsEnabled], [SortOrder], [SettingsID]
FROM cs_LinkCategories
WHERE SectionID = @SectionID and SettingsID = @SettingsID
Order By SortOrder

-- Do we need to return links as well?
IF (@PreLoadLinks = 1)
BEGIN
	SELECT [LinkID], l.[LinkCategoryID], [Title], [Url], l.[IsEnabled], l.[SortOrder], l.[SettingsID], [Rel], l.[Description], [DateCreated]
	FROM cs_Links l inner join cs_LinkCategories c on l.LinkCategoryID = c.LinkCategoryID
	WHERE c.SectionID = @SectionID and c.SettingsID = @SettingsID
	Order By c.SortOrder, l.SortOrder
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategories_Get] to public
go



/***********************************************
* Sproc: cs_LinkCategory_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_LinkCategory_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategory_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategory_CreateUpdateDelete]
GO

--exec dbo.cs_LinkCategory_CreateUpdateDelete @LinkCategoryID = 3, @DeleteLinkCategory = 1

CREATE PROCEDURE dbo.cs_LinkCategory_CreateUpdateDelete
	@DeleteLinkCategory bit=0,
	@SectionID int,
	@Name nvarchar(256)='',
	@Description nvarchar(2000)=null,
	@IsEnabled bit=1,
	@SortOrder int=0,
	@SettingsID int,
	@LinkCategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Are we deleting?
if @DeleteLinkCategory = 1
begin
	DELETE FROM cs_Links WHERE LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
	DELETE FROM cs_LinkCategories WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	RETURN
end

-- Are we updating?
if @LinkCategoryID > 0
begin
	UPDATE cs_LinkCategories SET
		[Name] = @Name,
		[Description] = @Description,
		IsEnabled = @IsEnabled,
		SortOrder = @SortOrder
	WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	If( @SortOrder = 0 )
	Begin
		Select @SortOrder = max(SortOrder) + 1 from cs_LinkCategories where SectionID = @SectionID and SettingsID = @SettingsID

		if(@SortOrder is null)
			Select	@SortOrder = 0
	End
	INSERT INTO cs_LinkCategories (SectionID, [Name], [Description], IsEnabled, SortOrder, SettingsID)
		VALUES (@SectionID, @Name, @Description, @IsEnabled, @SortOrder, @SettingsID)
	set @LinkCategoryID = SCOPE_IDENTITY()
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategory_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_LinkCategory_UpdateSortOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_LinkCategory_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategory_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategory_UpdateSortOrder]
GO



CREATE procedure [dbo].cs_LinkCategory_UpdateSortOrder
( 
            @LinkCategoryID int, 
	    @SettingsID int,
            @MoveUp bit 
) 
AS 
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN 
	set nocount on
	
	DECLARE @currentSortValue int 
	DECLARE @replaceSortValue int 
	DECLARE @replaceLinkCategoryID int
	DECLARE @SectionID int
	
	-- Get the current sort order 
	SELECT @currentSortValue = SortOrder, @SectionID = SectionID FROM cs_LinkCategories WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
	
	-- Move the item up or down? 
	IF (@MoveUp = 1) 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkCategoryID = coalesce(f.LinkCategoryID, -1)
			FROM cs_LinkCategories f
				inner join (
					select top 1 * 
					from cs_LinkCategories 
					WHERE SectionID = @SectionID and SortOrder < @currentSortValue  and SettingsID = @SettingsID order by SortOrder DESC
				) as pf on 
					pf.LinkCategoryID = f.LinkCategoryID  and f.SettingsID = @SettingsID

		if( @replaceSortValue != -1 And @replaceSortValue is Not Null  )
		begin	
			UPDATE cs_LinkCategories SET SortOrder = @currentSortValue WHERE LinkCategoryID = @replaceLinkCategoryID  and SettingsID = @SettingsID
			UPDATE cs_LinkCategories SET SortOrder = @replaceSortValue WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
		END 
	END 
	ELSE 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkCategoryID = coalesce(f.LinkCategoryID, -1)
			FROM cs_LinkCategories f
				inner join (
					select top 1 * 
					FROM cs_LinkCategories 
					WHERE SectionID = @SectionID and SortOrder > @currentSortValue  and SettingsID = @SettingsID order by SortOrder ASC				
				) as pf on 
					pf.LinkCategoryID = f.LinkCategoryID  and f.SettingsID = @SettingsID


		if( @replaceSortValue != -1 And @replaceSortValue is Not Null  )
		begin		
			UPDATE cs_LinkCategories SET SortOrder = @currentSortValue WHERE LinkCategoryID = @replaceLinkCategoryID  and SettingsID = @SettingsID
			UPDATE cs_LinkCategories SET SortOrder = @replaceSortValue WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
		end
	END 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategory_UpdateSortOrder] to public
go
/***********************************************
* Sproc: cs_Links_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Links_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Links_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Links_Get]
GO



CREATE PROCEDURE dbo.cs_Links_Get
	@LinkCategoryID int,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

	SELECT [LinkID], [LinkCategoryID], [Title], [Url], [IsEnabled], [SortOrder], [SettingsID], [Rel], [Description], [DateCreated]
	FROM cs_Links
	WHERE LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
	Order By SortOrder

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Links_Get] to public
go


/***********************************************
* Sproc: cs_Link_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Link_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Link_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Link_CreateUpdateDelete]
GO

CREATE PROCEDURE dbo.cs_Link_CreateUpdateDelete
	@DeleteLink bit=0,
	@LinkCategoryID int=0,
	@Title nvarchar(100)='',
	@Url nvarchar(255)='',
	@Rel nvarchar(100)='',
	@Description nvarchar(2000)='',
	@IsEnabled bit=1,
	@SortOrder int=0,
	@SettingsID int,
	@LinkID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting?
if @DeleteLink = 1
begin
	DELETE FROM cs_Links WHERE LinkID = @LinkID
end

-- Are we updating?
if @LinkID > 0
begin
	UPDATE cs_Links SET
		Title = @Title,
		Url = @Url,
		Rel = @Rel,
		[Description] = @Description,
		IsEnabled = @IsEnabled,
		SortOrder = @SortOrder
	WHERE LinkID = @LinkID and LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
end
else
begin
	If( @SortOrder = 0 )
	Begin
		Select @SortOrder = max(SortOrder) + 1 from cs_Links where LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID

		if(@SortOrder is null)
			Select @SortOrder = 0
	End
	INSERT INTO cs_Links (LinkCategoryID, Title, Url, Rel, [Description], IsEnabled, SortOrder, SettingsID)
		VALUES (@LinkCategoryID, @Title, @Url, @Rel, @Description, @IsEnabled, @SortOrder, @SettingsID)
	set @LinkID = SCOPE_IDENTITY()
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Link_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Link_UpdateSortOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Link_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Link_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Link_UpdateSortOrder]
GO



CREATE procedure [dbo].cs_Link_UpdateSortOrder
( 
            @LinkID int,
	    @SettingsID int, 
            @MoveUp bit 
) 
AS 
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN 
	set nocount on
	
	DECLARE @currentSortValue int 
	DECLARE @replaceSortValue int 
	DECLARE @replaceLinkID int
	DECLARE @LinkCategoryID int
	
	-- Get the current sort order 
	SELECT @currentSortValue = SortOrder, @LinkCategoryID = LinkCategoryID FROM cs_Links WHERE LinkID = @LinkID  and SettingsID = @SettingsID

	-- Move the item up or down? 
	IF (@MoveUp = 1) 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkID = coalesce(f.LinkID, -1)
			FROM cs_Links f
				inner join (
					select top 1 * 
					from cs_Links 
					WHERE LinkCategoryID = @LinkCategoryID and SortOrder < @currentSortValue and SettingsID = @SettingsID order by SortOrder DESC
				) as pf on 
					pf.LinkID = f.LinkID and f.SettingsID = @SettingsID
		if( @replaceSortValue != -1 And @replaceSortValue is Not Null )
		begin	
			UPDATE cs_Links SET SortOrder = @currentSortValue WHERE LinkID = @replaceLinkID and SettingsID = @SettingsID
			UPDATE cs_Links SET SortOrder = @replaceSortValue WHERE LinkID = @LinkID and SettingsID = @SettingsID
		END 
	END 
	ELSE 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkID = coalesce(f.LinkID, -1)
			FROM cs_Links f
				inner join (
					select top 1 * 
					FROM cs_Links 
					WHERE LinkCategoryID = @LinkCategoryID and SortOrder > @currentSortValue and SettingsID = @SettingsID order by SortOrder ASC				
				) as pf on 
					pf.LinkID = f.LinkID and f.SettingsID = @SettingsID


		if( @replaceSortValue != -1 And @replaceSortValue is Not Null )
		begin		
			UPDATE cs_Links SET SortOrder = @currentSortValue WHERE LinkID = @replaceLinkID and SettingsID = @SettingsID
			UPDATE cs_Links SET SortOrder = @replaceSortValue WHERE LinkID = @LinkID and SettingsID = @SettingsID
		end
	END 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Link_UpdateSortOrder] to public
go
/***********************************************
* Sproc: cs_MarkPostAsRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_MarkPostAsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_MarkPostAsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_MarkPostAsRead]
GO

CREATE         PROCEDURE [dbo].cs_MarkPostAsRead
(
	@PostID	int,
	@UserName nvarchar (50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- If @UserName is null it is an anonymous user
	IF @UserName IS NOT NULL
	BEGIN
		DECLARE @SectionID int
		DECLARE @PostDate datetime

		-- Mark the post as read
		-- *********************

		-- Only for PostLevel = 1
		IF EXISTS (SELECT PostID FROM cs_Posts WHERE PostID = @PostID AND PostLevel = 1 and SettingsID = @SettingsID)
			IF NOT EXISTS (SELECT HasRead FROM PostsReadx WHERE UserName = @UserName and PostID = @PostID and SettingsID = @SettingsID)
				INSERT INTO PostsRead (UserName, PostID, SettingsID) VALUES (@UserName, @PostID, @SettingsID)

	END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_MarkPostAsRead] to public
go
/***********************************************
* Sproc: cs_MarkThreadAsRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_MarkThreadAsRead'



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_MarkThreadAsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_MarkThreadAsRead]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.cs_MarkThreadAsRead
	@ThreadID int,
	@SectionID int,
	@UserID int,
	@SettingsID int
 AS

IF NOT EXISTS (SELECT ThreadID FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID and SectionID = @SectionID)
	INSERT INTO cs_ThreadsRead (UserID, ThreadID, SectionID, SettingsID) VALUES (@UserID, @ThreadID, @SectionID, @SettingsID)

IF @SectionID > 0
BEGIN
	DECLARE @MarkReadAfter int
	SELECT @MarkReadAfter = SR.MarkReadAfter
	FROM cs_SectionsRead SR
	WHERE SR.SettingsID = @SettingsID AND SR.UserID = @UserID AND SR.SectionID = @SectionID
	IF @MarkReadAfter IS NULL
		SET @MarkReadAfter = 0

	-- Check to see if all the threads in this section have been read
	IF (SELECT COUNT(*) 
		FROM cs_Threads T
		LEFT JOIN cs_ThreadsRead TR ON TR.SettingsID = T.SettingsID AND TR.UserID = @UserID AND TR.ThreadID = T.ThreadID AND TR.SectionID = T.SectionID
		WHERE T.SettingsID = @SettingsID AND T.SectionID = @SectionID AND TR.UserID IS NULL AND T.MostRecentPostID >= @MarkReadAfter) = 0
	BEGIN
		-- Update SectionsRead (forum)
		UPDATE cs_SectionsRead 
		SET
			NewPosts = 0,
			MarkReadAfter = (SELECT (MostRecentPostID + 1) FROM cs_Sections WHERE SectionID = @SectionID AND SettingsID = @SettingsID),
			LastActivity = GETDATE()
		WHERE
			SettingsID = @SettingsID
			AND UserID = @UserID
			AND SectionID = @SectionID

		IF @@ROWCOUNT = 0
		BEGIN
			INSERT INTO cs_SectionsRead (
				GroupID,
				SectionID,
				UserID,
				MarkReadAfter,
				NewPosts,
				LastActivity,
				SettingsID
			)
			SELECT
				GroupID,
				SectionID,
				@UserID,
				(MostRecentPostID + 1),
				0,
				GetDate(),
				SettingsID
			FROM
				cs_Sections
			WHERE
				SettingsID = @SettingsID
				AND SectionID = @SectionID
		END
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_MarkThreadAsRead]  TO [public]
GO


/***********************************************
* Sproc: cs_media_Moderate_PostSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_media_Moderate_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_media_Moderate_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_media_Moderate_PostSet]
GO
CREATE PROCEDURE dbo.cs_media_Moderate_PostSet
(
	@SectionID		int,
	@PageIndex 		int,
	@PageSize 		int,
	@SortBy 		int,
	@SortOrder 		bit,
	@UserID 		int,
	@ReturnRecordCount 	bit,
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID and PostID = ParentID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID and PostID = ParentID ORDER BY PostDate DESC

-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration,P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	jP.AttachmentFilename, jP.ContentType, jP.IsRemote, jP.Height, jP.Width, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created,
	Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = (SELECT count(UserID) from cs_Moderators where UserID = @UserID),
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
	JOIN cs_vw_PostsWithAttachmentDetails jP ON #PageIndex.PostID = jP.PostID
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_media_Moderate_PostSet]  TO [public]
GO
/***********************************************
* Sproc: cs_Media_Posts_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Media_Posts_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Media_Posts_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Media_Posts_Get]
GO

CREATE PROCEDURE [dbo].[cs_Media_Posts_Get]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate nText,
	@sqlPopulateCount ntext,
	@UserID int,
	@IncludeCategories bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
begin

	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalThreads int
	
	-- First set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	
	
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndex 
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		PostID int
	)

	exec sp_executesql @sqlPopulateCount, N'@recordCount int output', @recordCount = @TotalRecords output

	INSERT INTO #PageIndex (PostID)
	exec sp_executesql @sqlPopulate, N'@localRowsToReturn int', @localRowsToReturn = @RowsToReturn

	/* this is the size of the page */
	SET ROWCOUNT @PageSize

	SELECT 
		jT.ThreadStatus, jT.IsSticky, jT.IsLocked, jT.StickyDate, jT.MostRecentPostAuthorID, jT.MostRecentPostAuthor, jT.MostRecentPostID, jT.ThreadID, jT.ThreadDate, jT.RatingSum, jT.TotalRatings, jT.TotalReplies, jT.ThreadEmoticonID,	jP.PostID, jP.ThreadID, jP.ParentID, jP.PostAuthor, jP.UserID, jP.SectionID, jP.PostLevel, jP.SortOrder, jP.Subject, jP.PostDate, jP.IsApproved,
		jP.IsLocked, jP.IsIndexed, jP.TotalViews, jP.Body, jP.FormattedBody, jP.IPAddress, jP.PostType, jP.PostMedia, jP.EmoticonID, jP.SettingsID, jP.AggViews,
		jP.PostPropertyNames, jP.PostPropertyValues, jP.ApplicationPostType,
		jP.Points as PostPoints,
		jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.Height, jP.Width, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created,
		HasRead = 1,
		UserName = jT.PostAuthor,
		Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1 AND IsApproved = 1),
		Downloads = (SELECT COUNT(fD.UserID) FROM cs_Posts_Downloads fD (nolock) WHERE fD.PostID = jP.PostID)
	FROM 
		#PageIndex jPI
		JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
		JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND jP.SettingsID = @SettingsID and jT.SettingsID = @SettingsID
	ORDER BY
		IndexID	-- this is the ordering system we're using populated from the @sqlPopulate
	
	IF @IncludeCategories = 1
	Begin
	
		Select 
			Cats.[Name], PIC.PostID
		FROM 
			#PageIndex jPI
			JOIN cs_Posts_InCategories PIC on jPI.PostID = PIC.PostID
			JOIN cs_Post_Categories Cats on PIC.CategoryID = Cats.CategoryID
		WHERE 
			jPI.IndexID > @PageLowerBound
			AND jPI.IndexID < @PageUpperBound
			AND Cats.SettingsID = @SettingsID
	
	End
	
	DROP TABLE #PageIndex

end
GO

grant execute on [dbo].[cs_Media_Posts_Get] to public
go

/***********************************************
* Sproc: cs_Media_Post_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Media_Post_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Media_Post_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Media_Post_Get]
GO

CREATE PROCEDURE [dbo].[cs_Media_Post_Get]
/* Procedure for getting basic information on a single post. */
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int
) AS
begin


DECLARE @NextThreadID int
DECLARE @PrevThreadID int
DECLARE @ThreadID int 
DECLARE @SectionID int
DECLARE @SortOrder int
DECLARE @IsApproved bit

SELECT 
	@ThreadID = ThreadID, 
	@SectionID = SectionID, 
	@SortOrder = SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID

DECLARE @TrackingThread bit

IF @TrackViews = 1
BEGIN
	-- Update the counter for the number of times this post is viewed
	UPDATE cs_Posts SET TotalViews = (TotalViews + 1) WHERE PostID = @PostID
	UPDATE cs_Threads SET TotalViews = (TotalViews + 1) WHERE ThreadID = @ThreadID
END

-- If @UserID is 0 the user is anonymous
IF @UserID > 0 AND @IsApproved = 1
BEGIN

	-- Mark the post as read
	-- *********************
	IF NOT EXISTS (SELECT ThreadID FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		INSERT INTO cs_ThreadsRead (UserID, ThreadID, SectionID, SettingsID) VALUES (@UserID, @ThreadID, @SectionID, @SettingsID)

END

-- get the anonymous user id for this site
if( @UserID = 0 ) 
BEGIN
		SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = N'Anonymous' and SettingsID = @SettingsID
END


IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SELECT @TrackingThread = 1
ELSE
	SELECT @TrackingThread = 0

SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues, P.ApplicationPostType,
	P.Points as PostPoints,
	P.PostAuthor as [Username],
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	T.RatingSum,
	T.TotalRatings,
	HasRead = 0,
	/* TODO: the items below needs some massaging */
	EditNotes = null, /*(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),*/
	IndexInThread = (SELECT Count(P1.PostID) FROM cs_Posts P1 WHERE P1.IsApproved = 1 AND P1.ThreadID = @ThreadID AND P1.SortOrder <= @SortOrder),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],P.Created, P.Height, P.Width,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = P.UserID),
	Replies = (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1 AND IsApproved = 1),
	Downloads = (SELECT COUNT(fD.UserID) FROM cs_Posts_Downloads fD (nolock) WHERE fD.PostID = P.PostID),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P
INNER JOIN
	cs_Threads T ON P.ThreadID = T.ThreadID
WHERE 
	P.PostID = @PostID


end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Media_Post_Get] to public
go

/***********************************************
* Sproc: cs_Membership_ChangePasswordAnswer
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Membership_ChangePasswordAnswer'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Membership_ChangePasswordAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Membership_ChangePasswordAnswer]
GO


CREATE PROCEDURE [dbo].cs_Membership_ChangePasswordAnswer
(
	@ApplicationName nvarchar(256),
	@UserName nvarchar(256),
	@PasswordQuestion  nvarchar(256),
	@PasswordAnswer  nvarchar(256)
)
AS

	UPDATE
		M
	SET
		M.PasswordQuestion = @PasswordQuestion,
		M.PasswordAnswer = @PasswordAnswer
	FROM
		aspnet_Applications A
		INNER JOIN aspnet_Users U ON A.ApplicationId = U.ApplicationId
		INNER JOIN aspnet_Membership M ON U.UserId = M.UserId
	WHERE
		A.ApplicationName = @ApplicationName
		AND U.UserName = @UserName

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Membership_ChangePasswordAnswer] to public
go
/***********************************************
* Sproc: cs_Membership_GetUsersByName
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Membership_GetUsersByName'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Membership_GetUsersByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Membership_GetUsersByName]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[cs_Membership_GetUsersByName]
    @ApplicationName       NVARCHAR(256),
    @UserNames         NTEXT

AS
BEGIN

    DECLARE @ApplicationId UNIQUEIDENTIFIER
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0


	DECLARE @tbNames	table(Name nvarchar(256) collate database_default NOT NULL PRIMARY KEY) --Has to be removed until we can ensure uniqueness
	DECLARE @tbUsers	table(UserId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

    DECLARE @textpos  int --our chunks position in the ntext
    DECLARE @chunklen smallint
    DECLARE @UserNamesChunk   nvarchar(4000)
	DECLARE @delimiter nvarchar(1)
    DECLARE @leftover nvarchar(4000)

	SET @delimiter = N','
	SET @Num = 0
	SET @textpos = 1
	SET @leftover = ''

	WHILE @textpos <= DATALENGTH(@UserNames) /2
	BEGIN

		SET @chunklen = 4000 - DATALENGTH(@leftover) /2
		SET @UserNamesChunk = ltrim(@leftover + substring(@UserNames, @textpos, @chunklen))
		SET @textpos = @textpos + @chunklen

		SET @Pos = 1 

		WHILE(@Pos <= DATALENGTH(@UserNamesChunk))
		BEGIN
			SELECT @NextPos = CHARINDEX(@delimiter, @UserNamesChunk,  @Pos)
			IF (@NextPos = 0 OR @NextPos IS NULL)
			BEGIN
				--break us from the loop
				SELECT @NextPos = DATALENGTH(@UserNamesChunk) + 1
				--set the leftover string to use again in next iter
				SET @leftover = SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos)
			END
			ELSE
			BEGIN
				SELECT @Name = LOWER(RTRIM(LTRIM(SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos))))

				INSERT INTO @tbNames VALUES (@Name)

				SET @Num = @Num + 1
			END

			SELECT @Pos = @NextPos+1
		END

		IF(@Pos = DATALENGTH(@UserNamesChunk))
			SET @leftover = ''
	END

	INSERT INTO @tbNames VALUES (@leftover)


	INSERT INTO @tbUsers
	  SELECT UserId
	  FROM   dbo.aspnet_Users ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @ApplicationId


    SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate,
            m.LastLoginDate,
            u.LastActivityDate,
            m.LastPasswordChangedDate,
            u.UserId, m.IsLockedOut,
            m.LastLockoutDate
    FROM   dbo.aspnet_Membership m 
			JOIN dbo.aspnet_Users u ON u.UserId = m.UserId
			JOIN @tbUsers t ON u.UserId = t.UserId
    ORDER BY UserName

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Membership_GetUsersByName] to public
go
/***********************************************
* Sproc: cs_Membership_IsUserNameTaken
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Membership_IsUserNameTaken'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Membership_IsUserNameTaken]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Membership_IsUserNameTaken]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Membership_IsUserNameTaken]
    @ApplicationName       NVARCHAR(256),
    @UserName              NVARCHAR(256)

AS
BEGIN

    DECLARE @ApplicationId UNIQUEIDENTIFIER
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

    SELECT  COUNT(*)
    FROM    aspnet_Users
    WHERE   ApplicationId = @ApplicationId AND LoweredUserName = LOWER(@UserName)

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Membership_IsUserNameTaken] to public
go
/***********************************************
* Sproc: cs_Membership_RenameUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Membership_RenameUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Membership_RenameUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Membership_RenameUser]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Membership_RenameUser]
    @ApplicationName       NVARCHAR(256),
    @OldUserName           NVARCHAR(256),
    @NewUserName           NVARCHAR(256)

AS
BEGIN

    DECLARE @ApplicationId UNIQUEIDENTIFIER
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

    -- if new name is available
    IF NOT EXISTS (SELECT * FROM aspnet_Users WHERE ApplicationId = @ApplicationId AND LoweredUserName = LOWER(@NewUserName))
    BEGIN
        -- rename user
        UPDATE  aspnet_Users
        SET     UserName = @NewUserName,
                LoweredUserName = LOWER(@NewUserName)
        WHERE   ApplicationId = @ApplicationId AND UserName = @OldUserName
    END
    ELSE
    BEGIN
        -- new username was already taken
        SELECT 2
    END

    IF (@@ROWCOUNT = 0)
    BEGIN
        -- username not updated (possible old username was incorrect)
        SELECT 0
    END
    ELSE
    BEGIN
        -- username was updated
        SELECT 1
    END

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Membership_RenameUser] to public
go
/***********************************************
* Sproc: cs_Membership_ValidatePasswordAnswer
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Membership_ValidatePasswordAnswer'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Membership_ValidatePasswordAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Membership_ValidatePasswordAnswer]
GO


CREATE PROCEDURE [dbo].cs_Membership_ValidatePasswordAnswer
(
	@ApplicationName nvarchar(256),
	@UserName nvarchar(256),
	@PasswordAnswer nvarchar(256),
	@IsValid bit OUTPUT
)
AS

IF EXISTS
(
	SELECT *
	FROM
		aspnet_Applications A
		INNER JOIN aspnet_Users U ON A.ApplicationId = U.ApplicationId
		INNER JOIN aspnet_Membership M ON U.UserId = M.UserId
	WHERE
		A.ApplicationName = @ApplicationName
		AND U.UserName = @UserName
		AND LOWER(M.PasswordAnswer) = LOWER(@PasswordAnswer)
)
	SET @IsValid = 1
ELSE
	SET @IsValid = 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Membership_ValidatePasswordAnswer] to public
go
/***********************************************
* Sproc: cs_Message_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Message_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Message_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Message_CreateUpdateDelete]
GO

create procedure [dbo].cs_Message_CreateUpdateDelete
(
	@MessageID int,
	@Title NVarChar(1024),
	@Body NVarChar(4000),
	@Action int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	SELECT 'Not Implemented'
END
-- UPDATE
ELSE IF @Action  = 1
BEGIN
	UPDATE
		cs_Messages
	SET
		Title = @Title,
		Body = @Body
	WHERE
		MessageID = @MessageID and SettingsID = @SettingsID
END

-- DELETE
ELSE IF @Action = 2
BEGIN
	SELECT 'Not Implemented'
END	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Message_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Messaging_DeleteActivityMessage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_DeleteActivityMessage'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_DeleteActivityMessage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_DeleteActivityMessage]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_DeleteActivityMessage]
(
	@messageId uniqueidentifier
)
AS

DELETE FROM
	cs_Messaging_ActivityMessages
WHERE
	MessageId = @messageId

DELETE FROM
	cs_Messaging_Messages
WHERE
	MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_DeleteActivityMessage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_DeleteActivityMessagesForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_DeleteActivityMessagesForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_DeleteActivityMessagesForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_DeleteActivityMessagesForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_DeleteActivityMessagesForUser]
    @userId int 
AS

CREATE TABLE #ToDelete (MessageId uniqueidentifier)

INSERT INTO #ToDelete (MessageId)
    SELECT AM.MessageId
    FROM cs_Messaging_ActivityMessages AM
    INNER JOIN cs_Messaging_Messages M ON AM.MessageId = M.MessageId
    WHERE AM.UserId = @userId
    AND M.AuthorId = @userId

DELETE
FROM cs_Messaging_ActivityMessages
WHERE MessageId IN (SELECT MessageId FROM #ToDelete)

DELETE
FROM cs_Messaging_Messages
WHERE MessageId IN (SELECT MessageId FROM #ToDelete)

DROP TABLE #ToDelete

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_DeleteActivityMessagesForUser] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_DeleteProfileAnnouncement
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_DeleteProfileAnnouncement'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_DeleteProfileAnnouncement]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_DeleteProfileAnnouncement]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_DeleteProfileAnnouncement]
    @messageId uniqueidentifier
AS

-- Announcements are defined as messages that have the same
-- authorId and userId (target). In the schema, it's where
-- cs_Messaging_Messages.AuthorId = cs_Messaging_ProfileMessages.UserId

-- First get the row we need into a table variable
DECLARE @temp TABLE (MessageId uniqueidentifier)
INSERT INTO @temp (MessageId)
    SELECT a.MessageId
    FROM cs_Messaging_ProfileMessages a, cs_Messaging_Messages b
    WHERE a.UserId = b.AuthorId
    AND a.MessageId = @messageId
    AND b.MessageId = @messageId

-- Then delete from cs_Messaging_ProfileMessages
DELETE a
FROM cs_Messaging_ProfileMessages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

-- And then delete from cs_Messaging_Messages
DELETE a
FROM cs_Messaging_Messages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_DeleteProfileAnnouncement] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_DeleteProfileAnnouncementsForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_DeleteProfileAnnouncementsForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_DeleteProfileAnnouncementsForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_DeleteProfileAnnouncementsForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_DeleteProfileAnnouncementsForUser]
    @userId int
AS

-- Announcements are defined as messages that have the same
-- authorId and userId (target). In the schema, it's where
-- cs_Messaging_Messages.AuthorId = cs_Messaging_ProfileMessages.UserId

-- First get the rows we need into a table variable
DECLARE @temp TABLE (UserId int, MessageId uniqueidentifier)
INSERT INTO @temp (UserId, MessageId)
    SELECT a.UserId, a.MessageId
    FROM cs_Messaging_ProfileMessages a, cs_Messaging_Messages b
    WHERE a.UserId = @userId
    AND a.UserId = b.AuthorId
    AND a.MessageId = b.MessageId

-- Then delete from cs_Messaging_ProfileMessages
DELETE a
FROM cs_Messaging_ProfileMessages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

-- And then delete from cs_Messaging_Messages
DELETE a
FROM cs_Messaging_Messages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_DeleteProfileAnnouncementsForUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_DeleteProfileComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_DeleteProfileComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_DeleteProfileComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_DeleteProfileComment]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_DeleteProfileComment]
    @userId int,
    @messageId uniqueidentifier 
AS

-- Coments are defined as messages that have different
-- authorId and userId (target). In the schema, it's where
-- cs_Messaging_Messages.AuthorId <> cs_Messaging_ProfileMessages.UserId

-- First get the row we need into a table variable
DECLARE @temp TABLE (MessageId uniqueidentifier)
INSERT INTO @temp (MessageId)
    SELECT a.MessageId
    FROM cs_Messaging_ProfileMessages a, cs_Messaging_Messages b
    WHERE a.UserId <> b.AuthorId
    AND a.UserId = @userId
    AND a.MessageId = @messageId
    AND b.MessageId = @messageId

-- Then delete from cs_Messaging_ProfileMessages
DELETE a
FROM cs_Messaging_ProfileMessages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

-- And then delete from cs_Messaging_Messages
DELETE a
FROM cs_Messaging_Messages a
WHERE a.MessageId IN (SELECT MessageId FROM @temp)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_DeleteProfileComment] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetActivityMessage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetActivityMessage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetActivityMessage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetActivityMessage]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetActivityMessage]
    @messageId uniqueidentifier
AS

SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.[Type], b.GroupId
FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
WHERE a.MessageId = @messageId
AND b.MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetActivityMessage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetActivityMessagesForHub
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetActivityMessagesForHub'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetActivityMessagesForHub]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForHub]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForHub]
    @hubId int,
    @pageIndex int,
    @pageSize int,
	@includedMessageTypes varchar(4000),
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    [Type] nvarchar(50) collate database_default NOT NULL,
    GroupId int NULL
)

IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
BEGIN
	-- Fill temp table with all the hub's activity messages
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE a.MessageId = b.MessageId
		AND b.GroupId = @hubId
		ORDER BY DateCreated DESC

	SET @totalCount = @@ROWCOUNT

END ELSE BEGIN

	CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
	INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes

	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE a.MessageId = b.MessageId
		AND b.GroupId = @hubId
		AND b.[Type] in (SELECT [Type] FROM #TempMessageTypes)
		ORDER BY DateCreated DESC

	SET @totalCount = @@ROWCOUNT

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetActivityMessagesForHub] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetActivityMessagesForSite
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetActivityMessagesForSite'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetActivityMessagesForSite]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForSite]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForSite]
    @pageIndex int,
    @pageSize int,
	@includedMessageTypes varchar(4000),
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    [Type] nvarchar(50) collate database_default NOT NULL,
    GroupId int NULL
)

IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
BEGIN

	-- Put all user activity messages into temp table
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE b.GroupId IS NULL
		AND a.MessageId = b.MessageId
		ORDER BY a.DateCreated DESC

	SET @totalCount = @@ROWCOUNT

	-- Put all activity messages for groups into temp table (public groups only)
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b, cs_Sections c
		WHERE b.GroupId IS NOT NULL
		AND a.MessageId = b.MessageId
		AND b.GroupId = c.SectionID
		AND c.IsPublic = 1
		ORDER BY a.DateCreated DESC

	SET @totalCount = @totalCount + @@ROWCOUNT

END ELSE BEGIN

	CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
	INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes

	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE b.GroupId IS NULL
		AND a.MessageId = b.MessageId
		AND b.[Type] IN (SELECT [Type] FROM #TempMessageTypes)
		ORDER BY a.DateCreated DESC

	SET @totalCount = @@ROWCOUNT

	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b, cs_Sections c
		WHERE b.GroupId IS NOT NULL
		AND a.MessageId = b.MessageId
		AND b.GroupId = c.SectionID
		AND c.IsPublic = 1
		AND b.[Type] IN (SELECT [Type] FROM #TempMessageTypes)
		ORDER BY a.DateCreated DESC

	SET @totalCount = @totalCount + @@ROWCOUNT

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type]
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetActivityMessagesForSite] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetActivityMessagesForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetActivityMessagesForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetActivityMessagesForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
	@includedMessageTypes varchar(4000),
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    [Type] nvarchar(50) collate database_default NOT NULL,
    GroupId int NULL
)

IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
BEGIN

	-- Fill temp table with all the user's activity messages
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE a.AuthorId = @userId
		AND b.UserId = @userId
		AND a.MessageId = b.MessageId
		AND (b.GroupId IS NULL OR EXISTS(SELECT IsPublic FROM cs_Sections WHERE SectionID = b.GroupId AND IsPublic = 1))
		ORDER BY DateCreated DESC

	SET @totalCount = @@ROWCOUNT

END ELSE BEGIN
	
	CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
	INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes
		
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a, cs_Messaging_ActivityMessages b
		WHERE a.AuthorId = @userId
		AND b.UserId = @userId
		AND a.MessageId = b.MessageId
		AND (b.GroupId IS NULL OR EXISTS(SELECT IsPublic FROM cs_Sections WHERE SectionID = b.GroupId AND IsPublic = 1))
		AND b.[Type] in (SELECT [Type] FROM #TempMessageTypes)
		ORDER BY DateCreated DESC
	
	SET @totalCount = @@ROWCOUNT

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type]
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetActivityMessagesForUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetActivityMessagesForUserHubs
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetActivityMessagesForUserHubs'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetActivityMessagesForUserHubs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForUserHubs]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetActivityMessagesForUserHubs]
    @userId int,
    @pageIndex int,
    @pageSize int,
	@includedMessageTypes varchar(4000),
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    [Type] nvarchar(50) collate database_default NOT NULL,
    GroupId int NULL
)

IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
BEGIN

	-- Fill temp table with all the user's activity messages
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE b.GroupId IN (
						SELECT SectionID from cs_SectionMembers 
						WHERE UserID = @userId and MembershipType in (1, 2, 4))
		ORDER BY a.DateCreated DESC

	SET @totalCount = @@ROWCOUNT

END ELSE BEGIN
	
	CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
	INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes
		
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE EXISTS (
			SELECT 1 FROM cs_SectionMembers sm
			WHERE sm.UserID = @userId
				AND sm.MembershipType in (1, 2, 4)
				AND b.GroupId = sm.SectionID)
		AND b.[Type] in (SELECT [Type] FROM #TempMessageTypes)
		ORDER BY a.DateCreated DESC		
	
	SET @totalCount = @@ROWCOUNT

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type]
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetActivityMessagesForUserHubs] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetConversationByConversationId
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetConversationByConversationId'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetConversationByConversationId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetConversationByConversationId]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetConversationByConversationId]
    @conversationId uniqueidentifier
AS

-- Get the metadata
SELECT ConversationId, DateCreated, DateUpdated, ParticipantCount, MessageCount
FROM cs_Messaging_Conversations
WHERE ConversationId = @conversationId

-- Get the messages
SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated
FROM cs_Messaging_Messages a, cs_Messaging_Conversations b, cs_Messaging_ConversationMessages c
WHERE c.ConversationId = @conversationId
AND b.ConversationId = c.ConversationId
AND a.MessageId = c.MessageId

-- Get the participants
SELECT ParticipantId
FROM cs_Messaging_ConversationParticipants
WHERE ConversationId = @conversationId

-- Get the participants who have read the conversation
SELECT ParticipantId as ParticipantIdRead
FROM cs_Messaging_ConversationParticipants
WHERE ConversationId = @conversationId
AND IsRead = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetConversationByConversationId] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetConversationByMessageId
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetConversationByMessageId'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetConversationByMessageId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetConversationByMessageId]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetConversationByMessageId]
    @messageId uniqueidentifier
AS

DECLARE @conversationId uniqueidentifier

SET @conversationId = (SELECT ConversationId FROM cs_Messaging_ConversationMessages WHERE MessageId = @messageId)

EXECUTE cs_Messaging_GetConversationByConversationId @conversationId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetConversationByMessageId] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetConversationIdsForParticipant
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetConversationIdsForParticipant'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetConversationIdsForParticipant]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetConversationIdsForParticipant]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetConversationIdsForParticipant]
    @participantId int,
    @pageIndex int,
    @pageSize int,
    @isRead bit = null,
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	ConversationId uniqueidentifier NOT NULL
)

IF (@isRead IS NULL)
	-- Fill temp table with all the participant's active conversation IDs
	INSERT INTO #Temp (ConversationId)
	    SELECT cm.ConversationId
		FROM cs_Messaging_Messages mm
		INNER JOIN cs_Messaging_ConversationMessages cm ON cm.MessageId = mm.MessageId
		INNER JOIN
			cs_Messaging_ConversationParticipants cp ON cp.ConversationId = cm.ConversationId
				AND cp.ParticipantId = @participantId
				AND cp.Active = 1
		GROUP BY cm.ConversationId
		ORDER BY max(mm.DateCreated) DESC
ELSE
	-- Fill temp table with all the participant's active conversation IDs
	INSERT INTO #Temp (ConversationId)
	    SELECT cm.ConversationId
		FROM cs_Messaging_Messages mm
		INNER JOIN cs_Messaging_ConversationMessages cm ON cm.MessageId = mm.MessageId
		INNER JOIN
			cs_Messaging_ConversationParticipants cp ON cp.ConversationId = cm.ConversationId
				AND cp.ParticipantId = @participantId
				AND cp.Active = 1
				AND cp.IsRead = @isRead
		GROUP BY cm.ConversationId
		ORDER BY max(mm.DateCreated) DESC

-- Select total # of conversations for the participant
SET @totalCount = @@ROWCOUNT

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT ConversationId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetConversationIdsForParticipant] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetConversationMessage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetConversationMessage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetConversationMessage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetConversationMessage]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetConversationMessage]
    @messageId uniqueidentifier
AS

SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated
FROM cs_Messaging_Messages a, cs_Messaging_ConversationMessages b
WHERE a.MessageId = @messageId
AND b.MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetConversationMessage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetFriendsActivityMessagesForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetFriendsActivityMessagesForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetFriendsActivityMessagesForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetFriendsActivityMessagesForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetFriendsActivityMessagesForUser]
	@userId int,
	@pageIndex int,
	@pageSize int,
	@includedMessageTypes varchar(4000),
	@totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
	AuthorId int NOT NULL,
	[Subject] nvarchar(100) collate database_default NULL,
	Body ntext collate database_default NULL,
	DateCreated datetime NOT NULL,
	[Type] nvarchar(50) collate database_default NOT NULL,
	GroupId int NULL
)


	IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
	BEGIN
		-- Fill temp table with all activity messages for friends
		INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
			SELECT M.MessageId, M.AuthorId, M.Subject, M.Body, M.DateCreated, AM.[Type], AM.GroupId
			FROM cs_Messaging_Messages M
			INNER JOIN cs_Messaging_ActivityMessages AM ON M.MessageId = AM.MessageId
			INNER JOIN cs_Friends_xref F ON M.AuthorId = F.FriendUserID
			WHERE AM.UserId = F.FriendUserID
			AND AM.GroupId IS NULL
			AND F.UserID = @userId
			ORDER BY DateCreated DESC

		/* Select total # of activity messages */
		SET @totalCount = @@ROWCOUNT
	END ELSE BEGIN

		CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
		INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes

		INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
			SELECT M.MessageId, M.AuthorId, M.Subject, M.Body, M.DateCreated, AM.[Type], AM.GroupId
			FROM cs_Messaging_Messages M
			INNER JOIN cs_Messaging_ActivityMessages AM ON M.MessageId = AM.MessageId
			INNER JOIN cs_Friends_xref F ON M.AuthorId = F.FriendUserID
			WHERE AM.UserId = F.FriendUserID
			AND AM.GroupId IS NULL
			AND F.UserID = @userId
			AND AM.[Type] in (SELECT [Type] FROM #TempMessageTypes)
			ORDER BY DateCreated DESC

		/* Select total # of activity messages */
		SET @totalCount = @@ROWCOUNT
	END
    
-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type]
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetFriendsActivityMessagesForUser] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetProfileAnnouncement
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileAnnouncement'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileAnnouncement]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileAnnouncement]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileAnnouncement]
    @messageId uniqueidentifier
AS

-- Announcements are defined as messages that have the same
-- authorId and userId (target). In the schema, it's where
-- cs_Messaging_Messages.AuthorId = cs_Messaging_ProfileMessages.UserId

SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.UserId
FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
WHERE a.AuthorId = b.UserId
AND a.MessageId = @messageId
AND b.MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileAnnouncement] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetProfileAnnouncementsForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileAnnouncementsForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileAnnouncementsForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileAnnouncementsForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileAnnouncementsForUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    UserId int NOT NULL
)

-- Fill temp table with all the user's announcements
INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, UserId)
    SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.UserId
    FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
    WHERE b.UserId = @userId
    AND a.AuthorId = b.UserId
    AND a.MessageId = b.MessageId
    ORDER BY DateCreated DESC

-- Select total # of announcements for the user
SET @totalCount = @@ROWCOUNT

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, UserId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileAnnouncementsForUser] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetProfileCommentsByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileCommentsByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileCommentsByUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileCommentsByUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileCommentsByUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    UserId int NOT NULL
)

-- Fill temp table with all profile comments made by the user
INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, UserId)
    SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.UserId
    FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
    WHERE a.AuthorId = @userId
    AND a.AuthorId <> b.UserId
    AND a.MessageId = b.MessageId
    ORDER BY DateCreated DESC

-- Select total # of profile comments made by the user
SET @totalCount = @@ROWCOUNT

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, UserId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileCommentsByUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetProfileCommentsForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileCommentsForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileCommentsForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileCommentsForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileCommentsForUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    UserId int NOT NULL
)

-- Fill temp table with all profile comments for the user
INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, UserId)
    SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.UserId
    FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
    WHERE b.UserId = @userId
    AND a.AuthorId <> b.UserId
    AND a.MessageId = b.MessageId
    ORDER BY DateCreated DESC

-- Select total # of profile comments for the user
SET @totalCount = @@ROWCOUNT

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, UserId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileCommentsForUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetProfileMessage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileMessage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileMessage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileMessage]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileMessage]
	@messageId uniqueidentifier
AS

SELECT a.MessageId, a.AuthorId, a.[Subject], a.Body, a.DateCreated, b.UserId
FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
WHERE a.MessageId = @messageId
AND b.MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileMessage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_GetProfileMessagesForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetProfileMessagesForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetProfileMessagesForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetProfileMessagesForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetProfileMessagesForUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    UserId int NOT NULL
)

-- Fill temp table with all the user's profile messages (announcements and comments)
INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, UserId)
    SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.UserId
    FROM cs_Messaging_Messages a, cs_Messaging_ProfileMessages b
    WHERE b.UserId = @userId
    AND a.MessageId = b.MessageId
    ORDER BY DateCreated DESC

-- Select total # of profile messages for the user
SET @totalCount = @@ROWCOUNT

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, UserId
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetProfileMessagesForUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_GetSiteActivityMessagesForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_GetSiteActivityMessagesForUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_GetSiteActivityMessagesForUser]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_GetSiteActivityMessagesForUser]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_GetSiteActivityMessagesForUser]
    @userId int,
    @pageIndex int,
    @pageSize int,
	@includedMessageTypes varchar(4000),
    @totalCount int output
AS

DECLARE @rowsToReturn int
DECLARE @pageLowerBound int
DECLARE @pageUpperBound int

-- Create temp table
CREATE TABLE #Temp
(
	IndexId int identity (1, 1) NOT NULL,
	MessageId uniqueidentifier NOT NULL,
    AuthorId int NOT NULL,
    [Subject] nvarchar(100) collate database_default NULL,
    Body ntext collate database_default NULL,
    DateCreated datetime NOT NULL,
    [Type] nvarchar(50) collate database_default NOT NULL,
    GroupId int NULL
)

IF (@includedMessageTypes IS NULL OR LEN(@includedMessageTypes) = 0)
BEGIN

	-- Fill temp table with all the user's activity messages
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
	SELECT * FROM (
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE a.AuthorId = @userId
			AND b.UserId = @userId
			AND b.GroupId IS NULL
	UNION ALL
		SELECT M.MessageId, M.AuthorId, M.Subject, M.Body, M.DateCreated, AM.[Type], AM.GroupId
		FROM cs_Messaging_Messages M
			INNER JOIN cs_Messaging_ActivityMessages AM ON M.MessageId = AM.MessageId
			INNER JOIN cs_Friends_xref F ON M.AuthorId = F.FriendUserID
		WHERE AM.UserId = F.FriendUserID
			AND AM.GroupId IS NULL
			AND F.UserID = @userId
	UNION ALL
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE EXISTS (
					SELECT 1 FROM cs_SectionMembers sm
					WHERE sm.UserID = @userId
						AND sm.MembershipType in (1, 2, 4)
						AND b.GroupId = sm.SectionID)
	) AS Z ORDER BY DateCreated DESC

	SET @totalCount = @@ROWCOUNT

END ELSE BEGIN
	
	CREATE TABLE #TempMessageTypes ([Type] nvarchar(50) collate database_default NOT NULL)
	
	INSERT INTO #TempMessageTypes exec [dbo].[cs_split_varchar] @str = @includedMessageTypes
	
	-- Fill temp table with all the user's activity messages
	INSERT INTO #Temp (MessageId, AuthorId, [Subject], Body, DateCreated, [Type], GroupId)
	SELECT * FROM (
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE a.AuthorId = @userId
			AND b.UserId = @userId
			AND b.GroupId IS NULL
			AND b.[Type] in (SELECT [Type] FROM #TempMessageTypes)
	UNION ALL
		SELECT M.MessageId, M.AuthorId, M.Subject, M.Body, M.DateCreated, AM.[Type], AM.GroupId
		FROM cs_Messaging_Messages M
			INNER JOIN cs_Messaging_ActivityMessages AM ON M.MessageId = AM.MessageId
			INNER JOIN cs_Friends_xref F ON M.AuthorId = F.FriendUserID
		WHERE AM.UserId = F.FriendUserID
			AND AM.GroupId IS NULL
			AND F.UserID = @userId
			AND AM.[Type] in (SELECT [Type] FROM #TempMessageTypes)
	UNION ALL
		SELECT a.MessageId, a.AuthorId, a.Subject, a.Body, a.DateCreated, b.[Type], b.GroupId
		FROM cs_Messaging_Messages a
			INNER JOIN cs_Messaging_ActivityMessages b ON a.MessageId = b.MessageId 
		WHERE EXISTS (
			SELECT 1 FROM cs_SectionMembers sm
			WHERE sm.UserID = @userId
				AND sm.MembershipType in (1, 2, 4)
				AND b.GroupId = sm.SectionID)
			AND b.[Type] in (SELECT [Type] FROM #TempMessageTypes)
	) AS Z ORDER BY DateCreated DESC
	
	SET @totalCount = @@ROWCOUNT

END

-- Set the rowcount
SET @rowsToReturn = @pageSize * (@pageIndex + 1)
SET ROWCOUNT @rowsToReturn

-- Set the page bounds
SET @pageLowerBound = @pageSize * @pageIndex
SET @pageUpperBound = @pageLowerBound + @pageSize + 1

-- Select from temp table only the proper number of rows
SELECT MessageId, AuthorId, [Subject], Body, DateCreated, [Type]
FROM #Temp
WHERE #Temp.IndexId > @pageLowerBound
AND #Temp.IndexId <  @pageUpperBound 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_GetSiteActivityMessagesForUser] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_InsertIntoActivityMessages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoActivityMessages'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoActivityMessages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoActivityMessages]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoActivityMessages]
    @messageId uniqueidentifier,
    @userId int,
    @groupId int = NULL,
    @type nvarchar(50)
AS

INSERT INTO cs_Messaging_ActivityMessages (MessageId, UserId, GroupId, [Type])
VALUES (@messageId, @userId, @groupId, @type)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoActivityMessages] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Messaging_InsertIntoConversationMessages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoConversationMessages'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoConversationMessages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoConversationMessages]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoConversationMessages]
    @conversationId uniqueidentifier,
    @messageId uniqueidentifier
AS

INSERT INTO cs_Messaging_ConversationMessages (ConversationId, MessageId)
VALUES (@conversationId, @messageId)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoConversationMessages] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_InsertIntoConversationParticipants
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoConversationParticipants'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoConversationParticipants]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoConversationParticipants]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoConversationParticipants]
    @conversationId uniqueidentifier,
    @participantId int,
    @active bit,
    @isRead bit = null
AS

IF (@isRead IS NULL)
	INSERT INTO cs_Messaging_ConversationParticipants (ConversationId, ParticipantId, Active)
	VALUES (@conversationId, @participantId, @active)
ELSE
	INSERT INTO cs_Messaging_ConversationParticipants (ConversationId, ParticipantId, Active, IsRead)
	VALUES (@conversationId, @participantId, @active, @isRead)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoConversationParticipants] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_InsertIntoConversations
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoConversations'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoConversations]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoConversations]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoConversations]
    @conversationId uniqueidentifier,
    @dateCreated datetime,
    @dateUpdated datetime,
    @participantCount int,
    @messageCount int
AS

INSERT INTO cs_Messaging_Conversations (ConversationId, DateCreated, DateUpdated, ParticipantCount, MessageCount)
VALUES (@conversationId, @dateCreated, @dateUpdated, @participantCount, @messageCount)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoConversations] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_InsertIntoMessages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoMessages'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoMessages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoMessages]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoMessages]
    @messageId uniqueidentifier,
    @authorId int,
    @subject nvarchar(100),
    @body ntext,
    @dateCreated datetime
AS

INSERT INTO cs_Messaging_Messages (MessageId, AuthorId, [Subject], Body, DateCreated)
VALUES (@messageId, @authorId, @subject, @body, @dateCreated)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoMessages] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_InsertIntoProfileMessages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_InsertIntoProfileMessages'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_InsertIntoProfileMessages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_InsertIntoProfileMessages]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_InsertIntoProfileMessages]
    @userId int,
    @messageId uniqueidentifier
AS

INSERT INTO cs_Messaging_ProfileMessages (UserId, MessageId)
VALUES (@userId, @messageId)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_InsertIntoProfileMessages] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_UpdateConversationParticipants
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_UpdateConversationParticipants'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_UpdateConversationParticipants]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_UpdateConversationParticipants]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_UpdateConversationParticipants]
    @conversationId uniqueidentifier,
    @participantId int,
    @active bit,
    @isRead bit = null
AS

IF (@isRead IS NULL)
	UPDATE cs_Messaging_ConversationParticipants SET
	    Active = @active
	WHERE ConversationId = @conversationId
	AND ParticipantId = @participantId
ELSE
	UPDATE cs_Messaging_ConversationParticipants SET
	    Active = @active,
	    IsRead = @isRead
	WHERE ConversationId = @conversationId
	AND ParticipantId = @participantId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_UpdateConversationParticipants] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_UpdateConversations
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_UpdateConversations'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_UpdateConversations]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_UpdateConversations]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_UpdateConversations]
    @conversationId uniqueidentifier,
    @dateUpdated datetime,
    @messageCount int
AS

UPDATE cs_Messaging_Conversations SET
    DateUpdated = @dateUpdated,
    MessageCount = @messageCount
WHERE ConversationId = @conversationId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_UpdateConversations] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Messaging_UpdateProfileAnnouncement
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Messaging_UpdateProfileAnnouncement'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Messaging_UpdateProfileAnnouncement]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Messaging_UpdateProfileAnnouncement]
GO

CREATE PROCEDURE [dbo].[cs_Messaging_UpdateProfileAnnouncement]
    @messageId uniqueidentifier,
    @subject nvarchar(100),
    @body ntext
AS

-- Announcements are defined as messages that have the same
-- authorId and userId (target). In the schema, it's where
-- cs_Messaging_Messages.AuthorId = cs_Messaging_ProfileMessages.UserId

UPDATE cs_Messaging_Messages SET
    [Subject] = @subject,
    Body = @body
FROM cs_Messaging_ProfileMessages a, cs_Messaging_Messages b
WHERE a.UserId = b.AuthorId
AND a.MessageId = @messageId
AND b.MessageId = @messageId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Messaging_UpdateProfileAnnouncement] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Moderate_ApprovePost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_ApprovePost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_ApprovePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_ApprovePost]
GO


CREATE         procedure [dbo].cs_Moderate_ApprovePost
(
	@PostID		int,
	@ApprovedBy	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID 	int
DECLARE @ThreadID 	int
DECLARE @PostLevel 	int
DECLARE @UserID		int
DECLARE @IsLocked	bit

-- first make sure that the post is ALREADY non-approved
IF (SELECT IsApproved FROM cs_Posts (nolock) WHERE PostID = @PostID and SettingsID = @SettingsID) = 1
BEGIN
	print 'Post is already approved'
	SELECT 0
	RETURN
END
ELSE
BEGIN

	print 'Post is not approved'

	-- Get details about the thread and forum this post belongs in
	SELECT
		@SectionID = SectionID,
		@ThreadID = ThreadID,
		@PostLevel = PostLevel,
		@UserID	= UserID,
		@IsLocked = IsLocked
	FROM
		cs_Posts
	WHERE
		PostID = @PostID and SettingsID = @SettingsID

	-- Approve the post
	UPDATE 
		cs_Posts
	SET 
		IsApproved = 1
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID

	-- Approved the thread if necessary
	IF @PostLevel = 1
		UPDATE
			cs_Threads
		SET
			IsApproved = 1
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID

	-- Update the user's post count
	exec cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID

	-- Update the forum statistics
	exec cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

	-- Clean up unnecessary columns in forumsread
	-- exec cs_system_CleanForumsRead @SectionID, @SettingsID

	-- update the thread stats
	exec cs_system_UpdateThread @ThreadID, @PostID, @SettingsID

	-- Update Moderation audit table
	-- Update the ModerationAudit table
	exec cs_system_ModerationAction_AuditEntry 1, @ApprovedBy, @PostID, null, @SectionID, @SettingsID, null

	-- Send back a success code
	SELECT 1
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_ApprovePost] to public
go
/***********************************************
* Sproc: cs_Moderate_CheckUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_CheckUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_CheckUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_CheckUser]
GO

CREATE procedure [dbo].cs_Moderate_CheckUser 
(
	@UserID		int,
	@SectionID	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF EXISTS(SELECT SectionID FROM cs_Moderators WHERE UserID = @UserID AND SectionID = 0 and SettingsID = @SettingsID)
  SELECT 1
ELSE
  IF EXISTS (SELECT SectionID FROM cs_Moderators WHERE UserID = @UserID AND SectionID = @SectionID AND SettingsID = @SettingsID)
    SELECT 1
  ELSE
    SELECT 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_CheckUser] to public
go
/***********************************************
* Sproc: cs_Moderate_DeletePost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_DeletePost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_DeletePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_DeletePost]
GO

CREATE PROCEDURE [dbo].cs_Moderate_DeletePost
(
	@PostID INT,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@DeleteChildPosts BIT = 1,
	@SettingsID int
)
AS
-- Deletes the post

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @IsApproved bit
DECLARE @SectionID int

-- First, get information about the post that is about to be deleted.
SELECT
    @IsApproved = IsApproved,
    @SectionID = SectionID
FROM
    cs_Posts
WHERE
    PostID = @PostID and SettingsID = @SettingsID

-- If the post is not approved, permanently delete the post
IF (@IsApproved = 0)
BEGIN	
    	-- Delete the post.
	DELETE FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

	-- Update moderation statistics
	UPDATE	cs_Sections
	SET		PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID)
	WHERE	SectionID = @SectionID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
END	
ELSE
BEGIN
	DECLARE @DeletedSectionID INT
	DECLARE @OldThreadID INT
	DECLARE @NewThreadID INT
	
	-- Init data	
	SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50
	SELECT @OldThreadID = ThreadID, @SectionID = SectionID FROM cs_Posts WHERE SettingsID = @SettingsID AND PostID = @PostID
	SET @NewThreadID = NULL

	IF (@SectionID <> 0)
	BEGIN
		IF (@DeleteChildPosts = 1)
			-- Move the post and its replies to 'Deleted Posts' forum
			EXEC cs_system_DeletePostAndChildren @PostID, @DeleteChildPosts, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, NULL

		ELSE -- (@DeleteChildPosts <> 1)
			-- Move the post to 'Deleted Posts' forum, reassign children to deleted post's parent
			EXEC cs_system_DeletePostAndAdoptChildren @PostID, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUTPUT

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
		EXEC cs_system_ResetThreadStatistics @NewThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
		EXEC cs_system_ResetForumStatistics @DeletedSectionID
	END
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Moderate_DeletePost] to public
go
/***********************************************
* Sproc: cs_Moderate_Forums
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Forums'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Forums]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Forums]
GO

CREATE procedure [dbo].cs_Moderate_Forums
	(
		@SettingsID	int,
		@UserID int,	
		@ApplicationType smallint = 0
	)
	AS
	SET Transaction Isolation Level Read UNCOMMITTED
	BEGIN
	
SELECT
	LastUserActivity = '1/1/1797',
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnablePostPoints, F.EnableAnonymousPosting,
	F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.DefaultLanguage, F.IsPublic, F.HubSectionID, F.IsCommunityAggregated, W.*
FROM
	cs_Sections F
	--will this ever return a weblog?
	LEFT OUTER JOIN cs_weblog_Weblogs W on F.SectionID = W.SectionID 
WHERE
	F.IsActive = 1 AND F.SettingsID = @SettingsID AND F.ApplicationType = @ApplicationType

	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Forums] to public
go
/***********************************************
* Sproc: cs_Moderate_Forum_Roles
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Forum_Roles'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Forum_Roles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Forum_Roles]
GO




create procedure [dbo].cs_Moderate_Forum_Roles
(
	@SectionID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @Permissions TABLE
(
	RoleID uniqueidentifier NOT NULL,
	ProductAllow bit NULL,
	ProductDeny bit NULL,
	SectionAllow bit NULL,
	SectionDeny bit NULL
)

INSERT
	@Permissions
SELECT
	PP.RoleID,
	CASE WHEN (PP.AllowMask & CONVERT(bigint, 0x0000100000000000)) = (0x0000100000000000) THEN 1 ELSE 0 END,
	CASE WHEN (PP.DenyMask & CONVERT(bigint, 0x0000100000000000)) = (0x0000100000000000) THEN 1 ELSE 0 END, 
	NULL,
	NULL
FROM
	cs_ProductPermissions PP
WHERE
	PP.ApplicationType = 0
	AND PP.SettingsID = @SettingsID

UPDATE
	P
SET
	SectionAllow = CASE WHEN (SP.AllowMask & CONVERT(bigint, 0x0000100000000000)) = (0x0000100000000000) THEN 1 ELSE 0 END,
	SectionDeny = CASE WHEN (SP.DenyMask & CONVERT(bigint, 0x0000100000000000)) = (0x0000100000000000) THEN 1 ELSE 0 END
FROM
	@Permissions P INNER JOIN cs_SectionPermissions SP ON P.RoleID = SP.RoleID
WHERE
	SP.SectionID = @SectionID
	AND SP.SettingsID = @SettingsID

SELECT
	RoleID
FROM
	@Permissions
WHERE
	SectionAllow = 1 OR
	(ProductAllow = 1 AND ProductDeny = 0 AND SectionAllow IS NULL AND SectionDeny IS NULL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Moderate_Forum_Roles to public
go
/***********************************************
* Sproc: cs_Moderate_Post_Move
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Post_Move'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Post_Move]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Post_Move]
GO



CREATE    PROCEDURE [dbo].cs_Moderate_Post_Move
(
    @PostID int,
    @MoveToSectionID int,
    @MovedBy int,
    @IsModeratorOfTargetForum bit,
    @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ThreadID INT
DECLARE @SectionID INT
DECLARE @IsApproved BIT
DECLARE @PostLevel INT
DECLARE @Notes NVARCHAR(1024)

-- First, get information about the post that is about to be moved.
SELECT
	@ThreadID = ThreadID,
	@SectionID = SectionID,
	@PostLevel = PostLevel,
	@IsApproved = IsApproved
FROM
	cs_Posts
WHERE
	PostID = @PostID and SettingsID = @SettingsID

-- EAD: We only move the post if it is a top level post.
IF @PostLevel = 1
BEGIN
	DECLARE @MoveToIsModerated SMALLINT
	
	-- Get information about the destination forum.
	SELECT 
		@MoveToIsModerated = IsModerated
	FROM 
		cs_Sections
	WHERE 
		SectionID = @MoveToSectionID and SettingsID = @SettingsID
	
	-- If the post is not already approved, check the moderation status and permissions on the moderator for approved status.
	IF @IsApproved = 0
	BEGIN
		-- If the destination forum requires moderation, make sure the moderator has permission.
		IF @MoveToIsModerated = 1
		BEGIN
			IF @IsModeratorOfTargetForum = 1
			BEGIN
				-- The moderator has permissions to move the post and approve it.		
				UPDATE
					cs_Posts
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				UPDATE
					cs_PostAttachments
				SET
					SectionID = @MoveToSectionID
				WHERE
					PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

				UPDATE
					cs_Threads
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ThreadID

				-- approve the post
				EXEC cs_Moderate_ApprovePost @PostID, @MovedBy, @SettingsID
				
				SET @Notes = 'The post was moved and approved.'
				PRINT @Notes
				SELECT 2
			END
			ELSE BEGIN
				-- The moderator has permissions to move the post but not approve.			
				UPDATE
					cs_Posts
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				UPDATE
					cs_PostAttachments
				SET
					SectionID = @MoveToSectionID
				WHERE
					PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

				UPDATE
					cs_Threads
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ThreadID
				
				SET @Notes = 'The post was moved but not approved.'
				PRINT @Notes
				SELECT 1
			END
		END
		ELSE BEGIN
			UPDATE
				cs_Posts
			SET 
				SectionID = @MoveToSectionID
			WHERE 
				ThreadID = @ThreadID and SettingsID = @SettingsID

			UPDATE
				cs_PostAttachments
			SET
				SectionID = @MoveToSectionID
			WHERE
				PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

			UPDATE
				cs_Threads
			SET 
				SectionID = @MoveToSectionID
			WHERE 
				ThreadID = @ThreadID and SettingsID = @SettingsID

			DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ThreadID

			-- The destination forum is not moderated, approve the post and move the post.
			EXEC cs_Moderate_ApprovePost @PostID, @MovedBy, @SettingsID
			
			SET @Notes = 'The post was moved and approved.'
			PRINT @Notes
			SELECT 2
		END
	END
	ELSE BEGIN
		-- The post is already approved, move the post.
		UPDATE
			cs_Posts
		SET 
			SectionID = @MoveToSectionID
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID

		UPDATE
			cs_PostAttachments
		SET
			SectionID = @MoveToSectionID
		WHERE
			PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

		UPDATE
			cs_Threads
		SET 
			SectionID = @MoveToSectionID
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID

		DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ThreadID
		
		print 'The approved post was moved.'
		SET @Notes = 'The approved post was moved.'
		SELECT 3
	
	END

	-- Reset the statistics on both forums.
	EXEC cs_system_ResetForumStatistics @SectionID
	EXEC cs_system_ResetForumStatistics @MoveToSectionID
	
	-- Reset the thread statistics on the moved thread.
	EXEC cs_system_ResetThreadStatistics @ThreadID
		
	-- Update Moderation Audit table
	EXEC cs_system_ModerationAction_AuditEntry 3, @MovedBy, @PostID, null, @SectionID, @SettingsID, @Notes

END
ELSE BEGIN
	print 'The post was not moved.'
	SELECT 0
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Post_Move] to public
go
/***********************************************
* Sproc: cs_Moderate_Post_UpdateParent
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Post_UpdateParent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Post_UpdateParent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Post_UpdateParent]
GO

CREATE    PROCEDURE [dbo].cs_Moderate_Post_UpdateParent
(
	@PostID int,
	@ParentID int,
	@MovedBy int,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @ThreadID int

SELECT @ThreadID = ThreadID
FROM cs_Posts
WHERE PostID = @PostID
	 and SettingsID = @SettingsID

-- ensure the posts are in the same thread and that the post being moved is not the first post
IF @ThreadID is null 
	OR @ThreadID <> (SELECT ThreadID FROM cs_Posts WHERE PostID = @PostID and SettingsID = @SettingsID)
	OR @PostID = (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID and PostLevel = 0)
	RETURN

BEGIN TRAN

-- Do the Update
UPDATE
	cs_Posts
SET
	ParentID = @ParentID
WHERE
	PostID = @PostID and SettingsID = @SettingsID

-- Update thread statistics
EXEC cs_system_UpdateThread @ThreadID, 0, @SettingsID

-- Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 3, @MovedBy, @PostID, null, null, @SettingsID, null

COMMIT TRAN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Post_UpdateParent] to public
go
/***********************************************
* Sproc: cs_Moderate_Thread_Merge
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Thread_Merge'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Thread_Merge]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Thread_Merge]
GO


CREATE    PROCEDURE [dbo].cs_Moderate_Thread_Merge
(
	@ParentThreadID int,
	@ChildThreadID int,
	@JoinBy int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ParentSectionID int
DECLARE @LastPostInParent int
DECLARE @PostLevelInParent int
DECLARE @SortOrderInParent int
DECLARE @ChildSectionID int
DECLARE @FirstPostInChild int
DECLARE @PostLevelInChild int
DECLARE @SortOrderInChild int
DECLARE @LastPostInChild int

-- Check to ensure we can perform this opertation
IF ((SELECT ThreadID FROM cs_Threads WHERE ThreadID = @ChildThreadID and SettingsID = @SettingsID) = @ParentThreadID)
	RETURN

-- Get details on the parent thread
SELECT TOP 1
	@ParentSectionID = SectionID,
	@LastPostInParent = PostID,
	@PostLevelInParent = PostLevel,
	@SortOrderInParent = SortOrder
FROM
	cs_Posts
WHERE
	ThreadID = @ParentThreadID and SettingsID = @SettingsID
ORDER BY
	SortOrder DESC

-- Get details on the child thread
SELECT TOP 1
	@ChildSectionID = SectionID,
	@FirstPostInChild = PostID,
	@PostLevelInChild = PostLevel,
	@SortOrderInChild = SortOrder
FROM
	cs_Posts
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- don't know why this is here
-- Get the last post in the child thread
--SELECT 
--	@LastPostInChild = MostRecentPostID
--FROM
--	cs_Threads
--WHERE
--	ThreadID = @ChildThreadID

BEGIN TRAN

-- this is now done in the cs_system_UpdateThread sproc
-- Update the PostLevel and SortOrder for the Child posts before merging
--UPDATE 
--	cs_Posts
--SET
--	PostLevel = PostLevel + @PostLevelInParent
--WHERE
--	ThreadID = @ChildThreadID
--
--UPDATE 
--	cs_Posts
--SET
--	SortOrder = SortOrder + @SortOrderInParent
--WHERE
--	ThreadID = @ChildThreadID

-- Approve the post
UPDATE
	cs_Posts
SET
	IsApproved = 1
WHERE
	PostID = @FirstPostInChild AND SettingsID = @SettingsID

-- Do the Updates
UPDATE
	cs_PostAttachments
SET
	SectionID = @ParentSectionID
WHERE
	PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ChildThreadID AND SettingsID = @SettingsID)

UPDATE
	cs_Posts
SET
	ThreadID = @ParentThreadID,
	SectionID = @ParentSectionID,
	PostLevel = PostLevel + @PostLevelInParent,
	SortOrder = SortOrder + @SortOrderInParent,
	ParentID = @LastPostInParent
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Now delete all of the old thread info
DELETE FROM 
	cs_SearchBarrel
WHERE 
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Delete all thread tracking data.	
DELETE FROM 
	cs_TrackedThreads
WHERE 
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Cleanup ThreadsRead
DELETE
	cs_ThreadsRead
WHERE
	ThreadID = @ChildThreadID  and SettingsID = @SettingsID

-- Delete the child thread
DELETE 
	cs_Threads
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ChildThreadID

-- Update thread statistics
EXEC cs_system_UpdateThread @ParentThreadID, 0, @SettingsID

-- Update forum statistics
EXEC cs_system_UpdateForum @ParentSectionID, @ParentThreadID, @LastPostInParent, @SettingsID
EXEC cs_system_ResetForumStatistics @ChildSectionID

-- Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 7, @JoinBy, @ChildThreadID, null, null, @SettingsID, null

COMMIT TRAN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Thread_Merge] to public
go
/***********************************************
* Sproc: cs_Moderate_Thread_Split
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Moderate_Thread_Split'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Thread_Split]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Thread_Split]
GO



CREATE       PROCEDURE [dbo].cs_Moderate_Thread_Split
(
	@PostID INT,
	@MoveToForum INT,
	@SplitBy INT,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @IsSticky BIT
DECLARE @StickyDate DATETIME
DECLARE @IsLocked BIT
DECLARE @NewThreadID INT
DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @TopPostLevel INT
DECLARE @TopSortOrder INT
DECLARE @TotalReplies INT
DECLARE	@MostRecentPostAuthor NVARCHAR(64)
DECLARE	@MostRecentPostAuthorID INT
DECLARE	@MostRecentPostID INT

-- Get details on the post
SELECT 
	@PostDate = PostDate,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@IsSticky = 0,			-- shouldn't be a stickie when splitting
	@IsLocked = IsLocked,
	@StickyDate = GetDate(),
	@EmoticonID = EmoticonID,
	@OldThreadID = ThreadID		-- to delete later if no more replies
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

BEGIN TRAN

-- Create a new thread by inserting
INSERT cs_Threads 	
	( SectionID,
	PostDate, 
	UserID, 
	PostAuthor, 
	ThreadDate, 
	MostRecentPostAuthor, 
	MostRecentPostAuthorID, 	
	MostRecentPostID, 
	IsLocked, 
	IsApproved,
	IsSticky, 
	StickyDate, 
	ThreadEmoticonID,
	SettingsID )
VALUES
	( @MoveToForum, 	-- the forum we are moving to
	@PostDate, 
	@UserID, 
	@PostAuthor,
	@PostDate,
	@PostAuthor,	-- Dummy data until we move all posts below
	@UserID, 	-- Dummy data until we move all posts below
	0,		-- MostRecentPostID, which we don't know yet.
	@IsLocked,
	1,		-- Wouldn't be shown in the forum unless it wasn't approved already.
	@IsSticky,
	@StickyDate,
	@EmoticonID,
	@SettingsID )

SELECT @NewThreadID = SCOPE_IDENTITY()


-- Update post
UPDATE	cs_Posts
SET		PostLevel = 1,	-- this is now a thread starter
		IsApproved = 1	-- by splitting, if it wasn't approved, it is now
WHERE	PostID = @PostID AND SettingsID = @SettingsID

UPDATE
	cs_PostAttachments
SET
	SectionID = @MoveToForum
WHERE
	PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @OldThreadID AND (PostID = @PostID OR ParentID = @PostID) AND SettingsID = @SettingsID)

-- Update the post and it's childred (if any) with the new threadid
UPDATE 
	cs_Posts 
SET 
	ThreadID = @NewThreadID,
	SectionID = @MoveToForum,
	ParentID = @PostID	-- the toplevel post should now reference itself.
--	PostDate = GetDate()	-- We're not going to reset the DATETIME for the posts
WHERE
	ThreadID = @OldThreadID
	AND (PostID = @PostID OR ParentID = @PostID)  and SettingsID = @SettingsID

-- this is now controlled in the cs_system_UpdateThread sproc
-- Fix the PostLevel and SortOrder details of the new thread
--SELECT 
--	@TopPostLevel = PostLevel,
--	@TopSortOrder = SortOrder
--FROM 
--	cs_Posts 
--WHERE 
--	PostID = @PostID
--
--UPDATE 
--	cs_Posts 
--SET 
---	PostLevel = (PostLevel - @TopPostLevel) + 1,
--	SortOrder = (SortOrder - @TopSortOrder) + 1
--WHERE
--	ThreadID = @NewThreadID

-- Update the threads...
EXEC cs_system_UpdateThread @NewThreadID, 0, @SettingsID
EXEC cs_system_UpdateThread @OldThreadID, 0, @SettingsID

-- Update forum statistics
EXEC cs_system_UpdateForum @MoveToForum, @NewThreadID, @PostID, @SettingsID

-- #7. Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 8, @SplitBy, @PostID, null, null, @SettingsID, null


COMMIT TRAN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Thread_Split] to public
go
/***********************************************
* Sproc: cs_ModerationAudit_Message_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ModerationAudit_Message_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_Message_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_Message_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_Message_Get
(
	@PostID int,
	@PageIndex int,
	@PageSize int,
	@ReturnRecordCount bit,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #TmpPageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
	ID int
)

-- Select records
INSERT INTO #TmpPageIndex (ID)
	SELECT ID FROM cs_ModerationAudit (nolock) 
	WHERE PostID = @PostID AND SettingsID = @SettingsID 
	ORDER BY ModeratedOn ASC

SELECT
	MA.*,
	U.UserName AS ModeratorName
FROM 
	cs_ModerationAudit MA (nolock) LEFT JOIN cs_vw_Users_FullUser U ON U.UserID = MA.ModeratorID,
	#TmpPageIndex 
WHERE 
	MA.ID = #TmpPageIndex.ID AND
	#TmpPageIndex.IndexID > @PageLowerBound AND
	#TmpPageIndex.IndexID < @PageUpperBound AND 
	MA.SettingsID = @SettingsID
ORDER BY
	IndexID

IF @ReturnRecordCount = 1
	SELECT count(PostID) FROM cs_ModerationAudit (nolock) WHERE PostID = @PostID AND SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_Message_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_Summary_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ModerationAudit_Summary_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_Summary_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_Summary_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_Summary_Get 
(
	@PostID int = null,
	@UserID int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF (@PostID != NULL AND @UserID = NULL)
BEGIN
	SELECT 
		MAct.ModerationAction, 
		Total = (SELECT COUNT(MA.ModerationAction) FROM cs_ModerationAudit MA 
			WHERE MA.PostID = @PostID AND  MA.SettingsID =  @SettingsID AND MAct.ModerationAction = MA.ModerationAction 
			GROUP BY MA.ModerationAction)
	FROM 
		cs_ModerationAction MAct

END
ELSE IF (@UserID != NULL AND @PostID = NULL)
BEGIN
	SELECT 
		MAct.ModerationAction, 
		Total = (SELECT COUNT(MA.ModerationAction) FROM cs_ModerationAudit MA 
			WHERE MA.UserID = @UserID AND  MA.SettingsID =  @SettingsID AND MAct.ModerationAction = MA.ModerationAction 
			GROUP BY MA.ModerationAction)
	FROM 
		cs_ModerationAction MAct
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_Summary_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_User_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ModerationAudit_User_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_User_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_User_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_User_Get
(
	@UserID int,
	@ModerationAction int,
	@PageIndex int,
	@PageSize int,
	@ReturnRecordCount bit,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

--
-- IF @UserActionsFilter = 1 then we want to have the following moderation actions for provided UserID:
-- baan (12), unban (13), moderate (11), unmoderate (10), rst passwd (14), chg passwd (15), edit user (9);
-- OTHERWISE we want to these moderation actions:
-- post approved (1), post edited (2), post moved (3), post deleted (4), 5, 6, 7, 8
--
-- Sometimes the moderator is the user itself, so take both of them into account
--

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #TmpPageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
	ID int
)

-- Select records
INSERT INTO #TmpPageIndex (ID)
	SELECT ID FROM cs_ModerationAudit (nolock) 
	WHERE UserID = @UserID AND ModerationAction = @ModerationAction AND SettingsID = @SettingsID
	ORDER BY ModeratedOn ASC

SELECT
	MA.*,
	U.UserName AS ModeratorName
FROM 
	cs_ModerationAudit MA (nolock) LEFT JOIN cs_vw_Users_FullUser U ON U.UserID = MA.ModeratorID,
	#TmpPageIndex
WHERE 
	MA.ID = #TmpPageIndex.ID AND
	#TmpPageIndex.IndexID > @PageLowerBound AND
	#TmpPageIndex.IndexID < @PageUpperBound AND 
	MA.SettingsID = @SettingsID
ORDER BY
	IndexID

IF @ReturnRecordCount = 1
	SELECT COUNT(UserID) 
	FROM cs_ModerationAudit (nolock) 
	WHERE UserID = @UserID AND ModerationAction = @ModerationAction AND SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_User_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_User_SaveEvent
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ModerationAudit_User_SaveEvent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_User_SaveEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_User_SaveEvent]
GO

CREATE   procedure [dbo].cs_ModerationAudit_User_SaveEvent
(
	@UserID int,
	@ModeratorID int,
	@PasswordChanged bit = 0,
	@PasswordReset bit = 0,
	@UserBanned bit = 0,
	@BanDetails nvarchar(1024) = '',
	@UserUnbanned bit = 0,
	@UserEdited bit = 0,
	@UserModerated bit = 0,
	@UserIgnored bit = 0,
	@UserUnignored bit = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF @PasswordReset = 1
		exec cs_system_ModerationAction_AuditEntry 14, @ModeratorID, null, @UserID, null, @SettingsID, 'User password has been reset.'
	ELSE IF @PasswordChanged = 1
		exec cs_system_ModerationAction_AuditEntry 15, @ModeratorID, null, @UserID, null, @SettingsID, 'User password has been changed.'
	ELSE IF @UserBanned = 1
		exec cs_system_ModerationAction_AuditEntry 12, @ModeratorID, null, @UserID, null, @SettingsID, @BanDetails
	ELSE IF @UserUnbanned = 1
		exec cs_system_ModerationAction_AuditEntry 13, @ModeratorID, null, @UserID, null, @SettingsID, 'User profile  has been un-banned.'
	ELSE IF @UserEdited = 1
		exec cs_system_ModerationAction_AuditEntry 9, @ModeratorID, null, @UserID, null, @SettingsID, 'User profile has been updated.'
	ELSE IF @UserModerated = 1
		exec cs_system_ModerationAction_AuditEntry 11, @ModeratorID, null, @UserID, null, @SettingsID, 'User is moderated.'
	ELSE IF @UserIgnored = 1
		exec cs_system_ModerationAction_AuditEntry 20, @ModeratorID, null, @UserID, null, @SettingsID, 'User has been set to ignored.'
	ELSE IF @UserUnignored = 1
		exec cs_system_ModerationAction_AuditEntry 21, @ModeratorID, null, @UserID, null, @SettingsID, 'User has been unignored.'
	ELSE IF @UserModerated = 0
		exec cs_system_ModerationAction_AuditEntry 10, @ModeratorID, null, @UserID, null, @SettingsID, 'User is not moderated.'
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



grant execute on [dbo].cs_ModerationAudit_User_SaveEvent to public
go

/***********************************************
* Sproc: cs_nntp_GetArticlesToPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_nntp_GetArticlesToPost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetArticlesToPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetArticlesToPost]
GO

create procedure [dbo].cs_nntp_GetArticlesToPost
(
	@SectionID int
)
AS
DECLARE @MaxPostID int
DECLARE @ThreadID int
DECLARE @ParentID int
DECLARE @PostAuthor nvarchar(128)
DECLARE @Subject nvarchar(512)
DECLARE @PostDate datetime
DECLARE @SiteUrl nvarchar(512)

SET @MaxPostID = (SELECT max(PostID) FROM cs_nntp_Posts WHERE SectionID = @SectionID)

SET @SiteUrl = (	SELECT 
				SiteUrl 
			FROM 
				cs_Sites S, 
				cs_Sections SN,
				cs_SiteMappings F 
			WHERE 
				F.SiteID = S.SiteID AND 
				SN.SettingsID = F.SettingsID AND
				SN.SectionID = @SectionID
		)

CREATE TABLE #PostIndex 
(
	PostID int,
	NntpUniqueID nvarchar(1024) collate database_default
)

-- Temporary table for values we need to operate on
INSERT INTO #PostIndex (PostID, NntpUniqueID)
SELECT 
	PostID = P.PostID,
	NntpUniqueID = ('<' + CAST(P.PostID as nvarchar(64)) + '-' + CAST(P.ThreadID as nvarchar(64)) + '-' + CAST(P.ParentID as nvarchar(64)) + '@' + (@SiteUrl) + '>')
FROM 
	cs_Posts P
WHERE 
	P.PostID > @MaxPostID AND
	P.SectionID = @SectionID

-- Return values
SELECT 
	NntpReferenceId = (SELECT NntpUniqueID FROM cs_nntp_Posts WHERE PostID = P.ParentID),
	NntpGroup = (SELECT NntpGroup FROM cs_nntp_NewsGroups WHERE SectionID = @SectionID),
	P1.NntpUniqueID,
	P.*
FROM 
	cs_Posts P,
	#PostIndex P1
WHERE 
	P.PostID = P1.PostID

-- Mark items as NNTP Posts
INSERT INTO cs_nntp_Posts
SELECT 
	P.PostID,
	P.SectionID,
	0,
	P1.NntpUniqueID,
	P.SettingsID
FROM 
	cs_Posts P,
	#PostIndex P1
WHERE 
	P.PostID = P1.PostID
	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




grant execute on [dbo].[cs_nntp_GetArticlesToPost] to public
go
/***********************************************
* Sproc: cs_nntp_GetForumNewsgroups
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_nntp_GetForumNewsgroups'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetForumNewsgroups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetForumNewsgroups]
GO



CREATE    procedure [dbo].cs_nntp_GetForumNewsgroups
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT 
		*
	FROM 
		cs_nntp_Newsgroups 

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_nntp_GetForumNewsgroups] to public
go
/***********************************************
* Sproc: cs_nntp_GetLastArticleId
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_nntp_GetLastArticleId'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetLastArticleId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetLastArticleId]
GO



CREATE    procedure [dbo].cs_nntp_GetLastArticleId
(
	@SectionID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT 
		MAX(NntpPostID + 1)
	FROM 
		cs_nntp_Posts 
	WHERE 
		SectionID = @SectionID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_nntp_GetLastArticleId] to public
go
/***********************************************
* Sproc: cs_nntp_Post_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_nntp_Post_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_Post_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_Post_Add]
GO

CREATE           procedure [dbo].cs_nntp_Post_Add
(
	@NntpPostID 		int,
	@SectionID 		int,
	@NntpUniqueID 		nvarchar(256),
	@NntpParentUniqueID	nvarchar(245) = null,
	@UserName 		nvarchar(256),
	@Email	 		nvarchar(256),
	@Subject		nvarchar(256),
	@Body			ntext,
	@FormattedBody		ntext,
	@PostDate		datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @ParentID int
DECLARE @PostID int
DECLARE @ThreadID int
DECLARE @UserID int
DECLARE @SettingsID int

SELECT @SettingsID = SettingsID FROM cs_Sections WHERE SectionID = @SectionID

-- Set the Parent ID to 0
SET @ParentID = 0

-- Attempt to find the user
SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE Email = @Email

-- Not linked via email
IF @UserID IS NULL
BEGIN
	-- Attempt to link via the username
	SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName

	-- Can't find the user
	IF @UserID IS NULL
	BEGIN

		SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = 'Anonymous' and SettingsID = @SettingsID
	END
END

-- Already Added?
IF EXISTS (SELECT NntpPostID FROM cs_nntp_Posts WHERE NntpUniqueID = @NntpUniqueID)
	RETURN

-- Was a @NntpParentUniqueID specified?
IF @NntpParentUniqueID IS NOT NULL
BEGIN

	-- Attempt to find the ParentID of the Post
	SELECT 
		@ParentID = PostID
	FROM 
		cs_nntp_Posts 
	WHERE	
		NntpUniqueID = @NntpParentUniqueID

	IF @ParentID = 0
		RETURN
END

-- Insert the post into the cs_Posts table
exec cs_Post_CreateUpdate 
	@SectionID, 
	@ParentID, 
	1, 
	0,
	@Subject, 
	@UserID, 
	@UserName,
	@Body, 
	@FormattedBody, 
	0, 
	0, 
	0, 
	1,
	'1/1/1797', 
	0, 
	@PostDate, 
	'127.0.0.1', 
	null,
	null,
	@SettingsID,
	0,
	@PostID output,
	@ThreadID output

-- INSERT the post into the cs_nntp_Posts table
INSERT INTO
	cs_nntp_Posts
	(
		PostID,
		SectionID,
		NntpPostID,
		NntpUniqueID,
		SettingsID
	)
VALUES
	(
		@PostID,
		@SectionID,
		@NntpPostID,
		@NntpUniqueID,
		@SettingsID
	)

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_nntp_Post_Add] to public
go

/***********************************************
* Sproc: cs_OpenId_AssociateUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OpenId_AssociateUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OpenID_AssociateUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OpenID_AssociateUser]
GO




CREATE PROCEDURE [dbo].[cs_OpenID_AssociateUser]
(
	@OpenID nvarchar(512),
	@Email nvarchar(128),
	@UserID int,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

If Not Exists(Select UserID FROM cs_Users_OpenID where OpenID = @OpenID and SettingsID = @SettingsID)
	BEGIN
		Insert cs_Users_OpenID (OpenID, Email, UserID, SettingsID, LastAccessed, Created)
		Values (@OpenID, @Email, @UserID, @SettingsID, GetDate(), GetDate())
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OpenID_AssociateUser] to public
go
/***********************************************
* Sproc: cs_OpenId_Exists
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OpenId_Exists'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OpenID_Exists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OpenID_Exists]
GO




CREATE PROCEDURE [dbo].[cs_OpenID_Exists]
(
	@OpenID nvarchar(512),
	@SettingsID int,
	@Exists bit = 0 output
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

	Set @Exists = 0

	If Exists(Select UserID FROM cs_Users_OpenID where OpenID = @OpenID and SettingsID = @SettingsID)
	BEGIN
		Set @Exists = 1
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OpenID_Exists] to public
go
/***********************************************
* Sproc: cs_OpenId_GetOpenIds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OpenId_GetOpenIds'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OpenID_GetOpenIDs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OpenID_GetOpenIDs]
GO




CREATE PROCEDURE [dbo].[cs_OpenID_GetOpenIDs]
(
	@UserID int,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

	Select OpenID From cs_Users_OpenID where UserID = @UserID and SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OpenID_GetOpenIDs] to public
go
/***********************************************
* Sproc: cs_OpenId_GetUserId
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OpenId_GetUserId'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OpenID_GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OpenID_GetUserID]
GO




CREATE PROCEDURE [dbo].[cs_OpenID_GetUserID]
(
	@OpenID nvarchar(512),
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @UserID int

	Select @UserID = UserID From cs_Users_OpenID where OpenID = @OpenID and SettingsID = @SettingsID

	if(@UserID is not null)
	Begin
		Update cs_Users_OpenID
		Set LastAccessed = GetDate() where OpenID = @OpenID and SettingsID = @SettingsID
	End

	Select IsNull(@UserID,-1) as UserID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OpenID_GetUserID] to public
go
/***********************************************
* Sproc: cs_OpenId_UnssociateUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OpenId_UnssociateUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OpenID_UnassociateUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OpenID_UnassociateUser]
GO




CREATE PROCEDURE [dbo].[cs_OpenID_UnassociateUser]
(
	@OpenID nvarchar(512),
	@UserID int,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

delete from cs_Users_OpenID where OpenID = @OpenID and SettingsID = @SettingsID and UserID = @UserID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OpenID_UnassociateUser] to public
go
/***********************************************
* Sproc: cs_OverviewActivityReportRecords_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_OverviewActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OverviewActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OverviewActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_PageViews_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PageViews_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PageViews_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PageViews_Add]
GO
/***********************************************
* Sproc: cs_PageViews_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PageViews_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PageViews_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PageViews_Get]
GO
/***********************************************
* Sproc: cs_Page_Visits_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Page_Visits_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Page_Visits_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Page_Visits_Add]
GO
/***********************************************
* Sproc: cs_Permissions_DeleteByRole
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Permissions_DeleteByRole'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Permissions_DeleteByRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Permissions_DeleteByRole]
GO


--We will need to filter all by application name

create procedure [dbo].cs_Permissions_DeleteByRole
(
	@RoleID uniqueidentifier = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DELETE FROM cs_SectionPermissions WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	DELETE FROM cs_GroupPermissions WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	DELETE FROM cs_ProductPermissions WHERE RoleID = @RoleID AND SettingsID = @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Permissions_DeleteByRole] to public
go
/***********************************************
* Sproc: cs_Points_CalculateForPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Points_CalculateForPost'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPost]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPost
--	Calculates the points for a post
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPost]
(
	@SettingsID			int,
	@PostID				int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@VerifiedAnswerFactor int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- get post's reply count
	DECLARE		@ReplyCount		int,
				@ReplierCount	int
	SELECT		@ReplyCount = COUNT(P.PostID),
				@ReplierCount = COUNT(DISTINCT(P.UserID))
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.PostID = P.ParentID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		PP.SectionID = S.SectionID
	WHERE		PP.PostID = @PostID
		AND		PP.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation

	-- is post answered
	DECLARE		@VerifiedAnswerCount		int
	SELECT		@VerifiedAnswerCount = COUNT(PP.PostID)
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.ThreadID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		PP.SectionID = S.SectionID
	WHERE		PP.PostID = @PostID
		AND		PP.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND     (PP.PostStatus & 64) = 64   -- only get verified answers

	-- get post's rating sum
	DECLARE		@RatingSum	int
	SELECT		@RatingSum = ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		PR.PostID = @PostID
		AND		PR.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating


	-- get post's download count
	DECLARE		@DownloadCount		int,
				@DownloaderCount	int
	SELECT		@DownloadCount = COUNT(D.PostID),
				@DownloaderCount = COUNT(DISTINCT(D.UserID))
	FROM		cs_Posts_Downloads D
	INNER JOIN	cs_Posts P
		ON		D.PostID = P.PostID
	INNER JOIN	cs_Sections S
		ON		P.SectionID = S.SectionID
	WHERE		D.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		D.UserID <> P.UserID		-- ignore self-authored favorites
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- get post's favorite count
	DECLARE		@FavoriteCount	int
	SELECT		@FavoriteCount = COUNT(FP.PostID)
	FROM		cs_FavoritePosts FP
	INNER JOIN	cs_Posts P
		ON		FP.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		FP.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		FP.OwnerID <> P.UserID		-- ignore self-authored favorites
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- update post points
	UPDATE		P
	SET			Points =
				1 * @PostFactor
				+ @ReplyCount * @ReplyFactor
				+ @ReplierCount * @ReplierFactor
				+ @VerifiedAnswerCount * @VerifiedAnswerFactor
				+ @RatingSum * @RatingFactor
				+ @DownloadCount * @DownloadFactor
				+ @DownloaderCount * @DownloaderFactor
				+ @FavoriteCount * @FavoritePostFactor,
				PointsUpdated = GETDATE()
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		P.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPost] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForPostAndAuthor
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Points_CalculateForPostAndAuthor'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPostAndAuthor]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPostAndAuthor]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPostAndAuthor
--	Calculates the points for a post and its author
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPostAndAuthor]
(
	@SettingsID			int,
	@PostID				int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@VerifiedAnswerFactor int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@WikiPageEditFactor	int,
	@WikiPageCommentFactor	int,
	@WikiNewPageFactor	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- recalculate post points
	EXECUTE cs_Points_CalculateForPost @SettingsID, @PostID, @PostFactor, @ReplyFactor, @ReplierFactor, @VerifiedAnswerFactor, @RatingFactor, @DownloadFactor, @DownloaderFactor, @FavoritePostFactor, @ForumRatingType


	-- get post author
	DECLARE @UserID	int
	EXECUTE cs_Post_GetAuthorID @SettingsID, @PostID, @UserID OUTPUT


	-- recalculate author points
	EXECUTE cs_Points_CalculateForUser @SettingsID, @UserID, @FavoriteUserFactor, @RaterFactor, @ForumRatingType, @WikiPageEditFactor, @WikiPageCommentFactor, @WikiNewPageFactor


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPostAndAuthor] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForPost_Set
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Points_CalculateForPost_Set'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPost_Set]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPost_Set]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPost_Set
--	Calculates the points for a post set
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPost_Set]
(
	@SettingsID			int,
	@FilterType			int,
	@FilterValue		int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@VerifiedAnswerFactor int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	-- declare temp structures
	CREATE TABLE	#PostSet		(PostID int)
	CREATE TABLE	#ReplyData		(PostID int, ReplyCount int, ReplierCount int)
	CREATE TABLE	#VerifiedAnswerData	(PostID int, VerifiedAnswerCount int)
	CREATE TABLE	#RatingData		(PostID int, RatingSum int)
	CREATE TABLE	#DownloadData	(PostID int, DownloadCount int, DownloaderCount int)
	CREATE TABLE	#FavoriteData	(PostID int, Value int)


	-- get working post set
	INSERT INTO	#PostSet
				(PostID)
	EXECUTE		cs_Posts_GetPostIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get post's reply statistics
	INSERT INTO	#ReplyData
				(PostID, ReplyCount, ReplierCount)
	SELECT		PP.PostID, COUNT(P.PostID), COUNT(DISTINCT(P.UserID))
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.PostID = P.ParentID
	INNER JOIN	#PostSet PS
		ON		PP.PostID = PS.PostID
	WHERE		PP.SettingsID = @SettingsID
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
	GROUP BY	PP.PostID

	-- get post's verified answer statistics
	INSERT INTO	#VerifiedAnswerData
				(PostID, VerifiedAnswerCount)
	SELECT		PP.PostID, COUNT(PP.PostID)
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.ThreadID = P.PostID
	INNER JOIN	#PostSet PS
		ON		PP.PostID = PS.PostID
	WHERE		PP.SettingsID = @SettingsID
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
		AND     (PP.PostStatus & 64) = 64   -- only get verified answers
	GROUP BY	PP.PostID

	-- get post's rating statistics
	INSERT INTO	#RatingData
				(PostID, RatingSum)
	SELECT		PR.PostID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		PR.PostID = PS.PostID
	WHERE		PR.SettingsID = @SettingsID
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.PostID


	-- get post's download statistics
	INSERT INTO	#DownloadData
				(PostID, DownloadCount, DownloaderCount)
	SELECT		D.PostID, COUNT(D.PostID), COUNT(DISTINCT(D.UserID))
	FROM		cs_Posts_Downloads D
	INNER JOIN	cs_Posts P
		ON		D.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		D.PostID = PS.PostID
	WHERE		P.SettingsID = @SettingsID
		AND		D.UserID <> P.UserID		-- ignore self-downloads
	GROUP BY	D.PostID


	-- get post's favorite count
	INSERT INTO	#FavoriteData
				(PostID, Value)
	SELECT		FP.PostID, COUNT(FP.PostID)
	FROM		cs_FavoritePosts FP
	INNER JOIN	cs_Posts P
		ON		FP.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		FP.PostID = PS.PostID
	WHERE		FP.SettingsID = @SettingsID
		AND		FP.OwnerID <> P.UserID
	GROUP BY	FP.PostID


	-- disable triggers (nntp triggers make this update deathly SLOW!)
	ALTER TABLE cs_posts DISABLE TRIGGER ALL


	-- update post points
	UPDATE		P
	SET			Points =
				1 * @PostFactor
				+ ISNULL(RPD.ReplyCount, 0) * @ReplyFactor
				+ ISNULL(RPD.ReplierCount, 0) * @ReplierFactor
				+ ISNULL(VAD.VerifiedAnswerCount, 0) * @VerifiedAnswerFactor
				+ ISNULL(RTD.RatingSum, 0) * @RatingFactor
				+ ISNULL(DD.DownloadCount, 0) * @DownloadFactor
				+ ISNULL(DD.DownloaderCount, 0) * @DownloaderFactor
				+ ISNULL(FD.Value, 0) * @FavoritePostFactor,
				PointsUpdated = GETDATE()
	FROM		cs_Posts P
	INNER JOIN	#PostSet PS
		ON		P.PostID = PS.PostID
	LEFT JOIN	#ReplyData RPD
		ON		P.PostID = RPD.PostID
	LEFT JOIN	#VerifiedAnswerData VAD
		ON		P.PostID = VAD.PostID
	LEFT JOIN	#RatingData RTD
		ON		P.PostID = RTD.PostID
	LEFT JOIN	#DownloadData DD
		ON		P.PostID = DD.PostID
	LEFT JOIN	#FavoriteData FD
		ON		P.PostID = FD.PostID
	WHERE		P.SettingsID = @SettingsID


	-- enable triggers
	ALTER TABLE cs_posts ENABLE TRIGGER ALL


	-- clean up
	DROP TABLE	#FavoriteData
	DROP TABLE	#DownloadData
	DROP TABLE	#RatingData
	DROP TABLE  #VerifiedAnswerData
	DROP TABLE	#ReplyData
	DROP TABLE	#PostSet


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPost_Set] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Points_CalculateForUser'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser
--	Calculates the points for a user
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser]
(
	@SettingsID			int,
	@UserID				int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@WikiPageEditFactor	int,
	@WikiPageCommentFactor	int,
	@WikiNewPageFactor	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- get user's post points
	DECLARE		@PostPoints		int
	SELECT		@PostPoints = ISNULL(SUM(P.Points), 0)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		P.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
	
	-- get wiki page edit count
	DECLARE		@WikiPageEditCount	int
	SELECT		@WikiPageEditCount = count(P.UserId)
	FROM		cs_Wiki_PageRevisions P
	WHERE		P.UserId = @UserID
			AND P.RevisionNumber > 1

	DECLARE		@WikiPageTableEditCount	int
	SELECT		@WikiPageTableEditCount = count(P.UserId)
	FROM		cs_Wiki_Pages P
	WHERE		P.UserId = @UserID
			AND P.RevisionCount > 1

	-- get wiki page comment count
	DECLARE		@WikiPageCommentCount	int
	SELECT		@WikiPageCommentCount = count(P.UserId)
	FROM		cs_Wiki_PageComments P
	WHERE		P.UserId = @UserID

	-- get wiki new page count
	DECLARE		@WikiNewPageCount	int
	SELECT		@WikiNewPageCount = count(P.UserId)
	FROM		cs_Wiki_Pages P
	WHERE		P.UserId = @UserID 
			AND P.RevisionCount = 1

	DECLARE		@WikiNewPageRevisionCount int
	SELECT		@WikiNewPageRevisionCount = count(P.UserId)
	FROM		cs_Wiki_PageRevisions P
	WHERE		P.UserId = @UserID
			AND P.RevisionNumber = 1

	-- get user's rating sum
	DECLARE		@RatingSum	int
	SELECT		@RatingSum = ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		PR.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating


	-- update user points
	UPDATE		UP
	SET			Points =
					1 * @PostPoints
					+ @RatingSum * @RaterFactor
					+ @WikiNewPageCount * @WikiNewPageFactor
					+ @WikiPageCommentCount * @WikiPageCommentFactor
					+ @WikiPageEditCount * @WikiPageEditFactor
					+ @WikiPageTableEditCount * @WikiPageEditFactor
					+ @WikiNewPageRevisionCount * @WikiNewPageFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	WHERE		UP.UserID = @UserID
		AND		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForUser] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForUser_Set
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Points_CalculateForUser_Set'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser_Set]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser_Set]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser_Set
--	Calculates the points for a user set
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser_Set]
(
	@SettingsID			int,
	@FilterType			int,
	@FilterValue		varchar(255),
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@WikiPageCommentFactor 	int,
	@WikiPageEditFactor	int,
	@WikiNewPageFactor 	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- declare temp structures
	CREATE TABLE	#UserSet		(UserID int)
	CREATE TABLE	#PostData		(UserID int, Value int)
	CREATE TABLE	#RatingData		(UserID int, Value int)
	CREATE TABLE	#WikiEditsData		(UserID int, Value int)
	CREATE TABLE	#WikiPageEditsData	(UserID int, Value int)
	CREATE TABLE	#WikiCommentsData	(UserID int, Value int)
	CREATE TABLE	#WikiNewPagesData	(UserID int, Value int)
	CREATE TABLE	#WikiNewPageEditsData	(UserID int, Value int)

	-- get working user set
	INSERT INTO	#UserSet
				(UserID)
	EXECUTE		cs_Users_GetUserIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get user's post points
	INSERT INTO	#PostData
				(UserID, Value)
	SELECT		P.UserID, SUM(P.Points)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		P.UserID = US.UserID
	WHERE		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
	GROUP BY	P.UserID
	
	-- get user's wiki edits points
	INSERT INTO	#WikiEditsData
				(UserID, Value)
	SELECT		P.UserId, count(P.RevisionNumber)
	FROM		cs_Wiki_PageRevisions P
	INNER JOIN	#UserSet US
		ON		P.UserId = US.UserID
	WHERE P.RevisionNumber > 1
	GROUP BY	P.UserId

	INSERT INTO	#WikiPageEditsData
				(UserID, Value)
	SELECT		P.UserId, count(P.RevisionCount)
	FROM		cs_Wiki_Pages P
	INNER JOIN	#UserSet US
		ON		P.UserId = US.UserID
	WHERE P.RevisionCount > 1
	GROUP BY	P.UserId

	-- get user's wiki page comment points
	INSERT INTO	#WikiCommentsData
				(UserID, Value)
	SELECT		P.UserId, count(P.PageId)
	FROM		cs_Wiki_PageComments P
	INNER JOIN	#UserSet US
		ON		P.UserId = US.UserID
	GROUP BY	P.UserId

	-- get user's wiki new page points
	INSERT INTO	#WikiNewPagesData
				(UserID, Value)
	SELECT		P.UserId, count(P.PageId)
	FROM		cs_Wiki_Pages P
	INNER JOIN	#UserSet US
		ON		P.UserId = US.UserID
	WHERE P.RevisionCount = 1
	GROUP BY	P.UserId

	INSERT INTO	#WikiNewPageEditsData
				(UserID, Value)
	SELECT		P.UserId, count(P.RevisionNumber)
	FROM		cs_Wiki_PageRevisions P
	INNER JOIN	#UserSet US
		ON		P.UserId = US.UserID
	WHERE P.RevisionNumber = 1
	GROUP BY	P.UserId

	-- get user's rating sum
	INSERT INTO	#RatingData
				(UserID, Value)
	SELECT		PR.UserID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		PR.UserID = US.UserID
	WHERE		(PR.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.UserID


	-- update user points
	UPDATE		UP
	SET			Points =
					ISNULL(PD.Value, 0)	* 1
					+ ISNULL(RD.Value, 0) * @RaterFactor
					+ ISNULL(WNPD.Value, 0) * @WikiNewPageFactor
					+ ISNULL(WPCD.Value, 0) * @WikiPageCommentFactor
					+ ISNULL(WPED.Value, 0) * @WikiPageEditFactor
					+ ISNULL(WPD.Value, 0) * @WikiPageEditFactor
					+ ISNULL(WNPED.Value, 0) * @WikiNewPageFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	INNER JOIN	#UserSet US
		ON		UP.UserID = US.UserID
	LEFT JOIN	#PostData PD
		ON		UP.UserID = PD.UserID
	LEFT JOIN	#RatingData RD
		ON		UP.UserID = RD.UserID
	LEFT JOIN	#WikiEditsData WPED
		ON		UP.UserID = WPED.UserId
	LEFT JOIN	#WikiCommentsData WPCD
		ON		UP.UserID = WPCD.UserId
	LEFT JOIN	#WikiNewPagesData WNPD
		ON		UP.UserID = WNPD.UserId
	LEFT JOIN	#WikiNewPageEditsData WNPED
		ON		UP.UserID = WNPED.UserId
	LEFT JOIN	#WikiPageEditsData WPD
		ON		UP.UserID = WPD.UserId
	WHERE		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	-- clean up
	DROP TABLE	#RatingData
	DROP TABLE	#PostData
	DROP TABLE	#UserSet
	DROP TABLE	#WikiEditsData
	DROP TABLE	#WikiCommentsData
	DROP TABLE	#WikiNewPagesData
	DROP TABLE	#WikiNewPageEditsData
	DROP TABLE	#WikiPageEditsData

	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForUser_Set] to [public]

/***********************************************
* Sproc: cs_PostAttachment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment]
GO







create procedure [dbo].cs_PostAttachment
(
	@PostID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	
		SELECT
			[PostID], [SectionID], [UserID], [Created], [FileName],  
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [Height], [Width], [FriendlyFileName]
		FROM
			cs_PostAttachments
		WHERE
			PostID = @PostID


END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment] to public
go
/***********************************************
* Sproc: cs_PostAttachment_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Add]
GO










CREATE PROCEDURE [dbo].[cs_PostAttachment_Add]
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height] 	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
	end
	else
	begin
		INSERT INTO 
			cs_PostAttachments
		(
			PostID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			[Height],
			[Width]
		)
		VALUES
		(
			@PostID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			@Height,
			@Width
		)
	end
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_Add] to public
go

/***********************************************
* Sproc: cs_PostAttachment_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Delete]
GO


CREATE PROCEDURE dbo.cs_PostAttachment_Delete
(
	@PostID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @SettingsID int
	DECLARE @SectionID int

	SELECT @SettingsID = SettingsID, @SectionID = SectionID FROM cs_PostAttachments WHERE PostID = @PostID

	DELETE FROM cs_PostAttachments WHERE PostID = @PostID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_Delete] to public
go

/***********************************************
* Sproc: cs_PostAttachment_Delete_ForSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Delete_ForSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Delete_ForSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.[cs_PostAttachment_Delete_ForSection]
GO

create procedure [dbo].cs_PostAttachment_Delete_ForSection
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT PostID
	FROM cs_PostAttachments
	WHERE SectionID = @SectionID
		AND SettingsID = @SettingsID
		AND IsRemote = 0

	DELETE FROM cs_PostAttachments WHERE SectionID = @SectionID AND SettingsID = @SettingsID	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.[cs_PostAttachment_Delete_ForSection] to public
go
/***********************************************
* Sproc: cs_PostAttachment_Temp_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Create]
GO



CREATE Procedure [dbo].cs_PostAttachment_Temp_Create
(
	@UserID int,
	@SettingsID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@AttachmentID uniqueidentifier,
	@Height int = 0,
	@Width int = 0
)

as
SET Transaction Isolation Level Read UNCOMMITTED

		INSERT INTO 
		cs_PostAttachments_TEMP
		(
			AttachmentID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			Created,
			[Height],
			[Width]
		)
		VALUES
		(
			@AttachmentID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			getdate(),
			@Height,
			@Width
		)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Create]  TO [public]
GO


/***********************************************
* Sproc: cs_PostAttachment_Temp_Expire
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Expire'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Expire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Expire]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[cs_PostAttachment_Temp_Expire] 
(
	@Date datetime
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT AttachmentID
	FROM cs_PostAttachments_TEMP WHERE Created < @Date

	DELETE FROM cs_PostAttachments_TEMP WHERE Created < @Date

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Expire]  TO [public]
GO

/***********************************************
* Sproc: cs_PostAttachment_Temp_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Get]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE procedure [dbo].[cs_PostAttachment_Temp_Get] 
(
	@UserID int,
	@SectionID int,
	@AttachmentID uniqueidentifier,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

		SELECT
			-1 as [PostID],[SectionID], [UserID], [Created], [FileName], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [FriendlyFileName], [Height], [Width]
		FROM
			cs_PostAttachments_TEMP
		WHERE
			AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_PostAttachment_ToggleTemporary
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_ToggleTemporary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_ToggleTemporary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_ToggleTemporary]
GO


CREATE procedure dbo.cs_PostAttachment_ToggleTemporary 
(
	@AttachmentID uniqueidentifier,
	@UserID int,
	@PostID int,
	@FriendlyFileName nvarchar(256),
	@SectionID int,
	@SettingsID int,
	@DeleteTempOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

		SELECT
			@PostID as [PostID], [SectionID], [UserID], [Created], [FileName],  
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [FriendlyFileName], [Height], [Width]
		FROM
			cs_PostAttachments_TEMP
		WHERE
			AttachmentID = @AttachmentID and SettingsID = @SettingsID


	IF(@DeleteTempOnly = 0)
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
		BEGIN
			UPDATE cs_PostAttachments SET
				cs_PostAttachments.[FileName] 	= T.[FileName],
				cs_PostAttachments.[FriendlyFileName] = IsNull(@FriendlyFileName,T.FriendlyFileName),
				cs_PostAttachments.ContentSize	= T.ContentSize,
				cs_PostAttachments.IsRemote	= T.IsRemote,
				cs_PostAttachments.Height	= T.Height,
				cs_PostAttachments.Width	= T.Width,
				cs_PostAttachments.ContentType = T.ContentType,
				cs_PostAttachments.Created = T.Created,
				cs_PostAttachments.SectionID = @SectionID,
				cs_PostAttachments.UserID = @UserID
			FROM cs_PostAttachments_TEMP T
			WHERE
				cs_PostAttachments.PostID = @PostID and
				cs_PostAttachments.SettingsID = @SettingsID and
				T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID
		END
		ELSE
		BEGIN
			INSERT INTO 
			cs_PostAttachments
			(
				PostID,
				SectionID,
				UserID,
				[FileName],
				[FriendlyFileName],
				ContentType,
				ContentSize,
				IsRemote,
				SettingsID,
				Created,
				[Height],
				[Width]
			)
			Select @PostID,	@SectionID, @UserID,T.[FileName],IsNull(@FriendlyFileName,T.FriendlyFileName), T.ContentType,
				T.ContentSize,	T.IsRemote, T.SettingsID,T.Created, T.Height, T.Width
			FROM cs_PostAttachments_TEMP T
			WHERE T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID
		END
	END

	DELETE FROM cs_PostAttachments_TEMP where AttachmentID = @AttachmentID and SettingsID = @SettingsID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_ToggleTemporary] to public
go
/***********************************************
* Sproc: cs_PostAttachment_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostAttachment_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.[cs_PostAttachment_Update]
GO

create procedure [dbo].cs_PostAttachment_Update 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height]	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	

		EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
	end
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.[cs_PostAttachment_Update] to public
go
/***********************************************
* Sproc: cs_PostCategories_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostCategories_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get]
GO

CREATE PROCEDURE dbo.cs_PostCategories_Get
	@SectionID int=0,
	@ApplicationKey nvarchar(256)=null
AS

SET Transaction Isolation Level Read UNCOMMITTED


if @ApplicationKey Is Not Null
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	LEFT JOIN cs_Sections F ON F.SectionID = C.SectionID
	WHERE F.ApplicationKey = @ApplicationKey
end
else
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	WHERE C.SectionID = @SectionID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_PostCategories_Get_ByName
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostCategories_Get_ByName'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get_ByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get_ByName]
GO

CREATE PROCEDURE [dbo].[cs_PostCategories_Get_ByName]
	@Name nvarchar(256),
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC sp_executesql @SectionQuerySQL

SELECT
	C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
	C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.[Name] = @Name
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get_ByName]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategories_Get_WithoutPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostCategories_Get_WithoutPosts'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get_WithoutPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get_WithoutPosts]
GO

CREATE PROCEDURE [dbo].[cs_PostCategories_Get_WithoutPosts]
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC sp_executesql @SectionQuerySQL

SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.CategoryID not in (
		select CategoryID
		from cs_Posts_InCategories PiC
		inner join cs_Posts P on P.PostID = PiC.PostID
		where P.SectionID in (select SectionID from #Sections)
			and P.SettingsID = @SettingsID
		)
	and C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.CategoryID not in (
		select UpLevelID
		from cs_Post_Categories_Parents
		where SectionID in (select SectionID from #Sections)
			and UpLevelID <> CategoryID
		)	

DROP TABLE #Sections
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get_WithoutPosts]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategories_Parents_RebuildIndex
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostCategories_Parents_RebuildIndex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Parents_RebuildIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Parents_RebuildIndex]
GO
CREATE PROCEDURE [dbo].[cs_PostCategories_Parents_RebuildIndex]
	@SectionID INT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Create some temporary storage for the update
	DECLARE @pathtable TABLE(
		CategoryID int not null,
		UpLevelID int not null,
		[path] varchar(255) collate database_default,
		SectionID int not null,
		unique (CategoryID, UpLevelID))
	
	--Fix any orphaned categories
	UPDATE pc
	SET
		pc.ParentID = 0
	FROM
		cs_Post_Categories pc
	WHERE
		pc.ParentID <> 0
		AND pc.ParentID NOT IN ( SELECT pcx.CategoryID FROM cs_Post_Categories pcx )

	IF @SectionID IS NULL
	BEGIN

		--every post category is at least in itself
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/' FROM cs_Post_Categories
		
		--Get all the non parents parents
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0
	

		--Recurse until we have reached the root for all
		WHILE @@Rowcount > 0
		BEGIN
			
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT  C.SectionID, P.CategoryID, C.ParentID,  RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL

		END
	

	END
	ELSE
	BEGIN
		--every post category is at least in itself (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE SectionID = @SectionID

		--Get all the non parents parents (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0 AND SectionID = @SectionID

		--Recurse until we have reached the root for all (for this section)
		WHILE @@Rowcount > 0
		BEGIN
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT C.SectionID, P.CategoryID, C.ParentID,   RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL AND C.SectionID = @SectionID
		END
	END

	--Recalculate category stats for selected section
	UPDATE pc SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories pc
	INNER JOIN (
		SELECT P.UpLevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
		FROM 
			cs_Posts_InCategories PIC 
			INNER JOIN cs_Posts jP ON jP.PostID = PIC.PostID AND jP.PostLevel = 1 --AND jP.IsApproved = 1 -- this was not originally included in this sproc
			INNER JOIN @pathtable P ON PIC.CategoryID = P.CategoryID
		GROUP BY P.UpLevelID
	) QSUB ON pc.CategoryID = QSUB.CategoryID
	INNER JOIN (
		SELECT PIC.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
		FROM 
			cs_Posts_InCategories PIC 
			INNER JOIN cs_Posts jP ON jP.PostID = PIC.PostID AND jP.PostLevel = 1 --AND jP.IsApproved = 1 -- this was not originally included in this sproc
			INNER JOIN @pathtable P ON PIC.CategoryID = P.CategoryID
		GROUP BY PIC.CategoryID
	) QCURR ON pc.CategoryID = QCURR.CategoryID

	--Commit the path table for use in adding / deleting posts in categories
	-- adding Uplevels that were 
	INSERT INTO cs_Post_Categories_Parents (SectionID, CategoryID, UpLevelID)
	SELECT pt.SectionID, pt.CategoryID, pt.UpLevelID
	FROM @pathtable pt
	WHERE NOT EXISTS (
		select 1 from cs_Post_Categories_Parents pcp
		where pt.CategoryID = pcp.CategoryID
			and pt.UpLevelID = pcp.UpLevelID
	)
	
	IF @SectionID IS NULL
		DELETE pcp
		FROM cs_Post_Categories_Parents pcp
		WHERE
			not exists (
				select 1 from @pathtable pt
				where pt.CategoryID = pcp.CategoryID
					and pt.UpLevelID = pcp.UpLevelID
			)
	ELSE
		-- consider an index on SectionID on this table
		DELETE pcp
		FROM cs_Post_Categories_Parents pcp
		WHERE
			pcp.SectionID = @SectionID
			and not exists (
				select 1 from @pathtable pt
				where pt.CategoryID = pcp.CategoryID
					and pt.UpLevelID = pcp.UpLevelID
			)
	
	--Rebuild the path (for legacy support, this value is not currently used by the galleries)

	SELECT P.CategoryID, P.[path] from @pathtable P JOIN cs_Post_Categories C on P.UpLevelID = C.CategoryID and C.ParentID = 0

	--Commit the new path to the Categoies table
	UPDATE cs_Post_Categories SET cs_Post_Categories.[Path] = NewPath.[path] from cs_Post_Categories 
		JOIN 
			(SELECT P.CategoryID, P.[path] FROM @pathtable P 
				JOIN cs_Post_Categories C ON P.UpLevelID = C.CategoryID AND C.ParentID = 0
			) NewPath ON cs_Post_Categories.CategoryID = NewPath.CategoryID

END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Parents_RebuildIndex]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategory_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostCategory_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategory_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategory_CreateUpdateDelete]
GO





CREATE PROCEDURE [dbo].[cs_PostCategory_CreateUpdateDelete]
	@DeleteCategory bit=0,
	@SectionID int=0,
	@Name nvarchar(256)='',
	@IsEnabled bit=1,
	@ParentID int=0,
	@Description nvarchar(2000)=null,
	@SettingsID int,
	@FeaturedPostID int = null,
	@CategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting?
if @DeleteCategory = 1
begin
	DELETE FROM cs_Posts_InCategories WHERE CategoryID = @CategoryID
	DELETE FROM [cs_Post_Categories_Parents] WHERE CategoryID = @CategoryID
	DELETE FROM cs_Post_Categories WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID
	RETURN
end

-- Find out the new path
declare @Path nvarchar(255)
set @Path = isnull((select Path + convert(nvarchar, CategoryID) + '/' from cs_Post_Categories where CategoryID = @ParentID and SectionID = @SectionID and SettingsID = @SettingsID), '/')

-- Are we updating?
if @CategoryID > 0
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID AND CategoryID <> @CategoryID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	UPDATE cs_Post_Categories SET
		Name = @Name,
		IsEnabled = @IsEnabled,
		ParentID = @ParentID,
		Description = @Description,
		Path = @Path,
		FeaturedPostID = @FeaturedPostID
	WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	INSERT INTO cs_Post_Categories (SectionID, Name, IsEnabled, ParentID, [Description], [Path], SettingsID, FeaturedPostID)
		VALUES (@SectionID, @Name, @IsEnabled, @ParentID, @Description, @Path, @SettingsID, @FeaturedPostID)
	set @CategoryID = SCOPE_IDENTITY()
end
EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID

GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategory_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_PostMetadata_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostMetadata_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostMetadata_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostMetadata_Get]
GO


CREATE PROCEDURE dbo.cs_PostMetadata_Get
	@PostID int,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

select MetaKey, MetaType, MetaValue from cs_PostMetadata where PostID = @PostID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostMetadata_Get] to public
go
/***********************************************
* Sproc: cs_PostMetadata_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostMetadata_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostMetadata_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostMetadata_Update]
GO


CREATE PROCEDURE dbo.cs_PostMetadata_Update
	@PostID int,
	@MetadataList ntext,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
delete from cs_PostMetadata where PostID = @PostID

if @MetadataList is null --or len(ltrim(rtrim(@MetadataList))) = 0
return

declare @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @MetadataList

insert into cs_PostMetaData (PostID, MetaKey, MetaType, MetaValue)
	select @PostID, M.[key], M.[type], M.[value]
	from openxml(@idoc, '/entries/entry', 1)
		with ([key] nvarchar(100), [type] nvarchar(100), [value] nvarchar(100)) as M

EXEC sp_xml_removedocument @idoc
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostMetadata_Update] to public
go
/***********************************************
* Sproc: cs_PostPoints_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PostPoints_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostPoints_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostPoints_Add]
GO

/***********************************************
* Sproc: cs_posts_AddAuditDeletedPostContent
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_posts_AddAuditDeletedPostContent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_posts_AddAuditDeletedPostContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_posts_AddAuditDeletedPostContent]
GO


Create Proc [dbo].cs_posts_AddAuditDeletedPostContent
(
	@PostID int = -1,
	@UserID int  = -1,
	@SectionID int = -1,
	@SettingsID int = -1,
	@ApplicationType int = 9999,
	@ParentID int = -1,
	@ThreadID int = -1,
	@PostType int = -1,
	@PostLevel int = -1,
	@Body ntext = null,
	@Subject nvarchar(500) = null,
	@IPAddress nvarchar(50) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SpamScore int = -1,
	@PostStatus int = -1
)

as

Insert cs_posts_deleted_archive (PostID, UserID, SectionID, SettingsID, ApplicationType, Body, Subject, IPAddress, DeletedDate, ParentID, ThreadID, PostLevel, PostType, PropertyNames, PropertyValues, SpamScore, PostStatus)
Values (@PostID, @UserID, @SectionID, @SettingsID, @ApplicationType, @Body, @Subject, @IPAddress, getdate(), @ParentID, @ThreadID, @PostLevel, @PostType, @PropertyNames, @PropertyValues, @SpamScore, @PostStatus)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_posts_AddAuditDeletedPostContent to public
GO
/***********************************************
* Sproc: cs_Posts_GetPostIDByFilter
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_GetPostIDByFilter'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Posts_GetPostIDByFilter
--	Returns a list of filtered PostIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Posts_GetPostIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@PostSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of post set
		SET @PostSetSize = CONVERT(int, @FilterValue)

		-- limit number of posts to work with (non-positive = ALL)
		IF @PostSetSize > 0
			SET ROWCOUNT @PostSetSize

		-- get posts to work with
		SELECT		P.PostID
		FROM		cs_Posts P
		INNER JOIN	cs_Sections S				-- exclude private messages
			ON		P.SectionID = S.SectionID
		WHERE		P.SettingsID = @SettingsID
			AND		S.EnablePostPoints = 1		-- ignore excluded sections
			AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		ORDER BY	PointsUpdated				-- start with "stalest" posts

		-- limit has been used; reset to default
		IF @PostSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Posts_GetPostIDByFilter] to [public]

/***********************************************
* Sproc: cs_Posts_GetPostInCategories
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_GetPostInCategories'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostInCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostInCategories]
GO





CREATE PROCEDURE dbo.cs_Posts_GetPostInCategories
	@PostID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	C.*
FROM cs_Posts_InCategories P
RIGHT JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
WHERE P.PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Posts_GetPostInCategories]  TO [public]
GO

/***********************************************
* Sproc: cs_Posts_GetPostsInNoCategories
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_GetPostsInNoCategories'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostsInNoCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostsInNoCategories]
GO





CREATE PROCEDURE dbo.cs_Posts_GetPostsInNoCategories
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues
FROM cs_Posts P
WHERE P.SectionID = @SectionID
	AND P.ParentID = P.PostID
	AND P.PostID NOT IN ( SELECT PostID FROm cs_Posts_InCategories )
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Posts_GetPostsInNoCategories]  TO [public]
GO

/***********************************************
* Sproc: cs_Posts_ReindexByGroup
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_ReindexByGroup'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexByGroup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexByGroup]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByGroup]
(
	@GroupID	int,
	@SettingsID	int
)
AS
	-- first, set the post to be removed from the index
	INSERT cs_es_Search_RemoveQueue (PostID, SettingsID, ApplicationType) 
	SELECT P.PostID, P.SettingsID, A.ApplicationName
	FROM cs_Posts P 
	INNER JOIN cs_Sections S on S.SectionID = P.SectionID
	INNER JOIN cs_ApplicationType A ON A.ApplicationType = S.ApplicationType
	WHERE S.GroupID = @GroupID AND P.SettingsID = @SettingsID
	AND	PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, add post to reindex table
	UPDATE cs_Posts set IsIndexed = 0 
	FROM cs_Posts P 
	INNER JOIN cs_Sections S on S.SectionID = P.SectionID
	WHERE S.GroupID = @GroupID AND P.SettingsID = @SettingsID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexByGroup] to public
go
/***********************************************
* Sproc: cs_Posts_ReindexBySection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_ReindexBySection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexBySection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexBySection]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexBySection]
(
	@SectionID	int,
	@SettingsID	int
)
AS
	--this proc intentionally renames all posts across all settingsids by that user


	-- first, set the post to be removed from the index
	INSERT cs_es_Search_RemoveQueue (PostID, SettingsID, ApplicationType) 
	SELECT P.PostID, P.SettingsID, A.ApplicationName 
	FROM cs_Posts P 
	INNER JOIN cs_Sections S ON S.SectionID = P.SectionID
	INNER JOIN cs_ApplicationType A ON A.ApplicationType = S.ApplicationType
	WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID
	AND	PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, add post to reindex table
	UPDATE cs_Posts set IsIndexed = 0 
	FROM cs_Posts P 
	WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexBySection] to public
go
/***********************************************
* Sproc: cs_Posts_ReindexByTag
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_ReindexByTag'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexByTag]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexByTag]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByTag]
(
	@CategoryID	int,
	@SettingsID	int
)
AS
	-- first, set the post to be removed from the index
	INSERT cs_es_Search_RemoveQueue (PostID, SettingsID, ApplicationType) 
	SELECT P.PostID, P.SettingsID, A.ApplicationName 
	FROM cs_Posts P 
	JOIN cs_Posts_InCategories PIC on P.PostID = PIC.PostID 
	INNER JOIN cs_Sections S ON S.SectionID = P.SectionID
	INNER JOIN cs_ApplicationType A ON A.ApplicationType = S.ApplicationType
	WHERE PIC.CategoryID = @CategoryID AND P.SettingsID = @SettingsID
	AND	P.PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, reset post to be indexed
	UPDATE cs_Posts set IsIndexed = 0 
	From cs_Posts P 
		JOIN cs_Posts_InCategories PIC on P.PostID = PIC.PostID 
	WHERE PIC.CategoryID = @CategoryID AND P.SettingsID = @SettingsID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexByTag] to public
go
/***********************************************
* Sproc: cs_Posts_ReindexByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_ReindexByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexByUser]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByUser]
(
	@UserID	int
)
AS
	--this proc intentionally renames all posts across all settingsids by that user


	-- first, set the post to be removed from the index
	INSERT INTO	cs_es_Search_RemoveQueue (PostID, SettingsID, ApplicationType)
	SELECT		P.PostID, P.SettingsID, A.ApplicationName
	FROM		cs_Posts P
	INNER JOIN cs_Sections S ON S.SectionID = P.SectionID
	INNER JOIN cs_ApplicationType A ON A.ApplicationType = S.ApplicationType
	WHERE		P.UserID = @UserID
		AND	P.PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, add post to reindex table
	UPDATE	cs_Posts
	SET		IsIndexed =  0
	WHERE	UserID = @UserID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexByUser] to public
go
/***********************************************
* Sproc: cs_Posts_UpdatePostsInCategories
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_UpdatePostsInCategories'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_UpdatePostsInCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_UpdatePostsInCategories]
GO

CREATE PROCEDURE [dbo].[cs_Posts_UpdatePostsInCategories]
(
	@CategoryList nvarchar(4000) = null,
	@SectionID int,
	@PostID int,
	@SettingsID int = null,
	@UpdateStats bit = 1
)
as
begin

	set nocount on
	
	-- If the post is not in any categories, we have to rebuild the index incase we are deleting a post or removing categories
	IF @CategoryList Is Not Null AND LEN(LTRIM(RTRIM(@CategoryList))) > 0
	BEGIN
		DECLARE @idoc int
		-- declare @CategoryList nvarchar(4000)
		-- select @CategoryList = "<?xml version=""1.0"" ?><Categories><Category>Test</Category></Categories>"

		DECLARE @CategoryNameList TABLE (
			CategoryName nvarchar(255) collate database_default not null
		)
		EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList
		
		insert into @CategoryNameList(CategoryName)
		Select DISTINCT
			CONVERT(nvarchar(255), X.[text])
		FROM 
			OPENXML(@idoc, '/Categories/Category/', 2) X
		where 
			X.[text] is not null  

		EXEC sp_xml_removedocument @idoc
		
		--Insert Missing Categories
		INSERT INTO cs_Post_Categories (SectionID, [Name], IsEnabled, ParentID, [Description], SettingsID)
		Select
			@SectionID, X.CategoryName, 1, 0, null, @SettingsID
		FROM 
			@CategoryNameList X
		where 
			not exists (
				Select 1 FROM cs_Post_Categories pc
				where
					X.CategoryName = pc.[Name]
					and pc.SectionID = @SectionID
			) 
		
		IF @@ROWCOUNT > 0
			exec [cs_PostCategories_Parents_RebuildIndex] @SectionID

		--Insert Entry Categories
		INSERT INTO cs_Posts_InCategories ( PostID, CategoryID, SettingsID )
		SELECT
			@PostID, C.CategoryID, @SettingsID
		FROM
			cs_Post_Categories C
		WHERE
			C.SectionID = @SectionID
			and EXISTS (
				select 1 from @CategoryNameList x
				where
					C.[Name] = x.CategoryName
			)
			and not exists (
				select 1 from cs_Posts_InCategories pic
				where
					pic.PostID = @PostID
					and pic.CategoryID = C.CategoryID
					and pic.SettingsID = @SettingsID
			)
		
		DELETE pic FROM cs_Posts_InCategories pic
		WHERE
			pic.PostID = @PostID
			and not exists (
				select 1 from cs_Post_Categories C
				inner join @CategoryNameList x ON C.[Name] = x.CategoryName
				where
					C.CategoryID = pic.CategoryID
			)
		
	END ELSE BEGIN
	
		DELETE pic FROM cs_Posts_InCategories pic
		WHERE pic.PostID = @PostID
	
	END

	if(@UpdateStats = 1) --for changes we need to rebuild the entire section stats
	Begin
		UPDATE pc SET
			pc.TotalSubThreads = IsNull(QSUB.posts, 0),
			pc.MostRecentSubPostDate = QSUB.postdate,
			pc.TotalThreads = IsNull(QCURR.posts, 0),
			pc.MostRecentPostDate = QCURR.postdate
		FROM cs_Post_Categories pc
		LEFT JOIN (
			SELECT P.UpLevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate
			FROM
				cs_Posts_InCategories PIC
				INNER JOIN cs_Posts jP
					ON jP.PostID = PIC.PostID AND jP.IsApproved = 1 AND jP.PostLevel = 1
				INNER JOIN cs_Post_Categories_Parents P
					ON PIC.CategoryID = P.CategoryID AND jP.SectionID = P.SectionID AND P.SectionID = @SectionID
				INNER JOIN cs_Post_Categories C
					ON C.CategoryID = P.CategoryID
			GROUP BY P.UpLevelID
		) QSUB ON pc.CategoryID = QSUB.CategoryID
		LEFT JOIN (
			SELECT PIC.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
			FROM 
				cs_Posts_InCategories PIC 
				INNER JOIN cs_Posts jP
					ON jP.PostID = PIC.PostID AND jP.SectionID = @SectionID AND jP.PostLevel = 1 AND jP.IsApproved = 1
			GROUP BY PIC.CategoryID
		) QCURR ON pc.CategoryID = QCURR.CategoryID
		WHERE
			pc.SectionID = @SectionID
	End
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_UpdatePostsInCategories] to public
go

/***********************************************
* Sproc: cs_Posts_Views_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Posts_Views_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_Views_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_Views_Add]
GO

Create Proc [dbo].[cs_Posts_Views_Add]
(
	@PostID int,
	@AggCount int,
	@WebCount int,
	@WebThreadCount int
)

as
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	declare @ThreadID int
	declare @SectionID int
	
	-- using a non-documented "feature" of sql server that allows you
	-- to set a variable in an UPDATE statement.  This allows us to get
	-- a cheap read on the cs_Posts table.
	Update
		p
	Set 
		p.TotalViews = p.TotalViews + @WebCount,
		p.AggViews = p.AggViews + @AggCount,
		
		-- set some local variables for later queries
		@ThreadID = p.ThreadID,
		@SectionID = p.SectionID
	from
		cs_Posts p
	Where
		p.PostID = @PostID
	
	IF @WebThreadCount > 0 BEGIN
		update
			t
		set
			t.TotalViews = t.TotalViews + @WebThreadCount
		from
			cs_Threads t
		where
			t.ThreadID = @ThreadID
	END
	
	-- UPDATE Daily Views
	DECLARE @TotalViews int
	SET @TotalViews = @AggCount + @WebThreadCount
	IF @TotalViews > 0 BEGIN
		exec cs_Thread_Daily_Stats_Increment @SectionID, @ThreadID, @TotalViews
	END
end
go
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

grant execute on [dbo].[cs_Posts_Views_Add] to public
go
/***********************************************
* Sproc: cs_Post_CreateUpdate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_CreateUpdate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_CreateUpdate]
GO

CREATE PROCEDURE [dbo].[cs_Post_CreateUpdate]
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
 	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime = null,
	@UserHostAddress nvarchar(32),
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int, 
	@IsTracked bit = 0,
	@PostID int out,
	@ThreadID int=0 out,
	@PostConfiguration int = 0,
	@UpdateSectionStatistics bit = 1,
	@UserTime datetime = null,
	@ApplicationPostType int,
	@PostName nvarchar(256) =  null,
	@ThreadStatus int = 0,
	@ThreadType int = 0,
	@Points int = 0,
	@PostDisplayName nvarchar(64) = null,
	@AutoApprove bit = 0
) 
AS

--	stored procedure cs_Post_CreateUpdate
--	* Procedure now creates new threads here, from an identity column in cs_Threads.
--	* To update a Post, ParentID must not equal 0.
--	* To delete a post, use forums_Moderate_Posts_Move to move it to the Deleted Forum
--  * Default value for ThreadStatus is Not Set (0)

SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @ModeratedForum bit
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @ContextUserID int
DECLARE @ContextPostAuthor nvarchar(64)

-----------------------------
--	Enough data is not present here to accurately determine if this post is spam or not (specifically: PostStatus)
--	If this is updated to pass this information here, it needs a check for this bit and a call to cs_SpamPostArchive
-----------------------------

-- Set 'not set' for Sticky and Anouncement posts
IF ((@IsSticky = 1) OR ((@IsLocked = 1) AND ( @StickyDate > DATEADD( Year, 2, getdate() ) )))
	SET @ThreadStatus = 0 -- not set value

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

IF @UserTime IS NULL
	SET @UserTime = GetDate()

-- Get the real username for poster
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser  
	WHERE 
		UserID = @UserID and SettingsID = @SettingsID

-- Check if this is an anonymous post (value = 1)
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Anonymous ID
	SELECT @ContextUserID = UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1

	-- Set the username
	IF(@PostAuthor is not null)
	begin
		SET @ContextPostAuthor = @PostAuthor
	end
	else
	begin
		SET @ContextPostAuthor = ''
	end
END
ELSE
BEGIN
	-- Set the real user ID
	SET @ContextUserID = @UserID

	IF(@PostDisplayName is not null)
	Begin
		-- Set the real username
		SET @ContextPostAuthor = @PostDisplayName
	END
	ELSE
	BEGIN
		SET @ContextPostAuthor = @PostAuthor
	END
END

-- Do we care about duplicates?
IF @AllowDuplicatePosts = 0
BEGIN
	DECLARE @IsDuplicate bit
	exec cs_system_DuplicatePost @UserID, @Body, @DuplicateIntervalInMinutes, @SettingsID, @IsDuplicate output

	IF @IsDuplicate = 1
	BEGIN
		SET @PostID = -1	
		RETURN	-- Exit with error code.
	END
END

-- we need to get the SectionID, if the ParentID is not null (there should be a SectionID)
IF @SectionID = 0 AND @ParentID <> 0
	SELECT 
		@SectionID = SectionID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @ParentID and SettingsID = @SettingsID

-- Is this forum moderated?
SELECT 
	@ModeratedForum = IsModerated, @EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID

-- Determine if this post will be approved.
-- If the forum is NOT moderated, then the post will be approved by default.
SET NOCOUNT ON
BEGIN TRAN

IF @AutoApprove = 1
BEGIN
	SET @IsApproved = 1
END
ELSE IF @IsApproved = 1 AND @ModeratedForum = 1 AND @SectionID <> 0
BEGIN
	-- ok, this is a moderated forum.  Is this user trusted?  If he is, then the post is approved ; else it is not
	SET @IsApproved = ( 
		SELECT
			ModerationLevel
		FROM
			cs_UserProfile (nolock)
		WHERE
			UserID = @UserID and SettingsID = @SettingsID )
END


-- EAD: Modifying this sproc to insert directly into cs_Threads.  We are no longer keying
-- cs_Threads.ThreadID to be same number as the top PostID for the thread.  This is to allow
-- for the FKs to be put into place.

IF @ParentID = 0	-- parameter indicating this is a top-level post (for a new thread)
BEGIN
	-- First we create a new ThreadID.

	-- check the StickyDate to ensure it's not null
	IF @StickyDate < @PostDate
		SET @StickyDate = @PostDate

	INSERT cs_Threads 	
		( SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID,
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID,
		ThreadStatus,
		ThreadType )
	VALUES
		( @SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@ContextPostAuthor,
		@ContextUserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		@IsLocked,
		@IsApproved,
		@IsSticky,
		@StickyDate,
		@EmoticonID,
		@SettingsID,
		@ThreadStatus,
		@ThreadType )

	-- Get the new ThreadID
	SELECT 
		@ThreadID = SCOPE_IDENTITY()
	--FROM
		--cs_Threads
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 

		Body, 

		FormattedBody, 
		PostType, 
		PostMedia,
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostConfiguration,
		UserTime,
		PostName,
		ApplicationPostType,
		Points )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostConfiguration,
		@UserTime,
		@PostName,
		@ApplicationPostType,
		@Points )
		

	-- Get the new PostID
	SELECT 
		@PostID = SCOPE_IDENTITY()
--	FROM
--		cs_Posts

	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID and SettingsID = @SettingsID

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID and SettingsID = @SettingsID

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID  and SettingsID = @SettingsID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder and SettingsID = @SettingsID

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostConfiguration,
		UserTime,
		PostName,
		ApplicationPostType,
		Points )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostConfiguration,
		@UserTime,
		@PostName,
		@ApplicationPostType,
		@Points )


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1
	BEGIN		
		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = SCOPE_IDENTITY() 
--		FROM 
--			cs_Posts

		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		Select @StickyDate = StickyDate FROM cs_Threads where ThreadID = @ThreadID and SettingsID = @SettingsID

		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			MostRecentPostAuthor = @ContextPostAuthor,
			MostRecentPostAuthorID = @ContextUserID,
			MostRecentPostID = @PostID,
			TotalReplies = TotalReplies + 1, -- (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
			IsLocked = @IsLocked,
			StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
	END
	ELSE
	BEGIN
		-- Moderated Posts: get the new PostID
		SELECT @PostID = SCOPE_IDENTITY() 
	END

	-- Clean up ThreadsRead (this should work very well now)
	DELETE
		cs_ThreadsRead
	WHERE
		ThreadID = @ThreadID 
		AND UserID != @UserID and SettingsID = @SettingsID
END


-- Update the users tracking for the new post (if needed)
SELECT 
	@TrackThread = EnableThreadTracking 
FROM 
	cs_UserProfile (nolock) 
WHERE 
	UserID = @UserID and SettingsID = @SettingsID

IF @TrackThread = 1 and @IsTracked = 1
	-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
	IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @UserID  and SettingsID = @SettingsID)
		INSERT INTO cs_TrackedThreads 
			( ThreadID, UserID, SettingsID)
		VALUES
			( @ThreadID, @UserID, @SettingsID )

COMMIT TRAN
BEGIN TRAN

-- Update the forum statitics
IF @SectionID > 0 AND @UserID > 0
BEGIN
	IF @IsApproved = 1 AND @EnablePostStatistics = 1
	BEGIN
		EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
	END

	IF @UpdateSectionStatistics = 1
	BEGIN
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 1, @PostDisplayName
	END
END


COMMIT TRAN
SET NOCOUNT OFF

SELECT @PostID = @PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Post_CreateUpdate]  TO [public]
GO


/***********************************************
* Sproc: cs_Post_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Delete]
GO

CREATE PROCEDURE dbo.cs_Post_Delete
(
	@SectionID int,
	@SettingsID int,
	@PostID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
-- Permanently deletes one post at a time and eventually its thread.
-- If the post has some replies then subsequent calls are made till all the tree's nodes and leafs are removed.
-- Also if the post is level 1 then we can delete the thread itself without any other checkings.

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostLevel INT
DECLARE @ThreadID INT
DECLARE @HasReplies INT

-- Figure out if this is a thread starter post, who is its thread and if it has some replies
--------------------------------------------------------------------------------
SELECT 
	@PostLevel = PostLevel,
	@ThreadID = ThreadID	
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID AND
	SectionID = @SectionID AND
	SettingsID = @SettingsID

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SectionID = @SectionID AND SettingsID = @SettingsID)
--------------------------------------------------------------------------------

-- Is a starter thread post?
IF (@PostLevel = 1)
BEGIN
	-- Easy job: delete the thread and its content with statistics update
	--------------------------------------------------------------------------------
	EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, @ResetStatistics, @DeletedBy, ''

	RETURN 1
	--------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- This is not a thread starter post, so we have to delete it carefully

	-- Delete parent post
	--------------------------------------------------------------------------------	
	DELETE FROM cs_PostAttachments WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts_Downloads WHERE PostID = @PostID
	
	DELETE FROM cs_PostEditNotes WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts_InCategories WHERE PostID = @PostID AND SettingsID = @SettingsID
		
	DELETE FROM cs_PostsArchive WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID  AND ThreadID = @ThreadID AND PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts WHERE PostID = @PostID AND ThreadID = @ThreadID AND SectionID = @SectionID AND SettingsID = @SettingsID
	
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been permanently deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason	
	--------------------------------------------------------------------------------	

	-- Do we have some replies?
	--------------------------------------------------------------------------------	
	IF (@HasReplies > 0)
	BEGIN
		-- There should be some replies/children bound to this post.
		-- Get replying posts one by one through a local cursor and call its removal.

		DECLARE @CurrentPostID INT

		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @ThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID

		OPEN Posts_Cursor
		
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID

		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call with no statistics update
			EXEC cs_Post_Delete @SectionID, @SettingsID, @CurrentPostID, 0, @DeletedBy, @Reason

			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END

		CLOSE Posts_Cursor

		DEALLOCATE Posts_Cursor		
	END
	--------------------------------------------------------------------------------	
	
	-- Update statistics?
	--------------------------------------------------------------------------------	
	IF (@ResetStatistics = 1)
	BEGIN
		EXEC cs_system_ResetThreadStatistics @ThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	--------------------------------------------------------------------------------	

	RETURN 1
END

END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Post_Delete] to public
go
/***********************************************
* Sproc: cs_Post_Downloads_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_Downloads_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Downloads_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Downloads_Log]
GO

CREATE PROCEDURE [dbo].cs_Post_Downloads_Log
	@PostID int,
	@UserID int
AS

INSERT INTO cs_Posts_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Post_Downloads_Log to public
go
/***********************************************
* Sproc: cs_Post_GetAuthorID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_GetAuthorID'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetAuthorID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetAuthorID]
GO
--------------------------------------------------------------------------------
--	cs_Post_GetAuthorID
--	Returns a post author's userID
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Post_GetAuthorID]
(
	@SettingsID	int,
	@PostID		int,
	@UserID		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- lookup author for post
	SELECT	@UserID = P.UserID
	FROM	cs_Posts P
	WHERE	P.PostID = @PostID
		AND	P.SettingsID = @SettingsID


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Post_GetAuthorID] to [public]

/***********************************************
* Sproc: cs_Post_GetPageIndex
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_GetPageIndex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetPageIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetPageIndex]
GO



CREATE   PROCEDURE dbo.cs_Post_GetPageIndex
(
	@PostID int,
	@PageSize int,
	@SortBy int,
	@SortOrder bit,
	@AllowUnapproved bit = 0,
	@SettingsID int
)
AS

DECLARE @ThreadID int
SELECT @ThreadID = ThreadID FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (0, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY PostDate DESC

-- Sort by Author
IF @SortBy = 1 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID

ELSE IF @SortBy = 1 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID DESC

-- Sort by SortOrder
IF @SortBy = 2 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder

ELSE IF @SortBy = 2 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder DESC

SELECT (IndexID / @PageSize) + 1 AS PageIndex FROM #PageIndex WHERE PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_GetPageIndex] to public
go

/***********************************************
* Sproc: cs_Post_GetRandomPostID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_GetRandomPostID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetRandomPostID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetRandomPostID]
GO



/***********************************************
* Sproc: cs_Post_GetRating
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_GetRating'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetRating]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetRating]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/***********************************************
* Sproc: cs_post_IsTracked
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_post_IsTracked'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_thread_IsTracked]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_thread_IsTracked]
GO

CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_thread_IsTracked] to public
go
/***********************************************
* Sproc: cs_Post_Rate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Rate]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/***********************************************
* Sproc: cs_Post_ToggleSettings
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_ToggleSettings'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_ToggleSettings]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_ToggleSettings]
GO

CREATE   procedure [dbo].cs_Post_ToggleSettings
(
	@PostID int,
	@IsAnnouncement bit,
	@IsLocked bit,
	@ModeratorID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @CurrentLockState bit
	DECLARE @CurrentAnnouncementState bit
	
	DECLARE @ThreadID int
	DECLARE @PostLevel int
	SELECT 
		@ThreadID = ThreadID, 
		@PostLevel = PostLevel 
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

-- Is this a thread
IF @PostLevel =1
BEGIN
	print 'Toggling settings on a thread.'

	-- Get the current state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Threads 
	WHERE 
		ThreadID = @ThreadID

	-- Get current is announcement state of the thread
	IF EXISTS (	SELECT 
				ThreadID 
			FROM 
				cs_Threads
			WHERE
				ThreadID = @ThreadID 
				AND IsSticky = 1
				AND StickyDate > DateAdd( y, 20, GetDate() )
			)

		SET @CurrentAnnouncementState = 1
	ELSE
		SET @CurrentAnnouncementState = 0
		

	-- Is the Post getting locked?
	IF @CurrentLockState != @IsLocked
	BEGIN
		UPDATE
			cs_Threads
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		UPDATE
			cs_Posts
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		IF @IsLocked = 0
		BEGIN
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
		END
        		ELSE
		BEGIN
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
		END
	END


	-- Is the post an Annoucement
	IF @CurrentAnnouncementState != @IsAnnouncement
		IF @IsAnnouncement = 1
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 1,
				StickyDate = DateAdd(y, 25, ThreadDate)
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 16, @ModeratorID, @PostID, null, null, @SettingsID
	
		END
		ELSE
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 0,
				StickyDate = ThreadDate
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 17, @ModeratorID, @PostID, null, null, @SettingsID
		END
END
ELSE
	print 'Toggling settings on a post.'

	-- Get the current lock state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

	-- UPDATE The child posts
	UPDATE
	   	cs_Posts
	SET
		IsLocked = @IsLocked
	WHERE
		ParentID = @PostID
	
	IF @IsLocked != @CurrentLockState
		IF @IsLocked = 0
		  exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
	        ELSE
		  exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_ToggleSettings] to public
go
/***********************************************
* Sproc: cs_Post_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Post_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Update]
GO

CREATE PROCEDURE [dbo].cs_Post_Update
(
	@SectionID	int = null,
	@PostID	int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsAnnouncement bit,
	@EditedBy	int,
	@EditNotes	ntext = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@PostConfiguration int = 0,
	@PostName nvarchar(256) =  null,
	@IsApproved bit = null,
	@Points int = 0,
	@PostMedia int = null,
	@PostDate datetime = null,
	@PostStatus int = null,
	@SpamScore int = null,
	@ThreadType int = null
)
AS
	-- This sproc updates a post

	DECLARE @ThreadID int
	DECLARE @CurrentStickyDate datetime
	DECLARE @ParentID int
	--DECLARE @CurrentIsSticky BIT
	--DECLARE @CurrentSubject NVARCHAR(256)
	--DECLARE @StickyHasRemoved BIT
	--DECLARE @SubjectHasChanged BIT
	
	-- Get the thread and postdate this applies to
	SELECT 
		@ThreadID = P.ThreadID,
		@CurrentStickyDate = T.StickyDate,
		@ParentID = P.ParentID,
		@SectionID = P.SectionID
		--@CurrentIsSticky = T.IsSticky,
		--@CurrentSubject = P.Subject
	FROM 
		cs_Posts P
	LEFT JOIN
		cs_Threads T ON T.ThreadID = P.ThreadID
	WHERE 
		P.PostID = @PostID AND P.SettingsID = @SettingsID
	
	-- Check if subject has changed or stickiness has been removed.
	--SET @StickyHasRemoved = 0
	--SET @SubjectHasChanged = 0

	--IF (@IsSticky IS NOT NULL) AND (@IsSticky = 0) AND (@CurrentIsSticky = 1)
	--	SET @StickyHasRemoved = 1		
	
	--IF (@CurrentSubject <> @Subject)		
	--	SET @SubjectHasChanged = 1

	-- Update post's details
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostConfiguration = @PostConfiguration,
		PostName = @PostName,
		Points = @Points,
		IsApproved = IsNull(@IsApproved, IsApproved),
		PostMedia = IsNull(@PostMedia, PostMedia),
		PostStatus = IsNull(@PostStatus, PostStatus),
		SpamScore = IsNull(@SpamScore, SpamScore)
	WHERE 
		PostID = @PostID AND SettingsID = @SettingsID

	if(@PostID = @ParentID AND @IsApproved is not null)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	
	-- We need not to trigger thread and section stats rebuild if sticky has been 
	-- removed or subject has been changed.
	-- If something else has changed then we will trigger stats rebuild of info 
	-- but not the dates (is the meaning of 0, a new param).

	-- Update most recent info in cs_Threads but not any date
	-- IF (@ThreadID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0) 
	--	 EXEC cs_system_UpdateThread @ThreadID, @PostID, @SettingsID, 0
	
	-- Update most recent info in cs_Sections but not any date
	-- IF (@SectionID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0)
	--	 EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 0

	IF (@PostStatus IS NOT NULL)
		EXEC cs_Thread_Status_Update @ThreadID, null, @SettingsID

	-- Allow thread to update sticky properties.
	-- Also if this post got locked, then mark the thread locked too
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		DECLARE @ThreadIsLocked BIT
		SET @ThreadIsLocked = (@IsAnnouncement | @IsLocked)
	 
		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID  AND SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @CurrentStickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID AND SettingsID = @SettingsID 		
		END
	END

	IF @EditNotes IS NOT NULL
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostEditNotes WHERE PostID = @PostID)
			UPDATE 
				cs_PostEditNotes
			SET
				EditNotes = @EditNotes
			WHERE	
				PostID = @PostID AND SettingsID = @SettingsID
		ELSE
			INSERT INTO
				cs_PostEditNotes
			VALUES
				(@PostID, @EditNotes, @SettingsID)
	END
	
	IF @PostDate IS NOT NULL
	BEGIN
			UPDATE cs_Posts	SET	PostDate = @PostDate WHERE PostID = @PostID AND SettingsID = @SettingsID
			
			if(@PostID = @ParentID)
			Begin
				Update cs_Threads Set PostDate = @PostDate Where ThreadID = @ThreadID AND SettingsID = @SettingsID
			End
	END

	-- update thread emoticon if this is a thread starter
	IF (@PostID = @ParentID)
	BEGIN
		UPDATE cs_Threads SET ThreadEmoticonID = @EmoticonID WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID
	END

	-- Update thread type if this is a thread starter
	IF (@PostID = @ParentID) AND (@ThreadType IS NOT NULL)
	BEGIN
		UPDATE cs_Threads SET ThreadType = @ThreadType WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID
	END
	
	-- Mark thread as not read for anyone but the editor
	DELETE cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID AND UserID <> @EditedBy 

	-- We want to track what happened
	exec cs_system_ModerationAction_AuditEntry 2, @EditedBy, @PostID, NULL, NULL, @SettingsID, @EditNotes

	EXEC cs_system_ResetThreadStatistics @ThreadID
	IF @SectionID > 0	-- passing in "0" will recalculate stats for ALL sections (timeout on large sites)
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = null
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Post_Update]  TO [public]
GO


/***********************************************
* Sproc: cs_PrivateMessages_CreateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PrivateMessages_CreateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_CreateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_CreateDelete]
GO

/***********************************************
* Sproc: cs_PrivateMessages_Recipients
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PrivateMessages_Recipients'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_Recipients]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_Recipients]
GO

/***********************************************
* Sproc: cs_PrivateMessages_UnreadCount
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_PrivateMessages_UnreadCount'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_UnreadCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_UnreadCount]
GO

/***********************************************
* Sproc: cs_Profile_GetPropertiesForUsers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Profile_GetPropertiesForUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Profile_GetPropertiesForUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Profile_GetPropertiesForUsers]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Profile_GetPropertiesForUsers]
    @ApplicationName       NVARCHAR(256),
    @UserNames         NTEXT

AS
BEGIN

	SET NOCOUNT ON

    DECLARE @ApplicationId UNIQUEIDENTIFIER
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0

	DECLARE @tbNames	table(Name nvarchar(256) collate database_default NOT NULL PRIMARY KEY) --Has to be removed until we can ensure uniqueness
	DECLARE @tbUsers	table(UserId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

    DECLARE @textpos  int --our chunks position in the ntext
    DECLARE @chunklen smallint
    DECLARE @UserNamesChunk   nvarchar(4000)
	DECLARE @delimiter nvarchar(1)
    DECLARE @leftover nvarchar(4000)

	SET @delimiter = N','
	SET @Num = 0
	SET @textpos = 1
	SET @leftover = ''

	WHILE @textpos <= DATALENGTH(@UserNames) /2
	BEGIN

		SET @chunklen = 4000 - DATALENGTH(@leftover) /2
		SET @UserNamesChunk = ltrim(@leftover + substring(@UserNames, @textpos, @chunklen))
		SET @textpos = @textpos + @chunklen

		SET @Pos = 1 

		WHILE(@Pos <= DATALENGTH(@UserNamesChunk))
		BEGIN
			SELECT @NextPos = CHARINDEX(@delimiter, @UserNamesChunk,  @Pos)
			IF (@NextPos = 0 OR @NextPos IS NULL)
			BEGIN
				--break us from the loop
				SELECT @NextPos = DATALENGTH(@UserNamesChunk) + 1
				--set the leftover string to use again in next iter
				SET @leftover = SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos)
			END
			ELSE
			BEGIN
				SELECT @Name = LOWER(RTRIM(LTRIM(SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos))))
			
				INSERT INTO @tbNames VALUES (@Name)
			
				SET @Num = @Num + 1
			END

			SELECT @Pos = @NextPos+1
		END
		
		IF(@Pos = DATALENGTH(@UserNamesChunk))
			SET @leftover = ''
	END

	INSERT INTO @tbNames VALUES (@leftover)

	INSERT INTO @tbUsers
	  SELECT UserId
	  FROM   dbo.aspnet_Users ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @ApplicationId


    SELECT u.UserName, p.PropertyNames, p.PropertyValuesString, p.PropertyValuesBinary
    FROM         dbo.aspnet_Profile p
			JOIN dbo.aspnet_Users u ON u.UserId = p.UserId
			JOIN @tbUsers t ON u.UserId = t.UserId
    ORDER BY [UserName]

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Profile_GetPropertiesForUsers] to public
go
/***********************************************
* Sproc: cs_Ranks_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Ranks_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Ranks_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Ranks_Get]
GO







create proc [dbo].cs_Ranks_Get
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT r.*
	FROM
		cs_Ranks r where SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Ranks_Get] to public
go
/***********************************************
* Sproc: cs_Rank_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Rank_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rank_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rank_CreateUpdateDelete]
GO


CREATE proc [dbo].cs_Rank_CreateUpdateDelete
(
	@RankID				int out,
	@DeleteRank			bit	= 0,
	@RankName			nvarchar(60),
	@PostingCountMin	int,
	@PostingCountMax	int,	
	@RankIconUrl		nvarchar(512),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the rank
IF( @DeleteRank = 1 )
BEGIN

	DELETE cs_Ranks
	WHERE
		RankID	= @RankID and SettingsID = @SettingsID

	RETURN
END

-- are we updating the rank
IF( @RankID >  0 )
BEGIN

	UPDATE cs_Ranks SET
		  RankName			= @RankName
		, PostingCountMin	= @PostingCountMin
		, PostingCountMax	= @PostingCountMax
		, RankIconUrl		= @RankIconUrl
	WHERE
		  RankID	= @RankID and SettingsID = @SettingsID
		

END
ELSE
BEGIN
	INSERT INTO cs_Ranks (
		RankName, PostingCountMin, PostingCountMax, RankIconUrl, SettingsID
	)
	VALUES( 
		@RankName, @PostingCountMin, @PostingCountMax, @RankIconUrl, @SettingsID
	)

	SET @RankID = SCOPE_IDENTITY()
END

RETURN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Rank_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Ratings_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Ratings_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Ratings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Ratings_Get]
GO

CREATE procedure dbo.cs_Ratings_Get
(
	@RatingType	int,
	@ItemID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType = 0			-- Post

		SELECT
			U.*,
			'Post' AS RatingType,
			R.PostID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_PostRating R
		WHERE
			R.UserID = U.UserID AND
			R.PostID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID

	ELSE IF @RatingType = 1		-- Thread

		SELECT
			U.*,
			'Thread' AS RatingType,
			R.ThreadID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_ThreadRating R
		WHERE
			R.UserID = U.UserID AND
			R.ThreadID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Ratings_Get] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Rating_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Add]
GO

CREATE PROCEDURE dbo.cs_Rating_Add
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int,
	@ratingCount int OUTPUT,
	@ratingSum int OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_PostRating
			(UserID, PostID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID

		SELECT
			@ratingCount = TotalRatings,
			@ratingSum = RatingSum
		FROM
			cs_Posts
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID

	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_ThreadRating
			(UserID, ThreadID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID

		SELECT
			@ratingCount = TotalRatings,
			@ratingSum = RatingSum
		FROM
			cs_Threads
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID

	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Add] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Rating_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Get]
GO

CREATE PROCEDURE dbo.cs_Rating_Get
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@SettingsID	int,
	@Rating		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Setup default value (signifies not rated)
	SET	@Rating	= -1

	IF @RatingType = 0			--Post

		SELECT	@Rating = Rating
		FROM	cs_PostRating
		WHERE	UserID = @UserID
		AND		PostID = @ItemID
		AND		SettingsID = @SettingsID

	ELSE IF @RatingType = 1		--Thread

		SELECT	@Rating = Rating
		FROM	cs_ThreadRating
		WHERE	UserID = @UserID
		AND		ThreadID = @ItemID
		AND		SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Get] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Rate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Rating_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Rate]
GO

CREATE procedure dbo.cs_Rating_Rate
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@Rating		int,
	@SettingsID	int,
	@ratingCount int OUTPUT,
	@ratingSum int OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Get existing rating
	DECLARE @CurrentRating	int
	EXECUTE cs_Rating_Get @RatingType, @ItemID, @UserID, @SettingsID, @CurrentRating OUTPUT
	
	-- User has previously rated this item
	IF @CurrentRating >= 0

		-- Update the rating
		EXECUTE cs_Rating_Update @RatingType, @ItemID, @UserID, @Rating, @SettingsID, @CurrentRating, @ratingCount OUTPUT, @ratingSum OUTPUT

	ELSE

		-- Add the rating
		EXECUTE cs_Rating_Add @RatingType, @ItemID, @UserID, @Rating, @SettingsID, @ratingCount OUTPUT, @ratingSum OUTPUT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Rate] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Rating_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Update]
GO

CREATE PROCEDURE dbo.cs_Rating_Update
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int,
	@CurrentRating	int,
	@ratingCount int OUTPUT,
	@ratingSum int OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Update the rating
		UPDATE
			cs_PostRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			PostID = @ItemID and SettingsID = @SettingsID

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID

		SELECT
			@ratingCount = TotalRatings,
			@ratingSum = RatingSum
		FROM
			cs_Posts
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID
	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Update the rating
		UPDATE
			cs_ThreadRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			ThreadID = @ItemID and SettingsID = @SettingsID

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID

		SELECT
			@ratingCount = TotalRatings,
			@ratingSum = RatingSum
		FROM
			cs_Threads
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID

	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Update] TO [public]
GO

/***********************************************
* Sproc: cs_Referrals_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Referrals_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_referrals_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_referrals_Add]
GO
create procedure [dbo].[cs_referrals_Add]
(
	@UrlID int,
	@Url nvarchar(512),
	@SettingsID int,
	@SectionID int,
	@PostID int	
)
as
begin
	set transaction isolation level read uncommitted
	
	exec cs_Urls_Add @UrlID, @Url
	
	-- update the hit count for the SettingsID, SectionID, UrlID and PostID
	update r
	set 
		r.Hits = r.Hits + 1,
		r.LastDate = getdate()
	from
		cs_Referrals r
	where
		r.SettingsID = @SettingsID
		and r.SectionID = @SectionID
		and r.UrlID = @UrlID
		and r.PostID = @PostID
	
	if(@@ROWCOUNT = 0)
	begin
		-- insert the first hit count for the SettingsID, SectionID, UrlID and PostID
		insert cs_Referrals (SettingsID, SectionID, PostID, UrlID, Hits, LastDate)
		values (@SettingsID, @SectionID, @PostID, @UrlID, 1, getdate())
	end
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_referrals_Add] to public
go
/***********************************************
* Sproc: cs_referrals_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_referrals_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_referrals_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_referrals_Get]
GO

CREATE Proc [dbo].cs_referrals_Get
(
	@SettingsID int,
	@SectionID int,
	@PostID int,
	@PageSize int,
	@PageIndex int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


-- are we getting referrals for a single post
IF (@PostID <> -1)
BEGIN

	-- return all referrals (no paging)
	SELECT
		P.Subject,
		R.ReferralID,
		R.SettingsID,
		R.SectionID,
		P.PostID,
		U.Url,
		R.Hits,
		R.LastDate
	FROM
		cs_Referrals R
		INNER JOIN cs_Urls U ON R.UrlID = U.UrlID
		INNER JOIN cs_Posts P ON R.PostID = P.PostID
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID
	ORDER BY
		LastDate DESC	

	-- return record count
	SELECT
		@TotalRecords = COUNT(*)
	FROM
		cs_Referrals R
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID

	-- exit immediately
	RETURN
END


-- we are getting referrals for multiple posts (use paging)
DECLARE @RowsToReturn int
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ReferralID int
)

Insert #PageIndex (ReferralID)
Select ReferralID FROM cs_Referrals where SettingsID = @SettingsID and  SectionID = @SectionID order by LastDate desc

-- Reset rowcount and get count of total records
SET ROWCOUNT 0
Select @TotalRecords = count(*) From cs_Referrals Where SettingsID = @SettingsID and SectionID = @SectionID

Select  cs_Posts.Subject,  cs_Referrals.ReferralID, cs_Referrals.SettingsID,  cs_Referrals.SectionID, cs_Posts.PostID, Url, Hits, LastDate
FROM cs_Referrals, cs_Urls, #PageIndex, cs_Posts
Where
	cs_Referrals.ReferralID = #PageIndex.ReferralID and
	cs_Urls.UrlID = cs_Referrals.UrlID and 
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound AND 
	cs_Posts.PostID = cs_Referrals.PostID
Order by IndexID

DROP Table #PageIndex


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_referrals_Get] to public
go
/***********************************************
* Sproc: cs_RemoveAllPostTracking
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RemoveAllPostTracking'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RemoveAllPostTracking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RemoveAllPostTracking]
GO



CREATE PROCEDURE [dbo].cs_RemoveAllPostTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.UserID = @UserID AND 
			tt.SettingsID = @SettingsID
				
	ELSE
		DELETE FROM cs_TrackedThreads WHERE UserID = @UserID AND SettingsID = @SettingsID	
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.SettingsID = @SettingsID

	ELSE
		DELETE FROM cs_TrackedThreads WHERE SettingsID = @SettingsID	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RemoveAllPostTracking] to public
go
/***********************************************
* Sproc: cs_RemoveAllSectionTracking
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RemoveAllSectionTracking'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RemoveAllSectionTracking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RemoveAllSectionTracking]
GO


CREATE PROCEDURE [dbo].cs_RemoveAllSectionTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)			
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SettingsID = @SettingsID			
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE FROM cs_TrackedSections WHERE SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RemoveAllSectionTracking] to public
go
/***********************************************
* Sproc: cs_Reports_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Reports_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Reports_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Reports_Get]
GO







create proc [dbo].cs_Reports_Get
(
	@ReportID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	FROM
		cs_Reports
	WHERE
		ReportID = @ReportID or
		( 
			@ReportID = 0 AND
			1=1
		) and SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Reports_Get] to public
go
/***********************************************
* Sproc: cs_Report_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Report_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Report_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Report_CreateUpdateDelete]
GO

create proc [dbo].cs_Report_CreateUpdateDelete
(
	  @ReportID			int out
	, @DeleteReport		bit		= 0
	, @ReportName		varchar(20)
	, @Active			bit
	, @ReportCommand	varchar(6500)
	, @ReportScript		ntext
	, @SettingsID 		int
)
AS

IF( @DeleteReport > 0 )
BEGIN
	DELETE cs_Reports
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
	RETURN
END

IF( @ReportID > 0 )
BEGIN
	UPDATE cs_Reports SET
		  ReportName	= @ReportName
		, Active		= @Active
		, ReportCommand	= @ReportCommand
		, ReportScript	= @ReportScript
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
END
ELSE
BEGIN	
	INSERT INTO cs_Reports ( 
		ReportName, Active, ReportCommand, ReportScript, SettingsID 
	) VALUES (
		@ReportName, @Active, @ReportCommand, @ReportScript, @SettingsID
	)	

	SET @ReportID = SCOPE_IDENTITY()
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Report_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_report_GetBlogPostReplies
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_report_GetBlogPostReplies'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetBlogPostReplies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetBlogPostReplies]
GO
/***********************************************
* Sproc: cs_report_GetBlogPostViews
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_report_GetBlogPostViews'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetBlogPostViews]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetBlogPostViews]
GO
/***********************************************
* Sproc: cs_report_GetForumPostReplies
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_report_GetForumPostReplies'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetForumPostReplies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetForumPostReplies]
GO
/***********************************************
* Sproc: cs_report_GetForumPostViews
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_report_GetForumPostViews'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetForumPostViews]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetForumPostViews]
GO
/***********************************************
* Sproc: cs_report_ThreadViewsByDay
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_report_ThreadViewsByDay'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_ThreadViewsByDay]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_ThreadViewsByDay]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

create procedure [dbo].cs_report_ThreadViewsByDay
(
	@SectionID int = -1,
	@PostID int = -1,
	@ApplicationType smallint = -1,
	@Days int
)	
as
begin
	declare @StartDate as datetime

	set @StartDate = (select convert(char(10), dateadd(day, -@Days, getdate()), 120 ))

	if (@PostID > 0)
	begin
		declare @ThreadID as int

		set @ThreadID = (SELECT ThreadID from cs_Posts where PostID = @PostID)

		select
			S.SectionID,
			S.[Day],
			S.ThreadID,
			S.ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.SectionID = @SectionID and
			S.ThreadID = @ThreadID and
			S.[Day] > @StartDate
		order by
			[Day]
	end
	else if (@SectionID > 0)
		select
			S.SectionID,
			S.[Day],
			S.ThreadID,
			S.ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.SectionID = @SectionID and
			S.[Day] > @StartDate
		order by
			[Day]
	else if (@ApplicationType > -1)
		select
			-1 as SectionID,
			S.[Day],
			-1 as ThreadID,
			sum(S.ViewCount) as ViewCount
		from
			cs_Thread_Daily_Stats S
			inner join cs_Sections SS on SS.SectionID = S.SectionID
		where
			SS.ApplicationType = @ApplicationType and
			S.[Day] > @StartDate
		group by
			S.[Day]		
		order by 
			[Day]
	else
		select
			-1 as SectionID,
			S.[Day],
			-1 as ThreadID,
			sum(S.ViewCount) as ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.[Day] > @StartDate
		group by
			S.[Day]		
		order by 
			[Day]
end
go

grant execute on [dbo].[cs_report_ThreadViewsByDay] to [public]
go

/***********************************************
* Sproc: cs_ReverseTrackingOption
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ReverseTrackingOption'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ReverseTrackingOption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ReverseTrackingOption]
GO


create procedure [dbo].cs_ReverseTrackingOption 
(
	@UserID int,
	@ThreadID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- reverse the user's tracking options for a particular thread
	-- first get the threadID of the Post

	IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		-- the user is tracking this thread, delete this row
		DELETE FROM cs_TrackedThreads
		WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID
	ELSE
		-- this user isn't tracking the thread, so add her
		INSERT INTO cs_TrackedThreads (ThreadID, UserID, DateCreated, SettingsID)
		VALUES(@ThreadID, @UserID, GetDate(), @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ReverseTrackingOption] to public
go
/***********************************************
* Sproc: cs_RoleQuotas_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RoleQuotas_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RoleQuotas_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RoleQuotas_Get]
GO

CREATE PROCEDURE dbo.cs_RoleQuotas_Get
(
	@SettingsID int
)

AS
	/* SET NOCOUNT ON */
	SELECT RoleID, DiskQuota, ImageQuota
	FROM cs_RoleQuotas
	WHERE SettingsID = @SettingsID
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RoleQuotas_Get] to public
go

/***********************************************
* Sproc: cs_RoleQuota_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RoleQuota_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RoleQuota_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RoleQuota_CreateUpdateDelete]
GO

CREATE PROCEDURE dbo.cs_RoleQuota_CreateUpdateDelete
(
	@RoleID uniqueidentifier,
	@DiskQuota bigint = -1,
	@ImageQuota int = -1,
	@SettingsID int
)

AS
	IF @DiskQuota = -1 AND @ImageQuota = -1
		DELETE FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	ELSE
	BEGIN
		DECLARE @Exists bit
	
		SELECT @Exists = COUNT(*) FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
		IF @Exists = 0
			INSERT INTO cs_RoleQuotas (RoleID, DiskQuota, ImageQuota, SettingsID) VALUES (@RoleID, @DiskQuota, @ImageQuota, @SettingsID)
		ELSE
			UPDATE cs_RoleQuotas SET DiskQuota = @DiskQuota, ImageQuota = @ImageQuota WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	END
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RoleQuota_CreateUpdateDelete] to public
go

/***********************************************
* Sproc: cs_Roles_CreateRole
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roles_CreateRole'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_CreateRole]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.cs_Roles_CreateRole
    @ApplicationName  NVARCHAR(256),
    @RoleName         NVARCHAR(256),
    @Description      NVARCHAR(256) = NULL
AS
BEGIN

    DECLARE @ErrorCode     INT
    SET @ErrorCode = 0

    DECLARE @TranStarted   BIT
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0


    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	DECLARE @ApplicationId uniqueidentifier
	SELECT	@ApplicationId = ApplicationId
	FROM	aspnet_Applications
	WHERE	ApplicationName = @ApplicationName

    IF (EXISTS(SELECT RoleId FROM dbo.aspnet_Roles WHERE LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId))
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    INSERT INTO dbo.aspnet_Roles
                (ApplicationId, RoleName, LoweredRoleName, Description)
         VALUES (@ApplicationId, @RoleName, LOWER(@RoleName), @Description)

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Roles_CreateRole]  TO [public]
GO

/***********************************************
* Sproc: cs_Roles_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roles_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_CreateUpdateDelete]
GO


/***********************************************
* Sproc: cs_Roles_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roles_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_Get]
GO

CREATE   procedure [dbo].cs_Roles_Get
(
	@UserName NVARCHAR(256) = NULL,
	@ApplicationName NVARCHAR(256)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF (@UserName IS NULL OR LEN(@UserName) = 0)
		SELECT
			R.RoleId,
			R.RoleName as [Name],
			R.Description
		FROM
			aspnet_Roles R
			INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
		WHERE
			A.LoweredApplicationName = LOWER(@ApplicationName)
	ELSE
	BEGIN
		DECLARE @UserId UNIQUEIDENTIFIER
		SELECT
			@UserId = U.UserId
		FROM
			aspnet_Users U
			INNER JOIN aspnet_Applications A ON U.ApplicationId = A.ApplicationId
		WHERE
			U.LoweredUserName = LOWER(@UserName)
			AND A.LoweredApplicationName = LOWER(@ApplicationName)

		SELECT DISTINCT
			R.RoleId,
			R.RoleName as [Name],
			R.Description
		FROM 
			aspnet_UsersInRoles UIR
			INNER JOIN aspnet_Roles R ON UIR.RoleId = R.RoleId
			INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
		WHERE
			UIR.UserId = @UserId AND
			A.LoweredApplicationName = LOWER(@ApplicationName)
	END
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_Get] to public
go
/***********************************************
* Sproc: cs_Roles_GetRoleIdsForUsers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roles_GetRoleIdsForUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_GetRoleIdsForUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_GetRoleIdsForUsers]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Roles_GetRoleIdsForUsers]
	@ApplicationName	nvarchar(256),
    @UserNamesXml         NTEXT

AS
BEGIN


DECLARE @idoc int
	
EXEC sp_xml_preparedocument @idoc OUTPUT, @UserNamesXml


	SELECT DISTINCT
		U.[UserName],
		UIR.UserId,
		UIR.RoleId
	FROM
		aspnet_Applications A
		INNER JOIN dbo.aspnet_Users U ON A.ApplicationId = U.ApplicationId
		INNER JOIN dbo.aspnet_UsersInRoles UIR ON U.UserId = UIR.UserId
		INNER JOIN OPENXML(@idoc, '/UserNames/UserName', 2) WITH (UserName nvarchar(256) '.') X on U.LoweredUserName = LOWER(X.UserName)
	WHERE
		A.LoweredApplicationName = LOWER(@ApplicationName)
	ORDER BY U.UserName

EXEC sp_xml_removedocument @idoc

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_GetRoleIdsForUsers] to public
go
/***********************************************
* Sproc: cs_Roles_UpdateRole
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roles_UpdateRole'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_UpdateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_UpdateRole]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.cs_Roles_UpdateRole
    @ApplicationName  NVARCHAR(256),
    @RoleID           UNIQUEIDENTIFIER,
    @RoleName         NVARCHAR(256),
    @Description      NVARCHAR(256) = NULL
AS
BEGIN

    DECLARE @ErrorCode     INT
    SET @ErrorCode = 0

    DECLARE @TranStarted   BIT
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	DECLARE @ApplicationId uniqueidentifier
	SELECT	@ApplicationId = ApplicationId
	FROM	aspnet_Applications
	WHERE	ApplicationName = @ApplicationName

    UPDATE	aspnet_Roles
    SET		RoleName = @RoleName,
		LoweredRoleName = LOWER(@RoleName),
		Description = @Description
	WHERE	RoleId = @RoleID AND ApplicationId = @ApplicationId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Roles_UpdateRole]  TO [public]
GO

/***********************************************
* Sproc: cs_Role_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Role_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Role_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Role_Get]
GO


--We will need to filter all by application name

create procedure [dbo].cs_Role_Get
(
	@RoleID uniqueidentifier = null,
	@RoleName nvarchar(256) = null,
	@ApplicationName NVARCHAR(256)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT
		R.RoleId,
		R.RoleName as [Name],
		R.Description
	FROM
		aspnet_Roles R
		INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
	WHERE
		((@RoleID IS NOT NULL AND RoleId = @RoleID) OR @RoleID IS NULL) AND
		((@RoleName IS NOT NULL AND RoleName = @RoleName) OR @RoleName IS NULL) AND
		(A.LoweredApplicationName = LOWER(@ApplicationName))

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Role_Get] to public
go
/***********************************************
* Sproc: cs_Role_sprocs
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Role_sprocs'


/***********************************************
* Sproc: cs_RollerBlog_AddFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_AddFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_AddFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE        PROC [dbo].cs_RollerBlog_AddFeed
	@SectionID INT,
	@SettingsID INT,
	@FeedUrl NVARCHAR(512),
	@SiteUrl NVARCHAR(512),
    @Title NVARCHAR(512),
	@IntervalMin INT,
	@ExerptSize INT,
	@PostFullText BIT,
	@IsBlogAggregated BIT,
	@IsBlogRollAggregated BIT,
	@Enabled BIT,
	@State INT,
	@NewUrlID INT OUTPUT
AS

-- -- *** Test Data ***
-- DECLARE @SectionID INT
-- DECLARE @Url NVARCHAR(512)
-- DECLARE @Title NVARCHAR(512)
-- DECLARE @UrlId INT
-- 
-- SET @SectionID = 4 -- Sample Weblog
-- SET @Url = 'http://communityserver.org/roller/rss.ashx'
-- SET @Title = 'Community Server'
-- -- *** End Test Data ***

DECLARE @AUrlId INT
DECLARE @RecCount INT
DECLARE @CurrentDateTime DateTime
SET @CurrentDateTime = GetDate()

--Settings ID is now coming from the data layer
--DECLARE @SettingsID INT
--SET @SettingsID = (Select SettingsID FROM cs_Sections WHERE SectionID = @SectionID)

-- First, let's see if the url is already int cs_RollerBlogUrls.
SELECT @AUrlId = UrlID
FROM cs_RollerBlogUrls
WHERE Url = @FeedUrl --'http://communityserver.org/roller/rss.ashx'

-- If it's not, let's insert it and grab the FeedId.
IF (@AUrlId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_RollerBlogUrls
	(
		Url
	) 
	VALUES
	(
		@FeedUrl
	)

	-- Grab the identity generated.
	SELECT @AUrlId = SCOPE_IDENTITY()

  END

-- Let's see if this feed is already part of cs_RollerBlogFeeds based on the SectionID and UrlId.
SET @RecCount = (SELECT COUNT(SectionID) FROM cs_RollerBlogFeeds WHERE UrlID = @AUrlId AND SectionID = @SectionID)

IF (@RecCount = 0)
BEGIN
        -- Add the feed to cs_RollerBlogFeeds based on SectionID (users blog).
	INSERT INTO cs_RollerBlogFeeds
	(
		SectionID,
		UrlID,
		SettingsID,
		SiteUrl,
        IntervalMinutes,
		Title,
		SubscribeDate,
		LastUpdateDate,
		LastModifiedDate,
		PostFullArticle,
		ExerptSize,
		IsBlogAggregated,
		IsBlogRollAggregated,
		Enabled,
		State
	)
	VALUES
	(
		@SectionID,
		@AUrlId,
		@SettingsID,
		@SiteUrl,
		@IntervalMin,
		@Title,
	    @CurrentDateTime,
	    DateAdd(mi, -@IntervalMin, @CurrentDateTime),
	    @CurrentDateTime,
		@PostFullText,
		@ExerptSize,
		@IsBlogAggregated,
		@IsBlogRollAggregated,
		@Enabled,
		@State
	)
END
ELSE
BEGIN
        -- Enable the already existing feed.
	UPDATE cs_RollerBlogFeeds
	SET 
		Enabled = 1, 
		IntervalMinutes = @IntervalMin, 
		Title = @Title,
		PostFullArticle = @PostFullText, 
		ExerptSize = @ExerptSize,
        IsBlogAggregated = @IsBlogAggregated, 
		IsBlogRollAggregated = @IsBlogRollAggregated, 
		SiteUrl = @SiteUrl
	WHERE UrlID = @AUrlId AND SectionID = @SectionID
END

SELECT @NewUrlID = @AUrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_AddFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_AddPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_AddPost'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_AddPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_AddPost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_AddPost
	@PostID INT,
	@SectionID INT,
	@UrlID INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

INSERT INTO cs_RollerBlogPost
(
	PostID,
	SectionID,
	UrlID,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
)

VALUES
(
	@PostID,
	@SectionID,
	@UrlID,
	@PermaLink,
	@CommentsUrl,
	@CommentsCount,
	@GuidName,
	@GuidIsPermaLink
)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_AddPost] to public
go
/***********************************************
* Sproc: cs_RollerBlog_DeleteFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_DeleteFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_DeleteFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_DeleteFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROC [dbo].cs_RollerBlog_DeleteFeed
	@SectionID INT,
	@UrlId INT
AS

UPDATE cs_RollerBlogFeeds
SET 	LastUpdateDate = GetDate(), Enabled = 0
WHERE SectionID = @SectionID AND UrlID = @UrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_DeleteFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_GetAllEnabledFeeds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_GetAllEnabledFeeds'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetAllEnabledFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetAllEnabledFeeds]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetAllFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_GetAllFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetAllFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetAllFeeds]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetEnabledFeedsBySectionID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_GetEnabledFeedsBySectionID'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetEnabledFeedsBySectionID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetEnabledFeedsBySectionID]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetFeeds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_GetFeeds'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetFeeds]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].[cs_RollerBlog_GetFeeds]
(
	@SettingsID int,
	@EnabledOnly bit = 0,
	@UpdateNeededOnly bit = 0,
	@SectionID int = 0
)
AS

SELECT
	SectionID
	,rbf.UrlID
    ,rollerUrls.Url
    ,rbf.SiteUrl
	,rbf.SettingsID
	,rbf.Enabled
    ,rbf.IntervalMinutes
	,rbf.Title
	,rbf.SubscribeDate
	,rbf.LastUpdateDate
	,rbf.LastModifiedDate
	,rbf.PostFullArticle
	,rbf.ExerptSize
	,rbf.ETag
	,rbf.IsBlogAggregated
	,rbf.IsBlogRollAggregated

FROM
	cs_RollerBlogFeeds rbf
	INNER JOIN cs_RollerBlogUrls rollerUrls on rollerUrls.UrlID = rbf.UrlID
WHERE
	SettingsID = @SettingsID
	AND (rbf.Enabled = @EnabledOnly or @EnabledOnly = 0)
	AND (SectionID = @SectionID or @SectionID = 0)
	AND (DateAdd(mi, rbf.IntervalMinutes, LastUpdateDate) <= GetDate() or @UpdateNeededOnly = 0)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_GetFeeds] to public
go

/***********************************************
* Sproc: cs_RollerBlog_GetPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_GetPosts'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetPosts]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROC [dbo].cs_RollerBlog_GetPosts
	@SectionID INT,
	@UrlID INT

AS

SELECT
	SectionID,
	UrlID,
	PostID,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
FROM
	cs_RollerBlogPost
WHERE
	SectionID = @SectionID AND UrlID = @UrlID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_GetPosts] to public
go

/***********************************************
* Sproc: cs_RollerBlog_UpdateFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_UpdateFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_UpdateFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_UpdateFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




CREATE   PROC [dbo].cs_RollerBlog_UpdateFeed
	@SectionID INT,
	@UrlId INT,
    @FeedState INT,
   	@LastUpdateDate DateTime OUTPUT

AS

SELECT @LastUpdateDate = GetDate();
UPDATE cs_RollerBlogFeeds
SET 	
	-- we need to use the sql servers time for this
	LastUpdateDate = @LastUpdateDate, 
	State = @FeedState
WHERE SectionID = @SectionID AND UrlID = @UrlId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_UpdateFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_UpdatePost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_RollerBlog_UpdatePost'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_UpdatePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_UpdatePost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_UpdatePost
	@PostID INT,
	@SectionID INT,
	@UrlID INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

UPDATE cs_RollerBlogPost

SET
	SectionID = SectionID,
	UrlID = @UrlID,
	PermaLink = @PermaLink,
	CommentUrl = @CommentsUrl,
	CommentCount = @CommentsCount,
	GuidName = @GuidName,
	GuidIsPermaLink = @GuidIsPermaLink

WHERE
	PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_UpdatePost] to public
go
/***********************************************
* Sproc: cs_Roller_AddFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roller_AddFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_AddFeed]
GO

/***********************************************
* Sproc: cs_Roller_GetFeeds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roller_GetFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetFeeds]
GO

/***********************************************
* Sproc: cs_Roller_GetPosts
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roller_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetPosts]
GO

/***********************************************
* Sproc: cs_Roller_GetUnaggregatedFeeds
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Roller_GetUnaggregatedFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetUnaggregatedFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetUnaggregatedFeeds]
GO

/***********************************************
* Sproc: cs_SearchBarrel_Search
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SearchBarrel_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SearchBarrel_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SearchBarrel_Search]
GO
CREATE PROCEDURE [dbo].[cs_SearchBarrel_Search] (
	@SearchSQL NText,
	@PageIndex int = 0,
	@PageSize int = 25,
	@SettingsID int
)
AS
BEGIN

	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @StartTime datetime
		, @RowsToReturn int
		, @PageLowerBound int
		, @PageUpperBound int
		, @Count int
		, @TotalRecords int

	-- Used to calculate cost of query
	SET @StartTime = GetDate()

	-- Set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	--SET ROWCOUNT @RowsToReturn

	-- Calculate the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the results in
	CREATE TABLE #SearchResults
	(
		IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
		PostID int not null,
		SectionID int not null,
		Weight int,
		PostDate datetime
	)

	-- Fill the temp table
	INSERT INTO #SearchResults (PostID, SectionID, Weight, PostDate)
	exec sp_executesql @SearchSQL

	SET @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- SELECT actual search results from this table
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.Subject, P.PostDate,
		P.FormattedBody, P.IPAddress, P.PostType, P.SettingsID, P.UserTime,
		P.ApplicationPostType, P.PostName, P.UserTime,
		COALESCE(pa.[FileName], '') AS AttachmentFilename,
		S.ApplicationKey, S.GroupID, S.ApplicationType, S.[Name] as SectionName, S.HubSectionID
	FROM 
		cs_Posts P
	INNER JOIN
		cs_Sections S ON P.SettingsID = S.SettingsID AND P.SectionID = S.SectionID
	INNER JOIN
		#SearchResults R ON R.PostID = P.PostID
	LEFT OUTER JOIN
		cs_PostAttachments pa ON pa.PostID = P.PostID
	WHERE
		S.SettingsID = @SettingsID AND
		R.IndexID > @PageLowerBound AND
		R.IndexID < @PageUpperBound
	Order By IndexID

	DROP Table #SearchResults

	Select @TotalRecords

	SELECT Duration = GetDate() - @StartTime

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_SearchBarrel_Search]  TO [public]
GO


/***********************************************
* Sproc: cs_Search_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Search_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_Add]
GO




CREATE  procedure [dbo].cs_Search_Add (
	@WordHash int,
	@Word nvarchar(64),
	@Weight float,
	@PostID int,
	@ThreadID int,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	IF EXISTS (SELECT WordHash FROM cs_SearchBarrel WHERE PostID = @PostID AND WordHash = @WordHash)
		UPDATE 
			cs_SearchBarrel 
		SET
			Weight = @Weight
		WHERE
			WordHash = @WordHash AND
			PostID = @PostID and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_SearchBarrel
			(WordHash, Word, PostID, ThreadID, SectionID, Weight, SettingsID)
		VALUES
			(@WordHash, @Word, @PostID, @ThreadID, @SectionID, @Weight, @SettingsID)

	IF EXISTS (SELECT PostID From cs_Posts WHERE PostID = @PostID AND IsIndexed = 0 and SettingsID = @SettingsID)
		UPDATE cs_Posts SET IsIndexed = 1 WHERE PostID = @PostID and SettingsID = @SettingsID

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_Add] to public
go
/***********************************************
* Sproc: cs_Search_IgnoreWords
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Search_IgnoreWords'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_IgnoreWords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_IgnoreWords]
GO




CREATE   procedure [dbo].cs_Search_IgnoreWords
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		SELECT
			WordHash,
			Word
		FROM
			cs_SearchIgnoreWords
		WHERE
			SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_IgnoreWords] to public
go
/***********************************************
* Sproc: cs_Search_IgnoreWords_CreateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Search_IgnoreWords_CreateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_IgnoreWords_CreateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_IgnoreWords_CreateDelete]
GO





create procedure [dbo].cs_Search_IgnoreWords_CreateDelete
(
	@WordHash int,
	@Word nvarchar (64),
	@Action int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
IF NOT EXISTS(SELECT * FROM cs_SearchIgnoreWords WHERE WordHash = @WordHash)
	INSERT INTO 
		cs_SearchIgnoreWords
	VALUES
		(@WordHash, @Word, @SettingsID)
END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE 
		cs_SearchIgnoreWords 
	WHERE 
		WordHash = @WordHash and SettingsID = @SettingsID

	DELETE
		cs_SearchBarrel
	WHERE
		WordHash = @WordHash and SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_IgnoreWords_CreateDelete] to public
go
/***********************************************
* Sproc: cs_Search_PostReindex
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_PostReindex]
GO




/***********************************************
* Sproc: cs_Search_UpdatePostIndexStatus
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Search_UpdatePostIndexStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_UpdatePostIndexStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_UpdatePostIndexStatus]
GO




CREATE  procedure [dbo].cs_Search_UpdatePostIndexStatus (
	@PostID int,
	@SettingsID int,
	@Status bit = 1
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	UPDATE cs_Posts SET IsIndexed = @Status WHERE PostID = @PostID and SettingsID = @SettingsID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_UpdatePostIndexStatus] to public
go
/***********************************************
* Sproc: cs_SectionMembers_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionMembers_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionMembers_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionMembers_Add]
GO

CREATE PROCEDURE dbo.cs_SectionMembers_Add
(
	@SectionID			int,
	@UserID				int,
	@MembershipType		int,
	@DateAdded datetime OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


			UPDATE cs_SectionMembers
				Set MembershipType = @MembershipType
			WHERE
				SectionID = @SectionID AND UserID = @UserID

      IF @@ROWCOUNT = 0
      BEGIN
        INSERT INTO cs_SectionMembers
          (SectionID, UserID, MembershipType)
        VALUES
          (@SectionID, @UserID, @MembershipType)
      END
			SELECT @DateAdded = [DateAdded] from cs_SectionMembers WHERE SectionID = @SectionID AND UserID = @UserID AND MembershipType = @MembershipType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_SectionMembers_Add] to public

/***********************************************
* Sproc: cs_SectionMembers_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionMembers_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionMembers_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionMembers_Delete]
GO

CREATE PROCEDURE dbo.cs_SectionMembers_Delete
(
	@SectionID			int = NULL,
	@UserID				int = NULL,
	@MembershipType		int = NULL
)
AS

--Must pass either a sectionid or userid or a bad programmer could use this to delete all records

IF @SectionID is NULL and @UserID is NULL
	RETURN


		DELETE
		FROM	cs_SectionMembers
		WHERE	
		(SectionID = @SectionID OR @SectionID IS NULL) AND
		(UserID = @UserID OR @UserID IS NULL) AND
		(MembershipType = @MembershipType OR @MembershipType IS NULL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_SectionMembers_Delete] to public

/***********************************************
* Sproc: cs_SectionMembers_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionMembers_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionMembers_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionMembers_Get]
GO

CREATE procedure dbo.cs_SectionMembers_Get
(
	@SectionID			int = NULL,
	@UserID				int = NULL,
	@MembershipType		int = NULL
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


		SELECT
			SM.SectionID,
			SM.UserID,
			SM.MembershipType,
			SM.DateAdded,
			S.ApplicationType
		FROM
			cs_SectionMembers SM
			join cs_Sections S on S.SectionID = SM.SectionID and S.IsActive = 1
		WHERE
		(SM.SectionID = @SectionID OR @SectionID IS NULL) AND
		(SM.UserID = @UserID OR @UserID IS NULL) AND
		(SM.MembershipType & @MembershipType = SM.MembershipType OR @MembershipType IS NULL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_SectionMembers_Get] to public

/***********************************************
* Sproc: cs_Sections_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Sections_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_Get]
GO


CREATE PROCEDURE [dbo].[cs_Sections_Get]
(
	@SettingsID				int,
	@ApplicationType        smallint = null,
	@AllowInactive			bit = 0,
	@IncludePostTypeCounts	bit = 0,
	@sqlPopulate			ntext = null,
	@PageIndex				int = 0, 
	@PageSize				int = 2147483646,
	@IncludePageIndex		bit = 0,
	@IncludeMembers			bit = 0,
	@HubSectionID			int = 0,
	@TotalRecords			int = null output

)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalThreads int
	
	-- First set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	
	
	
	
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndex 
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		SectionID int not null
	)
	 
	
	if @sqlPopulate is not null
	BEGIN
		INSERT INTO #PageIndex (SectionID)
		EXEC sp_executesql @sqlPopulate
	END
	ELSE
	BEGIN
		IF @ApplicationType = 11 AND @HubSectionID = 0
		BEGIN
			INSERT INTO #PageIndex (SectionID)
			SELECT SectionID from cs_Sections where SettingsID = @SettingsID AND (ApplicationType = @ApplicationType OR @ApplicationType is null)
		END
		ELSE
		BEGIN
			INSERT INTO #PageIndex (SectionID)
			SELECT SectionID from cs_Sections where SettingsID = @SettingsID AND (ApplicationType = @ApplicationType OR @ApplicationType is null) AND HubSectionID = @HubSectionID
		END
	END
	
	SET @TotalRecords = @@rowcount
	
	-- if an index is to be created, it should come after the insertion
	--CREATE INDEX page_index ON #PageIndex(IndexID)
	
	SET ROWCOUNT @RowsToReturn
	
	
	-- Return all the sections
	SELECT  
		S.SectionID, S.SettingsID, S.IsActive, S.ParentID, S.GroupID, S.Name, S.NewsgroupName, 
		S.Description, S.DateCreated, S.Url, S.IsModerated, S.DaysToView, S.SortOrder, S.TotalPosts, 
		S.TotalThreads, S.DisplayMask, S.EnablePostStatistics, S.EnablePostPoints, S.EnableAnonymousPosting, 
		S.MostRecentPostID, S.MostRecentThreadID, S.MostRecentThreadReplies, S.MostRecentPostSubject, 
		S.MostRecentPostAuthor, S.MostRecentPostAuthorID, S.MostRecentPostDate, S.PostsToModerate, S.ForumType, 
		S.IsSearchable, S.ApplicationType, S.ApplicationKey, S.Path, S.PropertyNames as SectionPropertyNames, 
		S.PropertyValues as SectionPropertyValues, S.DefaultLanguage, S.DiskUsage, S.IsPublic, S.HubSectionID, 
		S.IsCommunityAggregated, W.MostRecentPostID as WeblogMostRecentPostID, 
		W.MostRecentPostDate as WeblogMostRecentPostDate, W.MostRecentPostName as WeblogMostRecentPostName, 
		W.MostRecentPostAuthorID as WeblogMostRecentPostAuthorID, W.MostRecentPostAuthor as WeblogMostRecentPostAuthor, 
		W.MostRecentPostSubject as WeblogMostRecentPostSubject, W.MostRecentArticleID, W.MostRecentArticleDate, 
		W.MostRecentArticleName, W.MostRecentArticleAuthorID, W.MostRecentArticleAuthor, W.MostRecentArticleSubject, 
		W.PostCount, W.ArticleCount, W.CommentCount, W.TrackbackCount
	FROM
		#PageIndex jPI
		INNER JOIN cs_Sections S on S.SettingsID = @SettingsID AND S.SectionID = jPI.SectionID
		LEFT OUTER JOIN cs_weblog_Weblogs W on S.SectionID = W.SectionID
	WHERE
		--(IsActive = 1 OR 1 = @AllowInactive) AND
		(ApplicationType = @ApplicationType or @ApplicationType is null) AND
		jPI.IndexID > @PageLowerBound AND 
		jPI.IndexID < @PageUpperBound
	ORDER BY
		IndexID	-- this is the ordering system we're using populated from the @sqlPopulate
	
	
	--Clear the rowcount
	SET ROWCOUNT 0
	
	--Declare @AnonID int
	--exec cs_GetAnonymousUserID @SettingsID, @AnonID output
	
	exec cs_Section_Permissions_Get @SettingsID, 0, @ApplicationType
	
	--Return the counts of each post type
	IF @IncludePostTypeCounts > 0
	BEGIN
		
		SELECT 
			F.ApplicationKey, P.ApplicationPostType, Count(*) as PostCount
		FROM 
			#PageIndex jPI
			INNER JOIN cs_Sections F on F.SettingsID = @SettingsID AND F.SectionID = jPI.SectionID
			INNER JOIN cs_Posts P on F.SettingsID = P.SettingsID AND F.SectionID = P.SectionID
		WHERE 
			jPI.IndexID > @PageLowerBound AND 
			jPI.IndexID < @PageUpperBound AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		GROUP BY 
			F.ApplicationKey, P.ApplicationPostType, jPI.IndexID
		ORDER BY
			IndexID	-- this is the ordering system we're using populated from the @sqlPopulate
		
	END
	
	SET ROWCOUNT 0
	
  IF @IncludeMembers = 1
  BEGIN

	SELECT
		SM.SectionID,
		SM.UserID,
		SM.MembershipType,
		SM.DateAdded,
		S.ApplicationType
	FROM
		#PageIndex jPI
		INNER JOIN dbo.cs_SectionMembers SM on SM.SectionID = jPI.SectionID
		INNER JOIN cs_Sections S on S.SettingsID = @SettingsID AND S.SectionID = jPI.SectionID
	WHERE
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
	ORDER BY
		SM.SectionID, SM.MembershipType

  End
	
	If @IncludePageIndex = 1 
	BEGIN
		SELECT IndexID, SectionID from #PageIndex ORDER BY IndexID
	END
	
	DROP TABLE #PageIndex
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Sections_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Sections_GetRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Sections_GetRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_GetRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_GetRead]
GO


create procedure [dbo].cs_Sections_GetRead (
	@UserID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	SectionID,
	LastActivity
FROM
	cs_SectionsRead
WHERE
	UserID = @UserID AND 
	SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_GetRead] to public
go
/***********************************************
* Sproc: cs_Sections_MoveOrReOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Sections_MoveOrReOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_MoveOrReOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_MoveOrReOrder]
GO

Create Proc [dbo].cs_Sections_MoveOrReOrder
(
	@NewGroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Declare @OldGroupId int
Select @OldGroupId = GroupID from cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

if(@NewGroupID <> @OldGroupId) -- move from one group to another
Begin
	--Move the group, mark order at the end
	update cs_Sections
	Set GroupID = @NewGroupID, SortOrder = 9999999 where SectionID = @SectionID and SettingsID = @SettingsID

	--Update Old Group
	exec cs_Sections_ResetOrder @OldGroupId, @SettingsID
End

--Reset the Section
exec cs_Section_MoveSection @NewGroupID, @SectionID, @SectionIndex, @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_MoveOrReOrder] to public
go
/***********************************************
* Sproc: cs_Sections_ResetOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Sections_ResetOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_ResetOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_ResetOrder]
GO

Create Proc [dbo].cs_Sections_ResetOrder
(
	@GroupID int,
	@SettingsID int
)
as

Declare @Sort int
Set @Sort = 0
Declare @SectionID int
DECLARE section_Cursor CURSOR FOR
SELECT SectionID FROM cs_Sections where GroupID = @GroupID and SettingsID = @SettingsID order by SortOrder

OPEN section_Cursor

FETCH NEXT FROM section_Cursor Into @SectionID
WHILE (@@FETCH_STATUS = 0)
Begin
	Update cs_Sections Set SortOrder = @Sort where SectionID = @SectionID
	Set @Sort = @Sort + 1
   FETCH NEXT FROM section_Cursor Into @SectionID
End

CLOSE section_Cursor
DEALLOCATE section_Cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_ResetOrder] to public
go
/***********************************************
* Sproc: cs_SectionTokens_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionTokens_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Add]
GO

Create Proc [dbo].[cs_SectionTokens_Add]
(
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int,
	@TokenID int output
)

as

Insert cs_SectionTokens (Token, Link, [Text], SettingsID, SectionID)
Values (@Token, @Link, @Text, @SettingsID, @SectionID)

Select @TokenID = SCOPE_IDENTITY()



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Add to public
go
/***********************************************
* Sproc: cs_SectionTokens_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionTokens_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Delete]
GO


Create Proc [dbo].[cs_SectionTokens_Delete]
(
	@TokenID int,
	@SectionID int,
	@SettingsID int
)
as
Delete FROM cs_SectionTokens where TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Delete to public
go
/***********************************************
* Sproc: cs_SectionTokens_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionTokens_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Get]
GO

Create Proc [dbo].[cs_SectionTokens_Get]
(
	@SectionID int,
	@SettingsID int
)
as
Select TokenID, Token, Link, [Text], SectionID FROM cs_SectionTokens where SettingsID = @SettingsID and SectionID = @SectionID Order by Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Get to public
go
/***********************************************
* Sproc: cs_SectionTokens_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SectionTokens_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Update]
GO

Create Proc [dbo].[cs_SectionTokens_Update]
(
	@TokenID int,
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int
)

as

update cs_SectionTokens
Set 
	Token = @Token,
	Link = @Link,
	[Text] = @Text
where
	TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Update to public
go
/***********************************************
* Sproc: cs_Section_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_CreateUpdateDelete]
GO


-- sp_helptext cs_Section_CreateUpdateDelete


CREATE PROCEDURE [dbo].cs_Section_CreateUpdateDelete
(
	@SectionID	int out,
	@DeleteForum	bit = 0,
	@Name		nvarchar(256) = '',
	@Url		nvarchar(512) = '',
	@Description	nvarchar(1000) = '',
	@ParentID	int = 0,
	@SettingsID	int,
	@GroupID	int = 0,
	@IsModerated	bit = 1,
	@IsSearchable   bit = 1,
	@DisplayPostsOlderThan	int = 0,
	@IsActive 	bit = 0,
	@EnablePostStatistics bit = 1,
	@EnablePostPoints bit = 1,
	@EnableAnonymousPosting bit = 0,
	@SortOrder int = 0,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ApplicationKey nvarchar(256) = null,
	@ApplicationType smallint = 0,
	@ForumType int = 0,
	@UserID int,
	@DefaultLanguage nvarchar(32) = null,
	@IsPublic 	bit = null,
	@IsCommunityAggregated 	bit = 1,
	@HubSectionID int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting the forum?
IF @DeleteForum = 1
BEGIN

	Select @ApplicationKey = 'Deleted Section ' + ApplicationKey FROM cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

	exec cs_system_ModerationAction_AuditEntry 19, @UserID, null, @UserID, @SectionID, @SettingsID,  @ApplicationKey


           DECLARE @SectionToDeleteParentID int
           SET @SectionToDeleteParentID = (SELECT ParentID FROM cs_Sections WHERE SectionID = @SectionID)

	-- delete the specified forum and all of its posts
	-- first we must remove all the thread tracking rows
	DELETE 
		cs_TrackedThreads
	WHERE 
		ThreadID IN (SELECT DISTINCT ThreadID FROM cs_Threads WHERE SectionID = @SectionID and SettingsID = @SettingsID)

	-- we must remove all of the moderators for this forum
	DELETE 
		cs_Moderators
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	-- we must remove all roller blog related data
	DELETE
		cs_RollerBlogPost
	FROM
		cs_RollerBlogPost RBP INNER JOIN cs_RollerBlogFeeds RBF ON  RBP.SectionID = RBF.SectionID AND RBP.UrlID = RBF.UrlID
	WHERE
		RBF.SectionID = @SectionID AND RBF.SettingsID = @SettingsID

	DELETE
		cs_RollerBlogFeeds
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- now we must remove all of the posts
	DELETE 
		cs_Posts
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE cs_weblog_Weblogs Where SectionID = @SectionID and SettingsID = @SettingsID

	-- remove all the explicit forum permissions
	DELETE
		cs_SectionPermissions
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- finally we can delete the actual forum
	DELETE 
		cs_Sections
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE 
		cs_Posts_InCategories
	WHERE
		CategoryID in (Select CategoryID FROM cs_Post_Categories where SectionID = @SectionID and SettingsID = @SettingsID)

	DELETE 
		cs_Post_Categories
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID		

	-- Clean up an child sectoins
       UPDATE
		cs_Sections
	SET 
		ParentID = @SectionToDeleteParentID
        WHERE
                ParentID = @SectionID


	RETURN
END

-- Are we updating a forum
IF @SectionID > 0
BEGIN
	-- if we are making the forum non-moderated, remove all forum moderators for this forum
	IF @IsModerated = 0
		DELETE 
			cs_Moderators
		WHERE 
			SectionID = @SectionID and SettingsID = @SettingsID

	-- Update the forum information
	UPDATE 
		cs_Sections 
	SET
		Name = @Name,
		Url = @Url,
		Description = @Description,
		ParentID = @ParentID,
		SettingsID = @SettingsID,
		GroupID = @GroupID,
		IsModerated = @IsModerated,
		IsActive = @IsActive,
		IsSearchable = @IsSearchable,
		DaysToView = @DisplayPostsOlderThan,
		EnablePostStatistics = @EnablePostStatistics,
		EnablePostPoints = @EnablePostPoints,
		EnableAnonymousPosting = @EnableAnonymousPosting,
		SortOrder = @SortOrder,
		ApplicationKey = @ApplicationKey,
		ApplicationType = @ApplicationType,
		ForumType = @ForumType,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		DefaultLanguage = @DefaultLanguage,
		IsPublic = @IsPublic,
		IsCommunityAggregated = @IsCommunityAggregated,
		HubSectionID = @HubSectionID
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID
END
ELSE
BEGIN

	if( @SortOrder = 0 ) 
	begin
		select @SortOrder = coalesce(max(SortOrder) + 1, 1) from cs_Sections where GroupID = @GroupID

		if(@SortOrder is null)
		Begin
			Select @SortOrder = 1
		End
	end

	-- Create a new Forum
	INSERT INTO 
		cs_Sections (
			Name, 
			Url,
			Description, 
			ParentID, 
			SettingsID, 
			GroupID, 
			IsModerated, 
			DaysToView, 
			IsActive,
			IsSearchable,
			EnablePostStatistics,
			EnablePostPoints,
			SortOrder,
			ApplicationKey,
			ApplicationType,
			ForumType,
			PropertyNames,
			PropertyValues,
			DefaultLanguage,
			IsPublic,
			IsCommunityAggregated,
			HubSectionID
			)
		VALUES (
			@Name,
			@Url,
			@Description,
			@ParentID,
			@SettingsID,
			@GroupID,
			@IsModerated,
			@DisplayPostsOlderThan,
			@IsActive,
			@IsSearchable,
			@EnablePostStatistics,
			@EnablePostPoints,
			@SortOrder,
			@ApplicationKey, 
			@ApplicationType,
			@ForumType,
			@PropertyNames,
			@PropertyValues,
			@DefaultLanguage,
			@IsPublic,
			@IsCommunityAggregated,
			@HubSectionID
			)
	
	SET @SectionID = scope_identity()

	If @ApplicationType = 1
	Begin
		Insert cs_weblog_Weblogs (SectionID, SettingsID) Values (@SectionID, @SettingsID)
	End

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Section_CreateUpdateDelete]  TO [public]
GO


/***********************************************
* Sproc: cs_Section_DiskUsage_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_DiskUsage_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_DiskUsage_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_DiskUsage_Update]
GO

CREATE PROCEDURE dbo.cs_Section_DiskUsage_Update
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	UPDATE cs_Sections SET DiskUsage = (SELECT COALESCE(SUM(Convert(bigint, ContentSize)),0) AS DiskUsage FROM cs_PostAttachments WHERE SectionID = @SectionID AND SettingsID = @SettingsID)
	WHERE SettingsID = @SettingsID AND SectionID = @SectionID
	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_DiskUsage_Update] to public
go

/***********************************************
* Sproc: cs_Section_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Get]
GO


/***********************************************
* Sproc: cs_Section_GetRandomSectionID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_GetRandomSectionID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_GetRandomSectionID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_GetRandomSectionID]
GO

CREATE PROCEDURE dbo.cs_Section_GetRandomSectionID
	@SettingsID int,
	@ApplicationType smallint,
	@AllowEmpty bit = 0
AS
SET Transaction Isolation Level Read UNCOMMITTED
select top 1 SectionID
	from cs_Sections
	where ApplicationType = @ApplicationType
		and SettingsID = @SettingsID
		and IsActive = 1
		and (TotalThreads > 0 OR 1 = @AllowEmpty)
	order by newid()

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_GetRandomSectionID] to public
go
/***********************************************
* Sproc: cs_Section_GetSectionIDByPostID
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_GetSectionIDByPostID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_GetSectionIDByPostID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_GetSectionIDByPostID]
GO









CREATE PROCEDURE [dbo].cs_Section_GetSectionIDByPostID
(
	@PostID			int = 0,
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Loop up the forum by PostID

SELECT SectionID FROM cs_Posts WHERE PostID = @PostID and SettingsID = @SettingsID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_GetSectionIDByPostID] to public
go
/***********************************************
* Sproc: cs_Section_IsPublic_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_IsPublic_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_IsPublic_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_IsPublic_Update]
GO

CREATE PROCEDURE dbo.cs_Section_IsPublic_Update
(
	@SectionID int,
	@SettingsID int,
	@IsPublic bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	UPDATE cs_Sections SET IsPublic = @IsPublic
	WHERE SettingsID = @SettingsID AND SectionID = @SectionID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_IsPublic_Update] to public
go

/***********************************************
* Sproc: cs_Section_IsPublic_UpdateAll
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_IsPublic_UpdateAll'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_IsPublic_UpdateAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_IsPublic_UpdateAll]
GO

CREATE PROCEDURE dbo.cs_Section_IsPublic_UpdateAll
(
	@SettingsID int,
	@RoleID uniqueidentifier,
	@ApplicationType int,
	@Reset bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

--SET @SettingsID = 1000
--SET @ApplicationType = 0
--SET @Reset = 1

--Select @RoleID = RoleID from aspnet_Roles where LoweredRoleName = 'everyone'

Update [dbo].[cs_Sections] set IsPublic = P.AllowViewBit FROM
	(
	SELECT
		F.SettingsID, 
		DefaultPermission = convert(bit, coalesce(P.AllowMask*0,1)), 
		F.SectionID, 
		F.ApplicationKey,
		AllowViewBit = coalesce(P.AllowMask, PP.AllowMask) & 1 --CONVERT(bigint, 0x0000000000000001)
	FROM 
		cs_Sections F
		LEFT OUTER JOIN cs_ProductPermissions PP on F.ApplicationType = PP.ApplicationType and PP.RoleID = @RoleID
		LEFT OUTER JOIN cs_SectionPermissions P on P.SectionID = F.SectionID and P.RoleID = @RoleID

	WHERE
		F.SettingsID = @SettingsID
		AND F.ApplicationType = @ApplicationType
		AND (F.IsPublic is null or @Reset = 1)

	) P JOIN cs_Sections F  ON P.SectionID = F.SectionID
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_IsPublic_UpdateAll] to public
go

/***********************************************
* Sproc: cs_Section_IsPublic_UpdateGroup
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_IsPublic_UpdateGroup'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_IsPublic_UpdateGroup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_IsPublic_UpdateGroup]
GO

CREATE PROCEDURE [dbo].[cs_Section_IsPublic_UpdateGroup]
(
	@SettingsID int,
	@RoleID uniqueidentifier,
	@GroupID int,
	@ApplicationType int,
	@Reset bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Update cs_Sections set IsPublic = P.AllowViewBit FROM
	(
	SELECT
		F.SettingsID, 
		DefaultPermission = convert(bit, coalesce(P.AllowMask*0,1)), 
		F.SectionID, 
		F.ApplicationKey,
		AllowViewBit = coalesce(P.AllowMask, GP.AllowMask, PP.AllowMask) & 1
	FROM 
		cs_Sections F
		LEFT OUTER JOIN cs_GroupPermissions GP on F.GroupID = GP.GroupID and GP.RoleID = @RoleID
		LEFT OUTER JOIN cs_ProductPermissions PP on F.ApplicationType = PP.ApplicationType and PP.RoleID = @RoleID
		LEFT OUTER JOIN cs_SectionPermissions P on P.SectionID = F.SectionID and P.RoleID = @RoleID

	WHERE
		F.SettingsID = @SettingsID
		AND F.GroupID = @GroupID
		AND F.ApplicationType = @ApplicationType
		AND (F.IsPublic is null or @Reset = 1)

	) P JOIN cs_Sections F ON P.SectionID = F.SectionID
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_IsPublic_UpdateGroup] to public
go

/***********************************************
* Sproc: cs_Section_MarkRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_MarkRead'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_MarkRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_MarkRead]
GO




CREATE    procedure [dbo].cs_Section_MarkRead
(
	@UserID int,
	@SectionID int = 0,
	@SettingsID int,
	@GroupID int = 0,
	@MarkAllThreadsRead bit = 0

)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @LastReadThread int

	SET NOCOUNT ON

	IF @UserID = 0
		RETURN

	-- Are we marking all forums as read?
	IF @GroupID = 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID and SettingsID = @SettingsID

		-- 2. INSERT into cs_SectionsRead
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking a particular forum group as read?
	IF @GroupID > 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID

		-- 2. Insert into cs_Sections Read
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE GroupID = @GroupID and SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking an individual forum as read?
	IF @SectionID > 0
	BEGIN
		IF @MarkAllThreadsRead = 1
			IF EXISTS (SELECT UserID FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID)
				UPDATE 
					cs_SectionsRead 
				SET 
					NewPosts = 0,
					MarkReadAfter = (SELECT (MostRecentPostID + 1) FROM cs_Sections F WHERE SectionID = @SectionID),
					LastActivity = GetDate()
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID  and SettingsID = @SettingsID
			ELSE
				INSERT INTO 
					cs_SectionsRead
				SELECT GroupID, SectionID, @UserID, (MostRecentPostID + 1), 0, GetDate(), SettingsID FROM cs_Sections F WHERE SectionID = @SectionID  and SettingsID = @SettingsID
		ELSE
			IF (SELECT NewPosts FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID) = 1
				UPDATE
					cs_SectionsRead							
				SET 
					NewPosts = 0
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID

	END
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_MarkRead] to public
go
/***********************************************
* Sproc: cs_Section_MoveSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_MoveSection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_MoveSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_MoveSection]
GO

Create Proc [dbo].cs_Section_MoveSection
(
	@GroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Set NoCount On

--Set Order
exec cs_Sections_ResetOrder @GroupID, @SettingsID

--Update all items at or below the updatedindex
update cs_Sections
Set SortOrder = SortOrder + 1 where SortOrder >= @SectionIndex and GroupID = @GroupID and SettingsID = @SettingsID

--Set the item we are updating
update cs_Sections
Set SortOrder = @SectionIndex where SectionID = @SectionID and SettingsID = @SettingsID

-- Make sure everything is sorted correctly
exec cs_Sections_ResetOrder @GroupID, @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_MoveSection] to public
go
/***********************************************
* Sproc: cs_Section_Permissions_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_Permissions_Get'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[cs_Section_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Permissions_Get]
GO

create procedure [dbo].[cs_Section_Permissions_Get]
(
	@SettingsID int,
	@SectionID int = 0,
	@ApplicationType smallint,
	@AllRoles ntext = NULL
)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	IF ( @SectionID = 0 )
	begin
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID
	
		UNION ALL
	
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			P.GroupID, 
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			G.ApplicationType 
		FROM 
			cs_GroupPermissions P
		INNER JOIN
			cs_Groups G
			ON P.GroupID = G.GroupID AND P.SettingsID = G.SettingsID
		WHERE
			G.SettingsID = @SettingsID AND
			(G.ApplicationType = @ApplicationType or @ApplicationType is null)
		
		UNION ALL
	
		-- Return section permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 0), 
			P.SectionID,
			GroupID = -1, 
			F.ApplicationKey,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			F.ApplicationType
		FROM 
			cs_SectionPermissions P
		INNER JOIN
			cs_Sections F
			ON P.SectionID = F.SectionID AND P.SettingsID = F.SettingsID
		WHERE
			F.SettingsID = @SettingsID AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		order by Implied asc, SectionID, GroupID desc
	
	end
	ELSE IF (@SectionID > 0)
	begin
		
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID
	
		UNION ALL

		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			P.GroupID,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			S.ApplicationType 
		FROM
			cs_GroupPermissions P
			INNER JOIN cs_Sections S on S.SectionID = @SectionID AND S.GroupID = P.GroupID
		WHERE 
			P.SettingsID = @SettingsID

		UNION ALL
		
		-- Return section permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 0), 
			P.SectionID,
			F.GroupID,
			F.ApplicationKey,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			F.ApplicationType 
		FROM 
			cs_SectionPermissions P
		INNER JOIN
			cs_Sections F
			ON P.SectionID = F.SectionID AND P.SettingsID = F.SettingsID
		WHERE
			F.SettingsID = @SettingsID AND
			F.SectionID = @SectionID  AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		order by Implied asc, SectionID, GroupID DESC
	END 
    ELSE BEGIN
	
	    DECLARE @Roles		table(RoleID uniqueidentifier NOT NULL PRIMARY KEY)
	    DECLARE @Num		int
	    DECLARE @Pos		int
	    DECLARE @NextPos	int
	    DECLARE @guid		nvarchar(256)
	
	    DECLARE @textpos  int --our chunks position in the ntext
	    DECLARE @chunklen smallint
	    DECLARE @chunk   nvarchar(4000)
	    DECLARE @delimiter nvarchar(1)
	    DECLARE @leftover nvarchar(4000)
	
		SET @delimiter = N','
		SET @Num = 0
		SET @textpos = 1
		SET @leftover = ''
	
		WHILE @textpos <= DATALENGTH(@AllRoles) /2
		BEGIN
	
			SET @chunklen = 4000 - DATALENGTH(@leftover) /2
			SET @chunk = ltrim(@leftover + substring(@AllRoles, @textpos, @chunklen))
			SET @textpos = @textpos + @chunklen
	
			SET @Pos = 1 
	
			WHILE(@Pos <= DATALENGTH(@chunk))
			BEGIN
				SELECT @NextPos = CHARINDEX(@delimiter, @chunk,  @Pos)
				IF (@NextPos = 0 OR @NextPos IS NULL)
				BEGIN
					--break us from the loop
					SELECT @NextPos = DATALENGTH(@chunk) + 1
					--set the leftover string to use again in next iter
					SET @leftover = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
				END
				ELSE
				BEGIN
					SELECT @guid = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
	
					INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @guid))
	
					SET @Num = @Num + 1
				END
	
				SELECT @Pos = @NextPos+1
			END
	
			IF(@Pos = DATALENGTH(@chunk))
				SET @leftover = ''
		END
	
		INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @leftover))
	
	
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			R.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),
			P.ApplicationType 
		FROM
			@Roles R
			left outer join cs_ProductPermissions P on R.RoleID = P.RoleID and (P.ApplicationType = @ApplicationType or @ApplicationType is null)and P.SettingsID = @SettingsID
	END
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_Permissions_Get] to public
go
/***********************************************
* Sproc: cs_Section_Permission_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_Permission_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_Permission_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Permission_CreateUpdateDelete]
GO

CREATE  procedure [dbo].cs_Section_Permission_CreateUpdateDelete
(
	@SettingsID 	int,
	@SectionID 	int,
	@GroupID 	int,
	@RoleID		uniqueidentifier,
	@Action		int,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@ApplicationType smallint
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

-- Create
IF @Action = 0
BEGIN

	IF( @SectionID <> -1) 
	begin
		-- Check if an entry already exists
		IF EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
	
		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		select @GroupID = GroupID from cs_Sections S where S.SectionID = @SectionID and S.SettingsID = @SettingsID
			
		if not exists( select * from cs_GroupPermissions where SettingsID = @SettingsID and RoleID = @RoleID and GroupID = @GroupID)
			insert into cs_GroupPermissions ( SettingsID, RoleID, AllowMask, DenyMask, GroupID )
				values( @SettingsID, @RoleID, 0x0, 0x0, @GroupID )
				
		--reindex the posts
		exec cs_Posts_ReindexBySection @SectionID, @SettingsID
	end
	ELSE IF (@GroupID <> -1)
	begin
		IF EXISTS (SELECT GroupID FROM cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_GroupPermissions (SettingsID, GroupID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@GroupID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		--reindex the posts
		exec cs_Posts_ReindexByGroup @GroupID, @SettingsID
	end
	ELSE
	begin
		insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
			values( @SettingsID, @RoleID, @AllowMask, @DenyMask, @ApplicationType )
	end
END
-- UPDATE
ELSE IF @Action = 1
BEGIN
	
	IF ( @SectionID <> -1 ) 
	begin
		IF NOT EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID )
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
		ELSE
			UPDATE
				cs_SectionPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				SectionID = @SectionID AND
				RoleID = @RoleID AND SettingsID = @SettingsID

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		select @GroupID = GroupID from cs_Sections S where S.SectionID = @SectionID and S.SettingsID = @SettingsID
			
		if not exists( select * from cs_GroupPermissions where SettingsID = @SettingsID and RoleID = @RoleID and GroupID = @GroupID)
			insert into cs_GroupPermissions ( SettingsID, RoleID, AllowMask, DenyMask, GroupID )
				values( @SettingsID, @RoleID, 0x0, 0x0, @GroupID )
	end
	ELSE IF (@GroupID <> -1)
	begin
		IF NOT EXISTS (SELECT GroupID FROM cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID )
			INSERT INTO 
				cs_GroupPermissions (SettingsID, GroupID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@GroupID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
		ELSE
			UPDATE
				cs_GroupPermissions
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				GroupID = @GroupID AND
				RoleID = @RoleID AND
				SettingsID = @SettingsID

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )	
	end
	ELSE
	begin
		if not exists( select * from cs_ProductPermissions where RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		else
			UPDATE
				cs_ProductPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end

END
ELSE IF @Action = 2
BEGIN
	IF( @SectionID <> -1 )
		DELETE cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID
	ELSE IF (@GroupID <> -1)
		DELETE cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID AND SettingsID = @SettingsID
	ELSE
	begin
		DELETE cs_SectionPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID
		DELETE cs_GroupPermissions WHERE RoleID = @RoleID AND SettingsID = @SettingsID
		DELETE cs_ProductPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end
	
END

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Section_Permission_CreateUpdateDelete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Section_RssPingback_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_RssPingback_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_RssPingback_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_RssPingback_Update]
GO






create procedure [dbo].cs_Section_RssPingback_Update (
	@SectionID int,
	@Pingback nvarchar(512),
	@Count int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT SectionID FROM cs_ForumPingback WHERE SectionID = @SectionID AND Pingback = @Pingback)
		UPDATE
			cs_ForumPingback
		SET
			[Count] = [Count] + @Count,
			LastUpdated = GetDate()
		WHERE
			SectionID = @SectionID AND
			Pingback = @Pingback and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_ForumPingback
		VALUES
			(@SectionID, @Pingback, @Count, GetDate(), @SettingsID)
			

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_RssPingback_Update] to public
go
/***********************************************
* Sproc: cs_Section_UpdateSortOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Section_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_UpdateSortOrder]
GO
/***********************************************
* Sproc: cs_security_ValidateUserPasswordAnswer
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_security_ValidateUserPasswordAnswer'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_security_ValidateUserPasswordAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_security_ValidateUserPasswordAnswer]
GO


/***********************************************
* Sproc: cs_Services_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Services_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Services_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Services_Get]
GO







create proc [dbo].cs_Services_Get
(
	@ServiceID int = 0,
	@SettingsID int
)
as 
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT
		*
	FROM
		cs_Services
	WHERE
		ServiceID = @ServiceID or
		(@ServiceID = 0 and 1=1) and SettingsID = @SettingsID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Services_Get] to public
go
/***********************************************
* Sproc: cs_Service_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Service_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Service_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Service_CreateUpdateDelete]
GO








create proc [dbo].cs_Service_CreateUpdateDelete
(
	  @ServiceID				int out
	, @DeleteService			bit = 0
	, @ServiceName				nvarchar(60)
	, @ServiceTypeCode			int
	, @ServiceAssemblyPath		nvarchar(512)
	, @ServiceFullClassName		nvarchar(512)
	, @ServiceWorkingDirectory	nvarchar(512)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the service
IF ( @DeleteService > 0 )
BEGIN

	DELETE cs_Services
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

	RETURN
END

IF( @ServiceID > 0 )
BEGIN

	UPDATE cs_Services SET
		  ServiceName				= @ServiceName
		, ServiceTypeCode			= @ServiceTypeCode
		, ServiceAssemblyPath		= @ServiceAssemblyPath
		, ServiceFullClassName		= @ServiceFullClassName
		, ServiceWorkingDirectory	= @ServiceWorkingDirectory
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

END
ELSE
BEGIN

	INSERT INTO cs_Services (
		ServiceName, ServiceTypeCode, ServiceAssemblyPath, ServiceFullClassName, ServiceWorkingDirectory, SettingsID
	) VALUES (
		@ServiceName, @ServiceTypeCode, @ServiceAssemblyPath, @ServiceFullClassName, @ServiceWorkingDirectory, @SettingsID
	)

	SET @ServiceID = SCOPE_IDENTITY()

END

RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Service_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_SetForumSubscriptionType
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SetForumSubscriptionType'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SetForumSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SetForumSubscriptionType]
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SetSectionSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SetSectionSubscriptionType]
GO





CREATE procedure [dbo].cs_SetSectionSubscriptionType
(
	@UserID int,
	@SectionID int,
	@subType int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
if (@subType=0)
	DELETE from cs_TrackedSections where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
IF Exists (select SubscriptionType from cs_TrackedSections (nolock) where UserID=@UserID AND SectionID=@SectionID and SettingsID = @SettingsID)
	UPDATE cs_TrackedSections Set SubscriptionType=@subType where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
	INSERT INTO cs_TrackedSections (UserID, SectionID, SubscriptionType, SettingsID) values (@UserID, @SectionID, @subType, @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SetSectionSubscriptionType to public
go
/***********************************************
* Sproc: cs_SettingsIDs_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SettingsIDs_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SettingsIDs_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SettingsIDs_Get]
GO


CREATE  PROCEDURE [dbo].cs_SettingsIDs_Get
AS
SET Transaction Isolation Level Read UNCOMMITTED

Select 
	sm.SettingsID, 
	s.SiteUrl 
FROM 
	cs_SiteMappings sm,
	cs_Sites s
Where
	s.SiteID = sm.SiteID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SettingsIDs_Get to public
go
/***********************************************
* Sproc: cs_shared_Threads_GetThreadSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_shared_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_shared_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_shared_Threads_GetThreadSet]
GO

CREATE  PROCEDURE [dbo].[cs_shared_Threads_GetThreadSet]
(
	@SectionID int,
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@sqlPopulateCount ntext,
	@UserID int,
	@IncludeCategories bit,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int

	/* First set the rowcount */
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)

	/* Set the page bounds */
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	/* Create a temp table to store the select results */
	CREATE TABLE #PageIndex
	(
		IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
		PostID int NOT NULL
	)

	exec sp_executesql @sqlPopulateCount, N'@recordCount int output', @recordCount = @TotalRecords output

	INSERT INTO #PageIndex (PostID)
	exec sp_executesql @sqlPopulate, N'@localRowsToReturn int', @localRowsToReturn = @RowsToReturn

	/* this is the size of the page */
	SET ROWCOUNT @PageSize

	SELECT
		SortOrder = jPI.IndexID,
		jP.PostID,
		jP.ThreadID,
		jP.ParentID,
		jP.PostAuthor,
		jP.UserID,
		jP.SectionID,
		jP.PostLevel,
		jP.SortOrder,
		jP.Subject,
		jP.PostDate,
		jP.IsApproved,
		jP.IsLocked as IsLocked,
		jP.IsIndexed,
		jP.TotalViews as PostTotalViews,  /* Conflicts with the Threads table which has precidence */
		jP.Body,
		jP.FormattedBody,
		jP.IPAddress,
		jP.PostType,
		jP.PostMedia,
		jP.EmoticonID,
		jP.SettingsID,
		jP.AggViews,
		jP.PostPropertyNames,
		jP.PostPropertyValues,
		jP.PostConfiguration,
		jP.Points AS PostPoints,
		jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created, jP.Height, jP.Width,
		jP.PostName,
		jP.ApplicationPostType,
		jP.UserTime,
		HasRead = 1,
		EditNotes = null, /*(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),*/

		jT.PostAuthor as UserName,
		jT.TotalReplies as Replies, /* (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1) */

	        jT.UserID as ThreadUserID,
	        jT.PostAuthor as ThreadPostAuthor,
	        jT.PostDate as ThreadPostDate,
	        jT.ThreadDate,
	        jT.LastViewedDate,
	        jT.StickyDate,
	        jT.TotalViews as TotalViews,
	        jT.TotalReplies,
	        jT.MostRecentPostAuthorID,
	        jT.MostRecentPostAuthor,
	        jT.MostRecentPostID,
	        jT.IsLocked as ThreadIsLocked,
	        jT.IsSticky,
	        jT.IsApproved as ThreadIsApproved,
	        jT.RatingSum,
	        jT.TotalRatings,
	        jT.ThreadEmoticonID,
	        jT.ThreadStatus,
	        jT.SettingsID
		, jP.PostStatus, jP.SpamScore
	FROM
		#PageIndex jPI
		INNER JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
		INNER JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	WHERE
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		/*AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,*/
		/*AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID*/
	ORDER BY
		IndexID	/* this is the ordering system we're using populated from the @sqlPopulate */

	SET ROWCOUNT 0

	IF @IncludeCategories = 1
	BEGIN
		declare @P table(PostID int not null primary key)

		insert into @P
		select jPI.PostID from #PageIndex jPI
		where jPI.IndexID > @PageLowerBound
			AND jPI.IndexID < @PageUpperBound

		SELECT
			Cats.[Name], PIC.PostID
		FROM
			@P jPI
			INNER JOIN cs_Posts_InCategories PIC ON jPI.PostID = PIC.PostID
			INNER JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	End

	DROP TABLE #PageIndex

	If @IncludePageIndex = 1
	BEGIN
		/* Create a temp table to store the select results */
		CREATE TABLE #PageIndex2
		(
			IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
			PostID int NOT NULL
		)

		/* this is the number of records to page from */
		SET ROWCOUNT 0

		INSERT INTO #PageIndex2 (PostID)
		exec sp_executesql @sqlPopulate, N'@localRowsToReturn int', @localRowsToReturn = 0 /* means to return all rows */

		SELECT IndexID, PostID from #PageIndex2 ORDER BY IndexID

		DROP TABLE #PageIndex2
	END
end
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_shared_Threads_GetThreadSet] to public
go
/***********************************************
* Sproc: cs_SiteSettings_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SiteSettings_Get'

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SiteSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SiteSettings_Get]
GO


CREATE  PROCEDURE [dbo].cs_SiteSettings_Get
(
	@SiteUrl nvarchar(512) = null,
	@SettingsID int = 0,
	@ReturnAll bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

If @ReturnAll = 0
Begin
	IF @SiteUrl is null
	Begin
		Select
			ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl
			FROM
				cs_SiteSettings ss
			LEFT OUTER JOIN
				cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
			LEFT OUTER JOIN
				cs_Sites s ON s.SiteID = sm.SiteID
			Where
				ss.SettingsID = @SettingsID
	End
	else
	begin
		select
			top 1 ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl
			FROM
				cs_SiteSettings ss
			LEFT OUTER JOIN
				cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
			LEFT OUTER JOIN
				cs_Sites s ON s.SiteID = sm.SiteID
			ORDER BY ss.SettingsID asc
	end
End
Else
Begin
	IF @SiteUrl = '*'
		Select
			ss.SettingsXML, ss.Disabled, ss.Version,
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl
		FROM
			cs_SiteSettings ss
		JOIN
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN
			cs_Sites s ON s.SiteID = sm.SiteID

	ELSE IF NOT EXISTS (SELECT * FROM cs_Sites WHERE SiteUrl = @SiteUrl OR SiteUrl = @SiteUrl + '/')
		RETURN
	ELSE
		Select
			ss.SettingsXML, ss.Disabled, ss.Version,
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl
		FROM
			cs_SiteSettings ss
		JOIN
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			(s.SiteUrl = @SiteUrl OR s.SiteUrl = @SiteUrl + '/')
End

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].cs_SiteSettings_Get to public
go
/***********************************************
* Sproc: cs_SiteSettings_Save
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SiteSettings_Save'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SiteSettings_Save]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SiteSettings_Save]
GO
--Select * FROM cs_SiteSettings

CREATE procedure [dbo].cs_SiteSettings_Save
(
	@Disabled		smallint,
	@SettingsXML	 	ntext = null,
	@ApplicationName	nvarchar(256),
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		UPDATE
			cs_SiteSettings
		SET
			Disabled = @Disabled,
			SettingsXML = @SettingsXML,
			ApplicationName = @ApplicationName
		WHERE
			SettingsID  = @SettingsID
END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_SiteSettings_Save] to public
go
/***********************************************
* Sproc: cs_Site_GetSiteUrls
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Site_GetSiteUrls'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Site_GetSiteUrls]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Site_GetSiteUrls]
GO

CREATE    procedure [dbo].cs_Site_GetSiteUrls
AS

select
 lower(SS.ApplicationName) as ApplicationName, S.SiteUrl
from cs_SiteSettings SS
left join cs_SiteMappings SM on (SM.SettingsID = SS.SettingsID)
left join cs_Sites S on (S.SiteID = SM.SiteID)

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Site_GetSiteUrls to public
go
/***********************************************
* Sproc: cs_Site_Statistics
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Site_Statistics'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Site_Statistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Site_Statistics]
GO




CREATE PROCEDURE [dbo].cs_Site_Statistics
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')


-- SELECT current statistics
SELECT 
	S.*,
	CurrentAnonymousUsers = (SELECT Count(*) FROM cs_AnonymousUsers where SettingsID = @SettingsID),
	MostReadSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostReadPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostViewsSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostViewsPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostActivePostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE UserID = S.MostActiveUserID and SettingsID = @SettingsID),''),
	NewestUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE UserID = S.NewestUserID and SettingsID = @SettingsID),'')
FROM
	cs_statistics_Site S
WHERE
	DateCreated = @LastUpdate  and SettingsID = @SettingsID

-- SELECT TOP 100 Users
SELECT TOP 100
	S.TotalPosts,
	U.*
FROM
	cs_statistics_User S,
	cs_vw_Users_FullUser U
WHERE
	S.UserID = U.UserID AND
	U.EnableDisplayInMemberList = 1 AND
	U.UserID > 0 and U.SettingsID = @SettingsID and S.SettingsID = @SettingsID
ORDER BY
	S.TotalPosts DESC

-- SELECT Moderator actions
SELECT
	Description,
	TotalActions
FROM
	cs_ModerationAction
WHERE
	TotalActions > 0
ORDER BY
	TotalActions DESC 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Site_Statistics] to public
go

/***********************************************
* Sproc: cs_Smiley_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Smiley_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Smiley_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Smiley_CreateUpdateDelete]
GO



CREATE proc [dbo].cs_Smiley_CreateUpdateDelete
(
	  @SmileyID		int out
	, @DeleteSmiley	bit = 0
	, @SmileyCode	nvarchar(20)
	, @SmileyUrl	nvarchar(512)
	, @SmileyText	nvarchar(512)
	, @BracketSafe	bit = 0
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED

IF( @DeleteSmiley > 0 ) 
BEGIN

	DELETE cs_Smilies
	WHERE
		SmileyID = @SmileyID and SettingsID = @SettingsID

	RETURN
END

IF( @SmileyID > 0 ) 
BEGIN
	UPDATE cs_Smilies SET
		  SmileyCode	= @SmileyCode
		, SmileyUrl		= @SmileyUrl
		, SmileyText	= @SmileyText
		, BracketSafe	= @BracketSafe
	WHERE
		SmileyID	= @SmileyID and SettingsID = @SettingsID
END
ELSE
BEGIN

	INSERT INTO cs_Smilies (
		SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID
	) VALUES (
		@SmileyCode, @SmileyUrl, @SmileyText, @BracketSafe, @SettingsID
	)

	SET @SmileyID = SCOPE_IDENTITY()
END
RETURN









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Smiley_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Smilies_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Smilies_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Smilies_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Smilies_Get]
GO







create proc [dbo].cs_Smilies_Get
(
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Smilies
	WHERE
		SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Smilies_Get] to public
go
/***********************************************
* Sproc: cs_SpamPostArchive
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SpamPostArchive'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SpamPostArchive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SpamPostArchive]
GO

CREATE PROCEDURE [dbo].[cs_SpamPostArchive]
(
	@SourceProcedure nvarchar(128)
	/* from cs_Post_CreateUpdate */
	, @SectionID int
	, @ParentID int
	, @AllowDuplicatePosts bit
	, @DuplicateIntervalInMinutes int
	, @Subject nvarchar(256)
	, @UserID int
	, @PostAuthor nvarchar(64)
	, @Body ntext
	, @FormattedBody ntext
	, @EmoticonID int
	, @IsLocked bit
	, @IsSticky bit
	, @IsApproved bit
	, @StickyDate datetime
	, @PostType int
	, @PostMedia int
	, @PostDate datetime
	, @UserHostAddress nvarchar(32)
	, @PropertyNames ntext
	, @PropertyValues ntext
	, @SettingsID int
	, @IsTracked bit
	, @PostID int
	, @ThreadID int
	, @PostConfiguration int
	, @UpdateSectionStatistics bit
	, @UserTime datetime
	, @ApplicationPostType int
	, @PostName nvarchar(256)
	, @ThreadStatus int
	, @Points int
	, @PostDisplayName nvarchar(64)
	, @AutoApprove bit

	/* from cs_weblog_Post_Create */
	, @TitleUrl nvarchar(256)
	, @PostConfig int
	, @BlogPostType tinyint
	, @Categories nvarchar(4000)
	, @SpamScore int
	, @PostStatus int
)
AS
begin
	SET NOCOUNT ON

	if @SourceProcedure IS NULL
	begin
		raiserror ( 'The parameter @SourceProcedure should not be NULL.', 16, 1 )
		return 1
	end
	
	if OBJECT_ID( @SourceProcedure ) IS NULL
	begin
		raiserror ( 'The parameter @SourceProcedure contains [%s] which is not currently a valid object in the database.', 16, 1, @SourceProcedure )
		return 2
	end
	
	select
		@PostDate = COALESCE( @PostDate, getdate() )
		, @UserTime = COALESCE( @UserTime, @PostDate )

	INSERT INTO [dbo].[cs_SpamPosts] (
		[SourceProcedure]
		, [SectionID], [ParentID], [AllowDuplicatePosts], [DuplicateIntervalInMinutes], [Subject], [UserID], [PostAuthor]
		, [Body], [FormattedBody], [EmoticonID], [IsLocked], [IsSticky], [IsApproved], [StickyDate]
		, [PostType], [PostMedia], [PostDate], [UserHostAddress], [PropertyNames], [PropertyValues], [SettingsID]
		, [IsTracked], [ThreadID], [PostConfiguration], [UpdateSectionStatistics], [UserTime], [ApplicationPostType]
		, [PostName], [ThreadStatus], [Points], [PostDisplayName], [AutoApprove], [TitleUrl], [PostConfig]
		, [BlogPostType], [Categories], [SpamScore], [PostStatus]
	) VALUES (
		@SourceProcedure
		, @SectionID, @ParentID, @AllowDuplicatePosts, @DuplicateIntervalInMinutes, @Subject, @UserID, @PostAuthor
		, @Body, @FormattedBody, @EmoticonID, @IsLocked, @IsSticky, @IsApproved, @StickyDate
		, @PostType, @PostMedia, @PostDate, @UserHostAddress, @PropertyNames, @PropertyValues, @SettingsID
		, @IsTracked, @ThreadID, @PostConfiguration, @UpdateSectionStatistics, @UserTime, @ApplicationPostType
		, @PostName, @ThreadStatus, @Points, @PostDisplayName, @AutoApprove, @TitleUrl, @PostConfig
		, @BlogPostType, @Categories, @SpamScore, @PostStatus
	)

end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_SpamPostArchive] TO [public]
GO


/***********************************************
* Sproc: cs_SpamPostDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SpamPostDelete'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SpamPostDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SpamPostDelete]
GO

CREATE PROCEDURE [dbo].[cs_SpamPostDelete]
(
	@SpamPostID bigint = null
	, @SettingsID int = null
	, @SectionID int = null
	, @ThreadID int = null
	, @RowCount int = null output
)
AS
begin
	SET NOCOUNT ON
	
    --	We will allow movement at a SpamPostID level, a SettingsID, SectionID, ThreadID level, and SettingsID, SectionID
    --	The default is SpamPostID - if that is set, it overrides any thing else

	if @SpamPostID IS NOT NULL
	begin
	
		/* Remove a single spam post */
		delete p from [dbo].[cs_SpamPosts] p
		where p.[SpamPostID] = @SpamPostID
		
		set @RowCount = @@ROWCOUNT
	
	end
	else if @SettingsID IS NOT NULL AND @SectionID IS NOT NULL
	begin
	
		if @ThreadID IS NOT NULL
		begin
		
			/* Remove spam posts by Thread */
			delete p from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID AND p.[ThreadID] = @ThreadID
			
			set @RowCount = @@ROWCOUNT
		
		end
		else
		begin
		
			/* Remove spam posts by Section */
			delete p from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID
			
			set @RowCount = @@ROWCOUNT
		
		end
	end
	
	return 0
end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_SpamPostDelete] TO [public]
GO


/***********************************************
* Sproc: cs_SpamPostRevive
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SpamPostRevive'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SpamPostRevive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SpamPostRevive]
GO

CREATE PROCEDURE [dbo].[cs_SpamPostRevive]
(
	@SettingsID int = null
	, @SectionID int = null
	, @ThreadID int = null
	, @RowCount int = null output
)
AS
begin

	SET NOCOUNT ON
	
	declare @ID bigint, @SpamPostID bigint, @TotalRowCount bigint

	declare @SpamPosts table (
		ID bigint identity(1, 1) not null primary key
		, SpamPostID bigint not null
		)

	select @ID = 1, @TotalRowCount = 0

	--We will allow movement at a SpamPostID level and a SettingsID, SectionID, ThreadID level.
	--The default is SpamPostID - if that is set, it overrides any thing else

	if @SettingsID IS NOT NULL AND @SectionID IS NOT NULL
	begin
	
		if @ThreadID IS NOT NULL
		begin
		
			/* Revive spam posts by Thread */
			insert into @SpamPosts ( [SpamPostID] )
			select p.[SpamPostID] from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID AND p.[ThreadID] = @ThreadID
		
		end
		else
		begin
		
			/* Revive spam posts by Section */
			insert into @SpamPosts ( [SpamPostID] )
			select p.[SpamPostID] from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID
		
		end
		
		while 1=1
		begin
			select @SpamPostID = (select p.[SpamPostID] from @SpamPosts p where p.[ID] = @ID)
			
			if @SpamPostID IS NULL break
			
			execute [dbo].[cs_SpamPostReviveOne] @SpamPostID = @SpamPostID, @RowCount = @RowCount output
			
			select
				@TotalRowCount = @TotalRowCount + @RowCount
				, @ID = @ID + 1
		end
	end
	
	set @RowCount = @TotalRowCount
	
	return 0

end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_SpamPostRevive] TO [public]
GO

/***********************************************
* Sproc: cs_SpamPostReviveOne
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SpamPostReviveOne'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SpamPostReviveOne]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SpamPostReviveOne]
GO

CREATE PROCEDURE [dbo].[cs_SpamPostReviveOne]
(
	@SpamPostID bigint = null
	, @RowCount int = null output
)
AS
begin
	SET NOCOUNT ON
	
	declare
		@return_value int
		, @SourceProcedure nvarchar(128)
		/* from cs_Post_CreateUpdate */
		, @SectionID int
		, @ParentID int
		, @AllowDuplicatePosts bit
		, @DuplicateIntervalInMinutes int
		, @Subject nvarchar(256)
		, @UserID int
		, @PostAuthor nvarchar(64)
		, @Body nvarchar(4000) --ntext
		, @FormattedBody nvarchar(4000) --ntext
		, @EmoticonID int
		, @IsLocked bit
		, @IsSticky bit
		, @IsApproved bit
		, @StickyDate datetime
		, @PostType int
		, @PostMedia int
		, @PostDate datetime
		, @UserHostAddress nvarchar(32)
		, @PropertyNames nvarchar(4000) --ntext
		, @PropertyValues nvarchar(4000) --ntext
		, @SettingsID int
		, @IsTracked bit
		, @PostID int
		, @ThreadID int
		, @PostConfiguration int
		, @UpdateSectionStatistics bit
		, @UserTime datetime
		, @ApplicationPostType int
		, @PostName nvarchar(256)
		, @ThreadStatus int
		, @Points int
		, @PostDisplayName nvarchar(64)
		, @AutoApprove bit
	
		/* from cs_weblog_Post_Create */
		, @TitleUrl nvarchar(256)
		, @PostConfig int
		, @BlogPostType tinyint
		, @Categories nvarchar(4000)
		, @SpamScore int
		, @PostStatus int
	
	if @SpamPostID IS NOT NULL
	begin

		select
			@SourceProcedure = p.[SourceProcedure]
			, @SectionID = p.[SectionID]
			, @ParentID = p.[ParentID]
			, @AllowDuplicatePosts = p.[AllowDuplicatePosts]
			, @DuplicateIntervalInMinutes = p.[DuplicateIntervalInMinutes]
			, @Subject = p.[Subject]
			, @UserID = p.[UserID]
			, @PostAuthor = p.[PostAuthor]
			, @Body = p.[Body]
			, @FormattedBody = p.[FormattedBody]
			, @EmoticonID = p.[EmoticonID]
			, @IsLocked = p.[IsLocked]
			, @IsSticky = p.[IsSticky]
			, @IsApproved = p.[IsApproved]
			, @StickyDate = p.[StickyDate]
			, @PostType = p.[PostType]
			, @PostMedia = p.[PostMedia]
			, @PostDate = p.[PostDate]
			, @UserHostAddress = p.[UserHostAddress]
			, @PropertyNames = p.[PropertyNames]
			, @PropertyValues = p.[PropertyValues]
			, @SettingsID = p.[SettingsID]
			, @IsTracked = p.[IsTracked]
			, @ThreadID = p.[ThreadID]
			, @PostConfiguration = p.[PostConfiguration]
			, @UpdateSectionStatistics = p.[UpdateSectionStatistics]
			, @UserTime = p.[UserTime]
			, @ApplicationPostType = p.[ApplicationPostType]
			, @PostName = p.[PostName]
			, @ThreadStatus = p.[ThreadStatus]
			, @Points = p.[Points]
			, @PostDisplayName = p.[PostDisplayName]
			, @AutoApprove = p.[AutoApprove]
			, @TitleUrl = p.[TitleUrl]
			, @PostConfig = p.[PostConfig]
			, @BlogPostType = p.[BlogPostType]
			, @Categories = p.[Categories]
			, @SpamScore = p.[SpamScore]
			, @PostStatus = p.[PostStatus]
			, @PostID = NULL /* resetting the PostID */
		from
			[dbo].[cs_SpamPosts] p
		where
			p.[SpamPostID] = @SpamPostID

		if @SourceProcedure = N'cs_Post_CreateUpdate'
		begin

			select
				@IsApproved = 1 /* @IsApproved will be set to 1.  If someone is moving a post, it should be approved.  Perhaps there should be a flag to set this,  */

			execute @return_value = [dbo].[cs_Post_CreateUpdate]
				@SectionID = @SectionID
				, @ParentID = @ParentID
				, @AllowDuplicatePosts = @AllowDuplicatePosts
				, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
				, @Subject = @Subject
				, @UserID = @UserID
				, @PostAuthor = @PostAuthor
				, @Body = @Body
				, @FormattedBody = @FormattedBody
				, @EmoticonID = @EmoticonID
				, @IsLocked = @IsLocked
				, @IsSticky = @IsSticky
				, @IsApproved = @IsApproved
				, @StickyDate = @StickyDate
				, @PostType = @PostType
				, @PostMedia = @PostMedia
				, @PostDate = @PostDate
				, @UserHostAddress = @UserHostAddress
				, @PropertyNames = @PropertyNames
				, @PropertyValues = @PropertyValues
				, @SettingsID = @SettingsID
				, @IsTracked = @IsTracked
					, @PostID = @PostID output
				, @ThreadID = @ThreadID
				, @PostConfiguration = @PostConfiguration
				, @UpdateSectionStatistics = @UpdateSectionStatistics
				, @UserTime = @UserTime
				, @ApplicationPostType = @ApplicationPostType
				, @PostName = @PostName
				, @ThreadStatus = @ThreadStatus
				, @Points = @Points
				, @PostDisplayName = @PostDisplayName
				, @AutoApprove = @AutoApprove

		end
		else if @SourceProcedure = N'cs_weblog_Post_Create'
		begin

			select
				@IsApproved = 1 /* @IsApproved will be set to 1.  If someone is moving a post, it should be approved.  Perhaps there should be a flag to set this,  */
				, @PostStatus = @PostStatus & 0x7ffffffd /* ensure that PostStatus=2 (spam) is not set since this is how a post gets here */

			execute @return_value = [dbo].[cs_weblog_Post_Create]
				@SectionID = @SectionID
				, @ParentID = @ParentID
				, @AllowDuplicatePosts = @AllowDuplicatePosts
				, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
				, @Subject = @Subject
				, @UserID = @UserID
				, @PostAuthor = @PostAuthor
				, @Body = @Body
				, @FormattedBody = @FormattedBody
				, @EmoticonID = @EmoticonID
				, @IsLocked = @IsLocked
				, @IsSticky = @IsSticky
				, @IsApproved = @IsApproved
				, @IsTracked = @IsTracked
				, @StickyDate = @StickyDate
				, @PostType = @PostType
				, @PostMedia = @PostMedia
				, @PostDate = @PostDate
				, @UserTime = @UserTime
				, @UserHostAddress = @UserHostAddress
				, @PostName = @PostName
				, @TitleUrl = @TitleUrl
				, @PostConfig = @PostConfig
				, @BlogPostType = @BlogPostType
				, @Categories = @Categories
				, @PropertyNames = @PropertyNames
				, @PropertyValues = @PropertyValues
				, @SettingsID = @SettingsID
				, @SpamScore = @SpamScore
				, @PostStatus = @PostStatus
					, @PostID = @PostID output
			
		end
	end
	
	if @return_value = 0
	begin
	
		delete p from [dbo].[cs_SpamPosts] p
		where
			p.[SpamPostID] = @SpamPostID
	
	end
	
	return @return_value
end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_SpamPostReviveOne] TO [public]
GO


/***********************************************
* Sproc: cs_SpamPosts_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SpamPosts_Get'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SpamPosts_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SpamPosts_Get]
GO

CREATE PROCEDURE [dbo].[cs_SpamPosts_Get]
(
	@SectionID int,
	@SpamStatus int,
	@PageIndex int,
	@PageSize int,
	@TotalRecords int out
)
AS
begin

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @RowsToReturn int
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- Create a temp table to store the select results
DECLARE @PageTable TABLE
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	SpamPostID bigint not null
)

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	
-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

INSERT INTO @PageTable(SpamPostID)
SELECT P.SpamPostID 
FROM cs_SpamPosts P (nolock)
WHERE (P.SectionID = @SectionID) AND (@SpamStatus = -1 OR P.PostStatus & @SpamStatus = @SpamStatus)
ORDER BY PostDate DESC

Set @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

SELECT 
	Convert(int, P.[SpamPostID]) as PostID, [SectionID], [ParentID], [AllowDuplicatePosts], [DuplicateIntervalInMinutes], [Subject], [UserID], [PostAuthor]
	, [Body], [FormattedBody], [EmoticonID], [IsLocked], [IsSticky], [IsApproved], [StickyDate]
	, [PostType], [PostMedia], [PostDate], [UserHostAddress] as IPAddress, [PropertyNames] as PostPropertyNames, [PropertyValues] as PostPropertyValues, [SettingsID]
	, [IsTracked], [ThreadID], [PostConfiguration], [UpdateSectionStatistics], [UserTime], [ApplicationPostType]
	, [PostName], [ThreadStatus], [Points] as PostPoints, [PostDisplayName], [AutoApprove], [TitleUrl], [PostConfig]
	, [BlogPostType], [Categories], [SpamScore], [PostStatus],
	[PostDate] as ThreadDate,
	Replies = 0, PostLevel = 1,
	TotalViews = 0, AggViews = 0,
	RatingSum = 0, TotalRatings = 0

FROM 
	cs_SpamPosts P (nolock),
	@PageTable pt
WHERE 
	P.SpamPostID = pt.SpamPostID AND
	pt.IndexID > @PageLowerBound AND
	pt.IndexID < @PageUpperBound
ORDER BY
	IndexID


end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE ON [dbo].[cs_SpamPosts_Get] TO [public]
GO


/***********************************************
* Sproc: cs_split_varchar
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_split_varchar'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_split_varchar]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_split_varchar]
GO

CREATE PROCEDURE [dbo].[cs_split_varchar]
    @str varchar(8000)
AS  
	CREATE TABLE #SplitItems
	(
		[Item] nvarchar(500) collate database_default NOT NULL
	)

    declare @frommarker tinyint, @tomarker tinyint, @strlen tinyint, @item varchar(500)

    select @frommarker=1, @tomarker=1
    
    while (@tomarker > 0)
    begin 
        set @tomarker = CHARINDEX (',', @str, @frommarker)
    
        if @tomarker > 0 
            set @strlen = @tomarker - @frommarker
        else
            set @strlen = LEN(@str) - @frommarker + 1

        set @item = ltrim(rtrim(SUBSTRING (@str, @frommarker, @strlen)))
        
		if not exists (select null from #SplitItems where Item = @item)
			insert into #SplitItems values(@item)
        
        set @frommarker = @tomarker + 1
    end

	select Item from #SplitItems



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_split_varchar] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Styles_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Styles_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Styles_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Styles_Get]
GO








create proc [dbo].cs_Styles_Get
(
	@StyleID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Styles
	WHERE
		StyleID = @StyleID OR
		(
			@StyleID = 0 AND
			1=1
		) and SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Styles_Get] to public
go
/***********************************************
* Sproc: cs_Style_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Style_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Style_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Style_CreateUpdateDelete]
GO







create proc [dbo].cs_Style_CreateUpdateDelete
(
	  @StyleID				int out
	, @DeleteStyle			bit = 0
	, @StyleName			varchar(30)
	, @StyleSheetTemplate	varchar(30)
	, @BodyBackgroundColor	int
	, @BodyTextColor		int
	, @LinkVisited			int
	, @LinkHover			int
	, @LinkActive			int
	, @RowColorPrimary		int
	, @RowColorSecondary	int
	, @RowColorTertiary		int
	, @RowClassPrimary		varchar(30)
	, @RowClassSecondary	varchar(30)
	, @RowClassTertiary		varchar(30)
	, @HeaderColorPrimary	int
	, @HeaderColorSecondary	int
	, @HeaderColorTertiary	int
	, @HeaderStylePrimary	varchar(30)
	, @HeaderStyleSecondary	varchar(30)
	, @HeaderStyleTertiary	varchar(30)
	, @CellColorPrimary		int
	, @CellColorSecondary	int
	, @CellColorTertiary	int
	, @CellClassPrimary		varchar(30)
	, @CellClassSecondary	varchar(30)
	, @CellClassTertiary	varchar(30)
	, @FontFacePrimary		varchar(30)	
	, @FontFaceSecondary	varchar(30)
	, @FontFaceTertiary		varchar(30)
	, @FontSizePrimary		smallint
	, @FontSizeSecondary	smallint
	, @FontSizeTertiary		smallint
	, @FontColorPrimary		int
	, @FontColorSecondary	int
	, @FontColorTertiary	int
	, @SpanClassPrimary		varchar(30)
	, @SpanClassSecondary	varchar(30)
	, @SpanClassTertiary	varchar(30)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF( @DeleteStyle = 1 ) 
BEGIN
	
	DELETE cs_Styles
	WHERE
		StyleID	= @StyleID and SettingsID = @SettingsID

	RETURN
END

IF( @StyleID > 0 )
BEGIN

	UPDATE cs_Styles SET
		  StyleName 			= @StyleName
		, StyleSheetTemplate 	= @StyleSheetTemplate
		, BodyBackgroundColor 	= @BodyBackgroundColor
		, BodyTextColor 		= @BodyTextColor
		, LinkVisited 			= @LinkVisited
		, LinkHover 			= @LinkHover
		, LinkActive 			= @LinkActive
		, RowColorPrimary 		= @RowColorPrimary
		, RowColorSecondary 	= @RowColorSecondary
		, RowColorTertiary 		= @RowColorTertiary
		, RowClassPrimary 		= @RowClassPrimary
		, RowClassSecondary 	= @RowClassSecondary
		, RowClassTertiary 		= @RowClassTertiary
		, HeaderColorPrimary 	= @HeaderColorPrimary
		, HeaderColorSecondary	= @HeaderColorSecondary
		, HeaderColorTertiary 	= @HeaderColorTertiary
		, HeaderStylePrimary 	= @HeaderStylePrimary
		, HeaderStyleSecondary 	= @HeaderStyleSecondary
		, HeaderStyleTertiary 	= @HeaderStyleTertiary
		, CellColorPrimary 		= @CellColorPrimary
		, CellColorSecondary	= @CellColorSecondary
		, CellColorTertiary 	= @CellColorTertiary
		, CellClassPrimary 		= @CellClassPrimary
		, CellClassSecondary 	= @CellClassSecondary
		, CellClassTertiary 	= @CellClassTertiary
		, FontFacePrimary 		= @FontFacePrimary
		, FontFaceSecondary 	= @FontFaceSecondary
		, FontFaceTertiary 		= @FontFaceTertiary
		, FontSizePrimary 		= @FontSizePrimary
		, FontSizeSecondary 	= @FontSizeSecondary
		, FontSizeTertiary 		= @FontSizeTertiary
		, FontColorPrimary 		= @FontColorPrimary
		, FontColorSecondary 	= @FontColorSecondary
		, FontColorTertiary 	= @FontColorTertiary
		, SpanClassPrimary 		= @SpanClassPrimary
		, SpanClassSecondary 	= @SpanClassSecondary
		, SpanClassTertiary 	= @SpanClassTertiary
	WHERE
		StyleID = @StyleID and SettingsID = @SettingsID


END
ELSE
BEGIN

	INSERT INTO cs_Styles (
		  StyleName				, StyleSheetTemplate		, BodyBackgroundColor		, BodyTextColor
		, LinkVisited			, LinkHover					, LinkActive				, RowColorPrimary
		, RowColorSecondary		, RowColorTertiary			, RowClassPrimary			, RowClassSecondary
		, RowClassTertiary		, HeaderColorPrimary		, HeaderColorSecondary		, HeaderColorTertiary
		, HeaderStylePrimary	, HeaderStyleSecondary		, HeaderStyleTertiary		, CellColorPrimary
		, CellColorSecondary	, CellColorTertiary			, CellClassPrimary			, CellClassSecondary
		, CellClassTertiary		, FontFacePrimary			, FontFaceSecondary			, FontFaceTertiary
		, FontSizePrimary		, FontSizeSecondary			, FontSizeTertiary			, FontColorPrimary
		, FontColorSecondary	, FontColorTertiary			, SpanClassPrimary			, SpanClassSecondary
		, SpanClassTertiary, SettingsID
	) VALUES (
		  @StyleName			, @StyleSheetTemplate		, @BodyBackgroundColor		, @BodyTextColor		, @LinkVisited			, @LinkHover				, @LinkActive				, @RowColorPrimary
		, @RowColorSecondary	, @RowColorTertiary			, @RowClassPrimary			, @RowClassSecondary
		, @RowClassTertiary		, @HeaderColorPrimary		, @HeaderColorSecondary		, @HeaderColorTertiary
		, @HeaderStylePrimary	, @HeaderStyleSecondary		, @HeaderStyleTertiary		, @CellColorPrimary
		, @CellColorSecondary	, @CellColorTertiary		, @CellClassPrimary			, @CellClassSecondary
		, @CellClassTertiary	, @FontFacePrimary			, @FontFaceSecondary		, @FontFaceTertiary
		, @FontSizePrimary		, @FontSizeSecondary		, @FontSizeTertiary			, @FontColorPrimary
		, @FontColorSecondary	, @FontColorTertiary		, @SpanClassPrimary			, @SpanClassSecondary
		, @SpanClassTertiary, @SettingsID
	)

	SELECT @StyleID = SCOPE_IDENTITY()
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Style_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_SubscribedSection_Confirm
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SubscribedSection_Confirm'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SubscribedSection_Confirm]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SubscribedSection_Confirm]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_SubscribedSection_Confirm]
(
	@SectionID int OUTPUT,
	@SubscriptionId uniqueidentifier
)
AS
	UPDATE [cs_SectionSubscriptions]
	SET IsConfirmed = 1, DateUnsubscribed = NULL
	WHERE	SubscriptionID = @SubscriptionId AND IsConfirmed = 0
	
	SELECT @SectionID = SectionID FROM [cs_SectionSubscriptions]
	WHERE SubscriptionID = @SubscriptionId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_SubscribedSection_Confirm] to public
go

/***********************************************
* Sproc: cs_SubscribedSection_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SubscribedSection_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SubscribedSection_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SubscribedSection_Get]
GO

CREATE procedure dbo.cs_SubscribedSection_Get
(
	@SectionID int,
	@Email nvarchar(256),
	@SettingsID int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT SubscriptionID, DateSubscribed, 
		SubscriptionFrequency as Frequency,
		IsConfirmed, DateUnsubscribed
	FROM cs_SectionSubscriptions
	WHERE
		SectionID = @SectionID AND Email = @Email AND SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_SubscribedSection_Get] to public

/***********************************************
* Sproc: cs_SubscribeToSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_SubscribeToSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SubscribeToSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SubscribeToSection]
GO

CREATE procedure dbo.cs_SubscribeToSection
(
	@UserID int,
	@SectionID int,
	@SettingsID int,
	@Email nvarchar(256),
	@SubscriptionType int,
	@SubscriptionID uniqueidentifier OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @counter int

	-- check to see if the user is currently subscribed to the section
	IF NOT EXISTS (SELECT SubscriptionID FROM cs_SectionSubscriptions
					WHERE SectionID = @SectionID AND
							SettingsID = @SettingsID AND Email = @Email)
		BEGIN
			SET @SubscriptionID = NEWID()
			-- this user isn't subscribed to the section, so add them
			INSERT INTO cs_SectionSubscriptions (SubscriptionID, SectionID, Email, SubscriptionType, UserID, SettingsID, DateSubscribed, DateUnsubscribed, SubscriptionFrequency)
			VALUES(@SubscriptionID, @SectionID, @Email, @SubscriptionType, @UserID, @SettingsID, GetDate(), NULL, 1)		
		END
	ELSE IF EXISTS (SELECT SubscriptionID FROM cs_SectionSubscriptions
						WHERE	SectionID = @SectionID AND
							SettingsID = @SettingsID AND Email = @Email)
		BEGIN
			-- the subscription exists but is unsubscribed, so subscribe it
			SELECT @counter = SubscriptionFrequency, @SubscriptionID = SubscriptionID 
				FROM cs_SectionSubscriptions 
				WHERE	SectionID = @SectionID AND
					SettingsID = @SettingsID AND Email = @Email AND
					DateUnsubscribed IS NOT NULL
			SET @counter = @counter + 1
		
			UPDATE cs_SectionSubscriptions
			SET DateUnsubscribed = NULL,
				DateSubscribed = GetDate(),
				SubscriptionFrequency = @counter
			WHERE	SectionID = @SectionID AND
					SettingsID = @SettingsID AND Email = @Email AND
					DateUnsubscribed IS NOT NULL
		END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_SubscribeToSection] to public

/***********************************************
* Sproc: cs_System_AddNewUrl.sql
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_System_AddNewUrl.sql'



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_System_AddNewUrl]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_System_AddNewUrl]
GO


------------------------------------------------------
--Adds another Url to an existing SiteSettings Record

--Author: Scott Watermasysk
--Date: 10/21/2004
------------------------------------------------------

CREATE Proc [dbo].cs_System_AddNewUrl
(
	@ExistingUrl nvarchar(512),
	@NewUrl nvarchar(512)
)

as

if exists(Select SiteID FROM cs_Sites where SiteUrl = @NewUrl)
Return -1 -->> The site @NewUrl already exists

Declare @SiteID int
Declare @SettingsID int 
Declare @NewSiteID int

Select @SiteID = SiteID FROM cs_Sites where SiteUrl = @ExistingUrl

If @SiteID is null
Return -2 -->> The site at @ExistingUrl does not Exist

Select @SettingsID = SettingsID FROM cs_SiteMappings where SiteID = @SiteID
If @SettingsID is null
Return -3 -->> This Application is not yet mapped

Insert cs_Sites Values (@NewUrl)
Select @NewSiteID = SCOPE_IDENTITY()

if @NewSiteID is null
Return -4 -->> Insert of new site failed

Insert cs_SiteMappings Values (@SettingsID, @NewSiteID)
Return 1

GO

grant execute on [dbo].[cs_System_AddNewUrl] to public
go
/***********************************************
* Sproc: cs_system_CalculatePagingInformation
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_CalculatePagingInformation'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_system_CalculatePagingInformation]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_system_CalculatePagingInformation]
GO

CREATE PROCEDURE [dbo].[cs_system_CalculatePagingInformation]
(
	@pageIndex int
	, @pageSize int
	, @rowsToReturn int = null output
	, @pageLowerBound int = null output
	, @pageUpperBound int = null output
)
AS
BEGIN

	/* This will need some work - only going to handle the basic scenarios */

	declare @minValue int, @maxValue int, @maxPageIndex int
	set @minValue = cast(0x0 as int)
	set @maxValue = cast(0x7fffffff as int)
	set @maxPageIndex = @maxValue / @pageSize

	if @pageSize = @maxValue
	begin
		select
			@rowsToReturn = @maxValue
			, @pageLowerBound = 0
			, @pageUpperBound = @maxValue
		return 0
	end

	select
		@rowsToReturn = @pageSize * (@pageIndex + 1)
		, @pageLowerBound = @pageSize * @pageIndex
		, @pageUpperBound = @pageLowerBound + @pageSize + 1

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_system_CalculatePagingInformation] TO PUBLIC
GO

/***********************************************
* Sproc: cs_system_CleanForumsRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_CleanForumsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CleanForumsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CleanForumsRead]
GO





create   procedure [dbo].cs_system_CleanForumsRead
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DELETE
		cs_SectionsRead
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_CleanForumsRead] to public
go
/***********************************************
* Sproc: cs_system_CreateAlias
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_CreateAlias'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CreateAlias]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CreateAlias]
GO

--exec cs_system_CreateAlias 'localhost/blahx','dev'


/***********************************************
* Sproc: cs_system_CreateCommunity
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_CreateCommunity'

--restore database CommunityServer from disk='c:\CommunityServer.bak'

go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CreateCommunity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CreateCommunity]
GO

--exec cs_system_CreateCommunity 'localhost/cs55sdf2','devs55ssss', 'admin@example.com', 'admin', 'sTrongPassw0rd', 0, 1

create Proc [dbo].cs_system_CreateCommunity
(
	@SiteUrl nvarchar(512),
	@ApplicationName nvarchar(512),
	@AdminEmail nvarchar(256),
	@AdminUserName nvarchar(256),
	@AdminPassword nvarchar(256),
	@PasswordFormat int = 0,	-- 0 = clear text, 1 = encrypted
	@CreateSamples bit = 1,
	@AdminSalt nvarchar(128) = N'DVZTktxeMzDtXR7eik7Cdw=='
)

as

--We must have both these values to continue
if(@SiteUrl is null OR @ApplicationName is  null)
BEGIN
	Select -1
	RETURN
END

--@SiteUrl must be unique
if exists(Select SiteID FROM cs_Sites where Lower(SiteUrl) = Lower(@SiteUrl))
BEGIN
	Select -2
	RETURN
END

Declare @SettingsID int
DECLARE @SiteID int 
Declare @ApplicationID uniqueidentifier
Declare @AdminUserID uniqueidentifier
DECLARE @Version nvarchar(64)
DECLARE @IsApplicationCreated bit
DECLARE @GroupID int
DECLARE @AdminRoleID uniqueidentifier

Set @IsApplicationCreated = 0

Set @Version = null

--Insert Site Record. This maps a Url to an ID
Insert cs_Sites (SiteUrl) Values(@SiteUrl)
Select @SiteID = SCOPE_IDENTITY()

--Get or Create the Application ID.
--An ApplicationName/ID can exist in more than one site, so it does not need to be unique
Set @ApplicationID = null
Select @ApplicationID = ApplicationId FROM aspnet_Applications where  LoweredApplicationName = Lower(@ApplicationName)

if(@ApplicationID is  null)
BEGIN
	exec aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId = @ApplicationID OUTPUT
	Set @IsApplicationCreated = 1
	Print 'Created New Application ' + @ApplicationName + '(' + Convert(varchar(36),@ApplicationID) + ')'

END
ELSE
BEGIN
	SET @IsApplicationCreated = 0
END

--Insert a record into the SiteSettings table
INSERT cs_SiteSettings (Disabled, Version, SettingsKey, ApplicationName)
VALUES (0,@Version,newID(),@ApplicationName)

--Get the SettingsID
Select @SettingsID = SCOPE_IDENTITY()
Print 'Created new SettingsID ' + Convert(varchar(5),@SettingsID)

--Site Mappings bind a specific Url to a SiteSetting (and ApplicationName/ID)
Insert cs_SiteMappings (SettingsID, SiteID) Values (@SettingsID, @SiteID)
Print 'SettingsID and ApplicationID Mapped'




print 'Creating moderation actions...'
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (1, 'ApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (2, 'EditPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (3, 'MovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (4, 'DeletePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (5, 'LockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (6, 'UnlockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (7, 'MergePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (8, 'SplitPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (9, 'EditUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (10, 'UnmoderateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (11, 'ModerateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (12, 'BanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (13, 'UnbanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (14, 'ResetPassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (15, 'ChangePassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (16, 'PostIsAnnouncement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (17, 'PostIsNotAnnoucement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (18, 'UnApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (19, 'DeleteSection', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (20, 'IgnoreUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (21, 'UnignoreUser', 0, @SettingsID)


----------------------------------------------------------
--WORD CENSORS (default list)
----------------------------------------------------------
print 'Creating a default list of censored words...'
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dyke', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'amcik', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'arse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'asshole', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'assramer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'atouche', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ayir', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b17ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b1tch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bastard', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bi7ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bitch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'boiolas', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bollock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'breast', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'c0ck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cabron', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cazzo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chink', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chraa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chuj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cipa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cunt', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'd4mn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dago', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'daygo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dego', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dildo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dirsa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dupa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dziwka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekrem', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'enculer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'faen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fag', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fancul', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fatass', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fcuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'feces', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ficken', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitte', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'flikker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fotze', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'futkretzn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fux0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'guiena', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h4x0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'helvete', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hoer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'honkey', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Huevon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hui', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'injun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kike', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ootzak', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'knulle', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kraut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuksuger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Kurac', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kurwa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kusi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kyrp', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbian', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mamhoon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'masturbat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merd', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merde', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mibun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'monkleigh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'motherfucker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mouliewop', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muie', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mulkku', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muschi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nazis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nepesaurio', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigga', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nutsack', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'orospu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'paska', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pendejo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'penisperse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'phuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'picka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pierdol', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pillu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimmel', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimpis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pizdapoontsee', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pr0n', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preteen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preud', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'prick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pula', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pule', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pusse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pussy', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qaHbeh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qweef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'rautenbergschaffer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheiss', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheisse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schlampe', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schmuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scrotum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmuta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmute', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shemale', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shipal', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Skribz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'skurwysyn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'slut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'smut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sphencter', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spic', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spierdalaj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'splooge', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'suka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'tits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'twatty', '***')

print 'Disallowed usernames...'
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dyke*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shit*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*amcik*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*arse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*asshole*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*assramer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*atouche*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ayir*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*b17ch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*b1tch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bastard*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bi7ch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bitch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*boiolas*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bollock*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*breast*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*c0ck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cabron*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cawk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cazzo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chink*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chraa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chuj*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cipa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*clit*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*clits*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cock*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cum*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cunt*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*d4mn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dago*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*daygo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dego*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dick*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dildo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dirsa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dupa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dziwka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ekrem*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ekto*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*enculer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*faen*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fag*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fancul*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fatass*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fcuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*feces*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ficken*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fitta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fitte*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*flikker*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fotze*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*futkretzn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fux0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*guiena*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*h0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*h4x0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*helvete*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*hoer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*honkey*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Huevon*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*hui*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*injun*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kawk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kike*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ootzak*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*knulle*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kraut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kuksuger*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Kurac*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kurwa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kusi*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kyrp*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*lesbian*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*lesbo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mamhoon*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*masturbat*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*merd*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*merde*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mibun*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*monkleigh*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*motherfucker*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mouliewop*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*muie*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mulkku*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*muschi*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nazis*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nepesaurio*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nigga*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nigger*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nutsack*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*orospu*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*paska*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pendejo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*penisperse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*phuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*picka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pierdol*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pillu*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pimmel*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pimpis*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pizdapoontsee*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pr0n*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*preteen*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*preud*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*prick*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pula*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pule*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pusse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pussy*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*puta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*puto*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*qaHbeh*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*queef*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*queer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*qweef*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*rautenbergschaffer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scheiss*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scheisse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*schlampe*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*schmuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scrotum*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sharmuta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sharmute*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shemale*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shipal*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shiz*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shiat*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Skribz*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*skurwysyn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*slut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*smut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sphencter*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*spic*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*spierdalaj*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*splooge*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*suka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*tits*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*twatty*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*satan*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*god*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*superuser*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*administrator*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*admin*')

print 'Creating the default smilies...'
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':)', 'emoticons/emotion-1.gif', 'Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':D', 'emoticons/emotion-2.gif', 'Big Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':O', 'emoticons/emotion-3.gif', 'Surprise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':P', 'emoticons/emotion-4.gif', 'Stick out tongue', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (';)', 'emoticons/emotion-5.gif', 'Wink', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':(', 'emoticons/emotion-6.gif', 'Sad', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':S', 'emoticons/emotion-7.gif', 'Tongue Tied', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':|', 'emoticons/emotion-8.gif', 'Indifferent', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':''(', 'emoticons/emotion-9.gif', 'Crying', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':$', 'emoticons/emotion-10.gif', 'Embarrassed', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('H', 'emoticons/emotion-11.gif', 'Cool', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':@', 'emoticons/emotion-12.gif', 'Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('A', 'emoticons/emotion-13.gif', 'Angel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('6', 'emoticons/emotion-14.gif', 'Devil', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-|', 'emoticons/emotion-15.gif', 'Geeked', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':#', 'emoticons/emotion-16.gif', 'Zip it!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':-*', 'emoticons/emotion-17.gif', 'Whisper', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':^)', 'emoticons/emotion-18.gif', 'Huh?', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('<:o)', 'emoticons/emotion-19.gif', 'Party!!!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('|-)', 'emoticons/emotion-20.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Y', 'emoticons/emotion-21.gif', 'Yes', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('B', 'emoticons/emotion-22.gif', 'Beer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('{', 'emoticons/emotion-24.gif', 'Left Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8', 'emoticons/emotion-29.gif', 'Music', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*', 'emoticons/emotion-30.gif', 'Star', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('O', 'emoticons/emotion-31.gif', 'Time', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('sn', 'emoticons/emotion-32.gif', 'Snail', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('pi', 'emoticons/emotion-33.gif', 'Pizza', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('au', 'emoticons/emotion-34.gif', 'Automobile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('um', 'emoticons/emotion-35.gif', 'Umbrella', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('co', 'emoticons/emotion-36.gif', 'Computer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('st', 'emoticons/emotion-37.gif', 'Storm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('mo', 'emoticons/emotion-38.gif', 'Moon', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8o|', 'emoticons/emotion-39.gif', 'Super Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^o)', 'emoticons/emotion-40.gif', 'Hmm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('+o(', 'emoticons/emotion-41.gif', 'Ick!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*-)', 'emoticons/emotion-42.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-)', 'emoticons/emotion-43.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('C', 'emoticons/emotion-44.gif', 'Coffee', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('N', 'emoticons/emotion-45.gif', 'No', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('D', 'emoticons/emotion-46.gif', 'Drinks', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Z', 'emoticons/emotion-47.gif', 'Person', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('}', 'emoticons/emotion-48.gif', 'Right Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^', 'emoticons/emotion-49.gif', 'Cake', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('U', 'emoticons/emotion-50.gif', 'Broken Heart', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('G', 'emoticons/emotion-51.gif', 'Gift', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('W', 'emoticons/emotion-52.gif', 'Wilted Flower', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('~', 'emoticons/emotion-53.gif', 'Movie', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('&', 'emoticons/emotion-54.gif', 'Dog', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('I', 'emoticons/emotion-55.gif', 'Idea', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('S', 'emoticons/emotion-56.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('E', 'emoticons/emotion-57.gif', 'Email', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ap', 'emoticons/emotion-58.gif', 'Travel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ip', 'emoticons/emotion-59.gif', 'Paradise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('li', 'emoticons/emotion-60.gif', 'Lightning', 0, @SettingsID)

Declare @DeletedSectionID int
Declare @ReportingSectionID int

INSERT INTO cs_Groups 
	( [Name], [SortOrder], SettingsID, ApplicationType)
VALUES 
	( 'Administrators', 99999, @SettingsID, 0 )

Select @GroupID = SCOPE_IDENTITY()
Print 'Created Admin ForumGroup'

--Reporting Forum of Reporting Forum Type
Print 'Created Reporting Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAnonymousPosting, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 60, 1, 0, @GroupID, 'Reporting Forums', 'Reporting_Forums-' + convert(nvarchar(10), @GroupID), 'When problems are reported they go in this forum.', GetDate(), '', 0, 7, 3, 0, 0, 0x0, 0, 0, 1, 0, 0, 0, '', 0, '1977-01-01', 0,  0
	)
Select @ReportingSectionID = SCOPE_IDENTITY()

Print 'Created Deleted Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAnonymousPosting, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 50, 1, 0, @GroupID, 'Deleted Posts', 'Deleted_Posts-' + convert(nvarchar(10), @GroupID), 'Deleted posts are archived in this forum.', GetDate(), '', 0, 7, 4, 0, 0, 0x0, 0, 0, 0, 0, 0, 0, '', 0, '1977-01-01', 0, 0
	)
Select @DeletedSectionID = SCOPE_IDENTITY()

declare @CategoryGroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @CategoryGroupID output, @ParentGroupID = 0, @Name = N'Sample Category', @Action = 0, @ApplicationType = 11, @SettingsID = @SettingsID
Print 'Created Default Group Category'

if(@IsApplicationCreated = 1)
Begin

	print 'Created default roles...'

	declare @EveryoneRoleID uniqueidentifier
	Set @EveryoneRoleID = newID()
	

	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (@EveryoneRoleID, @ApplicationID, N'Everyone', N'everyone', N'Do not add users to this role. This role exists only for permission mapping. All anonymous and registered users are automatically part of this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Registered Users', N'registered users', N'Users who create accounts are automatically added to this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Trusted Users', N'trusted users', N'Trusted users are given more permissions within the site.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Editor', N'editor', N'')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Moderator', N'moderator', N'Moderators are allowed to approve content.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ForumsAdministrator', N'forumsadministrator', N'Administration role for Forums.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'BlogAdministrator', N'blogadministrator', N'Administration role for Blogs')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'MediaGalleryAdministrator', N'mediagalleryadministrator', N'Administration role for Media Galleries')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'GroupAdministrator', N'groupadministrator', N'Administration role for Groups')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'MembershipAdministrator', N'membershipadministrator', N'Administration role for Member Management')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'SystemAdministrator', N'systemadministrator', N'Global Administration role.')	
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Owners', N'owners', N'Owners are the role used for bloggers and photogallery owners')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'WikiAdministrator', N'wikiadministrator', N'Administration role for Wikis')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'WikiModerator', N'wikimoderator', N'Moderator role for Wikis')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'WikiContributor', N'wikicontributor', N'Contributor role for Wikis')

	Declare @UserID uniqueidentifier
	Declare @cs_UserID int
	
	if(@AdminUserName is not null)
	Begin

		Set @UserID = newid()
		
		Print 'Create Admin User'
		INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
		      VALUES (@UserID, @ApplicationID, @AdminUserName, Lower(@AdminUserName), NULL, 0, getdate())
		--Do we need to make Salt configurable?
		INSERT INTO [aspnet_Membership] ([ApplicationId], [UserId], [Password],     [PasswordFormat], [PasswordSalt],	[MobilePIN],	[Email],		[LoweredEmail],		[PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment], FailedPasswordAnswerAttemptWindowStart, FailedPasswordAnswerAttemptCount, FailedPasswordAttemptWindowStart, FailedPasswordAttemptCount, LastLockoutDate, IsLockedOut) 
					 VALUES (@ApplicationID, @UserID,  @AdminPassword, @PasswordFormat,   @AdminSalt,	NULL,			@AdminEmail,	LOWER(@AdminEmail),	NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,                 '1753-01-01',                              0,                               '1753-01-01',                       0,                          '1753-01-01',      0)
		
		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
		VALUES(@UserID, 0,1, null, getdate(), '', @AdminUserName, @AdminEmail, 1, 0, getdate())


		Set @cs_UserID = SCOPE_IDENTITY()
		
		INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
		VALUES (@cs_UserID, 0, 0, 0, 0x01, 1, 0, 0, 0, 1, 0, 0, 1, 1, @UserID, @SettingsID, 'EnableDisplayName:S:0:4:EnableUserAvtars:S:4:4', 'TrueTrue')
		
		Print 'Created Admin User'
		
		Insert aspnet_UsersInRoles (UserId, RoleId) 
		Select @UserID, RoleId FROM aspnet_Roles where ApplicationId = @ApplicationID
	
	End
	
	
	Set @UserID = newid()
	
	Print 'Create Anonymous User'
	INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
	      VALUES (@UserID, @ApplicationID, 'Anonymous', Lower('Anonymous'), NULL, 1, getdate())
	--Do we need to make Salt configurable?
	INSERT INTO [aspnet_Membership] ([ApplicationId],[UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email],						[LoweredEmail],						[PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment],	[FailedPasswordAnswerAttemptWindowStart], [FailedPasswordAnswerAttemptCount],	[FailedPasswordAttemptWindowStart], [FailedPasswordAttemptCount],	[LastLockoutDate],	[IsLockedOut])
	                         VALUES (@ApplicationID, @UserID,  @UserID,         0,               N'DVZTktxeMzDtXR7eik7Cdw==', NULL,        'anonymous@localhost.com',    LOWER('anonymous@localhost.com'),  NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,			'1753-01-01',                              0,									'1753-01-01',                       0,								'1753-01-01',		0)
	
	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
	VALUES(@UserID, 0,1, null, getdate(), '', 'Anonymous', 'anonymous@localhost.com', 1, 1, getdate())

	Set @cs_UserID = SCOPE_IDENTITY()
	
	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	VALUES                          (@cs_UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, @UserID, @SettingsID, NULL, NULL)

	-- add the anonymous user to the everyone role
	INSERT INTO aspnet_UsersInRoles ([UserId], [RoleId]) VALUES( @UserID, @EveryoneRoleID )
END
ELSE
BEGIN
	Print 'Copied CS_UserProfile'
	--Import ApplicationID specific users from aspnet_Users if they dont already exists

	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
	SELECT aspnet.UserId, 0,1, null, getdate(), '', aspnet.UserName, aspnet.Email, aspnet.IsApproved, aspnet.IsAnonymous, getdate() from dbo.vw_aspnet_MembershipUsers aspnet LEFT OUTER JOIN dbo.cs_vw_Users_FullUser cs on aspnet.UserId = cs.MembershipID WHERE aspnet.ApplicationId = @ApplicationID and cs.MembershipID is null

	--Create cs_UserProfile records for any cs_Users without Profiles

	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	SELECT cs_Users.UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, cs_Users.MembershipID, @SettingsID, NULL, NULL FROM cs_Users LEFT OUTER JOIN cs_UserProfile on cs_Users.UserID = cs_UserProfile.UserID and cs_UserProfile.SettingsID = @SettingsID Where cs_UserProfile.UserID is null and cs_Users.MembershipID in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)

END

Declare @Perm_RoleID uniqueidentifier

	-- These items need to be set outside the if(@IsApplicationCreated = 1) since they need to be created based on the SettingsID and not ApplicationID


	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Everyone'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x000000000000000F, 0x00001007000000F0 ) -- Forum Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000001, 0x000000000000000C ) -- GuestBook Permission  >> Allow View,  Deny Post, Reply
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 ) -- Media Gallery Permission >> Allow  View, Read, Replay, Deny Post, Moderate, Vote, Delete, Edit
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000000000000000B, 0x0000700000000034 ) -- Wiki Permission >> Allow  View, Read, Comment
	-- SET SPECIFIC DELETED adn Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Registered Users'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x00000000000000BF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 ) -- Media Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- GuestBook Permission  >> Allow View, Reply  Deny Post	
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000020000000001F, 0xFFFFDFFFFFFFFFE0 )

	-- SET SPECIFIC DELETED and Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Editor'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000000F000000FF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 ) -- Media Gallery Permission

	-- SET SPECIFIC DELETED Forums Permission
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Moderator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000100F00000BFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'MediaGalleryAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'ForumsAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0100100F00000BFF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'BlogAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission  >> Allow View, Reply, Post

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'SystemAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x4100100F00000BFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x41001008000002FF, 0 ) -- Media Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x010070000000003F, 0 ) -- Wiki Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Owners'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post, and Attachments
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'WikiContributor'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000020000000001F, 0xFFFFDFFFFFFFFFE0 )
	
	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'WikiModerator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x000070000000003F, 0xFFFF8FFFFFFFFFC0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'WikiAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 53, @Perm_RoleID, 0x010070000000003F, 0 )

-- removed because its causing an issue with ThemePath defaults
	-- Set Public Only Aggregation for blogs
	-- INSERT INTO [cs_ApplicationConfigurationSettings] (SettingsID, ApplicationType, Settings) VALUES (@SettingsID, 1, N'<?xml version="1.0" encoding="utf-16"?><WeblogConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><AggPublicOnly>true</AggPublicOnly></WeblogConfiguration>')

	-- Set Public Only Aggregation for Galleries
    -- INSERT INTO [cs_ApplicationConfigurationSettings] (SettingsID, ApplicationType, Settings) VALUES (@SettingsID, 2, N'<GalleryConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><AggPublicOnly>true</AggPublicOnly></GalleryConfiguration>')

---Return New Data	

if @CreateSamples = 1
Begin
	exec cs_system_SampleMediaGallery @SettingsID, @AdminUserName
	exec cs_system_SampleWeblog @SettingsID, @AdminUserName
	exec cs_system_SampleForum @SettingsID, @AdminUserName
	exec cs_system_SampleGroups @SettingsID, @CategoryGroupID, @AdminUserName
	exec cs_system_SampleWiki @SettingsID, @AdminUserName
End

--Select * FROM cs_Sites
--DELETE FROM cs_Sites where ApplicationID > 50
Select * FROM aspnet_Applications where ApplicationId = @ApplicationID
Select * FROM aspnet_Users where ApplicationId = @ApplicationID
Select * FROM aspnet_Membership where UserId in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)
Select * FROM cs_UserProfile where SettingsID = @SettingsID
Select * FROM cs_Sites where SiteID = @SiteID
Select * FROM cs_SiteSettings where SettingsID = @SettingsID
Select * FROM cs_SiteMappings where SettingsID = @SettingsID and SiteID = @SiteID
Select * FROM cs_ProductPermissions where SettingsID = @SettingsID
Select * FROM cs_SectionPermissions where SettingsID = @SettingsID
Go

grant execute on [dbo].[cs_system_CreateCommunity] to public
go

/***********************************************
* Sproc: cs_system_CreateEvolutionNewsBlog
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_CreateEvolutionNewsBlog'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CreateEvolutionNewsBlog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CreateEvolutionNewsBlog]
GO

Create Proc [dbo].cs_system_CreateEvolutionNewsBlog
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

-- Get the user to make as the owner of the blog
Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

-- 'News' Blog Group
declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'News', @Action = 0, @ApplicationType = 1, @SettingsID = @SettingsID

-- 'News' Blog
declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'News', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 1, @ApplicationKey = N'news', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_CreateEvolutionNewsBlog] to public
go

/***********************************************
* Sproc: cs_system_dbreindex
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_dbreindex'

IF object_id( '[dbo].[cs_system_dbreindex]', N'P' ) IS NOT NULL
	drop procedure [dbo].[cs_system_dbreindex]
go

CREATE PROCEDURE [dbo].[cs_system_dbreindex]
as
begin

	declare @sql nvarchar(1000), @id int, @full_name sysname, @table_count int

	declare @t table (
		id int identity(1, 1) not null
		, full_name sysname collate database_default not null
	)

	set nocount on

	insert into @t ( full_name )
	select t.FULL_NAME from (
		select
			quotename(tx.TABLE_SCHEMA) + N'.' + quotename(tx.TABLE_NAME) as FULL_NAME
		from
			INFORMATION_SCHEMA.TABLES tx
	) as t
	where
		objectproperty( OBJECT_ID( t.FULL_NAME ), N'TableHasClustIndex' ) = 1
		and objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsMSShipped' ) = 0
	order by
		FULL_NAME

	set @table_count = @@ROWCOUNT

	print 'Beginning to perform a DBREINDEX on all ' + cast(@table_count as varchar) + ' tables at ' + convert(char(19), getdate(), 120)

	while 1=1
	begin
		select @id = t.id, @full_name = t.full_name from (
			select top 1 tx.* from @t tx order by id
		) as t
		
		if @id is null break
		
		print 'Doing a DBREINDEX on table ' + @full_name + ' at ' + convert(char(19), getdate(), 120)
		
		set @sql = N'dbcc dbreindex(''' + @full_name + N''')' -- with no_infomsgs
		exec sp_executesql @sql
		
		delete from @t where id = @id
		
		set @id = null
	end

	print 'Done with DBREINDEX at ' + convert(char(19), getdate(), 120)
end
go

grant execute on [dbo].[cs_system_dbreindex] to [public]
go
/***********************************************
* Sproc: cs_system_DeletePostAndAdoptChildren
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_DeletePostAndAdoptChildren'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DeletePostAndAdoptChildren]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DeletePostAndAdoptChildren]
GO


CREATE procedure [dbo].cs_system_DeletePostAndAdoptChildren
(
	@PostID int,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT
)
AS
-- Deleted Post is really moved to "Deleted Posts" forum (ForumType = 50)

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------
print @ParentID

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

-- This proc should only be called from non-thread starting posts
IF (@OldPostLevel <> 1)
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads
		(
			SectionID,
			PostDate,
			UserID,
			PostAuthor,
			ThreadDate,
			MostRecentPostAuthor,
			MostRecentPostAuthorID,
			MostRecentPostID,
			IsLocked,
			IsApproved,
			IsSticky,
			StickyDate,
			ThreadEmoticonID,
			SettingsID
		)
		VALUES
		(
			@DeletedSectionID,	-- the Deleted Posts forum
			@PostDate,
			@UserID,
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID,
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = SCOPE_IDENTITY()
	END

	-- First delete this post which is a parent post and should have its children adopted
	------------------------------------------------------------------------------------------
	-- Posts related updates
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID

	UPDATE
		cs_Posts
	SET
		SectionID = @DeletedSectionID,
		PostLevel = 1,
		ThreadID = @NewThreadID,
		ParentID = @PostID,
		SortOrder = 1
	WHERE
		PostID = @PostID AND
		SettingsID = @SettingsID

	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are there children to be adopted?
	------------------------------------------------------------------------------------------
	IF (@HasReplies > 0)
	BEGIN

print 'adopt children'
		-- Adopt children (by grandparent)
		UPDATE	cs_Posts
		SET		ParentID = @ParentID,
				PostLevel = @OldPostLevel
		WHERE	ParentID = @PostID AND
				ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		-- Get max post level (used for looping)
		DECLARE	@MaxPostLevel	INT
		SELECT	@MaxPostLevel = MAX(PostLevel)
		FROM	cs_Posts
		WHERE	ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		DECLARE	@level	int
		SET		@level = @OldPostLevel

		-- loop thru posting levels and recalculate (should just be a decrement)
		WHILE (@level <= @MaxPostLevel)
		BEGIN
			print 'reset levels'
			UPDATE	P
			SET		P.PostLevel = PP.PostLevel + 1
			FROM	cs_Posts P INNER JOIN cs_Posts PP ON P.ParentID = PP.PostID
			WHERE	P.PostLevel = @level AND
					P.ThreadID = @OldThreadID AND
					P.SectionID = @SectionID AND
					P.SettingsID = @SettingsID

			SET	@level = @level + 1
		END
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
	-- Decrease the TotalPosts on the user's profile.
--	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
--		UPDATE 
--			cs_UserProfile
--		SET 
--			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
--		WHERE 
--			UserID = @UserID and SettingsID = @SettingsID


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndAdoptChildren] to public
go
/***********************************************
* Sproc: cs_system_DeletePostAndChildren
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_DeletePostAndChildren'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DeletePostAndChildren]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DeletePostAndChildren]
GO


CREATE procedure [dbo].cs_system_DeletePostAndChildren
(
	@PostID int,
	@DeleteChildren bit = 1,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT,
	@NewPostLevel int = NULL
)
AS
-- Posts are not "deleted", but they are moved to SectionID=4.
-- Start deleting with @NewPostLevel being NULL

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

IF (@OldPostLevel = 1)
BEGIN		
	-- We may "move" the whole thread. So update and delete some records.
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID)

	UPDATE cs_Posts SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Threads related updates
	UPDATE cs_ThreadsRead SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	DELETE FROM cs_TrackedThreads WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	UPDATE cs_Threads SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Delete from the search index
	DELETE cs_SearchBarrel WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @OldThreadID
	
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
		
	RETURN 1
	------------------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads 	
		( 
			SectionID,
			PostDate, 
			UserID, 
			PostAuthor, 
			ThreadDate, 
			MostRecentPostAuthor, 
			MostRecentPostAuthorID, 	
			MostRecentPostID, 
			IsLocked, 
			IsApproved,
			IsSticky, 
			StickyDate, 
			ThreadEmoticonID,
			SettingsID 
		)
		VALUES
		( 
			@DeletedSectionID, 	-- the Deleted Posts forum
			@PostDate, 
			@UserID, 
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID, 
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID 
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = SCOPE_IDENTITY()		
	END
	------------------------------------------------------------------------------------------
		
	-- Calculate Post Level, Parent ID & Sort Order values
	------------------------------------------------------------------------------------------
	IF (@NewPostLevel IS NULL)
	BEGIN
		-- We have an unknown post level, so we have to figure out its values
		IF (NOT EXISTS(SELECT PostID FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID))
		BEGIN
			-- Set this post as a tread starter post
			SET @NewPostLevel = 1					
			SET @ParentID = @PostID
			SET @SortOrder = 1
		END
		ELSE
		BEGIN				
			-- Bind this post to the thread starter post
			SET @NewPostLevel = 2
			SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
		END
		
		-- Set children's post level
		SET @PostLevel = (@NewPostLevel + 1)
	END
	ELSE
	BEGIN
		--SET @PostLevel = 2
		SET @PostLevel = (@NewPostLevel + 1)
		SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
	END
	------------------------------------------------------------------------------------------

	-- First delete this post which is a parent post and should have its children removed
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID
		
	UPDATE 
		cs_Posts 
	SET 
		SectionID = @DeletedSectionID, 
		PostLevel = @NewPostLevel, 
		ThreadID = @NewThreadID,
		ParentID = @ParentID,
		SortOrder = @SortOrder
	WHERE 
		PostID = @PostID AND 
		SettingsID = @SettingsID
		
	-- TODO: Threads related updates?!
		
	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID
		
	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'
		
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are we allowed to delete children and there are some?
	------------------------------------------------------------------------------------------
	IF (@DeleteChildren = 1 AND @HasReplies > 0)
	BEGIN
		DECLARE @CurrentPostID INT

		-- Delete replying posts through a cursor loop
		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @OldThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID
	
		OPEN Posts_Cursor
			
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
	
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call
			EXEC cs_system_DeletePostAndChildren @CurrentPostID, @DeleteChildren, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, @PostLevel
	
			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END
	
		CLOSE Posts_Cursor
	
		DEALLOCATE Posts_Cursor		
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
	-- Decrease the TotalPosts on the user's profile.
--	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
--		UPDATE 
--			cs_UserProfile
--		SET 
--			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
--		WHERE 
--			UserID = @UserID and SettingsID = @SettingsID


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndChildren] to public
go
/***********************************************
* Sproc: cs_system_DuplicatePost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_DuplicatePost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DuplicatePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DuplicatePost]
GO





create procedure [dbo].cs_system_DuplicatePost
(
@UserID int,
@Body ntext,
@IntervalInMinutes int = 0,
@SettingsID int,
@IsDuplicate bit out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

	IF @IntervalInMinutes > 0
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body escape('[') AND PostDate > DateAdd(minute, -@IntervalInMinutes, GetDate()) )
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0
        ELSE
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body escape('['))
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_DuplicatePost] to public
go
/***********************************************
* Sproc: cs_system_GenerateWeblogYearMonthDayList
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_GenerateWeblogYearMonthDayList'

if object_id( 'dbo.cs_system_GenerateWeblogYearMonthDayList', N'P' ) IS NOT NULL
	drop procedure dbo.cs_system_GenerateWeblogYearMonthDayList
go

create procedure dbo.cs_system_GenerateWeblogYearMonthDayList
as
begin

--	this is the start of main step 1.  We would need to store the tblSuffix to know where the process is
--	so subsequent steps can continue on from this procedure
	declare
		@tblSuffix nvarchar(5)
		, @tblSuffixOld nvarchar(5)
		, @sql nvarchar(4000)

	/*	if table 1 is full, operate on table 2 and vice-versa */
	set @tblSuffix = case when exists (select 1 from dbo.cs_weblog_PostByYearMonth_tbl01)
		then N'tbl02' else N'tbl01' end
	
	/*	if tbl01 is the target table, the old table is tbl02 and vice-versa */
	set @tblSuffixOld = case @tblSuffix when N'tbl01' then N'tbl02' else N'tbl01' end

	print 'Using ['+@tblSuffix+'] for this data run.'

	print 'Truncate table: ' + convert(char(19), getdate(), 120)

	set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
	exec sp_executesql @sql

	print 'Removing PK from table: ' + convert(char(19), getdate(), 120)

	set @sql = case when exists (
		select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
		where
			c.CONSTRAINT_NAME = N'PK_cs_weblog_PostByYearMonth_' + @tblSuffix
			and c.TABLE_SCHEMA = N'dbo'
			and c.TABLE_NAME = N'cs_weblog_PostByYearMonth_' + @tblSuffix
			and c.CONSTRAINT_TYPE = N'PRIMARY KEY'
		)
		then N'alter table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' drop constraint PK_cs_weblog_PostByYearMonth_' + @tblSuffix
		else null end

	if @sql IS NOT NULL
		exec sp_executesql @sql

	print 'Insert base day data: ' + convert(char(19), getdate(), 120)
	
--		this could *possibly* reduce locks by only calculating the posts that have
--		been 'added' today ( getdate() ) and then filling in the previous data from the 'other'
--		table.  But, that doesn't consider if someone changes a PostDate from a previous day
--		on extremely high volume sites, I think it would be beneficial to only calculate the
--		previous day's numbers either once a day, or even calculate that once a week.
	set @sql = N'
	insert into dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' ([SectionID], [Year], [Month], [Day], [PostCount])
	Select
		p.SectionID
		, Year( coalesce(p.UserTime, p.PostDate) )
		, Month( coalesce(p.UserTime, p.PostDate) )
		, Day( coalesce(p.UserTime, p.PostDate) )
		, count(*)
	From
		cs_Posts p (nolock)
	where
		p.IsApproved = 1
		and p.ApplicationPostType = 1
		and p.PostDate <= getdate()
	group by
		p.SectionID
		, Year( coalesce(p.UserTime, p.PostDate) )
		, Month( coalesce(p.UserTime, p.PostDate) )
		, Day( coalesce(p.UserTime, p.PostDate) )'

	exec sp_executesql @sql

	if @@ERROR <> 0
	begin
		print 'Error occurred while inserting base data.  Truncating table: ' + convert(char(19), getdate(), 120)

		set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
		exec sp_executesql @sql
		return
	end

	print 'Insert base month data: ' + convert(char(19), getdate(), 120)

--		we could possibly add the constraint here and do this in two steps
--		this would be if we had extended times for this particular step
--		since there is no other process hitting this table at this time,
--		we shouldn't have issues with locking
	set @sql = N'insert into dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' ([SectionID], [Year], [Month], [Day], [PostCount])
	Select
		p.SectionID, p.[Year], p.[Month], 255 as [Day], sum( p.[PostCount] ) as [PostCount]
	From
		cs_weblog_PostByYearMonth_' + @tblSuffix + N' p
	group by
		p.SectionID, p.[Year], p.[Month]'

	exec sp_executesql @sql

	print 'Add constraint: ' + convert(char(19), getdate(), 120)

	set @sql = N'ALTER TABLE [dbo].[cs_weblog_PostByYearMonth_' + @tblSuffix + N']
		ADD CONSTRAINT [PK_cs_weblog_PostByYearMonth_' + @tblSuffix + N'] PRIMARY KEY CLUSTERED
	(
		[SectionID] ASC,
		[Year] DESC,
		[Month] DESC,
		[Day] DESC
	)
	WITH FILLFACTOR = 100 ON [PRIMARY]'

	exec sp_executesql @sql

	print 'Compute stats on new table: ' + convert(char(19), getdate(), 120)

	set @sql = N'dbcc dbreindex(''[dbo].[cs_weblog_PostByYearMonth_' + @tblSuffix + N']'')'

--		this is the start of main step 2.  We would need to store the tblSuffix to know where the process is
--		if this was to be split from the main stored procedure
	exec sp_executesql @sql

	print 'Alter view: ' + convert(char(19), getdate(), 120)

	/*	if the view doesn't exist, make it create instead of alter */
	set @sql = case when object_id(N'[dbo].[cs_vw_weblog_PostByYearMonth]', N'V') IS NOT NULL then N'alter' else 'create' end
		+ N' view dbo.cs_vw_weblog_PostByYearMonth as select * from cs_weblog_PostByYearMonth_' + @tblSuffix

	exec sp_executesql @sql

	if @@ERROR <> 0
	begin
		print 'Error occurred altering view.  Truncating table: ' + convert(char(19), getdate(), 120)

		set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
		exec sp_executesql @sql
		return
	end

--		this is the start of main step 3.  We would need to store the tblSuffix to know where the process is
--		if this was to be split from the main stored procedure
	print 'Clear old table: ' + convert(char(19), getdate(), 120)

	set @sql = N'truncate table cs_weblog_PostByYearMonth_' + @tblSuffixOld

	exec sp_executesql @sql

	print 'Compute stats on old table: ' + convert(char(19), getdate(), 120)

	set @sql = N'dbcc dbreindex(''[dbo].[cs_weblog_PostByYearMonth_' + @tblSuffixOld + N']'')'

	exec sp_executesql @sql

end
go

-- now to attempt to populate the table initially
if object_id(N'dbo.cs_vw_weblog_PostByYearMonth') IS NOT NULL
	exec [dbo].[cs_system_GenerateWeblogYearMonthDayList]

go

grant execute on [dbo].[cs_system_GenerateWeblogYearMonthDayList] to [public]
go

/***********************************************
* Sproc: cs_system_ModerationAction_AuditEntry
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_ModerationAction_AuditEntry'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ModerationAction_AuditEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ModerationAction_AuditEntry]
GO





create procedure [dbo].cs_system_ModerationAction_AuditEntry
(
	@ModerationAction int,
	@ModeratorID int,
	@PostID int = null,
	@UserID int = null,
	@SectionID int = null,
	@SettingsID int,
	@Notes nvarchar(1024) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	INSERT INTO
		cs_ModerationAudit
		(
			ModerationAction,
			PostID,
			UserID,
			SectionID,
			ModeratorID,
			Notes,
			SettingsID
		)
	VALUES
		(
			@ModerationAction,
			@PostID,
			@UserID,
			@SectionID,
			@ModeratorID,
			@Notes,
			@SettingsID
		)

	UPDATE
		cs_ModerationAction
	SET
		TotalActions = TotalActions + 1
	WHERE
		ModerationAction = @ModerationAction and SettingsID = @SettingsID

		
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ModerationAction_AuditEntry] to public
go
/***********************************************
* Sproc: cs_system_ResetForumStatistics
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_ResetForumStatistics'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ResetForumStatistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ResetForumStatistics]
GO




CREATE      procedure [dbo].cs_system_ResetForumStatistics
(
	@SectionID int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ThreadID int
DECLARE @PostID int

IF @SectionID = 0
BEGIN
	-- Reset the statistics on all of the forums.

	DECLARE ForumCount_Cursor CURSOR FOR
		SELECT SectionID FROM cs_Sections

	OPEN ForumCount_Cursor
	FETCH NEXT FROM ForumCount_Cursor INTO @SectionID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
		FETCH NEXT FROM ForumCount_Cursor INTO @SectionID
	END

	CLOSE ForumCount_Cursor
	DEALLOCATE ForumCount_Cursor
	
END
ELSE BEGIN

	DECLARE @SettingsID int

	Select @SettingsID = SettingsID FROM cs_Sections where SectionID = @SectionID

	-- Select the most recent post from the forum.
	SELECT TOP 1
		@ThreadID = ThreadID,
		@PostID = PostID
	FROM 
		cs_Posts
	WHERE 
		SectionID = @SectionID AND
		IsApproved = 1
	ORDER BY
		PostID DESC
   
	-- If the thread is null, reset the forum statistics.
	IF @ThreadID IS NULL
		UPDATE
			cs_Sections
		SET
			TotalThreads = 0,
			TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID),
			MostRecentPostID = 0,
			MostRecentThreadID = 0,
			MostRecentPostDate = '1/01/1797',
			MostRecentPostAuthorID = 0,
			MostRecentPostSubject = '',
			MostRecentPostAuthor = ''
		WHERE
			SectionID = @SectionID
	ELSE
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ResetForumStatistics] to public
go
/***********************************************
* Sproc: cs_system_ResetThreadStatistics
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_ResetThreadStatistics'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ResetThreadStatistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ResetThreadStatistics]
GO


CREATE PROCEDURE [dbo].cs_system_ResetThreadStatistics
(
	@ThreadID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @PostID int
DECLARE @UserID int
DECLARE @PostDate datetime
DECLARE @PostAuthor varchar(64)
DECLARE @Subject varchar(256)
DECLARE @SettingsID int
DECLARE @StickyDate datetime
DECLARE @IsSticky bit

-- Select the most recent post in the thread.
SELECT TOP 1
	@PostID = PostID,
	@UserID = UserID,
	@PostDate = PostDate,
	@PostAuthor = PostAuthor,
	@SettingsID = SettingsID
FROM
	cs_Posts
WHERE
	ThreadID = @ThreadID
	AND IsApproved = 1
ORDER BY
	PostID DESC

-- Get sticky date for the thread we need top update
SELECT @StickyDate = StickyDate, @IsSticky = IsSticky FROM cs_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

IF @StickyDate < @PostDate
	-- Sticky is expired
	SET @StickyDate = @PostDate

IF @IsSticky = 0 AND @StickyDate > @PostDate
	-- A replying post in this thread has just been deleted
	SET @StickyDate = @PostDate

-- Update the thread.	
UPDATE 
	cs_Threads
SET
	TotalReplies = (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1 AND SettingsID = @SettingsID),
	MostRecentPostAuthorID = @UserID,
	MostRecentPostAuthor = @PostAuthor,	
	MostRecentPostID = @PostID,
	ThreadDate = @PostDate,
	StickyDate = @StickyDate
WHERE
	ThreadID = @ThreadID AND
  SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ResetThreadStatistics] to public
go
/***********************************************
* Sproc: cs_system_SampleDownload
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleDownload'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleDownload]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleDownload]
GO

Create Proc [dbo].cs_system_SampleDownload
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Downloads', @Action = 0, @ApplicationType = 6, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 6, @ApplicationKey = N'sample_files', @PropertyNames = N'EnableExternalLinks:S:0:4:EnableDisclaimer:S:4:5:', @PropertyValues = N'TrueFalse', @SettingsID = @SettingsID, @UserID = @UserID


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Downloads', @IsEnabled = 1, @ParentID = 0, @Description = N'Files to download', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'The Latest Community Server Licensing Guide', @IsLocked = 0, @PostType = 1, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'This guide provides an overview of licensing for Community Server', @IsApproved = 1, @FormattedBody = N'This guide provides an overview of licensing for Community Server ', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ImageSize:S:0:6:', @PropertyValues = N'243742', @ApplicationPostType = 2, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'http://communityserver.org/r.ashx?D', @ContentType = N'application/pdf', @ContentSize = 243742, @SettingsID = @SettingsID, @FriendlyFileName = 'The Latest Community Server Licensing Guide', @IsRemote = 1, @Width= 425, @Height=283

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Downloads</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleDownload] to public
go

/***********************************************
* Sproc: cs_system_SampleForum
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleForum'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleForum]
GO

Create Proc [dbo].cs_system_SampleForum
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Forums', @Action = 0, @ApplicationType = 0, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @ForumType=0, @IsActive = 1, @ParentID = 0, @GroupID = @GroupID, @Name = N'Sample Forum', @ApplicationKey = N'sample_forum', @Description = N'', @IsModerated = 0, @DisplayPostsOlderThan = 7, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 0, @PropertyNames = null, @PropertyValues = null, @SettingsID = @SettingsID, @UserID = @UserID



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Sample Forum Posts', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is for forum posts', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



declare @ForumPostID int
declare @ForumThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)

exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Sample Forum Post', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'
		<p>sample forum post content</p>
', @IsApproved = 1, @FormattedBody = N'
		<p>sample forum post content</p>
', @UserHostAddress = N'127.0.0.1', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'', @PropertyValues = N'', @ApplicationPostType = 0, @PostID = @ForumPostID output, @ThreadID = @ForumThreadID output

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @ForumPostID, @CategoryList = N'<Categories><Category>Sample Forum Posts</Category></Categories>', @SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleForum] to public
go

/***********************************************
* Sproc: cs_system_SampleGallery
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleGallery'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleGallery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleGallery]
GO

Create Proc [dbo].cs_system_SampleGallery
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Photo Galleries', @Action = 0, @ApplicationType = 2, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 2, @ApplicationKey = N'sample', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Wildlife', @IsEnabled = 1, @ParentID = 0, @Description = N'Interesting Wildlife Pictures', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Ready for the chase', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'A picture from my backyard!', @IsApproved = 1, @FormattedBody = N'A picture from my backyard!', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ContentType:S:0:11:Width:S:11:3:Height:S:14:3:EXIF-DateTime:S:17:22:EXIF-Model:S:39:13:EXIF-ExposureTime:S:52:5:EXIF-FocalLength:S:57:1:EXIF-ApertureValue:S:58:5:EXIF-ISOSpeedRatings:S:63:3:EXIF-Flash:S:66:1:', @PropertyValues = N'image/pjpeg42528307/15/2004 09:08:18 AMCanon EOS 10D1/5008f/4.54000', @ApplicationPostType = 64, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'Cheetah.jpg', @ContentType = N'image/pjpeg', @ContentSize = 20558, @SettingsID = @SettingsID, @FriendlyFileName = 'Cheetah', @IsRemote = 0, @Width= 425, @Height=283


--	Commenting for now until CFS is worked out for this
--
--declare @ptr varbinary(16)
--select @ptr = textptr(Content) from cs_PostAttachments where PostID = @PicPostID
--writetext cs_PostAttachments.Content @ptr  

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Wildlife</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleGallery] to public
go

/***********************************************
* Sproc: cs_system_SampleGroups
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleGroups'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleGroups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleGroups]
GO

Create Proc [dbo].cs_system_SampleGroups
(
	@SettingsID int,
	@CategoryGroupID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @UserID = @UserID, @SettingsID = @SettingsID

exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID, @UserID = @UserID, @SettingsID = @SettingsID, @HubSectionID = @SectionID, @Name = N'Sample Group', @Description = N'', @ParentID = 0, @GroupID = @CategoryGroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 11, @ApplicationKey = N'sample_group', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @IsPublic = 1

declare @DateAdded datetime
exec dbo.cs_SectionMembers_Add @SectionID = @SectionID, @UserID = @UserID, @MembershipType = 1, @DateAdded = @DateAdded output

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleGroups] to public
go

/***********************************************
* Sproc: cs_system_SampleMediaGallery
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleMediaGallery'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleMediaGallery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleMediaGallery]
GO

Create Proc [dbo].cs_system_SampleMediaGallery
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Media Galleries', @Action = 0, @ApplicationType = 13, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample Media', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 13, @ApplicationKey = N'samplemedia', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Downloads', @IsEnabled = 1, @ParentID = 0, @Description = N'Files to download', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Community Server Documentation', @IsLocked = 0, @PostType = 1, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'', @IsApproved = 1, @FormattedBody = N'', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'', @PropertyValues = N'', @ApplicationPostType = 2, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'http://communityserver.org/r.ashx?S', @ContentType = N'text/html; charset=utf-8', @ContentSize = 50000, @SettingsID = @SettingsID, @FriendlyFileName = 'Community Server Documentation', @IsRemote = 1, @Width= 425, @Height=283

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Downloads</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleMediaGallery] to public
go

/***********************************************
* Sproc: cs_system_SampleWeblog
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleWeblog'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleWeblog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleWeblog]
GO

Create Proc [dbo].cs_system_SampleWeblog
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Weblogs', @Action = 0, @ApplicationType = 1, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample Weblog', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 1, @ApplicationKey = N'sample_weblog', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Blogging', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is about blogging', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



Declare @PostID int
Declare @Date datetime
Set @Date = GetDate()
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)
exec dbo.cs_weblog_Post_Create @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 1, @Subject = N'Welcome to Community Server Blogs!', @IsLocked = 0, @IsApproved = 1, @IsTracked = 0, @PostType = 1, @EmoticonID = 0, @UserID = @UserID, @Body = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>
', @FormattedBody = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>', @UserHostAddress = N'127.0.0.1', @PostDate = @Date, @UserTime = @Date, @PropertyNames = N'EnableRatings:S:0:4:EnableTrackBacks:S:4:4:', @PropertyValues = N'TrueTrue', @SettingsID = @SettingsID, @IsSticky = 0, @StickyDate = @PostStickyDate, @PostName = N'My First Post', @PostConfig = 11, @BlogPostType = 1, @Categories = N'<Categories><Category>Blogging</Category></Categories>', @PostID = @PostID output

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleWeblog] to public
go

/***********************************************
* Sproc: cs_system_SampleWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_SampleWiki'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleWiki]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleWiki]
GO

Create Proc [dbo].cs_system_SampleWiki
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

Declare @Date datetime
Set @Date = GetUtcDate()

declare @WikiID int
exec [dbo].[cs_Wiki_AddWiki]
    @wikiId = @WikiID output,
    @hubId = NULL,
    @name = N'Sample Wiki',
    @description = N'',
    @applicationKey = N'sample_wiki',
    @isEnabled = 1,
    @lastModifiedUtcDate = @Date

Declare @PageID int
exec [dbo].[cs_Wiki_AddPage]
    @pageId = @PageID OUTPUT,
    @wikiId = @WikiID,
    @userId = @UserID,
    @parentPageId = NULL,
    @title = N'Welcome to Community Server Wikis',
    @pageKey = N'welcome',
    @body = N'<p>A wiki enables member to be able to contribute and collaborate on any topic.</p>
		<p>Happy Collaborating!</p>',
    @formattedBody = N'<p>A wiki enables member to be able to contribute and collaborate on any topic.</p>
		<p>Happy Collaborating!</p>',
    @tagXml = N'<tags><tag>Sample Wiki</tag></tags>',
    @isPublished = 1,
    @ratingCount = 0,
    @ratingSum = 0,
    @lastModifiedUtcDate = @Date, 
    @revisionCount = 1, 
    @isLocked = 0,
    @isIndexed = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleWiki] to public
go

/***********************************************
* Sproc: cs_system_UpdateForum
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateForum'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateForum]
GO


CREATE PROCEDURE [dbo].cs_system_UpdateForum
(
	@SectionID int,
	@ThreadID int,
	@PostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1, -- new param with a default value,
	@PostDisplayName nvarchar(64) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @UserID 		int
DECLARE @PostDate 		datetime
DECLARE @TotalThreads 		int
DECLARE @TotalPosts 		int
DECLARE @PostsToModerate	int
DECLARE @Subject		nvarchar(64)
DECLARE @User 		nvarchar(64)
DECLARE @PostConfiguration	int
DECLARE @IsApproved bit
DECLARE @HubSectionID int


-- Set default
SET @PostConfiguration = 0

-- Get values necessary to update the forum statistics
SELECT
	@IsApproved = P.IsApproved,
	@UserID = P.UserID,
	@PostDate = PostDate,
	@TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 1 and SettingsID = @SettingsID),
	@TotalThreads = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.SectionID = @SectionID AND P2.IsApproved=1 AND P2.PostLevel=1 and P2.SettingsID = @SettingsID),
	@PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID),
	@Subject = P.Subject,
	@User = PostAuthor,
	@PostConfiguration = P.PostConfiguration
FROM
	cs_Posts P
WHERE
	PostID = @PostID and P.SettingsID = @SettingsID and P.SectionID = @SectionID

SELECT
	@HubSectionID = S.HubSectionID
FROM
	cs_Sections S
WHERE
	S.SectionID = @SectionID and S.SettingsID = @SettingsID

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1	
	SET @User = null
	SET @PostDisplayName = null
	
END

IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the post is not flagged as ignored. 
BEGIN 
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	-- Always update counters
	UPDATE 
		cs_Sections
	SET
		TotalPosts = isnull(@TotalPosts,0),
		TotalThreads = isnull(@TotalThreads,0),
		PostsToModerate = isnull(@PostsToModerate,0)
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- Only update Post-specific info if the current post is approved
	IF @IsApproved = 1
	BEGIN
		UPDATE 
			cs_Sections
		SET
			MostRecentPostID = isnull(@PostID,0),
			MostRecentThreadID = isnull(@ThreadID,0),
			MostRecentPostAuthorID = isnull(@UserID,0),
			MostRecentPostSubject = isnull(@Subject,''),
			MostRecentPostAuthor = isnull(@PostDisplayName,isnull(@User,'')),
			MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
		WHERE
			SectionID = @SectionID and SettingsID = @SettingsID
	
		IF @UpdateThreadDate = 1
			UPDATE 
				cs_Sections
			SET
				MostRecentPostDate = isnull(@PostDate,'1/01/1797')
			WHERE
				SectionID = @SectionID and SettingsID = @SettingsID

		-- If section has a hub, the update the hub's most recent post info
		if @HubSectionID > 0
		begin
			UPDATE 
				cs_Sections
			SET
				MostRecentPostID = isnull(@PostID,0),
				MostRecentThreadID = isnull(@ThreadID,0),
				MostRecentPostAuthorID = isnull(@UserID,0),
				MostRecentPostSubject = isnull(@Subject,''),
				MostRecentPostAuthor = isnull(@PostDisplayName,isnull(@User,'')),
				MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
			WHERE
				SectionID = @HubSectionID and SettingsID = @SettingsID

			IF @UpdateThreadDate = 1
				UPDATE 
					cs_Sections
				SET
					MostRecentPostDate = isnull(@PostDate,'1/01/1797')
				WHERE
					SectionID = @HubSectionID and SettingsID = @SettingsID
		end
	
		-- UPDATE Parent
		DECLARE @ParentID int
		SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @SectionID
	
		WHILE @ParentID > 0
		BEGIN
			UPDATE 
				cs_Sections
			SET
				MostRecentPostID = isnull(@PostID,0),
				MostRecentThreadID = isnull(@ThreadID,0),
				MostRecentPostAuthorID = isnull(@UserID,0),
				MostRecentPostSubject = isnull(@Subject,''),
				MostRecentPostAuthor = isnull(@User,''),
				MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
			WHERE
				SectionID = @ParentID and SettingsID = @SettingsID
			
			IF @UpdateThreadDate = 1
				UPDATE 
					cs_Sections
				SET
					MostRecentPostDate = isnull((SELECT top 1 MostRecentPostDate FROM cs_Sections WHERE SectionID = @ParentID and SettingsID = @SettingsID AND MostRecentPostDate > @PostDate), @PostDate)
				WHERE
					SectionID = @ParentID and SettingsID = @SettingsID
		
			-- Get the next ParentID
			SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @ParentID
		END
	
	END

END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateForum] to public
go

/***********************************************
* Sproc: cs_system_UpdateMostActiveUsers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateMostActiveUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateMostActiveUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateMostActiveUsers]
GO



CREATE   procedure [dbo].cs_system_UpdateMostActiveUsers
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	SET NOCOUNT ON

	DELETE FROM cs_statistics_User WHERE SettingsID = @SettingsID
	
	INSERT INTO cs_statistics_User
	SELECT TOP 100
		U.UserID,
		TotalPosts = ISNULL( (SELECT count(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SectionID = cs_Posts.SectionID and cs_Sections.SettingsID = @SettingsID AND UserID = U.UserID AND PostDate > DateAdd(day, -1, GetDate())), 0),
		@SettingsID
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.IsIgnored = 0   AND
		U.UserAccountStatus = 1 and U.SettingsID = @SettingsID
	ORDER BY
		TotalPosts DESC

	SET NOCOUNT OFF
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateMostActiveUsers] to public
go
/***********************************************
* Sproc: cs_system_UpdateSite
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateSite'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateSite]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateSite]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE PROCEDURE [dbo].[cs_system_UpdateSite]
(
	@UpdateUserPostRank bit = 1,
	@UpdateMostActiveUserList bit = 1,
	@SettingsID int,
	@UpdateWindow int = 3,
	@EveryoneRoleID uniqueidentifier,
	@ModeratorRoleID uniqueidentifier,
	@TotalModerators int
)
AS

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
DECLARE @DateWindow datetime

SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')
SET @DateWindow = DATEADD(hh, -@UpdateWindow, GetDate())

if (@LastUpdate <  @DateWindow)
BEGIN


	-- Get summary information - Total Users, Total Posts, TotalTopics, DaysPosts, and DaysTopics
	DECLARE @LastDateTimeUpdate datetime
	DECLARE @TotalUsers int
	DECLARE @TotalPosts int
	DECLARE @TotalTopics int
	DECLARE @TotalModeratedPosts int
	DECLARE @NewThreadsInPast24Hours int
	DECLARE @NewPostsInPast24Hours int
	DECLARE @NewUsersInPast24Hours int
	DECLARE @MostViewsPostID int
    DECLARE @ViewCount int
	DECLARE @MostActivePostID int
	DECLARE @ReplyCount int
	DECLARE @MostReadPostID int
	DECLARE @TotalAnonymousUsers int
	DECLARE @NewestUserID int
	DECLARE @MostActiveUserID int
	DECLARE @ApplicationName  NVARCHAR(256)

	SET @ApplicationName  = (Select Lower(ApplicationName) FROM cs_SiteSettings where SettingsID = @SettingsID)

	SET NOCOUNT ON

	SET @LastDateTimeUpdate = ISNULL( 
					(
						SELECT TOP 1
							DateCreated 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID
					), '1/1/1979 12:00:00')

	-- Reset top posters
	IF @UpdateUserPostRank = 1
		exec cs_system_UpdateUserPostRank @SettingsID

	IF @UpdateMostActiveUserList = 1
		exec cs_system_UpdateMostActiveUsers @SettingsID

	-- Total Anonymous Users
	-- ***********************************************
	SET @TotalAnonymousUsers = 0-- ISNULL((SELECT COUNT(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID), 0 )

	-- Total Moderators, for this site only
	-- ***********************************************


	-- Total Moderated Posts
	-- ***********************************************
	SET @TotalModeratedPosts  = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalModeratedPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
					ISNULL( 
					(
						SELECT 
							COUNT(ModerationAction) 
						FROM 
							cs_ModerationAudit 
						WHERE 
							ModeratedOn >= @LastDateTimeUpdate AND
							SettingsID = @SettingsID AND
							ModerationAction = 1
					), 0)
	IF @TotalModeratedPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalModeratedPosts = (SELECT COUNT(ModerationAction) FROM cs_ModerationAudit WHERE SettingsID = @SettingsID AND ModerationAction = 1)
	END

	-- Most "Viewed" thread, by grabbing the first post
	-- ***********************************************
	SET @MostViewsPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY 
							jT.TotalViews DESC
					), 0)

        -- "ViewCount" thread, by grabbing the first post
	-- ***********************************************
	SET @ViewCount = ISNULL(
					(
						SELECT TOP 1 
							jP1.TotalViews
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY
							jT.TotalViews DESC
					), 0)


	-- Most "Active" Thread, by grabbing the first post
	-- ***********************************************
	SET @MostActivePostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

        -- "ReplyCount" on a Thread, by grabbing the first post
	-- ***********************************************
	SET @ReplyCount = ISNULL(
					(
						SELECT TOP 1 
							jT.TotalReplies
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

	-- Most "Read" thread, by grabbing the first post
	-- ***********************************************
	SET @MostReadPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jF.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							( SELECT count(jTR.ThreadID) FROM cs_ThreadsRead jTR WHERE jP1.ThreadID = jTR.ThreadID ) DESC
					), 0)


	-- Most active user
	-- ***********************************************
	SET @MostActiveUserID = ISNULL(
					(
						SELECT TOP 1 
							jP.UserID
						FROM 
							cs_UserProfile jP
						WHERE
							jP.EnableDisplayInMemberList = 1 and jP.SettingsID = @SettingsID
						ORDER BY 
							jP.TotalPosts DESC
					), 0)
	-- Newest user
	-- ***********************************************
	SET @NewestUserID = ISNULL(
					(
						SELECT Max(jU.UserID) 

						FROM 
							cs_vw_Users_FullUser jU
							JOIN cs_UserProfile jP ON jP.UserID = jU.UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 AND
							jU.UserAccountStatus = 1 and jP.SettingsID = @SettingsID
					), 0)


	-- Total Users
	-- ***********************************************
	SET @TotalUsers = ISNULL( 
					(
						SELECT 
							COUNT(UserID) 
						FROM 
							cs_UserProfile 
						WHERE 
							SettingsID = @SettingsID
					) ,0) 


	-- Total Posts
	-- ***********************************************
	SET @TotalPosts = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) +
				 ISNULL( 
					(
						SELECT 
							COUNT(PostID) 
						FROM 
							cs_Posts, cs_Sections
						WHERE 
							ForumType = 0 and cs_Posts.SectionID = cs_Sections.SectionID and 
						PostDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SettingsID = @SettingsID)
	END


	-- Total Topics
	-- ***********************************************
	SET @TotalTopics = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalTopics 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
				ISNULL( 
					(
						SELECT 
							COUNT(ThreadID) 
						FROM 
							cs_Threads, cs_Sections 
						WHERE 
							ForumType = 0 AND cs_Threads.SectionID = cs_Sections.SectionID and 
							ThreadDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalTopics = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalTopics = (SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.SectionID = cs_Threads.SectionID and cs_Sections.ApplicationType = 0)
	END

	-- Total Posts in past 24 hours
	-- ***********************************************
	SET @NewPostsInPast24Hours = ISNULL( 
					(SELECT COUNT(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SettingsID = @SettingsID And cs_Sections.SectionID = cs_Posts.SectionID and ForumType = 0 and PostDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Users in past 24 hours
	-- ***********************************************
	SET @NewUsersInPast24Hours = ISNULL(
						(SELECT COUNT(U.IsApproved) FROM cs_Users U INNER JOIN cs_UserProfile UP ON U.UserID = UP.UserID WHERE UP.SettingsID = @SettingsID and U.CreateDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Topics in past 24 hours
	-- ***********************************************
	SET @NewThreadsInPast24Hours = ISNULL(
						(SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SectionID = cs_Threads.SectionID AND cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.ApplicationType = 0 AND PostDate > DATEADD(dd,-1,getdate())
					), 0)

	INSERT INTO cs_statistics_Site
	SELECT 
		DateCreated = GetDate(),
		TotalUsers = @TotalUsers,
		TotalPosts = @TotalPosts,
		TotalModerators = @TotalModerators,
		TotalModeratedPosts = @TotalModeratedPosts,
		TotalAnonymousUsers = @TotalAnonymousUsers,
		TotalTopics = @TotalTopics,
		DaysPosts = @NewPostsInPast24Hours, -- TODO remove
		DaysTopics = @NewThreadsInPast24Hours, -- TODO remove
		NewPostsInPast24Hours = @NewPostsInPast24Hours,
		NewThreadsInPast24Hours = @NewThreadsInPast24Hours,
		NewUsersInPast24Hours = @NewUsersInPast24Hours,
		MostViewsPostID = @MostViewsPostID,
		MostActivePostID = @MostActivePostID,
		MostActiveUserID = @MostActiveUserID,
		MostReadPostID = @MostReadPostID,
		NewestUserID = @NewestUserID,	
		SettingsID = @SettingsID,
        	ViewCount = @ViewCount,
        	ReplyCount = @ReplyCount
END

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateSite] to public
go

/***********************************************
* Sproc: cs_system_updatestatistics
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_updatestatistics'

IF object_id( '[dbo].[cs_system_updatestatistics]', N'P' ) IS NOT NULL
	drop procedure [dbo].[cs_system_updatestatistics]
go

CREATE PROCEDURE [dbo].[cs_system_updatestatistics]
as
begin

	declare @sql nvarchar(1000), @id int, @full_name sysname, @table_count int
		,@dbsid varbinary(85)

	declare @t table (
		id int identity(1, 1) not null
		, full_name sysname collate database_default not null
	)

	set nocount on
	
	select
		@dbsid = d.sid
	from
		master..sysdatabases d
	where
		d.name = db_name()
	
	-- Check the user sysadmin
	if not is_srvrolemember(N'sysadmin') = 1 and suser_sid() <> @dbsid
	begin
		raiserror( 15247, -1, -1 )
		return (1)
	end
	
	if DATABASEPROPERTYEX( db_name(), N'Updateability' ) = N'READ_ONLY'
	begin
		raiserror( 15635, -1, -1, N'cs_system_updatestatistics' )
		return (1)
	end
	
	insert into @t ( full_name )
	select t.FULL_NAME from (
		select
			quotename(tx.TABLE_SCHEMA) + N'.' + quotename(tx.TABLE_NAME) as FULL_NAME
		from
			INFORMATION_SCHEMA.TABLES tx
	) as t
	where
		objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsIndexed' ) = 1
		and objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsMSShipped' ) = 0
	order by
		FULL_NAME

	set @table_count = @@ROWCOUNT

	print 'Beginning to perform an UPDATE STATISTICS on all ' + cast(@table_count as varchar) + ' tables at ' + convert(char(19), getdate(), 120)

	while 1=1
	begin
		select @id = t.id, @full_name = t.full_name from (
			select top 1 tx.* from @t tx order by id
		) as t
		
		if @id is null break
		
		print 'Performing an UPDATE STATISTICS on table/view ' + @full_name + ' at ' + convert(char(19), getdate(), 120)
		
		set @sql = 'update statistics ' + @full_name -- with no_infomsgs
		exec sp_executesql @sql
		
		delete from @t where id = @id
		
		set @id = null
	end

	print 'Done with UPDATE STATISTICS at ' + convert(char(19), getdate(), 120)
end
go

grant execute on [dbo].[cs_system_updatestatistics] to [public]
go
/***********************************************
* Sproc: cs_system_UpdateSubscriptions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateSubscriptions'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateSubscriptions]
GO


/***********************************************
* Sproc: cs_system_UpdateThread
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateThread]
GO


CREATE PROCEDURE [dbo].cs_system_UpdateThread
(
	@ThreadID int,
	@ReplyPostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1 -- new param with a default value
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

SET NOCOUNT ON

DECLARE @ThreadDate datetime
DECLARE @StickyDate datetime
DECLARE @UserID int
DECLARE @PostAuthor nvarchar(64)
DECLARE @FirstPostID INT
DECLARE @PostConfiguration int

-- Set default
SET @PostConfiguration = 0

IF @ReplyPostID = 0
	SELECT TOP 1 
		@ReplyPostID = PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate DESC

-- Get details about the reply & PostConfiguration details
SELECT 
	@ThreadDate = PostDate, 
	@UserID = UserID, 
	@PostAuthor = PostAuthor,
	@PostConfiguration = PostConfiguration
FROM 
	cs_Posts 
WHERE 
	PostID = @ReplyPostID and SettingsID = @SettingsID

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1
	SET @PostAuthor = ''
END

SELECT 
	@StickyDate = StickyDate 
FROM 
	cs_Threads 
WHERE 
	ThreadID = @ThreadID and SettingsID = @SettingsID

IF @StickyDate < @ThreadDate
	SET @StickyDate = @ThreadDate

-- do the mass updates.
IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the most recent post hasn't been flagged as ignored. 
BEGIN
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	UPDATE 
		cs_Threads
	SET
		TotalReplies = (SELECT Count(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
		MostRecentPostAuthorID = @UserID,
		MostRecentPostAuthor = @PostAuthor,
		MostRecentPostID = @ReplyPostID
	WHERE
		ThreadID = @ThreadID and SettingsID = @SettingsID
	
	IF @UpdateThreadDate = 1	
		UPDATE 
			cs_Threads
		SET
			ThreadDate = @ThreadDate,
			StickyDate = @StickyDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- find any lingering ParentIDs that don't match any posts in
-- our thread (from a merge or split action)
SET @FirstPostID = (	
	SELECT TOP 1 
		PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate ASC 
	)

UPDATE
	cs_Posts
SET
	ParentID = @FirstPostID
WHERE
	ParentID NOT IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID)
	AND ThreadID = @ThreadID and SettingsID = @SettingsID


-- fix the PostLevel and SortOrder ordering, by date
-- this could be done better, as it's on a MassScale now.
UPDATE
	cs_Posts
SET
	SortOrder = SortOrder + 1
WHERE
	ThreadID = @ThreadID
	AND PostID > @ReplyPostID and SettingsID = @SettingsID

UPDATE p set p.PostLevel = 0
FROM cs_Posts p where p.ThreadID = @ThreadID
 
-- set initial post level
UPDATE p set p.PostLevel = 1
FROM cs_Posts p where p.PostID = p.ParentID and p.ThreadID = @ThreadID
 
-- reset all other post levels
while 1=1
begin
    UPDATE p set p.PostLevel = pp.PostLevel + 1
    FROM cs_Posts p
    inner join cs_Posts pp on p.ParentID = pp.PostID
    WHERE p.ThreadID = @ThreadID and p.PostLevel = 0 and pp.PostLevel > 0

    if @@ROWCOUNT = 0 BREAK
end


-- update the EmoticonID, if it's the first post
IF @ReplyPostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate ASC)
	UPDATE
		cs_Threads
	SET
		ThreadEmoticonID = (SELECT EmoticonID FROM cs_Posts WHERE PostID = @ReplyPostID and SettingsID = @SettingsID)
	WHERE
		ThreadID = @ThreadID	 and SettingsID = @SettingsID

SET NOCOUNT OFF

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



grant execute on [dbo].[cs_system_UpdateThread] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserPostCount
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateUserPostCount'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserPostCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserPostCount]
GO





create  procedure [dbo].cs_system_UpdateUserPostCount
(
	@SectionID 	int,
	@UserID		int,
	@SettingsID 	int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Does the forum track post statistics?
	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 0
		RETURN

	UPDATE cs_UserProfile SET TotalPosts = TotalPosts + 1 WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserPostCount] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserPostRank
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateUserPostRank'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserPostRank]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserPostRank]
GO

create procedure [dbo].cs_system_UpdateUserPostRank
(
	@SettingsID int
)
AS
BEGIN

	SET Transaction Isolation Level Read UNCOMMITTED
	DECLARE @LoopCounter int

	SET NOCOUNT ON

	CREATE Table #PostRank (
	  Rank int IDENTITY (1, 1) NOT NULL,
	  UserID int
	)

	-- Select into temp table
	INSERT INTO #PostRank (UserID)
	SELECT TOP 500
		P.UserID
	FROM
		cs_UserProfile P
	Where SettingsID = @SettingsID
	ORDER BY
		TotalPosts DESC

	-- First clear all the users
	UPDATE 
		cs_UserProfile
	SET 
		PostRank = 0x0
	WHERE 
		PostRank > 0 and SettingsID = @SettingsID

	-- Top 10
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x01
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank < 11 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 25
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x02
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 10 AND Rank < 26 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 50
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x04
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 25 AND Rank < 51 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 75
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x08
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 50 AND Rank < 76 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 100
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x10
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 75 AND Rank < 101 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 150
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x20
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 100 AND Rank < 151 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 200
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x40
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 150 AND Rank < 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 500
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x80
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID

END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserPostRank] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserSubscriptions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UpdateUserSubscriptions'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserSubscriptions]
GO


/***********************************************
* Sproc: cs_system_UserCanReadSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UserCanReadSection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UserCanReadSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UserCanReadSection]
GO


/***********************************************
* Sproc: cs_system_UserIsOnline
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_system_UserIsOnline'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UserIsOnline]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UserIsOnline]
GO

CREATE PROCEDURE [dbo].cs_system_UserIsOnline
(
	@UserID int,
	@LastAction nvarchar(1024),
	@SettingsID int,
	@LastActivity datetime = null output
)
AS
BEGIN
	SET Transaction Isolation Level Read UNCOMMITTED

	set @LastActivity = getdate()

	-- Update cs_Users table
	UPDATE
		cs_Users
	SET
		LastActivity = @LastActivity,
		LastAction = @LastAction
	WHERE
		UserID = @UserID
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_system_UserIsOnline] to public
go
/***********************************************
* Sproc: cs_Tags_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Tags_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Tags_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Tags_Get]
GO

CREATE PROCEDURE [dbo].[cs_Tags_Get] 
	@SectionXML ntext = null,
	@CategoryList nvarchar(4000) = null,
	@sqlPopulate ntext = null,
	@SettingsID int
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	DECLARE @Sections TABLE 
	(
		SectionID int
	)
	--DECLARE @FilterSections TABLE 
	--(
	--	SectionID int
	--)
	-- Create a temp table to store the select results
	CREATE TABLE #FilterSections 
	(
		SectionID int  NOT NULL
	)
	
	
	DECLARE @ret int, @iXml int
	
	IF @SectionXML IS NOT NULL
	BEGIN
	
		EXECUTE @ret = [master].[dbo].[sp_xml_preparedocument] @iXml OUTPUT, @SectionXML
	
		INSERT INTO #FilterSections (SectionID)
			SELECT
		    		a.sectionID
			FROM
		    		OPENXML(@iXml, '/xml/SectionIDs/i', 2) -- use element-centric mapping
			WITH ( sectionID int '.') AS a
	
		-- clean up the sqlxml object
		EXEC sp_xml_removedocument @iXml
	END
	
	--SQL POPULATE WAS ADDED TO SUPPORT THE ISPUBLIC FLAG AS AN OPTIONAL ALTERNATE WAY TO POPULATE THE SECTION LIST
	IF @sqlPopulate IS NOT NULL
	BEGIN
	
		INSERT INTO #FilterSections (SectionID)
		EXEC sp_executesql @sqlPopulate
	
	END   
	
	
	INSERT INTO @Sections (SectionID)
			SELECT
			    s.SectionID 
			FROM 
			   #FilterSections fs JOIN cs_Sections s on
			   	s.SettingsID = @SettingsID
			   	and fs.SectionID = s.SectionID
			   	and s.IsActive = 1
	
	DROP TABLE #FilterSections
	
	if @CategoryList is null begin
	
		select [Name], count(*) as TotalCount
		from cs_Post_Categories C
		inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
		inner join cs_Posts P on PiC.PostID = P.PostID
		where C.SettingsID = @SettingsID
			and C.SectionID IN (select sx.SectionID from @Sections sx)
			and P.IsApproved = 1
			and C.IsEnabled = 1
		group by [Name]
		order by [Name]
	
	end else begin
	
		declare @idoc int
		declare @categoryCount int
	
		declare @Tags TABLE
		(
			[Name] nvarchar(255) collate database_default
		)
	
		EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList
		
		insert into @Tags ([Name])
		select CONVERT(nvarchar(255), [text])
		from OPENXML(@idoc, '/Categories/Category/', 2)
		where [text] is not null
	
		set @categoryCount = @@ROWCOUNT
	
		-- clean up the sqlxml object
		EXEC sp_xml_removedocument @idoc
	
		select [Name], count(*) as TotalCount
		from cs_Post_Categories C
		inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
		where C.SettingsID = @SettingsID
			and C.SectionID in (select sx.SectionID from @Sections sx)
			and C.IsEnabled = 1
			and PiC.PostID in (
				select P2.PostID
				from @Tags X
				inner join cs_Post_Categories C2 on X.[Name] = C2.Name
				inner join cs_Posts_InCategories PiC2 on PiC2.CategoryID = C2.CategoryID
				inner join cs_Posts P2 on PiC2.PostID = P2.PostID
				where C2.SettingsID = @SettingsID
					and C2.SectionID in (select sx.SectionID from @Sections sx)
					and C2.IsEnabled = 1
					and P2.SettingsID = @SettingsID
					and P2.IsApproved = 1
				group by P2.PostID
				having count(*) = @categoryCount
				)
		group by [Name]
		having [Name] not in (select tx.[Name] from @Tags tx)
		order by [Name]
	
	end
end
go

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Tags_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_TemporaryUserTokens_Expire
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_TemporaryUserTokens_Expire'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_TemporaryUserTokens_Expire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_TemporaryUserTokens_Expire]
GO


create procedure [dbo].cs_TemporaryUserTokens_Expire
AS
SET Transaction Isolation Level Read UNCOMMITTED


DELETE
	cs_TemporaryUserTokens
WHERE
	ExpirationDate < getdate()


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserTokens_Expire] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Create'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_TemporaryUserToken_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_TemporaryUserToken_Create]
GO


create procedure [dbo].cs_TemporaryUserToken_Create
(
	@UserID			int,
	@SettingsID		int,
	@ExpirationDate	datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @Token uniqueidentifier
SET @Token = newid()

INSERT INTO
	cs_TemporaryUserTokens
	(
		UserID,
		SettingsID,
		Token,
		ExpirationDate
	)
VALUES
	(
		@UserID,
		@SettingsID,
		@Token,
		@ExpirationDate
	)

SELECT @Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Create] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_TemporaryUserToken_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_TemporaryUserToken_Delete]
GO


create procedure [dbo].cs_TemporaryUserToken_Delete
(
	@UserID		int,
	@SettingsID	int,
	@Token		uniqueidentifier
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


DELETE
	cs_TemporaryUserTokens
WHERE
	UserID = @UserID
	AND SettingsID = @SettingsID
	AND Token = @Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Delete] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Validate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Validate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_TemporaryUserToken_Validate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_TemporaryUserToken_Validate]
GO


create procedure [dbo].cs_TemporaryUserToken_Validate
(
	@UserID		int,
	@SettingsID	int,
	@Token		uniqueidentifier
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


IF EXISTS (SELECT * FROM cs_TemporaryUserTokens WHERE UserID = @UserID AND SettingsID = @SettingsID AND Token = @Token AND ExpirationDate > getdate())
	SELECT 1
ELSE
	SELECT 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Validate] to public
go
/***********************************************
* Sproc: cs_ThemeConfigurationData_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ThemeConfigurationData_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ThemeConfigurationData_Delete]
GO

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Delete
	@ThemeName nvarchar(255) = null,
	@SettingsID int,
	@SectionID int = null,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if (@ThemeName is null and @SectionID is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end 
	
	if (@SectionID is null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end
	
	if (@SectionID is not null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end
end else begin
	if (@ThemeName is null and @SectionID is not null) begin
		delete from cs_ThemeConfigurationData
		where SettingsID = @SettingsID
			and SectionID = @SectionID
	end 
	
	if (@SectionID is null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
	end
	
	if (@SectionID is not null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ThemeConfigurationData_Delete]  TO [public]
GO


/***********************************************
* Sproc: cs_ThemeConfigurationData_ExpireTemp
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_ExpireTemp'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ThemeConfigurationData_ExpireTemp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ThemeConfigurationData_ExpireTemp]
GO

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_ExpireTemp
	@HoursOld int,
	@SettingsID int
AS

declare @ExpireBefore datetime
set @ExpireBefore = dateadd(hour, -@HoursOld, getdate())

delete from cs_ThemeConfigurationData_TEMP
where LastModified < @ExpireBefore
	and SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ThemeConfigurationData_ExpireTemp]  TO [public]
GO


/***********************************************
* Sproc: cs_ThemeConfigurationData_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ThemeConfigurationData_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ThemeConfigurationData_Get]
GO

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Get
	@ThemeName nvarchar(255),
	@SettingsID int,
	@SectionID int,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if (exists(select ThemeName from cs_ThemeConfigurationData_TEMP	where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID)) begin
		select *
		from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end else begin
		select *
		from cs_ThemeConfigurationData
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end
end else begin
	select *
	from cs_ThemeConfigurationData
	where ThemeName = @ThemeName
		and SettingsID = @SettingsID
		and SectionID = @SectionID
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ThemeConfigurationData_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_ThemeConfigurationData_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ThemeConfigurationData_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ThemeConfigurationData_Update]
GO

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Update
	@ThemeName nvarchar(255),
	@SettingsID int,
	@SectionID int,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if exists(select ThemeName from cs_ThemeConfigurationData_TEMP where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID)
	begin
		update cs_ThemeConfigurationData_TEMP
		set PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues,
			LastModified = getdate()
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end else begin
		insert into cs_ThemeConfigurationData_TEMP (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues, ThemeConfigurationDataTempID, LastModified) 
		values (@ThemeName, @SettingsID, @SectionID, @PropertyNames, @PropertyValues, @ThemeConfigurationDataTempID, getdate())
	end
end else begin
	if exists(select ThemeName from cs_ThemeConfigurationData where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID)
	begin
		update cs_ThemeConfigurationData
		set PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end else begin
		insert into cs_ThemeConfigurationData (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues) 
		values (@ThemeName, @SettingsID, @SectionID, @PropertyNames, @PropertyValues)
	end
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ThemeConfigurationData_Update]  TO [public]
GO


/***********************************************
* Sproc: cs_Threads_GetThreadSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Threads_GetThreadSet'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_GetThreadSet]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].[cs_Threads_GetThreadSet]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlCount ntext,
	@sqlPopulate ntext,
	@UserID int,
	@SettingsID int,
	@ReturnRecordCount bit,
	@IncludeCategories bit = 0
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int
DECLARE @GroupID int

-- Set sticky posts unsticky by limiting the scope of the query: the ideea is any user will clean up its stickies when it gets the chance
IF (@SectionID IS NOT NULL AND @SectionID >= 0)
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE SectionID = @SectionID AND UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID
ELSE
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1


-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ThreadID int
)

INSERT INTO #PageIndex (ThreadID)
EXEC sp_executesql @sqlPopulate

SELECT
	jT.*, U.*,
	HasRead = 0,
	jP.PostID,
	jP.Subject,
	jP.Body,
	jP.FormattedBody,
	jP.PostMedia,
	jP.PostType,
	UserName = jT.PostAuthor,
	jP.PropertyNames as PostPropertyNames, jP.PropertyValues as PostPropertyValues,
	jP.PostConfiguration
FROM 
	#PageIndex jPI
	JOIN cs_Threads jT ON jPI.ThreadID = jT.ThreadID
	JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.UserID and U.SettingsID = @SettingsID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter
	AND (U.IsIgnored = 0 OR U.UserID = @UserID)	-- Ensure that you are not getting threads by ignored users unless the ignored user is requesting them
ORDER BY
	IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name], jP.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
		JOIN cs_Posts_InCategories PIC ON jP.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND jP.PostLevel = 1 AND jP.SettingsID = @SettingsID
End

-- Update that the user has read this forum
IF @UserID > 0
BEGIN
	IF @SectionID > 0
		EXEC cs_Section_MarkRead @UserID, @SectionID, @SettingsID, @GroupID
END

SET ROWCOUNT @RowsToReturn

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
	EXEC sp_executesql @sqlCount


END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Threads_GetThreadSet]  TO [public]
GO


/***********************************************
* Sproc: cs_Threads_ThreadSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Threads_ThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_ThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_ThreadSet]
GO


Go
/***********************************************
* Sproc: cs_Threads_ThreadSet_Unanswered
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Threads_ThreadSet_Unanswered'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_ThreadSet_Unanswered]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_ThreadSet_Unanswered]
GO




/***********************************************
* Sproc: cs_Thread_Daily_Stats_Increment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Daily_Stats_Increment'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Daily_Stats_Increment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Daily_Stats_Increment]
GO

Create PROCEDURE [dbo].[cs_Thread_Daily_Stats_Increment]
(
	@SectionID as int,
	@ThreadID as int,
	@ViewCount as int
)
AS
BEGIN
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @day datetime

	Set @day = convert( char(10), GetDate(), 120 )

	-- update daily stats
	UPDATE
		tds
	SET
		tds.ViewCount = tds.ViewCount + @ViewCount
	FROM
		cs_Thread_Daily_Stats tds
	WHERE
		tds.SectionID = @SectionID
		AND tds.ThreadID = @ThreadID
		AND tds.[Day] = @day

	-- if there was nothing to update, add it to the table
	IF @@ROWCOUNT = 0
		-- new stats record
		INSERT INTO cs_Thread_Daily_Stats ([SectionID], [ThreadID], [Day], [ViewCount])
		VALUES (@SectionID, @ThreadID, @day, @ViewCount)

END
GO


grant execute on [dbo].[cs_Thread_Daily_Stats_Increment] to public
go
/***********************************************
* Sproc: cs_Thread_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Delete]
GO


CREATE PROCEDURE [dbo].[cs_Thread_Delete]
(
	@SettingsID int,
	@SectionID int,
	@ThreadID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostID INT
DECLARE @PostSubject NVARCHAR(256)

SET @PostID = 0
SET @PostSubject = ''

-- Get thread starter's post ID and subject
SELECT
	@PostID = p.PostID,
	@PostSubject = p.Subject
FROM
	cs_Threads t 
	LEFT JOIN cs_Posts AS p 
	ON t.ThreadID = p.ThreadID AND p.PostLevel = 1
WHERE
	t.ThreadID = @ThreadID AND 
	t.SectionID = @SectionID AND
	t.SettingsID = @SettingsID

DELETE FROM cs_PostAttachments WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts_Downloads WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID)
	
DELETE FROM cs_PostEditNotes WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts_InCategories WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)
	
DELETE FROM cs_PostsArchive WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadRating WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID AND ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_Forum_EmbeddedThreadUrl WHERE ThreadID = @ThreadID

DELETE FROM cs_Threads WHERE ThreadID = @ThreadID

-- Update Moderation Audit table
IF (@PostID IS NOT NULL AND @PostID > 0)
BEGIN
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: thread starter post has been permanently deleted on request. Thread ID: ' + CAST(@ThreadID AS NVARCHAR(30)) + '. Thread Name: ' + @PostSubject

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
END

-- Update forum's statistics?
IF (@ResetStatistics = 1)
BEGIN
	EXEC cs_system_ResetForumStatistics @SectionID

	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID
END

END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Thread_Delete] to public
go
/***********************************************
* Sproc: cs_Thread_GetTrackedCount
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_GetTrackedCount'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Thread_GetTrackedCount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Thread_GetTrackedCount]
GO

CREATE PROCEDURE [dbo].[cs_Thread_GetTrackedCount]
(
	@SettingsID int,
	@ThreadID int,
	@TrackedCount int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Set @TrackedCount = (Select Coalesce(Count(cs_TrackedThreads.UserID),0) FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID);
Select @TrackedCount;

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Thread_GetTrackedCount] TO PUBLIC
GO
/***********************************************
* Sproc: cs_thread_IsTracked
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_thread_IsTracked'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_thread_IsTracked]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_thread_IsTracked]
GO



CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_thread_IsTracked] to public
go
/***********************************************
* Sproc: cs_Thread_Next
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Next'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Next]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Next]
GO

/***********************************************
* Sproc: cs_Thread_Previous
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Previous'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Previous]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Previous]
GO

/***********************************************
* Sproc: cs_Thread_PrevNext
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_PrevNext'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_PrevNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_PrevNext]
GO



CREATE procedure [dbo].cs_Thread_PrevNext
(
	@PostID int,
	@NavigationType int,
	@SettingsID int
)
AS

DECLARE @ThreadDate datetime
DECLARE	@SectionID int
DECLARE	@ThreadID int


-- Get thread info
SELECT
	@ThreadDate = T.StickyDate,
	@SectionID = T.SectionID
FROM
	cs_Threads T INNER JOIN cs_Posts P ON T.ThreadID = P.ThreadID
WHERE
	P.PostID = @PostID AND
	P.SettingsID = @SettingsID


-- Compute prev/next thread
IF @NavigationType = 1	-- previous thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate < @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky DESC,
		StickyDate DESC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the beginning, no previous, so find last thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky DESC,
			StickyDate DESC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END
ELSE IF @NavigationType = 0	-- next thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate > @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky ASC,
		StickyDate ASC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the end, no next, so find first thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky ASC,
			StickyDate ASC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END

SELECT ThreadID = @ThreadID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Thread_PrevNext] to public
go
/***********************************************
* Sproc: cs_Thread_Rate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Rate]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_Thread_Rate_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Rate_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Rate_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Rate_Get]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_Thread_Status_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Thread_Status_Update'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Status_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Status_Update]
GO


CREATE PROCEDURE [dbo].cs_Thread_Status_Update 
(
	@ThreadID int,
	@Status int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @Status IS NOT NULL
BEGIN

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END
ELSE
BEGIN

	IF EXISTS (SELECT * FROM cs_Posts WHERE ThreadID = @ThreadID AND (PostStatus & 64) = 64)
		SET @Status = 1	-- if at least one reply is marked as an answer, mark the thread as answered
	ELSE
		IF EXISTS (SELECT * FROM cs_Posts WHERE ThreadID = @ThreadID AND (PostStatus & 128) = 128)
			SET @Status = 3	-- if at least one reply is marked as proposed answer, mark the thread as answered (not verified)
		ELSE
			SET @Status = 2	-- otherwise, mark the thread as unanswered

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

grant execute on [dbo].[cs_Thread_Status_Update] to public
go
/***********************************************
* Sproc: cs_UnsubscribeFromSection
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UnsubscribeFromSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UnsubscribeFromSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UnsubscribeFromSection]
GO

CREATE procedure dbo.cs_UnsubscribeFromSection
(
	@SubscriptionID uniqueidentifier,
	@SectionID int OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Include the check for DateUnsubscribed so that a user can only be unsubscribed once
	UPDATE [cs_SectionSubscriptions]
	SET DateUnsubscribed = GetDate(), IsConfirmed = 0
	WHERE SubscriptionID = @SubscriptionID AND DateUnsubscribed IS NULL
	
	SELECT @SectionID = SectionID FROM [cs_SectionSubscriptions] 
	WHERE SubscriptionID = @SubscriptionID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UnsubscribeFromSection] to public

/***********************************************
* Sproc: cs_UnsubscribeFromThread
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UnsubscribeFromThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UnsubscribeFromThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UnsubscribeFromThread]
GO

CREATE procedure dbo.cs_UnsubscribeFromThread
(
	@UserID int,
	@PostID	int,
	@SettingsID int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @ThreadID INT
	
	-- First get the post info
	SELECT 
		@ThreadID = ThreadID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID
		
	IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		-- the user is tracking this thread, delete this row
		DELETE FROM cs_TrackedThreads
		WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UnsubscribeFromThread] to public

/***********************************************
* Sproc: cs_UpdateForumGroupSortOrder
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UpdateForumGroupSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UpdateForumGroupSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UpdateForumGroupSortOrder]
GO
/***********************************************
* Sproc: cs_UrlRedirects_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UrlRedirects_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UrlRedirects_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UrlRedirects_Get]
GO


CREATE proc [dbo].[cs_UrlRedirects_Get]
(
	@UrlID	int = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		UrlID, Url, Description, Impressions
	from
		cs_UrlRedirects
	where
		UrlID = @UrlID OR (@UrlID = 0)
	order by
		UrlID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UrlRedirects_Get] to public
go

/***********************************************
* Sproc: cs_UrlRedirect_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UrlRedirect_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UrlRedirect_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UrlRedirect_CreateUpdateDelete]
GO


CREATE proc [dbo].[cs_UrlRedirect_CreateUpdateDelete]
(
	@UrlID			int out,
	@Url			nvarchar(4000),
	@Description	nvarchar(2000),
	@Action 		int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

--Create
IF @Action = 0
BEGIN
	INSERT INTO
		cs_UrlRedirects (Url, Description)
	VALUES
		(@Url, @Description)

	SET @UrlID = SCOPE_IDENTITY()
END
--Update
ELSE IF @Action = 1
BEGIN
	UPDATE cs_UrlRedirects SET
		Description = @Description,
		Url = @Url
	WHERE
		UrlID = @UrlID
END
--Delete
ELSE IF @Action = 2
BEGIN
	DELETE FROM
		cs_UrlRedirects
	WHERE
		UrlID = @UrlID
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UrlRedirect_CreateUpdateDelete] to public
GO
/***********************************************
* Sproc: cs_Urls_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Urls_Add'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Urls_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Urls_Add]

Go

Create Proc [dbo].cs_Urls_Add
(
	@UrlID int,
	@Url nvarchar(512)
)

as 
SET Transaction Isolation Level Read UNCOMMITTED

if not exists (Select UrlID From cs_Urls where UrlID = @UrlID)
Begin
	Insert cs_Urls (UrlID, Url) values (@UrlID, @Url)
End
go



grant execute on [dbo].[cs_Urls_Add] to public
go


/***********************************************
* Sproc: cs_Urls_RedirectLookup
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Urls_RedirectLookup'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Urls_RedirectLookup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Urls_RedirectLookup]
GO


create procedure [dbo].[cs_Urls_RedirectLookup]
    @UrlID        int
as
BEGIN
	SELECT 
		Url
	FROM
		cs_UrlRedirects
	WHERE
		UrlID = @UrlID


	UPDATE
		cs_UrlRedirects
	SET
		Impressions = Impressions + 1
	WHERE
		UrlID = @UrlID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Urls_RedirectLookup] to public
go
/***********************************************
* Sproc: cs_UserActivityNightlyJob
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserActivityNightlyJob'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserActivityNightlyJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserActivityNightlyJob]
GO

/***********************************************
* Sproc: cs_UserActivityReportRecords_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_UserFeed_DeleteFeed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserFeed_DeleteFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserFeed_DeleteFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserFeed_DeleteFeed]
GO

/***********************************************
* Sproc: cs_UserHasPostsAwaitingModeration
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserHasPostsAwaitingModeration'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserHasPostsAwaitingModeration]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserHasPostsAwaitingModeration]
GO


create  procedure [dbo].cs_UserHasPostsAwaitingModeration
(
	@UserName nvarchar(50),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Can the user moderate all forums?
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE UserName=@UserName AND SectionID=0)

		-- return ALL posts awaiting moderation
		IF EXISTS(SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 and SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	ELSE
		-- return only those posts in the forum this user can moderate
		IF EXISTS (SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 AND P.SectionID IN (SELECT SectionID FROM Moderators (nolock) WHERE UserName=@UserName and SettingsID = @SettingsID)  and F.SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserHasPostsAwaitingModeration] to public
go
/***********************************************
* Sproc: cs_UserInvitations_Expire
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitations_Expire'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_Expire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_Expire]
GO

CREATE PROCEDURE [dbo].cs_UserInvitations_Expire
	@DateInvited datetime
AS

delete from cs_UserInvitation
where DateInvited < @DateInvited
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitations_Expire]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitations_GetBeforeDate
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitations_GetBeforeDate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_GetBeforeDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_GetBeforeDate]
GO

CREATE PROCEDURE [dbo].cs_UserInvitations_GetBeforeDate
	@DateInvited datetime
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where DateInvited < @DateInvited
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitations_GetBeforeDate]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitations_GetByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitations_GetByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_GetByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_GetByUser]
GO


CREATE PROCEDURE [dbo].cs_UserInvitations_GetByUser
	@UserID int
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where UserID = @UserID
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserInvitations_GetByUser] to public
go

/***********************************************
* Sproc: cs_UserInvitation_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitation_Create'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Create]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_UserInvitation_Create
	@UserID int,
	@Email nvarchar(255),
	@DateInvited datetime,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@InvitationKey uniqueidentifier out
AS

set @InvitationKey = newid()

insert into cs_UserInvitation (InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues)
values (@InvitationKey, @UserID, @Email, @DateInvited, @PropertyNames, @PropertyValues)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Create]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitation_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitation_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Delete]
GO

CREATE PROCEDURE [dbo].cs_UserInvitation_Delete
	@InvitationKey uniqueidentifier
AS

delete from cs_UserInvitation
where InvitationKey = @InvitationKey
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Delete]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitation_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserInvitation_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Get]
GO

CREATE PROCEDURE [dbo].cs_UserInvitation_Get
	@InvitationKey uniqueidentifier
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where InvitationKey = @InvitationKey

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_UserPoints_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserPoints_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserPoints_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserPoints_Add]
GO

/***********************************************
* Sproc: cs_UserReadPost_MarkPostRead
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_UserReadPost_MarkPostRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserReadPost_MarkPostRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserReadPost_MarkPostRead]
GO

/***********************************************
* Sproc: cs_users_BackPort
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_BackPort'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_BackPort]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_BackPort]
GO


--CREATE proc [dbo].cs_users_BackPort
--(
--	@SettingsID int,
--	@UserName nvarchar(256),
--	@Password nvarchar(128) = null,
--	@PasswordSalt nvarchar(128) = null,
--	@PasswordFormat int = null
--)
--as
--SET Transaction Isolation Level Read UNCOMMITTED
--if(@Password is null)
--Begin
--	Select a.Password, a.PasswordSalt, a.PasswordFormat  FROM cs_vw_Users_FullUser c, aspnet_Membership a where a.UserId = c.UserId and SettingsID = @SettingsID and @UserName = UserName
--End
--Else
--Begin
--	Declare @UserID uniqueidentifier
--	Select @UserID = MembershipId FROM cs_vw_Users_FullUser where UserName = @UserName and SettingsID = @SettingsID
--	
--	Update aspnet_Membership
--	Set Password = @Password, PasswordSalt = @PasswordSalt, PasswordFormat = @PasswordFormat
--	Where MembershipId = @UserID
--		
--End

go


-- grant execute on [dbo].[cs_users_BackPort] to public
go
/***********************************************
* Sproc: cs_users_count_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_count_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_count_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_count_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




--cs_users_count_Get 0, 10, 0, 0, null, 0, 1, 0, 0, 1000
CREATE          PROCEDURE [dbo].cs_users_count_Get
(
	@UsernameFilter nvarchar(128),
	@FilterIncludesEmailAddress bit = 0,
	@UserAccountStatus smallint = 1,
	@IncludeHiddenUsers bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @TotalUsers int

BEGIN

-- Do we need to return a record count?
-- *************************************
  IF ((@UsernameFilter IS NULL) OR (@UsernameFilter = ''))
    SET @TotalUsers = (SELECT count(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND (UserName LIKE @UsernameFilter OR Email LIKE @UsernameFilter))



END




  SELECT @TotalUsers
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_users_count_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_users_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].cs_users_Get
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@sqlPopulateCount ntext,
	@SearchText nvarchar(256),
	@ReturnModerationCounters bit = 0,
	@SettingsID int
)
AS
BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1
SET @RowsToReturn = @PageSize * (@PageIndex + 1)

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	UserID int not null
)

Exec sp_executesql @sqlPopulateCount, N'@SearchText nvarchar(256), @recordCount int output', @SearchText = @SearchText, @recordCount = @TotalUsers output

/* First set the rowcount to the total possible rows to return */
SET ROWCOUNT @RowsToReturn

INSERT INTO #PageIndexForUsers (UserID)
Exec sp_executesql @sqlPopulate, N'@SearchText nvarchar(256)', @SearchText = @SearchText

/* now set it to the page size */
SET ROWCOUNT @PageSize

/* Get the user details */
IF @ReturnModerationCounters = 1
begin
	/* I don't want to see the null removed from the aggregate message */
	set ANSI_WARNINGS OFF

	SELECT
		U.*
		, coalesce(mod.ApprovePost, 0) AS ApprovePost
		, coalesce(mod.EditPost, 0) AS EditPost
		, coalesce(mod.MovePost, 0) AS MovePost
		, coalesce(mod.DeletePost, 0) AS DeletePost
		, coalesce(mod.LockPost, 0) AS LockPost
		, coalesce(mod.UnlockPost, 0) AS UnlockPost
		, coalesce(mod.MergePost, 0) AS MergePost
		, coalesce(mod.SplitPost, 0) AS SplitPost
		, coalesce(mod.EditUser, 0) AS EditUser
		, coalesce(mod.UnmoderateUser, 0) AS UnmoderateUser
		, coalesce(mod.ModerateUser, 0) AS ModerateUser
		, coalesce(mod.BanUser, 0) AS BanUser
		, coalesce(mod.UnbanUser, 0) AS UnbanUser
		, coalesce(mod.ResetPassword, 0) AS ResetPassword
		, coalesce(mod.ChangePassword, 0) AS ChangePassword
		, coalesce(mod.PostIsAnnouncement, 0) AS PostIsAnnouncement
		, coalesce(mod.PostIsNotAnnoucement, 0) AS PostIsNotAnnoucement
		, coalesce(mod.UnApprovePost, 0) AS UnApprovePost
		/* (we do not seem to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID) */
	FROM
		cs_vw_Users_FullUser U (nolock)
	INNER JOIN
		#PageIndexForUsers jPI ON U.UserID = jPI.UserID
	LEFT OUTER JOIN (
		SELECT
			ma.UserID
			, count(case ma.ModerationAction when 1  then ma.UserID end) as [ApprovePost]
			, count(case ma.ModerationAction when 2  then ma.UserID end) as [EditPost]
			, count(case ma.ModerationAction when 3  then ma.UserID end) as [MovePost]
			, count(case ma.ModerationAction when 4  then ma.UserID end) as [DeletePost]
			, count(case ma.ModerationAction when 5  then ma.UserID end) as [LockPost]
			, count(case ma.ModerationAction when 6  then ma.UserID end) as [UnlockPost]
			, count(case ma.ModerationAction when 7  then ma.UserID end) as [MergePost]
			, count(case ma.ModerationAction when 8  then ma.UserID end) as [SplitPost]
			, count(case ma.ModerationAction when 9  then ma.UserID end) as [EditUser]
			, count(case ma.ModerationAction when 10 then ma.UserID end) as [UnmoderateUser]
			, count(case ma.ModerationAction when 11 then ma.UserID end) as [ModerateUser]
			, count(case ma.ModerationAction when 12 then ma.UserID end) as [BanUser]
			, count(case ma.ModerationAction when 13 then ma.UserID end) as [UnbanUser]
			, count(case ma.ModerationAction when 14 then ma.UserID end) as [ResetPassword]
			, count(case ma.ModerationAction when 15 then ma.UserID end) as [ChangePassword]
			, count(case ma.ModerationAction when 16 then ma.UserID end) as [PostIsAnnouncement]
			, count(case ma.ModerationAction when 17 then ma.UserID end) as [PostIsNotAnnoucement]
			, count(case ma.ModerationAction when 18 then ma.UserID end) as [UnApprovePost]
		FROM cs_ModerationAudit ma
		WHERE
			ma.SettingsID = @SettingsID
		GROUP BY
			ma.UserID
	) as mod ON U.UserID = mod.UserID
	WHERE
		jPI.IndexID > @PageLowerBound AND jPI.IndexID < @PageUpperBound
		and U.SettingsID = @SettingsID
	ORDER BY
		IndexID

	set ANSI_WARNINGS ON

end ELSE begin

	SELECT
		U.*
		/* (we do not seem to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID) */
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers pindex
	WHERE 
		U.UserID = pindex.UserID AND
		pindex.IndexID > @PageLowerBound AND
		pindex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		IndexID

end

set rowcount 0

/* Return the record count */
SELECT @TotalUsers

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_users_Get] TO [public]
GO


/***********************************************
* Sproc: cs_Users_GetUserIDByFilter
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Users_GetUserIDByFilter'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Users_GetUserIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Users_GetUserIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Users_GetUserIDByFilter
--	Returns a list of filtered UserIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Users_GetUserIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@UserSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of user set
		SET @UserSetSize = CONVERT(int, @FilterValue)

		-- limit number of users to work with (non-positive = ALL)
		IF @UserSetSize > 0
			SET ROWCOUNT @UserSetSize

		-- get posts to work with
		SELECT		UP.UserID
		FROM		cs_UserProfile UP
		WHERE		UP.SettingsID = @SettingsID
		ORDER BY	PointsUpdated			-- start with "stalest" users

		-- limit has been used; reset to default
		IF @UserSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Users_GetUserIDByFilter] to [public]

/***********************************************
* Sproc: cs_users_Online
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_Online'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_Online]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_Online]
GO


CREATE PROCEDURE [dbo].cs_users_Online
(
	@PastMinutes int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Get users 
	SELECT
		U.*
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.LastActivity  > DateAdd(minute, -@PastMinutes, GetDate()) AND
		U.SettingsID = @SettingsID
	ORDER BY UserName
	
	-- Get anonymous 
	SELECT
		UserID,
		LastActivity = LastLogin,
		LastAction
	FROM
		cs_AnonymousUsers where SettingsID = @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_users_Online] to public
go
/***********************************************
* Sproc: cs_users_UsersInRole_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_UsersInRole_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_UsersInRole_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_UsersInRole_Get]
GO

/***********************************************
* Sproc: cs_users_ValidateAnswer
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_users_ValidateAnswer'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_ValidateAnswereAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_ValidateAnswereAnswer]
GO


/***********************************************
* Sproc: cs_Users_WhoDownloadedPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Users_WhoDownloadedPost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Users_WhoDownloadedFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Users_WhoDownloadedFile]
GO

CREATE PROCEDURE [dbo].cs_Users_WhoDownloadedFile
(
	@PageIndex int,
	@PageSize int,
	@PostID int,
	@ReturnRecordCount bit = 0,
	@SettingsID int,
	@StartDate datetime,
	@EndDate datetime
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	LatestDownloadDate datetime,
	TotalDownloads int,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(distinct U.UserID) FROM cs_vw_Users_FullUser U, cs_Posts_Downloads D WHERE D.UserID = U.UserID and D.PostID = @PostID and U.SettingsID = @SettingsID and D.DownloadDate between @StartDate and @EndDate)

-- Special case depending on what the user wants and how they want it ordered by
-- *************************************

INSERT INTO #PageIndexForUsers (UserID, LatestDownloadDate, TotalDownloads)
SELECT U.UserID, Max(D.DownloadDate), count(*)
FROM cs_vw_Users_FullUser U, cs_Posts_Downloads D 
WHERE D.UserID = U.UserID 
	and D.PostID = @PostID 
	and U.SettingsID = @SettingsID 
	and D.DownloadDate between @StartDate and @EndDate
GROUP BY U.UserID
ORDER BY Max(DownloadDate)

-- Get the user details
SELECT
	*, @PostID as PostID
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers pindex
WHERE 
	U.UserID = pindex.UserID AND
	pindex.IndexID > @PageLowerBound AND
	pindex.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	IndexID
END

-- Return the record count if necessary

IF (@ReturnRecordCount = 1)
  SELECT @TotalUsers

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Users_WhoDownloadedFile  to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Count
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_Anonymous_Count'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Anonymous_Count]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Anonymous_Count]
GO


CREATE  procedure [dbo].cs_User_Anonymous_Count
(
	@TimeWindow int,
	@SettingsID int,
	@AnonymousUserCount int out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @StatDate datetime

	-- Clean up the anonymous users table
	DELETE cs_AnonymousUsers WHERE LastLogin < DateAdd(minute, -@TimeWindow, GetDate())	 and  SettingsID = @SettingsID

	-- Get a count of anonymous users
	SET @AnonymousUserCount = (SELECT count(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID)

	-- Do we need to update our forum statistics?
	SET @StatDate = (SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID)
	IF (SELECT TotalAnonymousUsers FROM cs_statistics_Site WHERE DateCreated = @StatDate and SettingsID = @SettingsID) < @AnonymousUserCount 
		UPDATE
			cs_statistics_Site
		SET 
			TotalAnonymousUsers = @AnonymousUserCount
		WHERE
			DateCreated = @StatDate and SettingsID = @SettingsID

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Anonymous_Count] to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_Anonymous_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Anonymous_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Anonymous_Update]
GO







CREATE     PROCEDURE [dbo].cs_User_Anonymous_Update
(
	@UserID char(36),
	@LastActivity datetime,
	@LastAction nvarchar(1024) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Does the user already exist?
	IF EXISTS (SELECT UserID FROM cs_AnonymousUsers WHERE UserID = @UserID and SettingsID = @SettingsID)

		UPDATE 
			cs_AnonymousUsers
		SET 
			LastLogin = @LastActivity,
			LastAction = @LastAction
		WHERE
			UserID = @UserID and SettingsID = @SettingsID

	ELSE

		INSERT INTO
			cs_AnonymousUsers
			(UserID, LastLogin, LastAction, SettingsID) 
		VALUES
			(@UserID, @LastActivity, @LastAction, @SettingsID)

END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Anonymous_Update] to public
go
/***********************************************
* Sproc: cs_user_CreateUpdateDelete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_user_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_user_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_user_CreateUpdateDelete]
GO


CREATE  procedure [dbo].cs_user_CreateUpdateDelete 
(
	@cs_UserID int out,
	@UserID uniqueidentifier = null,
	@UserName   nvarchar (64) = '',
	@Email nvarchar(256) = '',
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '',
	@CreateDate	datetime = null,
	@IsApproved bit = 1,
	@ForumView   int = 0,
	@TimeZone   float = 0.0,
	@PostRank   binary(1) = 0x0,
	@PostSortOrder   int = 0,
	@IsAvatarApproved   smallint  = 0,
	@ForceLogin   bit   = 0,
	@ModerationLevel  smallint  = 0,
	@EnableThreadTracking  smallint  = 0,
	@EnableDisplayUnreadThreadsOnly smallint  = 0,
	@EnableAvatar    smallint  = 0,
	@EnableDisplayInMemberList  smallint  = 1,
	@EnablePrivateMessages  smallint  = 1,
	@EnableOnlineStatus smallint  = 1,
	@EnableEmail smallint  = 1,
	@EnableHtmlEmail   smallint  = 1,
	@EnableFavoriteSharing bit = 1,
	@AllowSiteToContact bit = 0,
	@AllowSitePartnersToContact bit = 0,
	@SettingsID int,
	@Action    int,
	@UpdateAllSettingsID bit = 0
)
AS

--This sproc returns an int that indicates the CreateUserStatus enum value:
--	UnknownFailure = 0
--	Created = 1
--	DuplicateUsername = 2
--	DuplicateEmailAddress = 3
--	InvalidFirstCharacter = 4
--	DisallowedUsername = 5
--	Updated = 6
--	Deleted = 7
--	InvalidQuestionAnswer = 8
--	InvalidPassword = 9


IF @CreateDate is null
	SET @CreateDate = GetDate()
-- first, we need to check if the username is a dup

-- Are we creating a user?
IF @Action = 0
BEGIN
	IF (@IsAnonymous = 1)
	BEGIN
		SELECT @cs_UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName AND IsAnonymous = 1 AND SettingsID = @SettingsID
		
		-- Check if the anonymous user already exists
		IF @cs_UserID IS NOT NULL
		Begin
			SELECT 1
			RETURN
		End
		
	END
	ELSE
	BEGIN
		--A WSHA User can exist in multiple sites. We need to find all the site's this user will have access to
		-- and create the coresponding records
		Declare @ApplicationName nvarchar(256)
		Select @ApplicationName = ApplicationName FROM cs_SiteSettings where SettingsID = @SettingsID

		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsAnonymous], [CreateDate], [IsApproved])
		VALUES(@UserID, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '', @UserName, @Email, @IsAnonymous, @CreateDate, @IsApproved)
		IF (@@ERROR <> 0)
		BEGIN
			Select 0
			RETURN
		END

		Select @cs_UserID = SCOPE_IDENTITY()

		INSERT INTO cs_UserProfile ( [UserID], [TimeZone], [TotalPosts], 	[PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableEmail], [EnableHtmlEmail], [IsIgnored], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues], [EnableFavoriteSharing], [AllowSiteToContact], [AllowSitePartnersToContact])
		Select @cs_UserID, @TimeZone, 0, @PostSortOrder, @PostRank, @IsAvatarApproved, @ModerationLevel, @EnableThreadTracking,  @EnableDisplayUnreadThreadsOnly,  @EnableAvatar,   @EnableDisplayInMemberList, @EnablePrivateMessages,   @EnableOnlineStatus,  @EnableEmail, @EnableHtmlEmail, @IsIgnored,  @UserID, SettingsID, @PropertyNames, @PropertyValues, @EnableFavoriteSharing, @AllowSiteToContact, @AllowSitePartnersToContact
		FROM cs_SiteSettings where ApplicationName = @ApplicationName
		
		Select 1
		RETURN
	END
END
ELSE
BEGIN

	UPDATE
		cs_UserProfile
	SET
		TimeZone = @TimeZone,
		PostRank = @PostRank,
		PostSortOrder = @PostSortOrder,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		IsAvatarApproved = @IsAvatarApproved,
		ModerationLevel = @ModerationLevel,
		EnableThreadTracking = @EnableThreadTracking,
		EnableDisplayUnreadThreadsOnly = @EnableDisplayUnreadThreadsOnly,
		EnableAvatar = @EnableAvatar,
		EnableDisplayInMemberList = @EnableDisplayInMemberList,
		EnablePrivateMessages = @EnablePrivateMessages,
		EnableOnlineStatus = @EnableOnlineStatus,
		EnableEmail = @EnableEmail,
		EnableHtmlEmail = @EnableHtmlEmail,
		EnableFavoriteSharing = @EnableFavoriteSharing,
		AllowSiteToContact = @AllowSiteToContact,
		AllowSitePartnersToContact = @AllowSitePartnersToContact,
		IsIgnored = @IsIgnored
	WHERE
		UserID = @cs_UserID
		AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
	

  
	-- Some properties will be created/defaulted by SHS Create User.
	-- These values will be updated by Membership.UpdateUser as well. 
	-- Here we just update the properties which fall outside of MembershipUser
	-- First Update the cs_vw_forums_Users table

	UPDATE
		cs_Users
	SET
		Email = @Email,
		IsAnonymous = @IsAnonymous,
		IsApproved = @IsApproved,
		AppUserToken = @AppUserToken,
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		MembershipID = @UserID

	SELECT 6
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_user_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_User_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Delete]
GO


CREATE procedure [dbo].[cs_User_Delete]
(
	@UserID					int,
	@ReassignUserName		nvarchar(256)
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- locals
	DECLARE	@ApplicationGuid	uniqueidentifier
	DECLARE	@UserGuid			uniqueidentifier
	DECLARE	@ReassignUserID		int


	-- lookup application, user
	SELECT	@ApplicationGuid = ASP.ApplicationId, @UserGuid = ASP.UserId
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID


	-- lookup reassign user
	SELECT	@ReassignUserID = CS.UserID
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	LoweredUserName = LOWER(@ReassignUserName)
		AND	ApplicationId = @ApplicationGuid


	-- does the reassign user exist?
	IF (@ReassignUserID IS NULL)
	BEGIN
		SELECT 2 -- InvalidReassignUserName
		RETURN
	END


	-- reassign user appears valid
	BEGIN TRANSACTION


	-- be sure posts are set to be reindexed BEFORE they are reassigned
	EXECUTE cs_Posts_ReindexByUser @UserID
	IF (@@ERROR <> 0) GOTO Failure


	-- reassign content
	UPDATE	cs_InkData
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_ModerationAudit
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments_TEMP
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Posts
	SET		UserID = @ReassignUserID,
			PostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Posts_Deleted_Archive
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostsArchive
	SET		UserName = CONVERT(nvarchar(64), @ReassignUserName)
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Sections
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		UserID = @ReassignUserID,
			PostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentArticleAuthorID = @ReassignUserID,
			MostRecentArticleAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentArticleAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure
    
	-- delete content
	DELETE
	FROM	cs_FavoritePosts
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FavoriteSections
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ModerationAudit
	WHERE	ModeratorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_PostRating
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_SectionsRead
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Statistics_User
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ThreadRating
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ThreadsRead
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_TrackedSections
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_TrackedThreads
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserAvatar
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserInvitation
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserReadPost
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Votes
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	csm_EmailIds
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Posts_Downloads
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_SectionMembers
	WHERE 	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Users_OpenID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Friends_xref
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Friends_xref
	WHERE	FriendUserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FriendRequests
	WHERE	RequestorUserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FriendRequests
	WHERE	RequesteeUserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

    -- Deleting user announcements has to occur before
    -- other messages are reassigned
    EXEC cs_Messaging_DeleteProfileAnnouncementsForUser @UserID  
    IF (@@ERROR <> 0) GOTO Failure

    -- Deleting user activity messages has to occur before
    -- other messages are reassigned
    EXEC cs_Messaging_DeleteActivityMessagesForUser @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
    UPDATE cs_Messaging_ProfileMessages
    SET    UserId = @ReassignUserID
    WHERE  UserId = @UserID
    IF (@@ERROR <> 0) GOTO Failure

    UPDATE cs_Messaging_ConversationParticipants
    SET    ParticipantId = @ReassignUserID
    WHERE  ParticipantId = @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
    UPDATE cs_Messaging_Messages
    SET    AuthorId = @ReassignUserID
    WHERE  AuthorId = @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
	-- delete user
	DELETE
	FROM	cs_Moderators
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserProfile
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Users
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_UsersInRoles
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Profile
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Membership
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Users
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Delete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_user_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_user_Get'

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Get]
GO

CREATE PROCEDURE [dbo].cs_User_Get
(
	@UserID int,
	@UserName nvarchar(64) = null,
	@IsOnline bit = 0,
	@LastAction nvarchar(1024) = N'',
	@SettingsID int
)
AS
BEGIN
	SET Transaction Isolation Level Read UNCOMMITTED
	DECLARE @MembershipID uniqueidentifier

	-- Looking up by UserName?
	IF @UserName IS NOT NULL
	BEGIN

		SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName AND SettingsID = @SettingsID

		SELECT
			U.*
		FROM
			cs_vw_Users_FullUser U (nolock)
		WHERE
			U.UserName = @UserName AND U.SettingsID = @SettingsID
	END

	-- Looking up the user by ID
	ELSE
	BEGIN

		IF (@UserID = 0)
			SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = N'Anonymous' and SettingsID = @SettingsID

		-- Get the user details
		SELECT
			U.*
		FROM
			cs_vw_Users_FullUser U (nolock)
		WHERE
			U.UserID = @UserID and U.SettingsID = @SettingsID
	END

	IF @IsOnline = 1
	BEGIN
		EXEC cs_system_UserIsOnline @UserID = @UserID, @LastAction = @LastAction, @SettingsID = @SettingsID
	END
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_User_Get] to public
go
/***********************************************
* Sproc: cs_User_GetByEmail
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_GetByEmail'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_GetByEmail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_GetByEmail]
GO






create procedure [dbo].cs_User_GetByEmail
(
	@Email		nvarchar(64),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	UserID
FROM
	cs_vw_Users_FullUser
WHERE
	Email = @Email and SettingsID = @SettingsID





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_GetByEmail] to public
go
/***********************************************
* Sproc: cs_User_GetOpmlFeedsFolders
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_GetOpmlFeedsFolders'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_GetOpmlFeedsFolders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_GetOpmlFeedsFolders]
GO

/***********************************************
* Sproc: cs_User_PasswordAnswer_Change
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_PasswordAnswer_Change'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_PasswordAnswer_Change]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_PasswordAnswer_Change]
GO


/***********************************************
* Sproc: cs_User_Rename
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_Rename'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Rename]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Rename]
GO


CREATE procedure [dbo].[cs_User_Rename]
(
	@UserID					int,
	@DesiredUserName		nvarchar(256),
	@IgnoreDisallowedNames	bit = 0
)
AS
	-- do we care about disallowed names?
	IF (@IgnoreDisallowedNames = 0)
		-- is username allowed?
		IF EXISTS (SELECT * FROM cs_DisallowedNames WHERE @DesiredUserName LIKE REPLACE(DisallowedName, '*', '%'))
		BEGIN
			SELECT 3 -- DisallowedUserName
			RETURN
		END


	-- is the desired username available?
	IF EXISTS (SELECT * FROM aspnet_Users WHERE LoweredUserName = LOWER(@DesiredUserName) AND ApplicationId = (SELECT ApplicationId FROM aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID WHERE CS.UserID = @UserID) AND UserId <> (SELECT CS2.MembershipID FROM cs_Users CS2 WHERE CS2.UserID = @UserID)) -- username is taken
	BEGIN
		SELECT 2 -- DuplicateUserName
		RETURN
	END


	-- username is available, begin update
	BEGIN TRANSACTION


	-- handle ASP.NET membership system
	UPDATE	aspnet_Users
	SET	UserName = @DesiredUserName, LoweredUserName = LOWER(@DesiredUserName)
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle users
	UPDATE	cs_Users
	SET	UserName = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle posts
	UPDATE	cs_Posts
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle post archive
	UPDATE	cs_PostsArchive
	SET	UserName = @DesiredUserName
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle sections
	UPDATE	cs_Sections
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle threads
	UPDATE	cs_Threads
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_Threads
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle blogs
	UPDATE	cs_weblog_Weblogs
	SET	MostRecentArticleAuthor = @DesiredUserName
	WHERE	MostRecentArticleAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_weblog_Weblogs
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- be sure posts are reindexed
	EXECUTE cs_Posts_ReindexByUser @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Rename] TO PUBLIC
GO
/***********************************************
* Sproc: cs_User_ToggleSettings
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_User_ToggleSettings'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_ToggleSettings]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_ToggleSettings]
GO


CREATE   procedure [dbo].[cs_User_ToggleSettings]
(
	@UserID int,
	@ModerationLevel int,
	@UserAccountStatus int,
	@ForceLogin bit = 0,
	@IsAvatarApproved bit,
	@ModeratorID int,
	@SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE	@CurrentUserAccountStatus	int
	SELECT	@CurrentUserAccountStatus = UserAccountStatus
	FROM	cs_Users
	WHERE	UserID = @UserID

	UPDATE 
		cs_Users
	SET
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		UserID = @UserID 

	DECLARE	@CurrentModerationLevel	int
	SELECT	@CurrentModerationLevel = ModerationLevel
	FROM	cs_UserProfile
	WHERE	UserID = @UserID
	AND		SettingsID = @SettingsID

	UPDATE
		cs_UserProfile
	SET
		ModerationLevel = @ModerationLevel,
		IsAvatarApproved = @IsAvatarApproved
	WHERE
		UserID = @UserID AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

	IF (@ModerationLevel != @CurrentModerationLevel)		-- moderation level has changed
	BEGIN
		IF (@ModerationLevel = 0)
			exec cs_system_ModerationAction_AuditEntry 11, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 10, @ModeratorID, null, @UserID, null, @SettingsID
	END

	IF (@UserAccountStatus != @CurrentUserAccountStatus)	-- user account status has changed
	BEGIN
		IF @UserAccountStatus = 1
			exec cs_system_ModerationAction_AuditEntry 13, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 12, @ModeratorID, null, @UserID, null, @SettingsID
	END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_ToggleSettings] to public
go


/***********************************************
* Sproc: cs_Vote_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Vote_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Vote_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Vote_Create]
GO


create procedure [dbo].cs_Vote_Create (
  @PostID int,
  @UserID int,
  @Vote nvarchar(2),
  @SettingsID int
)
AS
IF NOT EXISTS (
    SELECT
        PostID 
    FROM 
        cs_VoteSummary
    WHERE 
        PostID = @PostID AND Vote = @Vote and SettingsID = @SettingsID
)
BEGIN
        INSERT INTO 
            cs_VoteSummary
        VALUES
        (
            @PostID,
            @Vote,
            1,
	    @SettingsID
        )

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
END
ELSE
BEGIN
	IF EXISTS(SELECT UserID FROM cs_Votes WHERE PostID = @PostID AND UserID = @UserID)
		-- Already voted
		RETURN

        UPDATE 
          cs_VoteSummary
        SET 
          VoteCount  =  VoteCount + 1
        WHERE 
          PostID = @PostID AND
          Vote = @Vote and SettingsID = @SettingsID

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Vote_Create] to public
go
/***********************************************
* Sproc: cs_Vote_GetSummary
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Vote_GetSummary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Vote_GetSummary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Vote_GetSummary]
GO

CREATE   procedure [dbo].cs_Vote_GetSummary (
	@PostID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
  SELECT
	Vote,
	VoteCount
  FROM
	cs_VoteSummary
  WHERE
	PostID = @PostID

  SELECT
	UserID,
	Vote
  FROM
	cs_Votes
  WHERE
	PostID = @PostID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Vote_GetSummary] to public
go
/***********************************************
* Sproc: cs_WeblogContactRequests_Add
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_WeblogContactRequests_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_WeblogContactRequests_Add]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_WeblogContactRequests_Add]
GO

CREATE PROCEDURE [dbo].[cs_WeblogContactRequests_Add]
(
    @Id int OUTPUT,
    @WeblogId int,
    @Subject nvarchar(256) = '',
    @Name nvarchar(256) = '',
    @EmailAddress nvarchar(256) = '',
    @Body ntext,
    @IsModerated bit,
    @CreationDate datetime
)
AS
BEGIN

	INSERT INTO [cs_Weblog_ContactRequests]
	(
		WeblogId,
		Subject,
		Name,
		EmailAddress,
		CreationDate,
		Body,
		IsModerated
	)
	VALUES
	(
		@WeblogId,
		@Subject,
		@Name,
		@EmailAddress,
		@CreationDate,
		@Body,
		@IsModerated
	)

	SET @Id = scope_identity()
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_WeblogContactRequests_Add] TO PUBLIC
GO

/***********************************************
* Sproc: cs_WeblogContactRequests_Approve
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_WeblogContactRequests_Approve'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_WeblogContactRequests_Approve]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_WeblogContactRequests_Approve]
GO

CREATE PROCEDURE [dbo].[cs_WeblogContactRequests_Approve]
(
    @Id int,
    @WeblogId int
)
AS
BEGIN
	UPDATE [cs_Weblog_ContactRequests] 
	SET IsModerated = 0	
	WHERE Id = @Id AND WeblogId = @WeblogId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_WeblogContactRequests_Approve] TO PUBLIC
GO

/***********************************************
* Sproc: cs_WeblogContactRequests_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_WeblogContactRequests_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_WeblogContactRequests_Delete]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_WeblogContactRequests_Delete]
GO

CREATE PROCEDURE [dbo].[cs_WeblogContactRequests_Delete]
(
    @Id int,
    @WeblogId int
)
AS
BEGIN
	DELETE FROM [cs_Weblog_ContactRequests] WHERE Id = @Id AND WeblogId = @WeblogId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_WeblogContactRequests_Delete] TO PUBLIC
GO

/***********************************************
* Sproc: cs_WeblogContactRequests_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_WeblogContactRequests_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_WeblogContactRequests_Get]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_WeblogContactRequests_Get]
GO

CREATE PROCEDURE [dbo].[cs_WeblogContactRequests_Get]
(
    @WeblogId int,
    @IsModerated bit = NULL,
    @PageIndex int,
    @PageSize int,
    @TotalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	CREATE TABLE #Results
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		Id int NOT NULL
	)

	INSERT INTO #Results
		(Id)
	SELECT
		CR.Id
	FROM
		[dbo].[cs_Weblog_ContactRequests] CR
	WHERE
		CR.WeblogId = @WeblogId
		AND (@IsModerated IS NULL OR CR.IsModerated = @IsModerated)
	ORDER BY
		CR.CreationDate DESC

	SET @TotalCount = @@ROWCOUNT

	SET @rowsToReturn = @PageSize * (@PageIndex + 1)
	SET @pageLowerBound = @PageSize * @PageIndex
	SET @pageUpperBound = @pageLowerBound + @PageSize + 1

	SET ROWCOUNT @rowsToReturn

	SELECT
		CR.Id,
		CR.WeblogId,
		CR.Subject,
		CR.Name,
		CR.EmailAddress,
		CR.CreationDate,
		CR.Body,
		CR.IsModerated
	FROM
		[dbo].[cs_Weblog_ContactRequests] CR
		INNER JOIN #Results R ON CR.Id = R.Id
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

	DROP TABLE #Results
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_WeblogContactRequests_Get] TO PUBLIC
GO
/***********************************************
* Sproc: cs_WeblogContactRequest_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_WeblogContactRequest_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_WeblogContactRequest_Get]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_WeblogContactRequest_Get]
GO

CREATE PROCEDURE [dbo].[cs_WeblogContactRequest_Get]
(
    @Id int
)
AS
BEGIN

	SELECT
		CR.Id,
		CR.WeblogId,
		CR.Subject,
		CR.Name,
		CR.EmailAddress,
		CR.CreationDate,
		CR.Body,
		CR.IsModerated
	FROM
		[dbo].[cs_Weblog_ContactRequests] CR
	WHERE
		CR.Id = @Id

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_WeblogContactRequest_Get] TO PUBLIC
GO
/***********************************************
* Sproc: cs_weblog_DeleteStaleSpamComments
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_DeleteStaleSpamComments'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_DeleteStaleSpamComments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_DeleteStaleSpamComments]
GO
CREATE PROCEDURE [dbo].[cs_weblog_DeleteStaleSpamComments]
(
	@SettingsID int,
	@ExpirationDays int = 2,
	@Increment int = 250 /* new parameter that is default */
)
AS
BEGIN

	/* temporarily store posts to delete */
	set nocount on

	declare @curdate datetime
		, @purgeDate datetime
		, @bottom int
		, @top int
		, @possibleSpamPurgeDate datetime
		, @PossibleSpamExpirationDays int
		, @rc int

	create table #Posts (
		id int identity(1, 1) not null primary key clustered
		, PostID int not null
	)

	select
		@curdate = GETDATE()
		/* ensuring @ExpirationDays has a value */
		, @ExpirationDays = COALESCE( @ExpirationDays, 2 )
		/* set a purgedate based on the days in the past to truncate from */
		, @purgeDate = dateadd(day, -1 * @ExpirationDays, @curdate )
		/* ensuring @Increment has a value */
		, @Increment = COALESCE( @Increment, 250 )
		/*	seed the top at zero.  This is so logic for determining the next 'top' is cleaner */
		, @top = 0
		/* initial rowcount */
		, @rc = 0
		/* range checking.  If ExpirationDays exceeds half of the max value of INT, then make it the max value of INT */
		, @PossibleSpamExpirationDays = case when @ExpirationDays >= cast(0x7fffffff as int) / 2
			then cast(0x7fffffff as int) else @ExpirationDays * 2 end
		/* set a purgedate based on the days in the past to truncate from */
		, @possibleSpamPurgeDate = dateadd(day, -1 * @PossibleSpamExpirationDays, @curdate )

	print 'Calculating spam posts to be deleted: ' + convert(char(19), getdate(), 120)

	/* inserting for definite spam */
	INSERT INTO #Posts (PostID)
	SELECT P.PostID FROM cs_Posts P (nolock)
	INNER JOIN
		cs_Sections S (nolock) on P.SettingsID = S.SettingsID and P.SectionID = S.SectionID
	WHERE
		S.SettingsID = @SettingsID
		AND (
			( S.ApplicationType = 1	/* only weblogs */
            AND P.ApplicationPostType IN (4, 8)	) /* only comments/trackbacks */
			OR
			( S.ApplicationType = 13 /* only media gallery */
            AND P.ApplicationPostType = 1 ) /* only comments */
		)
		AND	(P.PostStatus & 2) = 2			/* only posts marked as DEFINITE spam */
		AND P.IsApproved = 0				/* make sure they are not approved */
		AND P.PostLevel > 1					/* ensure they are replies only */
		AND	P.PostDate < @purgeDate			/* only posts that have been around for a while */

	set @rc = @rc + @@ROWCOUNT

	/* inserting possible spam from weblog posts */
	INSERT INTO #Posts (PostID)
	SELECT P.PostID FROM cs_Posts P (nolock)
	INNER JOIN
		cs_Sections S (nolock) on P.SettingsID = S.SettingsID and P.SectionID = S.SectionID
	WHERE
		S.SettingsID = @SettingsID
		AND (
			( S.ApplicationType = 1	/* only weblogs */
            AND P.ApplicationPostType IN (4, 8)	) /* only comments/trackbacks */
			OR
			( S.ApplicationType = 13 /* only media gallery */
            AND P.ApplicationPostType = 1 ) /* only comments */
		)
		AND	(P.PostStatus & 4) = 4			/* only posts marked as POSSIBLE spam */
		AND P.IsApproved = 0				/* make sure they are not approved */
		AND P.PostLevel > 1					/* ensure they are replies only */
		AND	P.PostDate < @possibleSpamPurgeDate	/* only posts that have been around for a while */

	set @rc = @rc + @@ROWCOUNT

	print 'Total number of spam posts that will be deleted: ' + cast(@rc as varchar) + ': ' + convert(char(19), getdate(), 120)

	while ( 1 = 1 )
	begin

		select
			@top = @top + @Increment
			, @bottom = @top + 1 - @Increment
		
		print 'Deleting from index ' + cast(@bottom as varchar) + ' to ' + cast(@top as varchar) + ': ' + convert(char(19), getdate(), 120)

		delete p
		from cs_Posts P
		inner join
			#Posts px on P.PostID = px.PostID
		where
			px.id between @bottom and @top

		if @@ROWCOUNT < @Increment begin break end

	end

	drop table #Posts

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_weblog_DeleteStaleSpamComments] to public
go

/***********************************************
* Sproc: cs_weblog_Feedback_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Feedback_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Feedback_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Feedback_Get]
GO
/***********************************************
* Sproc: cs_weblog_PostsByMonth
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_PostsByMonth'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostsByMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostsByMonth]
GO


CREATE proc [dbo].cs_weblog_PostsByMonth
(
	@SectionID int,
	@Year int,
	@Month int
)
as
begin

	SET Transaction Isolation Level Read UNCOMMITTED
	declare @tYear smallint, @tMonth tinyint

	-- let's convert to make sure these are in the right range
	select @tYear = convert(smallint, @Year), @tMonth = convert(tinyint, @Month)

	select
		@Month as [Month], @Year as [Year], cast(t.[Day] as int) as [Day], t.[PostCount] as [Count]
	from
		dbo.cs_vw_weblog_PostByYearMonth t
	where
		t.[SectionID] = @SectionID
		and t.[Year] = @tYear
		and t.[Month] = @tMonth
		and t.[Day] < 255 -- we store the month level data where Day == 255
	order by [Day] asc

end

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonth] to public
go
/***********************************************
* Sproc: cs_weblog_PostsByMonthList
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_PostsByMonthList'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostsByMonthList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostsByMonthList]
GO


CREATE proc [dbo].cs_weblog_PostsByMonthList
(
	@SectionID int
)
as
begin

	SET Transaction Isolation Level Read UNCOMMITTED

	select
		CAST(t.[Month] as int) as [Month], cast(t.[Year] as int) as [Year], 1 as [Day], t.[PostCount] as [Count]
	from
		dbo.cs_vw_weblog_PostByYearMonth t
	where
		t.[SectionID] = @SectionID
		and t.[Year] > 0
		and t.[Month] > 0
		and t.[Day] = 255
	order by [Year] desc, [Month] desc

end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonthList] to public
go
/***********************************************
* Sproc: cs_weblog_PostSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostSet]
GO





CREATE PROCEDURE dbo.cs_weblog_PostSet
(
	@SectionID int,
	@PostID	int,
	@PostName nvarchar(512) = null,
	@PageIndex int,
	@PageSize int,
	@UserID int,
	@ReturnFullThread bit,
	@IncludeCategories bit,
	@TotalRecords int output
)
AS

BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int


-- Get the ThreadID
if(@PostName is null)
Begin
	SELECT
		@ThreadID = ThreadID
	FROM 
		cs_Posts
	WHERE 
		PostID = @PostID and SectionID = @SectionID
End
Else
Begin
	SELECT
		@ThreadID = P.ThreadID, @PostID = P.PostID
	FROM 
		cs_Posts P
	WHERE 
		P.SectionID = @SectionID and P.PostName = @PostName

End

--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, 
		P.SortOrder, P.Subject, P.PostDate, P.IsApproved, P.IsLocked, P.IsIndexed, P.TotalViews, 
		P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, 
		P.AggViews, P.PostPropertyNames, P.PostPropertyValues, P.PostConfiguration,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, T.TotalReplies as Replies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostName, P.UserTime,P.ApplicationPostType, P.Points as PostPoints,
		P.PostAuthor as Username,
		EditNotes = null,
		AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize,[FileName], P.Created, P.Height, P.Width,
		IsModerator = 0,
		HasRead = 0 -- not used,
		, P.PostStatus, P.SpamScore
	FROM 
		cs_vw_PostsWithAttachmentDetails P (nolock),
		cs_Threads T
	WHERE 
		P.PostID = @PostID AND
		T.ThreadID = P.ThreadID



--Do we want/need categories
	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End


--Are we going to honor paging?
if @ReturnFullThread = 0
Begin
	-- First set the rowcount
	DECLARE @RowsToReturn int
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1


	-- Create a temp table to store the select results
	CREATE TABLE #PageIndex 
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		PostID int
	)

	INSERT INTO #PageIndex (PostID)
	SELECT P.PostID 
	FROM cs_Posts P (nolock)
	WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel > 1 and P.ApplicationPostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY PostDate

	Set @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.ApplicationPostType, P.UserTime,
		P.Points as PostPoints,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		#PageIndex.*,
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0,
		IsModerator = 0, 
		HasRead = 0 -- not used
		, P.PostStatus, P.SpamScore
	FROM 
		cs_Posts P (nolock),
		cs_Threads T,
		#PageIndex
	WHERE 
		P.PostID = #PageIndex.PostID AND
		T.ThreadID = P.ThreadID AND
		#PageIndex.IndexID > @PageLowerBound AND
		#PageIndex.IndexID < @PageUpperBound
	ORDER BY
		IndexID

	--SELECT @TotalRecords = count(*) FROM #PageIndex  

	DROP TABLE #PageIndex
END
ELSE --No Paging, just get all of the comments/trackbacks
BEGIN
	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.ApplicationPostType, P.UserTime,
		P.Points as PostPoints, P.PostStatus, P.SpamScore,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0, 
		IsModerator = 0, 
		HasRead = 0 -- not used
	FROM 
		cs_Posts P,
		cs_Threads T
	WHERE 
		P.ThreadID = T.ThreadID AND
		T.ThreadID = @ThreadID AND P.PostLevel > 1 AND P.IsApproved = 1 
		AND P.PostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY
		PostID

	SELECT @TotalRecords = Count(P.PostID) FROM cs_Posts P (nolock) WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel <> 1 and P.PostType <> 16

END

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_Posts_GetPostSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Posts_GetPostSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Posts_GetPostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Posts_GetPostSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_Post_Create
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Post_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Create]
GO

CREATE PROCEDURE [dbo].[cs_weblog_Post_Create]
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit = 0,
	@IsTracked bit = 0,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime,
	@UserTime datetime,
	@UserHostAddress nvarchar(32),
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@SpamScore int = 0,
	@PostStatus int = 0,
	@PostID int out
) 
AS
SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ThreadID int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @IsComment bit

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType)
	Begin
		Return 2
	End
End

if(@BlogPostType = 1 OR @BlogPostType = 2)
	SET @IsComment = 0
Else
	SET @IsComment = 1

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

If @UserTime IS NULL
	-- ensuring UserTime is not null
	SET @UserTime = COALESCE( @PostDate, GETDATE() )

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		UserID = @UserID

-- Do we care about duplicates?
IF @AllowDuplicatePosts = 0 and @IsComment = 1
BEGIN
	DECLARE @IsDuplicate bit
	exec cs_system_DuplicatePost @UserID, @Body, @DuplicateIntervalInMinutes, @SettingsID, @IsDuplicate output

	IF @IsDuplicate = 1
	BEGIN
		SET @PostID = -1	
		RETURN 1-- Exit with error code.
	END
END

-- we need to get the SectionID, if the ParentID is not null (there should be a SectionID)
IF @SectionID = 0 AND @ParentID <> 0
	SELECT 
		@SectionID = SectionID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @ParentID

--Set @ModeratedForum = (@PostConfig & 16)
SELECT 
	@EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID


IF @ParentID <> 0
BEGIN

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID


	IF @PostStatus & 2 = 2 /* This is spam */
	begin

		execute [dbo].[cs_SpamPostArchive]
			@SourceProcedure = N'cs_weblog_Post_Create'
			/* from cs_Post_CreateUpdate */
			, @SectionID = @SectionID
			, @ParentID = @ParentID
			, @AllowDuplicatePosts = @AllowDuplicatePosts
			, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
			, @Subject = @Subject
			, @UserID = @UserID
			, @PostAuthor = @PostAuthor
			, @Body = @Body
			, @FormattedBody = @FormattedBody
			, @EmoticonID = @EmoticonID
			, @IsLocked = @IsLocked
			, @IsSticky = @IsSticky
			, @IsApproved = @IsApproved
			, @StickyDate = @StickyDate
			, @PostType = @PostType
			, @PostMedia = @PostMedia
			, @PostDate = @PostDate
			, @UserHostAddress = @UserHostAddress
			, @PropertyNames = @PropertyNames
			, @PropertyValues = @PropertyValues
			, @SettingsID = @SettingsID
			, @IsTracked = @IsTracked
			, @PostID = @PostID
			, @ThreadID = @ThreadID
			, @PostConfiguration = @PostConfig
			, @UpdateSectionStatistics = NULL /* @UpdateSectionStatistics */
			, @UserTime = @UserTime
			, @ApplicationPostType = @PostType
			, @PostName = @PostName
			, @ThreadStatus = NULL /* @ThreadStatus */
			, @Points = 0 /* @Points */
			, @PostDisplayName = NULL /* @PostDisplayName */
			, @AutoApprove = NULL /* @AutoApprove */
		
			/* from cs_weblog_Post_Create */
			, @TitleUrl = @TitleUrl
			, @PostConfig = @PostConfig
			, @BlogPostType = @BlogPostType
			, @Categories = @Categories
			, @SpamScore = @SpamScore
			, @PostStatus = @PostStatus

		return 3 -- error to indicate this was spam so we can do something with it
	end
END



-- Determine if this post will be approved.
-- If the forum is NOT moderated, then the post will be approved by default.
SET NOCOUNT ON
BEGIN TRAN

IF @ParentID = 0	-- parameter indicating this is a top-level post (for a new thread)
BEGIN
	-- First we create a new ThreadID.

	-- check the StickyDate to ensure it's not null
	IF @StickyDate < @PostDate
		SET @StickyDate = @PostDate

	INSERT cs_Threads 	
		( SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID, 
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID )
	VALUES
		( @SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@PostAuthor,
		@UserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		@IsLocked,
		@IsApproved,
		@IsSticky,
		@StickyDate,
		@EmoticonID,
		@SettingsID )

	-- Get the new ThreadID
	SELECT @ThreadID = SCOPE_IDENTITY()
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore
		
	        )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore )
		

	-- Get the new PostID
	SELECT 
		@PostID = SCOPE_IDENTITY()


	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = SCOPE_IDENTITY() 


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1 
	BEGIN		
		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			--MostRecentPostAuthor = @PostAuthor, << We do not track comments
			--MostRecentPostAuthorID = @UserID, << We do not track comments
			--MostRecentPostID = @PostID, << We do not track Comments
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE  p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
			--IsLocked = @IsLocked,
			--StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			--ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID
	END
	ELSE
	BEGIN
		-- Recalculate the number of moderated posts for this blog
		UPDATE cs_Sections
		SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
		WHERE SectionID = @SectionID AND SettingsID = @SettingsID

	END

	-- Clean up ThreadsRead (this should work very well now)
	-- Not tracking in blogs
--	DELETE
--		cs_ThreadsRead
--	WHERE
--		ThreadID = @ThreadID 
--		AND UserID <> @UserID

END

--Increments posts totals ignoring settings id
IF @EnablePostStatistics = 1 AND @UserID > 0 AND @IsApproved = 1
BEGIN
	EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
END

IF(@BlogPostType = 1 OR @BlogPostType = 2)
BEGIN
	IF @IsTracked = 1
		BEGIN
		INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
		VALUES	( @ThreadID, @UserID, @SettingsID )
	END
	
	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
END

--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

	
COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Post_Create] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Post_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Delete]
GO


CREATE PROCEDURE [dbo].[cs_weblog_Post_Delete]
(
	@SectionID int,
	@PostID int,
	@UserID int,
	@BlogPostType tinyint = 1,
	@SettingsID int
) 
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @ThreadID int
Select @ThreadID = ThreadID FROM cs_Posts where PostID = @PostID

if(@BlogPostType = 4 or @BlogPostType = 8)
Begin
	Delete FROM cs_Posts where PostID = @PostID
End
ELSE
Begin

	Delete FROM cs_Posts_InCategories where PostID = @PostID and SettingsID = @SettingsID
	Delete FROM cs_PostAttachments where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_ThreadRating where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Referrals where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_TrackedThreads where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Posts where ThreadID = @ThreadID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_Threads where ThreadID = @ThreadID

End


exec cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID

-- Update thread statistics
exec cs_system_ResetThreadStatistics @ThreadID

-- Recalculate the number of moderated posts for this blog
UPDATE cs_Sections
SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
WHERE SectionID = @SectionID AND SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_weblog_Post_Delete] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Post_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Get]
GO




CREATE PROCEDURE dbo.cs_weblog_Post_Get --11, 36, 0, 1, 0
(

	@PostID	int,
	@IncludeCategories bit,
	@IsApprovedFilter bit,
	@SettingsID int
)
AS
BEGIN

DECLARE	@SectionID int
DECLARE @ThreadID int 
DECLARE @SortOrder int
DECLARE @IsApproved bit


SELECT 
	@SectionID = SectionID,
	@ThreadID = ThreadID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and  SettingsID = @SettingsID


SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues,
	P.PostConfiguration, P.UserTime, P.PostName,P.ApplicationPostType,
	P.Points as PostPoints,
	T.*, U.*,
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	HasRead = 0,
	EditNotes = null, -- (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = 0,  -- (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],P.Created, P.Height, P.Width,
	IsModerator = 0, -- (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID),
	Replies = T.TotalReplies, -- (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = 0,
	IsTracked = Convert(bit,0) -- Convert(bit, (Select Count(*) FROM cs_TrackedThreads where UserID = @UserID and ThreadID = P.ThreadID))
	, P.PostStatus, P.SpamScore
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND P.SettingsID = @SettingsID and T.SettingsID = @SettingsID AND
	U.SettingsID = @SettingsID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.UserID AND
	P.IsApproved <> case @IsApprovedFilter when 1 then 0 else -1 END

	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_Post_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_Post_Update
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Post_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Update]
GO






CREATE  PROCEDURE [dbo].cs_weblog_Post_Update
(
	@PostID	int,
	@SectionID int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsApproved     bit = 0,
	@IsTracked      bit = 0,
	@EditedBy	int,
	@PostMedia int = 0, 
	@Excerpt nvarchar(500) = null,
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@UserTime datetime,
	@PostDate datetime,
	@PostStatus int = 0,
	@SpamScore int = 0
)
AS

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType and p.PostID <> @PostID)
	Begin
		Return 2
	End
End

	DECLARE @ThreadID int
	DECLARE @ParentID int
	--DECLARE @PostDate datetime

	Select @ThreadID = ThreadID, @ParentID = ParentID FROM cs_Posts where PostID = @PostID

	If @UserTime IS NULL
		-- ensuring UserTime is not null
		SET @UserTime = COALESCE( @PostDate, GETDATE() )

	-- this sproc updates a post (called from the moderate/admin page)
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		IsApproved = @IsApproved,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostDate = @PostDate,
		PostName = @PostName,
		UserTime = @UserTime,
		PostConfiguration = @PostConfig,
		ApplicationPostType = @BlogPostType,
		PostMedia = @PostMedia,
		PostStatus = @PostStatus,
		SpamScore = @SpamScore
		
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID


	IF(@PostID = @ParentID)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	ELSE 
	BEGIN
		-- This is a comment being updated. Recalculate the number of moderated posts for this blog
		UPDATE cs_Sections
		SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
		WHERE SectionID = @SectionID AND SettingsID = @SettingsID
	END


	-- Allow thread to update sticky properties.
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		-- Get the thread and postdate this applies to
		SELECT 
			@ThreadID = ThreadID,
			@PostDate = PostDate 
		FROM 
			cs_Posts 
		WHERE 
			PostID = @PostID and SettingsID = @SettingsID

		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @PostDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID		
		END
	END

	IF(@BlogPostType = 1 OR @BlogPostType = 2)
	BEGIN


		IF @IsTracked = 1
		BEGIN
			-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
			IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @EditedBy )
				INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
			VALUES	( @ThreadID, @EditedBy, @SettingsID)
		END
		Else
		Begin
			DELETE FROM cs_TrackedThreads where ThreadID = @ThreadID and UserID = @EditedBy and SettingsID = @SettingsID
		End


	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
	END


		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
		WHERE
			ThreadID = @ThreadID

	--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Post_Update] to public
go

/***********************************************
* Sproc: cs_weblog_Search
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search]
GO

/***********************************************
* Sproc: cs_weblog_Search_PostReindex
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search_PostReindex]
GO




/***********************************************
* Sproc: cs_weblog_Threads_GetThreadSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Threads_GetThreadSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_TrackedThreadsByUser
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_TrackedThreadsByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_TrackedThreadsByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_TrackedThreadsByUser]
GO



CREATE PROCEDURE dbo.cs_weblog_TrackedThreadsByUser
(
	@SectionID int,
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		T.*, U.*,P.PostName, P.UserTime, P.ApplicationPostType, P.PostConfiguration,
		P.Points as PostPoints,
		T.IsLocked,
		T.IsSticky,
		Username = P.PostAuthor,
		EditNotes = '',
		AttachmentFilename = null, -- ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		Replies = 0,-- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
		IsModerator = 0, --(SELECT count(UserID) from cs_Moderators where UserID = @UserID),
		HasRead = 0, -- not used
		P.PostStatus, P.SpamScore
FROM
		dbo.cs_TrackedThreads TT INNER JOIN
		dbo.cs_Threads T ON TT.ThreadID = T.ThreadID INNER JOIN
		dbo.cs_Posts P (nolock) ON T.ThreadID = P.ThreadID INNER JOIN
		dbo.cs_vw_Users_FullUser U ON TT.UserID = U.UserID
WHERE
		(TT.SettingsID = @SettingsID) 
		AND (TT.UserID = @UserID) 
		AND (T.SectionID = @SectionID) 
		AND (P.PostLevel = 1) 
		AND (P.IsApproved = 1)


END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_weblog_TrackedThreadsByUser to public
go

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_TrackedThreadsByUser]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_UpdateContentHistory
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_UpdateContentHistory'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateContentHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_UpdateContentHistory]
GO



-- TO ADD existing blog data
--Insert cs_weblog_Weblogs (SectionID)
--Select SectionID FROM cs_Sections where applicationtype = 1


CREATE Proc [dbo].cs_weblog_UpdateContentHistory
(
	@SectionID int,
	@BlogPostTypeFilter tinyint = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
If @BlogPostTypeFilter = 1
BEGIN

	Declare @MostRecentPostID int
	Declare @MostRecentPostDate datetime
	Declare @MostRecentPostName nvarchar(256)
	Declare @MostRecentPostAuthorID int
	Declare @MostRecentPostAuthorName nvarchar(256)
	Declare @MostRecentPostSubject nvarchar(256)
	Declare @PostCount int

	--Get Post Info
	Select Top 1 
		@MostRecentPostID = P.PostID, 
		@MostRecentPostDate =  P.PostDate, 
		@MostRecentPostAuthorID = UserID, 
		@MostRecentPostAuthorName = PostAuthor, 
		@MostRecentPostName = PostName,
		@MostRecentPostSubject = Subject 
	FROM cs_Posts P
	where P.ApplicationPostType = 1 and P.SectionID = @SectionID and P.IsApproved = 1 Order by PostDate Desc

	Select @PostCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 1)

	update cs_weblog_Weblogs
	Set
		MostRecentPostID = isnull(@MostRecentPostID,0),
		MostRecentPostDate = isnull(@MostRecentPostDate,getdate()),
		MostRecentPostAuthorID = isnull(@MostRecentPostAuthorID,0),
		MostRecentPostAuthor = isnull(@MostRecentPostAuthorName,''),
		MostRecentPostName = @MostRecentPostName,
		MostRecentPostSubject = isnull(@MostRecentPostSubject,''),
		PostCount = @PostCount
	Where SectionID = @SectionID
END
Else If @BlogPostTypeFilter = 2
BEGIN

	Declare @MostRecentArticleID int
	Declare @MostRecentArticleDate datetime
	Declare @MostRecentArticleName nvarchar(256)
	Declare @MostRecentArticleAuthorID int
	Declare @MostRecentArticleAuthorName nvarchar(256)
	Declare @MostRecentArticleSubject nvarchar(256)
	Declare @ArticleCount int

--Get Article Info
	Select Top 1 
		@MostRecentArticleID = P.PostID, 
		@MostRecentArticleDate = P.PostDate, 
		@MostRecentArticleAuthorID = UserID, 
		@MostRecentArticleAuthorName = PostAuthor, 
		@MostRecentArticleName = PostName,
		@MostRecentArticleSubject = Subject
	FROM cs_Posts P
	where P.ApplicationPostType = 2 and P.SectionID = @SectionID and P.IsApproved = 1 Order by PostDate Desc

	Select @ArticleCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 2)


	update cs_weblog_Weblogs
	Set
		MostRecentArticleID = isnull(@MostRecentArticleID,0),
		MostRecentArticleDate = isnull(@MostRecentArticleDate,getdate()),
		MostRecentArticleAuthorID = isnull(@MostRecentArticleAuthorID,0),
		MostRecentArticleAuthor = isnull(@MostRecentArticleAuthorName,''),
		MostRecentArticleName = @MostRecentArticleName,
		MostRecentArticleSubject = isnull(@MostRecentArticleSubject,''),
		ArticleCount = @ArticleCount
	Where SectionID = @SectionID
End
ELSE If @BlogPostTypeFilter = 4
BEGIN
	Declare @CommentCount int
	Select @CommentCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 4)
	update cs_weblog_Weblogs
	Set
		CommentCount = @CommentCount
	Where SectionID = @SectionID
END
ELSE If @BlogPostTypeFilter = 8
BEGIN
	Declare @TrackBackCount int
	Select @TrackBackCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 8)
	update cs_weblog_Weblogs
	Set
		TrackbackCount = @TrackBackCount
	Where SectionID = @SectionID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_UpdateContentHistory] to public
go
/***********************************************
* Sproc: cs_weblog_UpdateWeblogRecentContent_Job
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_UpdateWeblogRecentContent_Job'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateWeblogRecentContent_Job]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[cs_weblog_UpdateWeblogRecentContent_Job]
GO

Create Proc [dbo].[cs_weblog_UpdateWeblogRecentContent_Job]
(
	@SettingsID int
)
as

SET Transaction Isolation Level Read UNCOMMITTED

set nocount on

Update w
Set
	w.MostRecentPostID = P.PostID,
	w.MostRecentPostDate = P.UserTime,
	w.MostRecentPostName = P.PostName,
	w.MostRecentPostAuthorID = P.UserID,
	w.MostRecentPostAuthor = P.PostAuthor,
	w.MostRecentPostSubject = P.Subject
FROM
	cs_weblog_Weblogs w
inner join (
		Select Max(px.PostID) as PostID, px.SectionID
		FROM cs_Posts px
		where px.ApplicationPostType = 1 and px.IsApproved = 1 and px.UserTime <= getdate() and px.SettingsID = @SettingsID
		Group by px.SectionID
	) sub
	ON w.SectionID = sub.SectionID
inner join
	cs_Posts P on P.PostID = sub.PostID
where
	w.SettingsID = @SettingsID



--We may be able to can the articles part
Update w
Set
	w.MostRecentArticleID = P.PostID ,
	w.MostRecentArticleDate = P.UserTime,
	w.MostRecentArticleName = P.PostName,
	w.MostRecentArticleAuthorID = P.UserID,
	w.MostRecentArticleAuthor = P.PostAuthor,
	w.MostRecentArticleSubject = P.Subject
FROM
	cs_weblog_Weblogs w
inner join (
		Select Max(p.PostID) as PostID, p.SectionID
		FROM cs_Posts p
		where p.ApplicationPostType = 2 and p.IsApproved = 1 and p.UserTime <= getdate() and p.SettingsID = @SettingsID
		Group by p.SectionID
	) sub
	ON w.SectionID = sub.SectionID
inner join
	cs_Posts P on P.PostID = sub.PostID
where
	w.SettingsID = @SettingsID


--Update Count Items
update w
set
	w.PostCount = p.[PostCount]
	, w.ArticleCount = p.[ArticleCount]
	, w.CommentCount = p.[CommentCount]
	, w.TrackbackCount = p.[TrackbackCount]
from
	cs_weblog_Weblogs w
inner join (
	Select
		px.SectionID
		, sum(case when px.ApplicationPostType = 1 then 1 else 0 end) [PostCount]
		, sum(case when px.ApplicationPostType = 2 then 1 else 0 end) [ArticleCount]
		, sum(case when px.ApplicationPostType = 4 then 1 else 0 end) [CommentCount]
		, sum(case when px.ApplicationPostType = 8 then 1 else 0 end) [TrackbackCount]
	FROM
		cs_Posts px
	where
		px.SettingsID = @SettingsID
		AND px.IsApproved = 1
	group by
		px.SectionID
) as p
ON
	w.SectionID = p.SectionID
where
	w.SettingsID = @SettingsID


-- Update Weblog Section records.
-- NOTE: Other applications update the Section table stats via cs_system_UpdateForum, called from cs_Post_CreateUpdate
UPDATE s
SET
	s.TotalPosts = isnull((Select Count(*) FROM cs_Posts p where p.SettingsID = s.SettingsID and p.SectionID = s.SectionID and p.IsApproved = 1), 0),
	s.TotalThreads = isnull((Select Count(*) FROM cs_Posts p where p.SettingsID = s.SettingsID and p.SectionID = s.SectionID and p.IsApproved = 1 and p.PostLevel = 1), 0),
	-- For weblogs, only count feedback that is not approved (ignore posts/articles)
	s.PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SettingsID = s.SettingsID and p.SectionID = s.SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
FROM
	cs_Sections s
WHERE
	s.SettingsID = @SettingsID
	and s.ApplicationType = 1


-- Update any hubs that have weblogs
UPDATE
	H
SET
	H.MostRecentPostID = W.MostRecentPostID,
	H.MostRecentPostAuthorID = W.MostRecentPostAuthorID,
	H.MostRecentPostSubject = W.MostRecentPostSubject,
	H.MostRecentPostAuthor = W.MostRecentPostAuthor,
	H.MostRecentPostDate = W.MostRecentPostDate
FROM
	cs_Sections H
inner join (
		Select S.HubSectionID, S.SectionID FROM cs_Sections S
		where S.ApplicationType = 1 and S.HubSectionID > 0 and S.SettingsID = @SettingsID
		Group by S.SectionID, S.HubSectionID
	) sub ON H.SectionID = sub.HubSectionID
inner join
	cs_weblog_Weblogs W
	ON W.SectionID = sub.SectionID
where
	H.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_weblog_UpdateWeblogRecentContent_Job] to public
go

/***********************************************
* Sproc: cs_weblog_Weblogs_Get
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_weblog_Weblogs_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Weblogs_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Weblogs_Get]
GO




CREATE        PROCEDURE [dbo].cs_weblog_Weblogs_Get
(
	@SettingsID	int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
-- Return all the forums

SELECT 
	F.[SectionID], F.[SettingsID], F.[IsActive], F.[ParentID], F.[GroupID], F.[Name], F.[NewsgroupName], F.[Description], F.[DateCreated], F.[Url], F.[IsModerated], F.[DaysToView], F.[SortOrder], F.[TotalPosts], F.[TotalThreads], F.[DisplayMask], F.[EnablePostStatistics], F.[EnablePostPoints], F.[EnableAnonymousPosting], F.[MostRecentThreadID], F.[MostRecentThreadReplies], F.[PostsToModerate], F.[ForumType], F.[IsSearchable], F.[ApplicationType], F.[ApplicationKey], 
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.[DefaultLanguage], F.[DiskUsage], W.*,
	null as	LastUserActivity, F.IsPublic, F.HubSectionID
		
FROM
	cs_Sections F, cs_weblog_Weblogs W
WHERE
	F.SettingsID = @SettingsID AND
	 ApplicationType = 1 AND F.SectionID = W.SectionID


exec cs_Section_Permissions_Get @SettingsID, 0, 1









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Weblogs_Get] to public
go
/***********************************************
* Sproc: cs_Wiki_AddPage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_AddPage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_AddPage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_AddPage]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_AddPage]
(
    @pageId int OUTPUT,
    @wikiId int,
    @userId int,
    @parentPageId int = NULL,
    @title nvarchar(256),
    @pageKey nvarchar(256),
    @body ntext,
    @formattedBody ntext,
    @tagXml ntext,
    @isPublished bit,
    @ratingCount int,
    @ratingSum int,
    @lastModifiedUtcDate datetime, 
    @revisionCount int = 1, 
    @isLocked bit = 0,
    @isIndexed bit = 0
)
AS
BEGIN
	IF @parentPageId = -1
		SET @parentPageId = NULL

	INSERT INTO
		cs_Wiki_Pages
		(
			WikiId,
			UserId,
			ParentPageId,
			Title,
			PageKey,
			Body,
			FormattedBody,
			IsPublished,
			RatingCount,
			RatingSum,
			LastModifiedUtcDate, 
			RevisionCount, 
			IsLocked,
			IsIndexed
		)
	VALUES
	(
		@wikiId,
		@userId,
		@parentPageId,
		@title,
		@pageKey,
		@body,
		@formattedBody,
		@isPublished,
		@ratingCount,
		@ratingSum,
		@lastModifiedUtcDate,
		@revisionCount, 
		@isLocked,
		@isIndexed
	)

	SET @pageId = scope_identity()

	-- If PageKey is null/blank, then use PageID as the default for now
	IF ((@pageKey is NULL) OR (LEN(@pageKey) = 0))
	BEGIN
		UPDATE cs_Wiki_Pages
		SET PageKey = CAST(@pageId AS nvarchar(256))
		WHERE PageId = @pageId
	END

	EXECUTE cs_Wiki_UpdatePageTags @pageId, @tagXml
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_AddPage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_AddPageComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_AddPageComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_AddPageComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_AddPageComment]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_AddPageComment]
(
    @pageCommentId int OUTPUT,
    @pageId int,
    @userId int,
    @body ntext,
    @formattedBody ntext,
    @ratingCount int,
    @ratingSum int,
    @publishedUtcDate datetime
)
AS
BEGIN
	INSERT INTO
		cs_Wiki_PageComments
		(
			PageId,
			UserId,
			Body,
			FormattedBody,
			RatingCount,
			RatingSum,
			PublishedUtcDate
		)
	VALUES
	(
		@pageId,
		@userId,
		@body,
		@formattedBody,
		@ratingCount,
		@ratingSum,
		@publishedUtcDate
	)

	SET @pageCommentId = scope_identity()
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_AddPageComment] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_AddPageViews
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_AddPageViews'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_AddPageViews]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_AddPageViews]
GO

Create Proc [dbo].[cs_Wiki_AddPageViews]
(
	@pageId int,
	@viewCount int
)

as
begin

	SET Transaction Isolation Level Read UNCOMMITTED
	
	Update
		cs_Wiki_Pages
	Set 
		TotalViews = TotalViews + @viewCount
	Where
		PageId = @pageId

end
go
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

grant execute on [dbo].[cs_Wiki_AddPageViews] to public
go
/***********************************************
* Sproc: cs_Wiki_AddPermission
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_AddPermission'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_AddPermission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_AddPermission]
GO

CREATE  procedure [dbo].cs_Wiki_AddPermission
(
	@WikiId 	int,
	@RoleId		uniqueidentifier,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@SettingsId	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	
	DECLARE @ApplicationType smallint
	SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Wiki'
	
	IF (@WikiId <> -1) 
	begin
		IF EXISTS (SELECT WikiId FROM cs_Wiki_Permissions WHERE WikiId = @WikiId AND RoleId = @RoleId)
			exec cs_Wiki_UpdatePermission @WikiId, @RoleId, @AllowMask, @DenyMask, @SettingsId
		ELSE
			INSERT INTO 
				cs_Wiki_Permissions (WikiId, RoleId, AllowMask, DenyMask)
			VALUES	(
					@WikiId,
					@RoleId,
					@AllowMask,
					@DenyMask
				)
	
		IF NOT EXISTS(SELECT * FROM cs_ProductPermissions WHERE SettingsID = @SettingsId and RoleID = @RoleId and ApplicationType = @ApplicationType)
			INSERT INTO cs_ProductPermissions (SettingsID, RoleID, AllowMask, DenyMask, ApplicationType)
				VALUES (@SettingsId, @RoleId, 0x0, 0x0, @ApplicationType)
	end
	ELSE
	begin
		IF NOT EXISTS(SELECT * FROM cs_ProductPermissions WHERE SettingsID = @SettingsId and RoleID = @RoleId and ApplicationType = @ApplicationType)
			INSERT INTO cs_ProductPermissions (SettingsID, RoleID, AllowMask, DenyMask, ApplicationType)
				VALUES (@SettingsId, @RoleId, @AllowMask, @DenyMask, @ApplicationType)
		ELSE
			exec cs_Wiki_UpdatePermission @WikiId, @RoleId, @AllowMask, @DenyMask, @SettingsId
	end

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_AddPermission] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Wiki_AddWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_AddWiki'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_AddWiki]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_AddWiki]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_AddWiki]
(
    @wikiId int OUTPUT,
    @hubId int = NULL,
    @name nvarchar(256),
    @description nvarchar(1000),
    @applicationKey nvarchar(256),
    @isEnabled bit,
    @lastModifiedUtcDate datetime
)
AS
BEGIN
	IF @hubId = -1
		SET @hubId = NULL

	INSERT INTO
		cs_Wiki_Wikis
		(
			HubId,
			Name,
			Description,
			ApplicationKey,
			IsEnabled,
			LastModifiedUtcDate
		)
	VALUES
	(
		@hubId,
		@name,
		@description,
		@applicationKey,
		@isEnabled,
		@lastModifiedUtcDate
	)

	SET @wikiId = scope_identity()
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_AddWiki] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_DeletePage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_DeletePage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_DeletePage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_DeletePage]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_DeletePage]
(
    @pageId int,
	@deleteChildPages bit
)
AS
BEGIN

	IF (@deleteChildPages = 0)
	BEGIN
		-- Select parent page of the page to be deleted
		DECLARE @ParentPageID int
		SELECT @ParentPageID=ParentPageId FROM cs_Wiki_Pages WHERE PageId = @pageId

		-- Update child pages to assume the parent of the deleted page
		UPDATE
			cs_Wiki_Pages
		SET
			ParentPageId = @ParentPageID
		WHERE
			ParentPageId = @pageId
	END
	ELSE
	BEGIN
		-- Set child pages to be unpublished (Deleted)
		UPDATE
			cs_Wiki_Pages
		SET
			IsPublished = 0
		WHERE
			ParentPageId = @pageId
	END

	UPDATE
		cs_Wiki_Pages
	SET
		IsPublished = 0
	WHERE
		PageId = @pageId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_DeletePage] TO PUBLIC
GO


/***********************************************
* Sproc: cs_Wiki_DeletePageComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_DeletePageComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_DeletePageComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_DeletePageComment]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_DeletePageComment]
(
    @pageCommentId int
)
AS
BEGIN
	DELETE FROM
		cs_Wiki_PageComments
	WHERE
		PageCommentId = @pageCommentId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_DeletePageComment] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_DeletePermission
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_DeletePermission'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_DeletePermission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_DeletePermission]
GO

CREATE  procedure [dbo].cs_Wiki_DeletePermission
(
	@WikiId 	int,
	@RoleId		uniqueidentifier,
	@SettingsId	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	
	DECLARE @ApplicationType smallint
	SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Wiki'
	
	IF (@WikiId <> -1)
		DELETE FROM cs_Wiki_Permissions WHERE WikiId = @WikiId AND RoleId = @RoleId
	ELSE
	begin
		DELETE FROM cs_Wiki_Permissions WHERE RoleId = @RoleId
		DELETE FROM cs_ProductPermissions WHERE RoleID = @RoleId and SettingsID = @SettingsId and ApplicationType = @ApplicationType
	end

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_DeletePermission] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Wiki_DeleteWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_DeleteWiki'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_DeleteWiki]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_DeleteWiki]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_DeleteWiki]
(
    @wikiId int
)
AS
BEGIN


	-- NOTE: Content related to this wiki will get autodeleted in all other Wiki tables because cascaded delete constraints

	DELETE FROM
		cs_Wiki_Wikis
	WHERE
		WikiId = @wikiId

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_DeleteWiki] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_FollowPage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_FollowPage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_FollowPage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_FollowPage]
GO

CREATE PROCEDURE [dbo].cs_Wiki_FollowPage
(
	@PageId int,
	@UserId int,
	@Follow bit
)
AS

SET Transaction Isolation Level Read UNCOMMITTED


IF (@Follow = 1)
BEGIN
	-- Insert row if one doesn't exist
	IF NOT EXISTS(SELECT PageId FROM cs_Wiki_PageFollowers (nolock) WHERE PageId = @PageId AND UserId = @UserId)
	BEGIN
		INSERT INTO cs_Wiki_PageFollowers (PageId, UserId)
		VALUES (@PageId, @UserId)
	END
END
ELSE
BEGIN
	DELETE cs_Wiki_PageFollowers
	WHERE PageId = @PageId
		and UserId = @UserId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Wiki_FollowPage to public
go

/***********************************************
* Sproc: cs_Wiki_GetPage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPage]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPage]
(
    @pageId int
)
AS
BEGIN
	SELECT
		P.PageId,
		P.WikiId,
		P.UserId,
		P.ParentPageId,
		P.Title,
		P.PageKey,
		P.Body,
		P.FormattedBody,
		P.IsPublished,
		P.RatingCount,
		P.RatingSum,
		P.LastModifiedUtcDate, 
		P.RevisionCount, 
		P.IsLocked,
		P.IsIndexed,
		P.TotalViews
	FROM
		cs_Wiki_Pages P
		INNER JOIN cs_Wiki_Wikis W on W.WikiId = P.WikiId
	WHERE
		W.IsEnabled = 1 
		AND P.PageId = @pageId

	SELECT
		T.[Name]
	FROM
		cs_Wiki_Tags T
		INNER JOIN cs_Wiki_PageTags PT ON T.TagId = PT.TagId
		INNER JOIN cs_Wiki_Pages P ON P.PageId = PT.PageId
		INNER JOIN cs_Wiki_Wikis W on W.WikiId = P.WikiId
	WHERE
		W.IsEnabled = 1 
		AND PT.PageId = @pageId
	ORDER BY
		T.[Name] ASC
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPage] TO PUBLIC
GO


/***********************************************
* Sproc: cs_Wiki_GetPageByPageKey
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageByPageKey'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageByPageKey]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageByPageKey]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageByPageKey]
(
    @wikiId int,
    @pageKey nvarchar(256),
    @searchRevisions bit
)
AS
BEGIN

DECLARE @pageId int

SELECT
	@pageId = P.PageId
FROM
	cs_Wiki_Pages P
	INNER JOIN cs_Wiki_Wikis W on W.WikiId = P.WikiId
WHERE
	W.IsEnabled = 1 
	AND P.WikiId = @wikiId
	AND P.PageKey = @pageKey

-- If the PageKey was not found, and the @searchRevisions option is true
-- then search page revisions for the page key
IF (@pageId is null AND @searchRevisions = 1)
BEGIN

	SELECT TOP 1
		@pageId = P.PageId
	FROM
		cs_Wiki_Pages P 
		INNER JOIN cs_Wiki_PageRevisions PR on P.PageId = PR.PageId
		INNER JOIN cs_Wiki_Wikis W on W.WikiId = P.WikiId
	WHERE
		W.IsEnabled = 1
		AND P.WikiId = @wikiId
		AND PR.PageKey = @pageKey

END


EXECUTE cs_Wiki_GetPage @pageId

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageByPageKey] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageComment]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageComment]
(
    @pageCommentId int
)
AS
BEGIN
	SELECT
		PC.PageCommentId,
		PC.PageId,
		PC.UserId,
		PC.Body,
		PC.FormattedBody,
		PC.RatingCount,
		PC.RatingSum,
		PC.PublishedUtcDate
	FROM
		cs_Wiki_PageComments PC
	WHERE
		PC.PageCommentId = @pageCommentId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageComment] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageCommentRating
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageCommentRating'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageCommentRating]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageCommentRating]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageCommentRating]
(
    @pageCommentId int,
    @userId int,
    @rating int OUTPUT
)
AS
BEGIN
	SELECT
		@rating = COALESCE(PCR.Rating, 0)
	FROM
		cs_Wiki_PageCommentRatings PCR
	WHERE
		PageCommentId = @pageCommentId
		AND UserId = @userId

	IF @rating IS NULL
		SET @rating = 0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageCommentRating] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageComments
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageComments'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageComments]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageComments]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageComments]
(
    @pageId int,
    @pageIndex int,
    @pageSize int,
    @sortBy nvarchar (256), 
    @sortOrder nvarchar (256), 
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	/* how many comments are there in total? doing this first to offset other processing */
	SET @totalCount = (
		SELECT
			count(*) as CountOfPageComments
		FROM
			cs_Wiki_PageComments PC
		WHERE
			PC.PageId = @pageId
		)

	/* we want nothing but the total count */
	if @pageSize = 0
	begin
		SELECT
			PC.PageCommentId,
			PC.PageId,
			PC.UserId,
			PC.Body,
			PC.FormattedBody,
			PC.RatingCount,
			PC.RatingSum,
			PC.PublishedUtcDate
		FROM
			cs_Wiki_PageComments PC
		WHERE
			1 = 0

		/* exit prematurely */
		return 0
	end

	/* we actually want data */

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	declare @Results table
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		PageCommentId int NOT NULL
	)

	IF ((@sortBy is NULL) OR (LEN(@sortBy) = 0))
		BEGIN
			SET @sortBy = N'PublishedDate';
		END

	IF ((@sortOrder is NULL) OR (LEN(@sortOrder) = 0))
		BEGIN
			SET @sortOrder = N'Ascending';
		END

	/* setting the minimum number of records that needs to come into this table */
	SET ROWCOUNT @rowsToReturn

	IF (@sortBy = N'RatingAverage') 
		BEGIN
			-- By RatingAverage (desc only, no asc)
			INSERT INTO @Results
				(PageCommentId)
			SELECT
				PC.PageCommentId
			FROM
				cs_Wiki_PageComments PC
			WHERE
				PC.PageId = @pageId
			ORDER BY
				(RatingSum / (RatingCount + .1)) DESC, RatingCount, RatingSum
		END
	ELSE IF (@sortBy=N'MostRecent' OR (@sortBy = N'PublishedDate' AND @sortOrder = N'Descending'))
		BEGIN
			-- By PublishedDate Desc
			INSERT INTO @Results
				(PageCommentId)
			SELECT
				PC.PageCommentId
			FROM
				cs_Wiki_PageComments PC
			WHERE
				PC.PageId = @pageId
			ORDER BY
				PublishedUtcDate DESC
		END
	ELSE 
		BEGIN
			-- The Default by PublishedDate asc
			INSERT INTO @Results
				(PageCommentId)
			SELECT
				PC.PageCommentId
			FROM
				cs_Wiki_PageComments PC
			WHERE
				PC.PageId = @pageId
			ORDER BY
				PublishedUtcDate ASC
		END

	SET ROWCOUNT @pageSize

	SELECT
		PC.PageCommentId,
		PC.PageId,
		PC.UserId,
		PC.Body,
		PC.FormattedBody,
		PC.RatingCount,
		PC.RatingSum,
		PC.PublishedUtcDate
	FROM
		cs_Wiki_PageComments PC
		INNER JOIN @Results R ON PC.PageCommentId = R.PageCommentId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageComments] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageCommentsByWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageCommentsByWiki'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageCommentsByWiki]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageCommentsByWiki]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageCommentsByWiki]
(
    @wikiID int,
    @pageIndex int,
    @pageSize int,
    @sortBy nvarchar (256), 
    @sortOrder nvarchar (256), 
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	/* this sproc will eventually need to be setup with partial paging */

	declare @Results table
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		PageCommentId int NOT NULL
	)

	IF ((@sortBy is NULL) OR (LEN(@sortBy) = 0))
		BEGIN
			SET @sortBy = 'PublishedDate';
		END
        IF ((@sortOrder is NULL) OR (LEN(@sortOrder) = 0))
		BEGIN
			SET @sortOrder = 'Ascending';
		END

	IF (@sortBy = 'RatingAverage') 
		BEGIN
			-- By RatingAverage (desc only, no asc)
			INSERT INTO @Results
				(PageCommentId)
			SELECT
				PC.PageCommentId
			FROM
				cs_Wiki_PageComments PC inner join cs_Wiki_Pages P on P.PageId = PC.PageId
			WHERE
				P.WikiId = @wikiID
			ORDER BY
				(PC.RatingSum / (PC.RatingCount + .1)) DESC, PC.RatingCount, PC.RatingSum
		END
	
	ELSE
		BEGIN 
			IF (@sortBy='MostRecent' OR (@sortBy = 'PublishedDate' AND @sortOrder = 'Descending'))
				BEGIN
					-- By PublishedDate Desc
					INSERT INTO @Results
						(PageCommentId)
					SELECT
						PC.PageCommentId
					FROM
						cs_Wiki_PageComments PC inner join cs_Wiki_Pages P on P.PageId = PC.PageId
					WHERE
						P.WikiId = @wikiID
					ORDER BY
						PC.PublishedUtcDate DESC
				END
			ELSE 
				BEGIN
					-- The Default by PublishedDate asc
					INSERT INTO @Results
						(PageCommentId)
					SELECT
						PC.PageCommentId
					FROM
						cs_Wiki_PageComments PC inner join cs_Wiki_Pages P on P.PageId = PC.PageId
					WHERE
						P.WikiId = @wikiID
					ORDER BY
						PC.PublishedUtcDate ASC
				END
		END

	SET @totalCount = @@ROWCOUNT

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	SET ROWCOUNT @rowsToReturn

	SELECT
		PC.PageCommentId,
		PC.PageId,
		PC.UserId,
		PC.Body,
		PC.FormattedBody,
		PC.RatingCount,
		PC.RatingSum,
		PC.PublishedUtcDate
	FROM
		cs_Wiki_PageComments PC
		INNER JOIN @Results R ON PC.PageCommentId = R.PageCommentId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageCommentsByWiki] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageFollowers
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageFollowers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_GetPageFollowers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_GetPageFollowers]
GO

CREATE PROCEDURE [dbo].cs_Wiki_GetPageFollowers
(
	@PageId int,
	@UserId int = -1
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	U.UserID,
	U.Email, 
	U.EnableHtmlEmail,
	U.[PublicToken],
	U.[UserName]
FROM 
	cs_Wiki_PageFollowers F
	INNER JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = F.UserId
WHERE
	F.PageId = @PageId
	and (F.UserId = @UserId OR @UserId = -1)
	and U.EnableEmail = 1
	and U.UserAccountStatus = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Wiki_GetPageFollowers] to public
go

/***********************************************
* Sproc: cs_Wiki_GetPageHierarchy
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageHierarchy'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWikiPageHierarchy]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWikiPageHierarchy]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWikiPageHierarchy]
(
	@WikiId int
)
AS
BEGIN
	SELECT PageId, ParentPageId, PageKey, Title
	FROM cs_Wiki_Pages
	WHERE WikiId = @WikiId
		AND IsPublished = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWikiPageHierarchy] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageRating
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageRating'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageRating]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageRating]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageRating]
(
    @pageId int,
    @userId int,
    @rating int OUTPUT
)
AS
BEGIN
	SELECT
		@rating = COALESCE(PR.Rating, 0)
	FROM
		cs_Wiki_PageRatings PR
	WHERE
		PageId = @pageId
		AND UserId = @userId

	IF @rating IS NULL
		SET @rating = 0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageRating] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageRevision
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageRevision'


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageRevision]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageRevision]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageRevision]
(
    @pageId int,
    @revisionNumber int
)
AS
BEGIN

	SELECT
		PR.PageRevisionId,
		PR.PageId,
		PR.UserId,
		PR.Title,
		PR.PageKey,
		PR.Body,
		PR.FormattedBody,
		PR.Tags,
		PR.LastModifiedUtcDate,
		PR.RevisionNumber
	FROM
		cs_Wiki_PageRevisions PR
	WHERE
		PR.PageId = @pageId
		AND PR.RevisionNumber = @revisionNumber

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageRevision] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPageRevisions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPageRevisions'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPageRevisions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPageRevisions]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPageRevisions]
(
    @pageId int,
    @pageIndex int,
    @pageSize int,
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	/*** This is a candidate to do partial paging ***/

	declare @Results table
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		PageRevisionId int NOT NULL
	)

	INSERT INTO @Results
		(PageRevisionId)
	SELECT
		PR.PageRevisionId
	FROM
		cs_Wiki_PageRevisions PR
	WHERE
		PR.PageId = @pageId
	ORDER BY
		PageRevisionId DESC

	SET @totalCount = @@ROWCOUNT

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	SET ROWCOUNT @rowsToReturn

	SELECT
		PR.PageRevisionId,
		PR.PageId,
		PR.UserId,
		PR.Title,
		PR.PageKey,
		PR.Body,
		PR.FormattedBody,
		PR.Tags,
		PR.LastModifiedUtcDate,
		PR.RevisionNumber
	FROM
		cs_Wiki_PageRevisions PR
		INNER JOIN @Results R ON PR.PageRevisionId = R.PageRevisionId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPageRevisions] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPages'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPages]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPages]
(
    @wikiId int,
    @pageIndex int,
    @pageSize int,
    @isPublished bit = NULL,
    @userId int = NULL,
    @isNew bit = NULL,
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	declare @Results table
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		PageId int NOT NULL
	)

	INSERT INTO @Results
		(PageId)
	select PageId from (
	SELECT
		P.PageId, P.LastModifiedUtcDate
	FROM
		cs_Wiki_Pages P
		INNER JOIN cs_Wiki_Wikis W on P.WikiId = W.WikiId
	WHERE
		(P.WikiId = @wikiId OR (@wikiId = -1 and W.HubId is null))
		AND W.IsEnabled = 1
		AND (@isPublished IS NULL OR P.IsPublished = @isPublished)
		AND (@userId IS NULL OR P.UserId = @userId OR P.PageId in (SELECT PR.PageId FROM cs_Wiki_PageRevisions PR WHERE PR.UserId = @userId))
		AND (@isNew IS NULL OR 
			(@isNew = 0 AND P.PageId in (SELECT PR.PageId FROM cs_Wiki_PageRevisions PR)) OR
			(@isNew = 1 AND P.PageId not in (SELECT PR.PageId FROM cs_Wiki_PageRevisions PR)))
	) as z
	ORDER BY
		LastModifiedUtcDate DESC

	SET @totalCount = @@ROWCOUNT

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	SET ROWCOUNT @rowsToReturn

	SELECT
		P.PageId,
		P.WikiId,
		P.UserId,
		P.ParentPageId,
		P.Title,
		P.PageKey,
		P.Body,
		P.FormattedBody,
		P.IsPublished,
		P.RatingCount,
		P.RatingSum,
		P.LastModifiedUtcDate, 
		P.RevisionCount, 
		P.IsLocked,
		P.IsIndexed,
		P.TotalViews
	FROM
		cs_Wiki_Pages P
		INNER JOIN @Results R ON P.PageId = R.PageId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPages] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPagesByTags
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPagesByTags'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPagesByTags]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPagesByTags]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPagesByTags]
(
    @wikiId int = -1,
    @pageIndex int,
    @pageSize int,
    @tagXml ntext = NULL,
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int
	DECLARE @tagCount int

	DECLARE @iDoc int
	DECLARE @Tags TABLE
	(
		Name nvarchar(256) COLLATE DATABASE_DEFAULT NOT NULL
	)

	EXECUTE sp_xml_preparedocument @iDoc OUTPUT, @tagXml

	INSERT INTO @Tags (Name)
	SELECT CONVERT(nvarchar(255), X.[text])
	FROM OPENXML(@iDoc, '/tags/tag/', 2) X
	WHERE X.[text] IS NOT NULL

	SET @tagCount = @@ROWCOUNT

	EXEC sp_xml_removedocument @iDoc

	declare @Results table
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		PageId int NOT NULL
	)

	INSERT INTO @Results
		(PageId)
	select PageId from (
	SELECT
		P.PageId, P.LastModifiedUtcDate
	FROM
		cs_Wiki_Pages P
	INNER JOIN
		cs_Wiki_Wikis W on P.WikiId = W.WikiId
	WHERE
		(P.WikiId = @wikiId OR (@wikiId = -1 and W.HubId is null))
		AND W.IsEnabled = 1
		AND EXISTS (
			SELECT 1 FROM cs_Wiki_PageTags PT
			INNER JOIN
				cs_Wiki_Tags WT on PT.TagId = WT.TagId
			INNER JOIN
				@Tags T on WT.[Name] = T.[Name]
			WHERE
				P.PageId = PT.PageId
			GROUP BY
				PT.PageId
			HAVING
				/* this says to only get posts that have at least all of the tags we are requesting */
				COUNT(*) >= @tagCount
		)
	) as z
	ORDER BY
		LastModifiedUtcDate DESC

	SET @totalCount = @@ROWCOUNT

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	SET ROWCOUNT @rowsToReturn

	SELECT
		P.PageId,
		P.WikiId,
		P.UserId,
		P.ParentPageId,
		P.Title,
		P.PageKey,
		P.Body,
		P.FormattedBody,
		P.IsPublished,
		P.RatingCount,
		P.RatingSum,
		P.LastModifiedUtcDate, 
		P.RevisionCount, 
		P.IsLocked,
		P.IsIndexed,
		P.TotalViews
	FROM
		cs_Wiki_Pages P
		INNER JOIN @Results R ON P.PageId = R.PageId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound
	ORDER BY
		IndexId

	SET ROWCOUNT 1000

	SELECT
		T.[Name], R.PageId as TagPageId, (select count(TagId) from cs_Wiki_PageTags WPT where WPT.PageId = R.PageId) as PageTagCount
	FROM
		cs_Wiki_Tags T
		INNER JOIN cs_Wiki_PageTags PT ON T.TagId = PT.TagId
		INNER JOIN @Results R ON PT.PageId = R.PageId
	ORDER BY
		[Name] ASC

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPagesByTags] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetPagesIndexed
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPagesIndexed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetPagesIndexed]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetPagesIndexed]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetPagesIndexed]
(
    @isIndexed bit = 0,
    @totalCount int OUTPUT
)
AS
BEGIN
	SELECT
		P.PageId,
		P.WikiId,
		P.UserId,
		P.ParentPageId,
		P.Title,
		P.PageKey,
		P.Body,
		P.FormattedBody,
		P.IsPublished,
		P.RatingCount,
		P.RatingSum,
		P.LastModifiedUtcDate, 
		P.RevisionCount, 
		P.IsLocked,
		P.IsIndexed,
		P.TotalViews
	FROM
		cs_Wiki_Pages P
		INNER JOIN [cs_Wiki_Wikis] W ON W.WikiId = P.WikiId
	WHERE
		P.[IsIndexed] = @isIndexed AND
		P.[IsPublished] = 1 AND
		W.[IsEnabled] = 1

	SET @totalCount = @@ROWCOUNT

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetPagesIndexed] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Wiki_GetPermissions
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetPermissions'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[cs_Wiki_GetPermissions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_GetPermissions]
GO

create procedure [dbo].[cs_Wiki_GetPermissions]
(
	@WikiId int = 0,
	@AllRoles ntext = NULL
)
AS
begin

	DECLARE @ApplicationType smallint
	SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Wiki'

	SET Transaction Isolation Level Read UNCOMMITTED
	
	IF (@WikiId = 0)
	begin
		-- Return product permissions
		SELECT 
			Implied = convert(bit, 1), 
			WikiId = -1,
			PP.RoleID as RoleId, 
			AllowMask = convert(bigint, coalesce(PP.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(PP.DenyMask, 0x00))
		FROM
			cs_ProductPermissions PP
		WHERE 
			(PP.ApplicationType = @ApplicationType or @ApplicationType is null)
	
		UNION ALL
	
		-- Return wiki permissions
		SELECT
			Implied = convert(bit, 0), 
			WP.WikiId,
			WP.RoleId, 
			AllowMask = convert(bigint, coalesce(WP.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(WP.DenyMask, 0x00))
		FROM 
			cs_Wiki_Permissions WP
		order by Implied asc, WikiId desc
	
	end
	ELSE IF (@WikiId > 0)
	begin
		
		-- Return product permissions
		SELECT 
			Implied = convert(bit, 1), 
			WikiId = -1,
			PP.RoleID as RoleId, 
			AllowMask = convert(bigint, coalesce(PP.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(PP.DenyMask, 0x00))
		FROM
			cs_ProductPermissions PP
		WHERE 
			(PP.ApplicationType = @ApplicationType or @ApplicationType is null)
	
		UNION ALL
		
		-- Return wiki permissions
		SELECT
			Implied = convert(bit, 0), 
			WP.WikiId,
			WP.RoleId, 
			AllowMask = convert(bigint, coalesce(WP.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(WP.DenyMask, 0x00))
		FROM 
			cs_Wiki_Permissions WP
		WHERE
			WP.WikiId = @WikiId
		order by Implied asc, WikiId DESC
	end 
    	ELSE 
	begin
	
	    DECLARE @Roles		table(RoleId uniqueidentifier NOT NULL PRIMARY KEY)
	    DECLARE @Num		int
	    DECLARE @Pos		int
	    DECLARE @NextPos	int
	    DECLARE @guid		nvarchar(256)
	
	    DECLARE @textpos  int --our chunks position in the ntext
	    DECLARE @chunklen smallint
	    DECLARE @chunk   nvarchar(4000)
	    DECLARE @delimiter nvarchar(1)
	    DECLARE @leftover nvarchar(4000)
	
		SET @delimiter = N','
		SET @Num = 0
		SET @textpos = 1
		SET @leftover = ''
	
		WHILE @textpos <= DATALENGTH(@AllRoles) /2
		BEGIN
	
			SET @chunklen = 4000 - DATALENGTH(@leftover) /2
			SET @chunk = ltrim(@leftover + substring(@AllRoles, @textpos, @chunklen))
			SET @textpos = @textpos + @chunklen
	
			SET @Pos = 1 
	
			WHILE(@Pos <= DATALENGTH(@chunk))
			BEGIN
				SELECT @NextPos = CHARINDEX(@delimiter, @chunk,  @Pos)
				IF (@NextPos = 0 OR @NextPos IS NULL)
				BEGIN
					--break us from the loop
					SELECT @NextPos = DATALENGTH(@chunk) + 1
					--set the leftover string to use again in next iter
					SET @leftover = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
				END
				ELSE
				BEGIN
					SELECT @guid = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
	
					INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @guid))
	
					SET @Num = @Num + 1
				END
	
				SELECT @Pos = @NextPos+1
			END
	
			IF(@Pos = DATALENGTH(@chunk))
				SET @leftover = ''
		END
	
		INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @leftover))
	
	
		-- Return product permissions
		SELECT 
			Implied = convert(bit, 1), 
			WikiId = -1,
			R.RoleId, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))
		FROM
			@Roles R
			left outer join cs_ProductPermissions P on R.RoleId = P.RoleID and (P.ApplicationType = @ApplicationType or @ApplicationType is null)
	end
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Wiki_GetPermissions] to public
go
/***********************************************
* Sproc: cs_Wiki_GetTags
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetTags'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetTags]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetTags]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetTags]
(
    @wikiId int,
    @tagXml ntext = NULL
)
AS
BEGIN


IF @tagXml IS NULL
BEGIN

	SELECT t.[Name], count(*) as TotalCount
	FROM cs_Wiki_Tags t
		inner join cs_Wiki_PageTags pt on t.TagId = pt.TagId
		inner join cs_wiki_Pages p on pt.PageId = p.PageId
	WHERE
		(p.WikiId = @wikiId OR @wikiId = -1)
		AND p.IsPublished = 1
	GROUP BY t.[Name]
	ORDER BY t.[Name]

END ELSE BEGIN

	DECLARE @iDoc int
	DECLARE @Tags TABLE
	(
		--Name nvarchar(256) COLLATE DATABASE_DEFAULT NOT NULL primary key
		TagId int NOT NULL primary key
	)

	EXECUTE sp_xml_preparedocument @iDoc OUTPUT, @tagXml

	INSERT INTO @Tags ([TagId])
	SELECT t.[TagId]--CONVERT(nvarchar(255), X.[text])
	FROM OPENXML(@iDoc, '/tags/tag/', 2) X
	INNER JOIN cs_Wiki_Tags t
		ON CONVERT(nvarchar(255), X.[text]) = t.[Name]
		AND X.[text] IS NOT NULL

	EXEC sp_xml_removedocument @iDoc
	
	SELECT t.[Name], count(*) as TotalCount
	FROM cs_Wiki_Tags t
		INNER JOIN cs_Wiki_PageTags pt on t.TagId = pt.TagId
		INNER JOIN cs_Wiki_Pages p on pt.PageId = p.PageId AND p.IsPublished = 1
		INNER JOIN (
			SELECT P.PageId
			FROM cs_Wiki_Pages P
				INNER JOIN cs_Wiki_PageTags PT on P.PageId = PT.PageId
				INNER JOIN cs_Wiki_Tags WT on PT.TagId = WT.TagId
				INNER JOIN @Tags T on WT.[TagId] = T.[TagId]
			WHERE ((P.WikiId = @wikiId) OR (@wikiId = -1)) AND p.IsPublished = 1
		) PIDs on PIDs.PageId = p.PageId
	WHERE
		NOT EXISTS (
			SELECT 1 FROM @Tags fTags
			WHERE fTags.[TagId] = t.[TagId]
		)
	GROUP BY t.[Name]
	ORDER BY t.[Name]

END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetTags] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetWiki'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWiki]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWiki]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWiki]
(
    @wikiId int
)
AS
BEGIN
	SELECT
		W.WikiId,
		W.HubId,
		W.Name,
		W.Description,
		W.ApplicationKey,
		W.IsEnabled,
		W.LastModifiedUtcDate
	FROM
		cs_Wiki_Wikis W
	WHERE
		W.WikiId = @wikiId AND
		W.IsEnabled = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWiki] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetWikiByApplicationKey
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetWikiByApplicationKey'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWikiByApplicationKey]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWikiByApplicationKey]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWikiByApplicationKey]
(
    @applicationKey nvarchar(256)
)
AS
BEGIN
	SELECT
		W.WikiId,
		W.HubId,
		W.Name,
		W.Description,
		W.ApplicationKey,
		W.IsEnabled,
		W.LastModifiedUtcDate
	FROM
		cs_Wiki_Wikis W
	WHERE
		W.ApplicationKey = @applicationKey AND
		W.IsEnabled = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWikiByApplicationKey] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetWikiByHub
* File Date: 11/6/2008 12:57
***********************************************/
Print 'Creating...cs_Wiki_GetWikiByHub'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWikiByHub]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWikiByHub]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWikiByHub]
(
    @hubId int
)
AS
BEGIN
	SELECT
		W.WikiId,
		W.HubId,
		W.Name,
		W.Description,
		W.ApplicationKey,
		W.IsEnabled,
		W.LastModifiedUtcDate
	FROM
		cs_Wiki_Wikis W
	WHERE
		W.HubId = @hubId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWikiByHub] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetWikiIncludeDisabled
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetWikiIncludeDisabled'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWikiIncludeDisabled]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWikiIncludeDisabled]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWikiIncludeDisabled]
(
    @wikiId int
)
AS
BEGIN
	SELECT
		W.WikiId,
		W.HubId,
		W.Name,
		W.Description,
		W.ApplicationKey,
		W.IsEnabled,
		W.LastModifiedUtcDate
	FROM
		cs_Wiki_Wikis W
	WHERE
		W.WikiId = @wikiId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWikiIncludeDisabled] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_GetWikis
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_GetWikis'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_GetWikis]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_GetWikis]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_GetWikis]
(
    @pageIndex int,
    @pageSize int,
    @isEnabled bit = NULL,
    @totalCount int OUTPUT
)
AS
BEGIN

	DECLARE @rowsToReturn int
	DECLARE @pageLowerBound int
	DECLARE @pageUpperBound int

	exec [dbo].[cs_system_CalculatePagingInformation]
		@pageIndex, @pageSize
		, @rowsToReturn output, @pageLowerBound output, @pageUpperBound output

	SET @totalCount = (
			SELECT
				count(*) CountOfWikis
			FROM
				cs_Wiki_Wikis W
			WHERE
				(@isEnabled IS NULL OR W.IsEnabled = @isEnabled)
				AND (W.HubId IS NULL OR W.HubId < 1)
		)

	declare @Results TABLE
	(
		IndexId int IDENTITY(1, 1) NOT NULL,
		WikiId int NOT NULL
	)

	SET ROWCOUNT @rowsToReturn

	INSERT INTO @Results
		(WikiId)
	SELECT
		W.WikiId
	FROM
		cs_Wiki_Wikis W
	WHERE
		(@isEnabled IS NULL OR W.IsEnabled = @isEnabled)
		AND (W.HubId IS NULL OR W.HubId < 1)
	ORDER BY
		W.Name ASC

	SET ROWCOUNT @pageSize

	SELECT
		W.WikiId,
		W.HubId,
		W.Name,
		W.Description,
		W.ApplicationKey,
		W.IsEnabled,
		W.LastModifiedUtcDate
	FROM
		cs_Wiki_Wikis W
		INNER JOIN @Results R ON W.WikiId = R.WikiId
	WHERE
		R.IndexId > @pageLowerBound
		AND R.IndexId < @pageUpperBound

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_GetWikis] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_RatePage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_RatePage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_RatePage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_RatePage]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_RatePage]
(
    @pageId int,
    @userId int,
    @rating int,
	@ratingCount int OUTPUT,
	@ratingSum int OUTPUT
)
AS
BEGIN
	UPDATE
		cs_Wiki_PageRatings
	SET
		Rating = @rating
	WHERE
		PageId = @pageId
		AND UserId = @userId

	IF @@ROWCOUNT = 0
	BEGIN
		INSERT INTO
			cs_Wiki_PageRatings
			(
				PageId,
				UserId,
				Rating
			)
		VALUES
		(
			@pageId,
			@userId,
			@rating
		)
	END

	SELECT
		@ratingCount = PS.RatingCount,
		@ratingSum = PS.RatingSum
	FROM
		cs_Wiki_Pages P
		INNER JOIN
		(
			SELECT
				PR.PageId,
				COUNT(*) AS RatingCount,
				SUM(PR.Rating) AS RatingSum
			FROM
				cs_Wiki_PageRatings PR
			WHERE
				PR.PageId = @pageId
			GROUP BY
				PR.PageId
		) PS ON PS.PageId = P.PageId
	WHERE
		P.PageId = @pageId

	UPDATE
		cs_Wiki_Pages
	SET
		RatingCount = @ratingCount,
		RatingSum = @ratingSum
	WHERE
		PageId = @pageId

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_RatePage] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_RatePageComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_RatePageComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_RatePageComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_RatePageComment]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_RatePageComment]
(
    @pageCommentId int,
    @userId int,
    @rating int,
	@ratingCount int OUTPUT,
	@ratingSum int OUTPUT
)
AS
BEGIN
	UPDATE
		cs_Wiki_PageCommentRatings
	SET
		Rating = @rating
	WHERE
		PageCommentId = @pageCommentId
		AND UserId = @userId

	IF @@ROWCOUNT = 0
	BEGIN
		INSERT INTO
			cs_Wiki_PageCommentRatings
			(
				PageCommentId,
				UserId,
				Rating
			)
		VALUES
		(
			@pageCommentId,
			@userId,
			@rating
		)
	END

	SELECT
		@ratingCount = PCS.RatingCount,
		@ratingSum = PCS.RatingSum
	FROM
		cs_Wiki_PageComments PC
		INNER JOIN
		(
			SELECT
				PCR.PageCommentId,
				COUNT(*) AS RatingCount,
				SUM(PCR.Rating) AS RatingSum
			FROM
				cs_Wiki_PageCommentRatings PCR
			WHERE
				PCR.PageCommentId = @pageCommentId
			GROUP BY
				PCR.PageCommentId
		) PCS ON PCS.PageCommentId = PC.PageCommentId
	WHERE
		PC.PageCommentId = @pageCommentId


	UPDATE
		cs_Wiki_PageComments
	SET
		RatingCount = @ratingCount,
		RatingSum = @ratingSum
	WHERE
		PageCommentId = @pageCommentId

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_RatePageComment] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_ReindexPages
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_ReindexPages'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_ReindexPages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_ReindexPages]
GO


CREATE PROCEDURE [dbo].[cs_Wiki_ReindexPages]
(
	@WikiId	int = -1,
	@SettingsId int
)
AS
	IF (@WikiId > -1)
	BEGIN
		INSERT cs_es_Search_RemoveQueue (PostID, SettingsID, ApplicationType) 
		SELECT PageId, @SettingsId, 'Wiki' 
		FROM [cs_Wiki_Pages] 
		WHERE WikiId = @WikiId
		AND PageId NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue WHERE ApplicationType = 'Wiki')

		UPDATE cs_Wiki_Pages set IsIndexed = 0
		WHERE WikiId = @WikiId
	END
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Wiki_ReindexPages] to public
go
/***********************************************
* Sproc: cs_Wiki_UpdatePage
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdatePage'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_UpdatePage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_UpdatePage]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_UpdatePage]
(
    @pageId int,
    @wikiId int,
    @userId int,
    @parentPageId int = NULL,
    @title nvarchar(256),
    @pageKey nvarchar(256),
    @body ntext,
    @formattedBody ntext,
    @tagXml ntext,
    @isPublished bit,
    @ratingCount int,
    @ratingSum int,
    @lastModifiedUtcDate datetime, 
    @isLocked bit = 0,
    @isindexed bit = 0,
    @saveRevision bit = 1
)
AS
BEGIN
	IF @parentPageId = -1
		SET @parentPageId = NULL

	-- If PageKey is null/blank, then use PageID as the default for now
	IF ((@pageKey is NULL) OR (LEN(@pageKey) = 0))
		SET @pageKey = CAST(@pageId AS nvarchar(256))

	IF @saveRevision = 1
	BEGIN
	
		DECLARE @revNumber int
		SELECT @revNumber = IsNull(MAX(RevisionNumber), 0) FROM cs_Wiki_PageRevisions WHERE PageId = @pageId
		SET @revNumber = @revNumber + 1

		DECLARE @pagetags AS VARCHAR(MAX)
		SELECT @pagetags = COALESCE(@pagetags + ', ', '') + T.[Name]
		FROM
			cs_Wiki_Tags T
			INNER JOIN cs_Wiki_PageTags PT ON T.TagId = PT.TagId
			INNER JOIN cs_Wiki_Pages P ON P.PageId = PT.PageId
		WHERE
			PT.PageId = @pageId	
		SELECT @pagetags = COALESCE(@pagetags, '')
		
		INSERT INTO
			cs_Wiki_PageRevisions
			(
				PageId,
				UserId,
				Title,
				Body,
				FormattedBody,
				Tags,
				LastModifiedUtcDate,
				RevisionNumber,
				PageKey
			)
		SELECT
			P.PageId,
			P.UserId,
			P.Title,
			P.Body,
			P.FormattedBody,
			@pagetags,
			P.LastModifiedUtcDate,
			@revNumber,
			P.PageKey
		FROM
			cs_Wiki_Pages P
		WHERE
			P.PageId = @pageId
	END

	UPDATE
		cs_Wiki_Pages
	SET
		WikiId = @wikiId,
		UserId = @userId,
		ParentPageId = @parentPageId,
		Title = @title,
		PageKey = @pageKey,
		Body = @body,
		FormattedBody = @formattedBody,
		IsPublished = @isPublished,
		RatingCount = @ratingCount,
		RatingSum = @ratingSum,
		LastModifiedUtcDate = @lastModifiedUtcDate,
		IsLocked = @isLocked,
		IsIndexed = @isindexed,
		RevisionCount = (SELECT     COALESCE (COUNT(r.PageRevisionId), 0) AS cnt
			FROM          cs_Wiki_PageRevisions r
			WHERE r.PageId = [cs_Wiki_Pages].PageId) + 1
	WHERE
		PageId = @pageId

	EXECUTE cs_Wiki_UpdatePageTags @pageId, @tagXml
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_UpdatePage] TO PUBLIC
GO


/***********************************************
* Sproc: cs_Wiki_UpdatePageComment
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdatePageComment'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_UpdatePageComment]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_UpdatePageComment]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_UpdatePageComment]
(
    @pageCommentId int,
    @pageId int,
    @userId int,
    @body ntext,
    @formattedBody ntext,
    @ratingCount int,
    @ratingSum int,
    @publishedUtcDate datetime
)
AS
BEGIN
	UPDATE
		cs_Wiki_PageComments
	SET
		PageId = @pageId,
		UserId = @userId,
		Body = @body,
		FormattedBody = @formattedBody,
		RatingCount = @ratingCount,
		RatingSum = @ratingSum,
		PublishedUtcDate = @publishedUtcDate
	WHERE
		PageCommentId = @pageCommentId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_UpdatePageComment] TO PUBLIC
GO

/***********************************************
* Sproc: cs_Wiki_UpdatePageIndexStatus
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdatePageIndexStatus'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_UpdatePageIndexStatus]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_UpdatePageIndexStatus]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_UpdatePageIndexStatus]
(
    @pageId int,
    @isindexed bit = 0
)
AS
BEGIN
	UPDATE
		cs_Wiki_Pages
	SET
		IsIndexed = @isindexed
	WHERE
		PageId = @pageId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_UpdatePageIndexStatus] TO PUBLIC
GO


/***********************************************
* Sproc: cs_Wiki_UpdatePageTags
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdatePageTags'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_UpdatePageTags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_UpdatePageTags]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_UpdatePageTags]
(
	@pageId int,
	@tagXml ntext
)
AS
BEGIN
		DECLARE @iDoc int

		DECLARE @Tags TABLE
		(
			Name nvarchar(256) COLLATE DATABASE_DEFAULT NOT NULL
		)
		
		EXECUTE sp_xml_preparedocument @iDoc OUTPUT, @tagXml

		INSERT INTO
			@Tags
			(
				Name
			)
		SELECT
			CONVERT(nvarchar(255), X.[text])
		FROM
			OPENXML(@iDoc, '/tags/tag/', 2) X
		WHERE
			X.[text] IS NOT NULL

		EXEC sp_xml_removedocument @iDoc

		INSERT INTO
			cs_Wiki_Tags
			(
				Name
			)
		SELECT
			X.Name
		FROM
			@Tags X
		WHERE
			NOT EXISTS
			(
				SELECT 1
				FROM
					cs_Wiki_Tags T
				WHERE
					X.Name = T.Name
			)

		INSERT INTO
			cs_Wiki_PageTags
			(
				PageId,
				TagId
			)
		SELECT
			@pageId,
			T.TagId
		FROM
			cs_Wiki_Tags T
		WHERE
			EXISTS
			(
				SELECT 1
				FROM @Tags X
				where
					T.Name = X.Name
			)
			AND NOT EXISTS
			(
				SELECT 1
				FROM
					cs_Wiki_PageTags PT
				WHERE
					PT.PageId = @pageId
					AND PT.TagId = T.TagId
			)

		DELETE
			PT
		FROM
			cs_Wiki_PageTags PT
		WHERE
			PT.PageId = @pageId
			AND NOT EXISTS
			(
				SELECT 1
				FROM
					cs_Wiki_Tags T
					INNER JOIN @Tags X ON T.Name = X.Name
				WHERE
					T.TagId = PT.TagId
			)
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_Wiki_UpdatePageTags] to public
go

/***********************************************
* Sproc: cs_Wiki_UpdatePermission
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdatePermission'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Wiki_UpdatePermission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Wiki_UpdatePermission]
GO

CREATE  procedure [dbo].cs_Wiki_UpdatePermission
(
	@WikiId 	int,
	@RoleId		uniqueidentifier,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@SettingsId	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	
	DECLARE @ApplicationType smallint
	SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Wiki'
	
	IF (@WikiId <> -1) 
	begin
		IF NOT EXISTS (SELECT WikiId FROM cs_Wiki_Permissions WHERE WikiId = @WikiId AND RoleId = @RoleId)
			exec cs_Wiki_AddPermission @WikiId, @RoleId, @AllowMask, @DenyMask, @SettingsId
		ELSE
			UPDATE
				cs_Wiki_Permissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				WikiId = @WikiId AND
				RoleId = @RoleId

		IF NOT EXISTS (SELECT * from cs_ProductPermissions WHERE SettingsID = @SettingsId and RoleID = @RoleId and ApplicationType = @ApplicationType)
			INSERT INTO cs_ProductPermissions (SettingsID, RoleID, AllowMask, DenyMask, ApplicationType)
				VALUES(@SettingsId, @RoleId, 0x0, 0x0, @ApplicationType)
	end
	ELSE
	begin
		IF NOT EXISTS (SELECT * FROM cs_ProductPermissions WHERE RoleID = @RoleId and SettingsID = @SettingsId and ApplicationType = @ApplicationType)
			exec cs_Wiki_AddPermission @WikiId, @RoleId, @AllowMask, @DenyMask, @SettingsId
		ELSE
			UPDATE
				cs_ProductPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				RoleID = @RoleId and SettingsID = @SettingsId and ApplicationType = @ApplicationType
	end

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_UpdatePermission] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Wiki_UpdateWiki
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...cs_Wiki_UpdateWiki'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_Wiki_UpdateWiki]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_Wiki_UpdateWiki]
GO

CREATE PROCEDURE [dbo].[cs_Wiki_UpdateWiki]
(
    @wikiId int,
    @hubId int = NULL,
    @name nvarchar(256),
    @description nvarchar(1000),
    @applicationKey nvarchar(256),
    @isEnabled bit,
    @lastModifiedUtcDate datetime
)
AS
BEGIN
	IF @hubId = -1
		SET @hubId = NULL

	UPDATE
		cs_Wiki_Wikis
	SET
		HubId = @hubId,
		Name = @name,
		Description = @description,
		ApplicationKey = @applicationKey,
		IsEnabled = @isEnabled,
		LastModifiedUtcDate = @lastModifiedUtcDate
	WHERE
		WikiId = @wikiId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Wiki_UpdateWiki] TO PUBLIC
GO

/***********************************************
* Sproc: forums_Threads_GetThreadSet
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...forums_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[forums_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[forums_Threads_GetThreadSet]
GO

/***********************************************
* Sproc: HasReadPost
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...HasReadPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[HasReadPost]') and OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
drop function [dbo].[HasReadPost]
GO

/***********************************************
* Sproc: mg_EmailQueue_Delete
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...mg_EmailQueue_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[mg_EmailQueue_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[mg_EmailQueue_Delete]
GO


create proc dbo.mg_EmailQueue_Delete
	@EmailID uniqueidentifier 
as
SET Transaction Isolation Level Read UNCOMMITTED
	delete from mg_EmailQueue where EmailID = @EmailID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON dbo.mg_EmailQueue_Delete TO public
GO
/***********************************************
* Sproc: mg_EmailQueue_Failure
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...mg_EmailQueue_Failure'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[mg_EmailQueue_Failure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[mg_EmailQueue_Failure]
GO


create proc dbo.mg_EmailQueue_Failure
	@EmailID uniqueidentifier,
	@FailureInterval int,
	@MaxNumberOfTries int
as
SET Transaction Isolation Level Read UNCOMMITTED
declare @NumberOfTries int
select @NumberOfTries = NumberOfTries + 1 from mg_EmailQueue where EmailID = @EmailID

if @NumberOfTries <= @MaxNumberOfTries
begin
	update mg_EmailQueue set
		NumberOfTries = @NumberOfTries,
		NextTryTime = dateadd(minute, @NumberOfTries * @FailureInterval, getdate())
	where EmailID = @EmailID
end
else
begin
	delete from mg_EmailQueue where EmailID = @EmailID
end
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.mg_EmailQueue_Failure TO public
GO
/***********************************************
* Sproc: mg_Emails_Dequeue
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...mg_Emails_Dequeue'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[mg_Emails_Dequeue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[mg_Emails_Dequeue]
GO



CREATE    PROCEDURE [dbo].mg_Emails_Dequeue
(
  @MessageLimit int=1000,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

  if @MessageLimit > 0
  begin
    SET ROWCOUNT @MessageLimit
  end

	SELECT * FROM mg_EmailQueue Where SettingsID = @SettingsID and NextTryTime < getdate() order by NextTryTime asc
	
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].mg_Emails_Dequeue to public
go
/***********************************************
* Sproc: mg_Emails_Enqueue
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...mg_Emails_Enqueue'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[mg_Emails_Enqueue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[mg_Emails_Enqueue]
GO


CREATE  PROCEDURE [dbo].mg_Emails_Enqueue
(
	@EmailXml	ntext,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	INSERT INTO
		mg_EmailQueue
		(
			EmailXml,
			SettingsID,
			NextTryTime
		)
	VALUES
		(
			@EmailXml,
			@SettingsID,
			getdate()
		)		
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].mg_Emails_Enqueue to public
go
/***********************************************
* Sproc: spam_GetRecentPostCountFromIP
* File Date: 10/31/2008 1:12
***********************************************/
Print 'Creating...spam_GetRecentPostCountFromIP'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spam_GetRecentPostCountFromIP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spam_GetRecentPostCountFromIP]
GO

CREATE PROCEDURE [dbo].[spam_GetRecentPostCountFromIP]
(
	@IPAddress	nvarchar(64),
	@Duration	int,
	@SettingsID	int
)
AS
	SELECT	COUNT(*)
	FROM	cs_Posts
	WHERE	SettingsID = @SettingsID AND
			IPAddress = @IPAddress AND
			PostDate > DATEADD(s, -@Duration, GETDATE())

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[spam_GetRecentPostCountFromIP] TO PUBLIC
GO
