
/***********************************************
* Schema Patches
***********************************************/

-- Versions 43 & 44 are missing from the cs_SchemaVersion table for some people who installed CS 2.0 Beta 2 from scratch. Fix this here:

DECLARE @Installed DateTime
Select @Installed = InstallDate from cs_SchemaVersion where Major=2 and Minor=0 and Patch=43
If(@Installed is null)
BEGIN
	Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (2, 0, 43, GetDate())
END

Select @Installed = InstallDate from cs_SchemaVersion where Major=2 and Minor=0 and Patch=44
If(@Installed is null)
BEGIN
	Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (2, 0, 44, GetDate())
END


/***********************************************
* Patch: cs_Schema_Patch_2.1.00
* File Date: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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: 8/8/2006 9:28:23 AM
***********************************************/
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 


/***********************************************
* View: cs_vw_EveryOne_Role
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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

CREATE View [dbo].cs_vw_EveryOne_Role
as

SELECT jA.LoweredApplicationName, jA.[ApplicationId], [RoleId], [RoleName], [LoweredRoleName], aspnet_Roles.[Description] 

FROM [aspnet_Roles]
JOIN aspnet_Applications jA on aspnet_Roles.ApplicationId = jA.ApplicationId

Where LoweredRoleName = 'everyone'












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_EveryOne_Role] to public
/***********************************************
* View: cs_vw_HasReadForum
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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

CREATE VIEW [dbo].cs_vw_UsersInRoles
AS

SELECT 
	cu.UserID, ur.RoleId
FROM
	aspnet_UsersInRoles ur (nolock)
	INNER JOIN aspnet_Users au (nolock) on au.UserId = ur.UserId
	INNER JOIN cs_Users cu (nolock) on au.UserId = cu.MembershipID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_UsersInRoles] to public



/***********************************************
* View: cs_vw_Users_FullUser
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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 
	au.UserName, au.IsAnonymous, au.UserId, au.LastActivityDate,
	am.PasswordQuestion, am.Email, am.IsApproved,am.CreateDate, am.LastLoginDate, am.LastPasswordChangedDate, am.IsLockedOut, am.LastLockoutDate,
	am.Comment, cu.UserID as cs_UserID, cu.ForceLogin as cs_ForceLogin, cu.UserAccountStatus as cs_UserAccountStatus, cu.AppUserToken as cs_AppUserToken, am.PasswordFormat,
	cu.LastActivity as cs_LastActivity, cu.LastAction as cs_LastAction, fup.IsIgnored,fup.PublicToken,
	fup.TimeZone, fup.TotalPosts, fup.PostSortOrder, fup.PropertyNames as UserPropertyNames, fup.PropertyValues as UserPropertyValues, fup.PostRank, fup.IsAvatarApproved, fup.ModerationLevel, 
	fup.EnableThreadTracking, fup.EnableDisplayUnreadThreadsOnly, fup.EnableAvatar, fup.EnableDisplayInMemberList, fup.EnablePrivateMessages, 
	fup.EnableOnlineStatus, fup.EnableEmail, fup.EnableHtmlEmail, fup.SettingsID, ap.PropertyNames as ProfileNames, ap.PropertyValuesString, ap.PropertyValuesBinary,
	fup.Points as UserPoints, fup.FavoritesShared, fup.AllowSiteToContact, fup.AllowSitePartnersToContact
From
	aspnet_Membership  am (nolock)

INNER JOIN aspnet_Users au (nolock) on am.UserId = au.UserId
INNER JOIN cs_Users cu (nolock) on au.UserId = cu.MembershipID
INNER JOIN cs_UserProfile  fup (nolock) on cu.UserID = fup.UserID
LEFT  JOIN aspnet_Profile ap (nolock) on au.UserId = ap.UserId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--Select * FROM cs_vw_Users_FullUser

grant select on [dbo].[cs_vw_Users_FullUser] to public



/***********************************************
* Sproc: csm_EmailIDs_FindUserEmailID
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:14 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, 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
FROM
	csm_MailingLists M
LEFT JOIN cs_Sections F ON 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: 8/8/2006 9:28:17 AM
***********************************************/
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,
		R.RoleName, 
		P.RoleID, 
		P.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		M.EmailAddress,
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		F.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		csm_MailingLists M,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID AND
		P.SectionID = M.SectionID AND
		F.SectionID = M.SectionID 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_Post_FindPostParent
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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_ApplicationConfigurationSettings_CreateUpdate
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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.cs_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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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 = @@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 = @@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 = @@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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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 = @@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 = @@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 = @@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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportAggregate_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE      PROCEDURE [dbo].cs_BlogActivityReportAggregate_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)

AS
BEGIN

-- declare @Paged BIT
-- set @Paged = 1
-- declare @EndReportDate DateTime
-- set @EndReportDate = '1/1/2008'
-- declare @BegReportDate DateTime
-- set @BegReportDate = '1/1/1900'
-- declare @nRecordNumberStart INT
-- set @nRecordNumberStart = 1
-- declare @nRecordNumberEnd INT
-- set @nRecordNumberEnd = 100


IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
		--------------------------------------------------------------------
		-- Define the table to do the filtering and paging
		--------------------------------------------------------------------
		DECLARE @tblTempData TABLE
		(
			nID INT IDENTITY
			,DayViews INT
			,DayComments INT
			,DayTrackbacks INT
			,DayPosts INT
			,DayArticles INT
			,ApplicationKey varchar(100)
		)
		INSERT INTO @tblTempData
		(
			DayViews
			,DayComments
			,DayTrackbacks
			,DayPosts
			,DayArticles
			,ApplicationKey
		)
		SELECT
			SUM(DayViews) AS DayViews, SUM(DayComments) AS DayComments, SUM(DayTrackBacks) AS DayTrackBacks
			,SUM(DayPosts) AS DayPosts, SUM(DayArticles) AS DayArticles
			,(SELECT  ApplicationKey FROM cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
		FROM
			cs_BlogActivityReport AS bar
			INNER JOIN cs_Sections sec ON sec.SectionID = bar.SectionID
		WHERE 
			ApplicationType = 1
		        AND bar.CoverageDate between @BegReportDate and @EndReportDate
			AND DayViews > 0
		GROUP BY
			bar.SectionID
		ORDER BY
			DayViews DESC
		SET @totalRecords = @@rowcount
		-------------------------------------------------------------------------------------
		
		SELECT
			DayViews
			,DayComments
			,DayTrackbacks
			,DayPosts
			,DayArticles
			,ApplicationKey
		FROM
			@tblTempData 
		WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
		ORDER BY 
			nID ASC
		
		--Return Record Count
		SELECT @totalRecords

		--Return TotalBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1

		--Return TotalEnabledBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1 AND IsActive = 1

		--Return TotalDisabledBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1 AND IsActive = 0
	END
ELSE
	BEGIN
		SELECT
			(SELECT  ApplicationKey FROM cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
			,SUM(DayViews) As TotalViews
			,SUM(DayComments) As TotalComments
			,SUM(DayTrackBacks) As TotalTrackBacks
			,SUM(DayPosts) As TotalPosts
			,SUM(DayArticles) As TotalArticles
		FROM
			cs_BlogActivityReport AS bar
			INNER JOIN cs_Sections sec ON sec.SectionID = bar.SectionID
		WHERE
			ApplicationType = 1
		        AND bar.CoverageDate between @BegReportDate and @EndReportDate
		GROUP BY
			bar.SectionID
		ORDER BY
			TotalViews DESC
	END
END                                                                                                                                                                                                                               


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_BlogActivityReportAggregate_Get] to public
go

/***********************************************
* Sproc: cs_BlogActivityReportRecords_Get
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportRecords_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  PROCEDURE [dbo].cs_BlogActivityReportRecords_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
)

AS
BEGIN
	DECLARE @totalRecords INT

	--------------------------------------------------------------------
    	-- Define the table to do the filtering and paging
    	--------------------------------------------------------------------
    	DECLARE @tblTempData TABLE
        (
        	nID INT IDENTITY
        	,SectionID INT
        	,ThreadID INT
		,CoverageDate DateTime
        	,TotalViews INT
		,DayViews INT
		,DayComments INT
		,DayTrackbacks INT
		,IsPost bit
		,IsArticle bit
		,JobExecutionTimeStamp DateTime
		,PostID INT
		,PostSubject varchar(256)
		,ApplicationPostType INT
		,ApplicationKey varchar(100)
        )
	INSERT INTO @tblTempData
	(
        	SectionID
        	,ThreadID
		,CoverageDate
        	,TotalViews
		,DayViews
		,DayComments
		,DayTrackbacks
		,IsPost
		,IsArticle
		,JobExecutionTimeStamp
		,PostID
		,PostSubject
		,ApplicationPostType
		,ApplicationKey
        )
    	SELECT  SectionID, ThreadID, CoverageDate, TotalViews, DayViews, DayComments, DayTrackBacks, IsPost, IsArticle, JobExecutionTimeStamp,
    		(SELECT  PostID FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS PostID,
		(SELECT  Subject FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS PostSubject,
    		(SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS ApplicationPostType,
    		(SELECT  ApplicationKey FROM     cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
	FROM     cs_BlogActivityReport AS bar
	WHERE 
		(((SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) = 1)
                OR ((SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) = 2))
                AND bar.CoverageDate between @BegReportDate and @EndReportDate
	ORDER BY
		bar.CoverageDate
	SET @totalRecords = @@rowcount
        ---------------------------------------------------------------------------------------------------------------------------------------
	SELECT
        	SectionID
        	,ThreadID
        	,TotalViews
		,DayViews
		,DayComments
		,DayTrackbacks
		,IsPost
		,IsArticle
		,JobExecutionTimeStamp
		,PostID
		,PostSubject
		,ApplicationPostType
		,ApplicationKey
		,CoverageDate
    	FROM
		@tblTempData 
    	WHERE
		nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
    	ORDER BY 
        	nID ASC

-- Return totalRecords
SELECT @totalRecords

END
                                                                                                                                                                                                                                         


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_BlogActivityReportRecords_Get to public
go

/***********************************************
* Sproc: cs_Censorships_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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(40) = '',
	@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: 8/8/2006 9:28:12 AM
***********************************************/
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(40)
	, @DeleteWord 	bit = 0
	, @Replacement	nvarchar(40)
	, @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_Content_CreateUpdateDelete
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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 
		c.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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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_EmailQueue_Delete
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...cs_EmailQueue_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EmailQueue_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EmailQueue_Delete]
GO


create proc dbo.cs_EmailQueue_Delete
	@EmailID uniqueidentifier 
as
SET Transaction Isolation Level Read UNCOMMITTED
	delete from cs_EmailQueue where EmailID = @EmailID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON dbo.cs_EmailQueue_Delete TO public
GO
/***********************************************
* Sproc: cs_EmailQueue_Failure
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_EmailQueue_Failure'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EmailQueue_Failure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EmailQueue_Failure]
GO


create proc dbo.cs_EmailQueue_Failure
	@EmailID uniqueidentifier,
	@FailureInterval int,
	@MaxNumberOfTries int
as
SET Transaction Isolation Level Read UNCOMMITTED
declare @NumberOfTries int
select @NumberOfTries = NumberOfTries + 1 from cs_EmailQueue where EmailID = @EmailID

if @NumberOfTries <= @MaxNumberOfTries
begin
	update cs_EmailQueue set
		NumberOfTries = @NumberOfTries,
		NextTryTime = dateadd(minute, @NumberOfTries * @FailureInterval, getdate())
	where EmailID = @EmailID
end
else
begin
	delete from cs_EmailQueue where EmailID = @EmailID
end
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_EmailQueue_Failure TO public
GO
/***********************************************
* Sproc: cs_Emails_Dequeue
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
Print 'Creating...cs_Emails_Dequeue'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_Dequeue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_Dequeue]
GO



CREATE    PROCEDURE [dbo].cs_Emails_Dequeue
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT * FROM cs_EmailQueue Where SettingsID = @SettingsID and NextTryTime < getdate()
	
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Emails_Dequeue to public
go
/***********************************************
* Sproc: cs_Emails_Enqueue
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_Emails_Enqueue'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_Enqueue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_Enqueue]
GO


CREATE  PROCEDURE [dbo].cs_Emails_Enqueue
(
	@EmailTo	nvarchar(2000),
	@EmailCc	ntext,
	@EmailBcc	ntext,
	@EmailFrom	nvarchar(256),
	@EmailSubject	nvarchar(1024),
	@EmailBody	ntext,
	@EmailPriority	int,
	@EmailBodyFormat int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	INSERT INTO
		cs_EmailQueue
		(
			emailTo,
			emailCc,
			emailBcc,
			EmailFrom,
			EmailSubject,
			EmailBody,
			emailPriority,
			emailBodyFormat,
			SettingsID
		)
	VALUES
		(
			@EmailTo,
			@EmailCc,
			@EmailBcc,
			@EmailFrom,
			@EmailSubject,
			@EmailBody,
			@EmailPriority,
			@EmailBodyFormat,
			@SettingsID
		)		
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_Emails_Enqueue to public
go
/***********************************************
* Sproc: cs_Emails_TrackingSection
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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 @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)
BEGIN
	-- this is a new thread (1 & 2)
	
	-- Check if this is a PM message
	IF (@SectionID = 0)
	BEGIN
		
		-- we have to bind to the PM users for this ThreadID
		SELECT
			U.cs_UserID as UserID,
			U.Email,
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
			JOIN cs_PrivateMessages PM ON PM.UserID = F.UserID AND PM.ThreadID = @ThreadID
		WHERE
			F.SectionID IN (-1, 0) AND F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and 
			U.EnableThreadTracking = 1 and
			F.SubscriptionType & 3 <> 0
	END
	ELSE BEGIN

		SELECT
			U.cs_UserID as UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
		WHERE
			F.SectionID = @SectionID AND F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
			U.EnableThreadTracking = 1 and
			F.SubscriptionType & 3 <> 0
	END
END
ELSE BEGIN
	-- this is a reply to an existing post (2)

	-- Check if this is a PM message
	IF (@SectionID = 0)
	BEGIN
		
		-- we have to bind to the PM users for this ThreadID
		SELECT
			U.cs_UserID as UserID,
			U.Email,
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
			JOIN cs_PrivateMessages PM ON PM.UserID = F.UserID AND PM.ThreadID = @ThreadID
		WHERE
			F.SectionID IN (-1, 0) AND U.SettingsID = @SettingsID and F.SettingsID = @SettingsID and
			F.SubscriptionType & 3 = 3

	END
	ELSE BEGIN

		SELECT
			U.cs_UserID as UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID			
		WHERE
			F.SectionID = @SectionID AND U.SettingsID = @SettingsID and F.SettingsID = @SettingsID 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: 8/8/2006 9:28:19 AM
***********************************************/
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


-- Check if this is a PM message
IF (@SectionID = 0)
BEGIN
	
	-- we have to bind to the PM users for this ThreadID
	SELECT
		U.cs_UserID as UserID,
		U.Email,
		U.EnableHtmlEmail
	FROM
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = T.UserID
				JOIN cs_PrivateMessages PM ON PM.UserID = T.UserID AND PM.ThreadID = @ThreadID
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID and PM.SettingsID = @SettingsID and
		U.EnableThreadTracking = 1

END
ELSE BEGIN

	SELECT
		U.cs_UserID as UserID,
		U.Email, 
		U.EnableHtmlEmail
	FROM 
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = T.UserID			
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID 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: 8/8/2006 9:28:21 AM
***********************************************/
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,
	@Add bit
)

as

if @Add = 1
Begin

	Insert cs_es_Search_RemoveQueue (PostID, SettingsID) Values (@PostID, @SettingsID)

End
ELSE
BEGIN
	DELETE FROM cs_es_Search_RemoveQueue where PostID = @PostID and SettingsID = @SettingsID
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 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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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	EL.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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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
		E.DateLastOccurred DESC, E.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
		E.Frequency DESC, E.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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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 = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers 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: 8/8/2006 9:28:19 AM
***********************************************/
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,
	@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.cs_UserID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE
	FP.OwnerID = @UserID
	AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID AND U.SettingsID = @SettingsID
ORDER BY
	jP.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: 8/8/2006 9:28:20 AM
***********************************************/
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,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		F.SectionID,
		F.ApplicationType
	FROM
		cs_FavoriteSections 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_GetSections] to public

/***********************************************
* Sproc: cs_Favorites_GetUsers
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsers]
GO

CREATE procedure dbo.cs_Favorites_GetUsers
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.UserID = U.cs_UserID AND
		F.OwnerID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsers] to public

/***********************************************
* Sproc: cs_Favorites_GetUsersWatching
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsersWatching'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsersWatching]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsersWatching]
GO

CREATE procedure dbo.cs_Favorites_GetUsersWatching
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.OwnerID = U.cs_UserID AND
		F.UserID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID AND
		(U.FavoritesShared & 2) = 2		-- sharing users

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsersWatching] to public

/***********************************************
* Sproc: cs_Favorite_Add
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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 = 2	-- User
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteUsers F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	UserID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteUsers
				(OwnerID, SettingsID, UserID, 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: 8/8/2006 9:28:11 AM
***********************************************/
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 = 2	-- User

		DELETE
		FROM	cs_FavoriteUsers
		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: 8/8/2006 9:28:19 AM
***********************************************/
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 = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers 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: 8/8/2006 9:28:20 AM
***********************************************/
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 = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.OwnerID = @UserID AND
			F.UserID = @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: 8/8/2006 9:28:20 AM
***********************************************/
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


CREATE PROC [dbo].cs_FeedPost_GetPost
	@FeedPostId INT
AS


SELECT 	FeedPostId,
	FeedId,
	Author,
	Title,
	Description,
	Source,
	GuidName,
	GuidIsPermaLink,
	Link,
	PubDate,
	CommentsUrl,
	EnclosureUrl,
	EnclosureLength,
	EnclosureType,
	Creator,
	CommentApiUrl,
	CommentRssUrl,
	CommentCount
FROM cs_FeedPost
WHERE FeedPostId = @FeedPostId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_GetPost  TO PUBLIC
GO

/***********************************************
* Sproc: cs_FeedPost_GetPostFullDetails
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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


CREATE PROC [dbo].cs_FeedPost_GetPostFullDetails
	@FeedId INT
AS


SELECT 	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_FeedPost fp,
	cs_Feed f
WHERE f.FeedId = fp.FeedId
  AND fp.FeedPostId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_GetPostFullDetails  TO PUBLIC
GO

/***********************************************
* Sproc: cs_FeedPost_UpdatePosts
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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



CREATE PROC [dbo].cs_FeedPost_UpdatePosts
	@FeedId INT,
	@FeedItemList NTEXT
AS

SET NOCOUNT ON

DECLARE @idoc INT
DECLARE @FeedPosts TABLE
(
	FeedId INT,
	Author NVARCHAR(255),
	Title NVARCHAR(255),
	Description NTEXT,
	Source NVARCHAR(255),
	GuidName NVARCHAR(255) collate database_default,
	GuidIsPermaLink BIT,
	Link NVARCHAR(255),
	PubDate DATETIME,
	CommentsUrl NVARCHAR(255),
	EnclosureUrl VARCHAR(255),
	EnclosureLength BIGINT,
	EnclosureType NVARCHAR(100),
	Creator NVARCHAR(255) NULL,
	CommentApiUrl NVARCHAR(255) NULL,
	CommentRssUrl NVARCHAR(255) NULL,
	CommentCount INT NULL
)

EXEC sp_xml_preparedocument @idoc OUTPUT, @FeedItemList

-- First off, let's move all the XML into the table variable.
INSERT INTO @FeedPosts
  SELECT C.FeedId,
	C.Author,
	C.Title,
	C.Description,
	C.Source,
	C.GuidName,
	C.GuidIsPermaLink,
	C.Link,
	C.PubDate,
	C.CommentsUrl,
	C.EnclosureUrl,
	C.EnclosureLength,
	C.EnclosureType,
	C.Creator,
	C.CommentApiUrl,
	C.CommentRssUrl,
	C.CommentCount
FROM OPENXML(@idoc, '/feeds/feed', 3)  
WITH (	FeedId INT,
	Author NVARCHAR(255),
	Title NVARCHAR(255),
	Description NTEXT,
	Source NVARCHAR(255),
	GuidName NVARCHAR(255),
	GuidIsPermaLink BIT,
	Link NVARCHAR(255),
	PubDate DATETIME,
	CommentsUrl NVARCHAR(255),
	EnclosureUrl VARCHAR(255),
	EnclosureLength BIGINT,
	EnclosureType NVARCHAR(100),
	Creator NVARCHAR(255),
	CommentApiUrl NVARCHAR(255),
	CommentRssUrl NVARCHAR(255),
	CommentCount INT) AS C

-- Insert missing posts
INSERT INTO cs_FeedPost
(
	FeedId,
	Author,
	Title,
	Description,
	Source,
	GuidName,
	GuidIsPermaLink,
	Link,
	PubDate,
	CommentsUrl,
	EnclosureUrl,
	EnclosureLength,
	EnclosureType,
	Creator,
	CommentApiUrl,
	CommentRssUrl,
	CommentCount
	
)
SELECT 	C.FeedId,
	C.Author,
	C.Title,
	C.Description,
	C.Source,
	C.GuidName,
	C.GuidIsPermaLink,
	C.Link,
	C.PubDate,
	C.CommentsUrl,
	C.EnclosureUrl,
	C.EnclosureLength,
	C.EnclosureType,
	C.Creator,
	C.CommentApiUrl,
	C.CommentRssUrl,
	C.CommentCount
FROM @FeedPosts AS C
WHERE C.GuidName NOT IN 	(
  SELECT GuidName FROM cs_FeedPost 
  WHERE FeedId = @FeedId
			)  

-- Update existing posts.
UPDATE cs_FeedPost
SET	Author = C.Author,
	Title = C.Title,
	Description = C.Description,
	Source = C.Source,
	GuidName = C.GuidName,
	GuidIsPermaLink = C.GuidIsPermaLink,
	Link = C.Link,
	PubDate = C.PubDate,
	CommentsUrl = C.CommentsUrl,
	EnclosureUrl = C.EnclosureUrl,
	EnclosureLength = C.EnclosureLength,
	EnclosureType = C.EnclosureType,
	Creator = C.Creator,
	CommentApiUrl = C.CommentApiUrl,
	CommentRssUrl = C.CommentRssUrl,
	CommentCount = C.CommentCount
FROM @FeedPosts AS C
WHERE cs_FeedPost.GuidName = C.GuidName



EXEC sp_xml_removedocument @idoc



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_UpdatePosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_AddFeed
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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


CREATE PROC [dbo].cs_Feed_AddFeed
	@FolderId INT = NULL,
	@UserId INT,
	@Url NVARCHAR(255),
	@SettingsID INT,
	@FeedId INT OUTPUT
AS


DECLARE @NewFeedId INT


-- First, let's see if the feed is already registered.
SELECT @NewFeedId = FeedId
FROM cs_Feed
WHERE Url = @Url and SettingsID = @SettingsID


-- If it's not, let's insert it and grab the FeedId.
IF (@NewFeedId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_Feed
	(
		Url,
		SettingsID
	) 
	VALUES
	(
		@Url,
		@SettingsID
	)

	-- Grab the identity generated.
	SELECT @NewFeedId = @@IDENTITY

  END

-- Add the feed to the user's folder.
INSERT INTO cs_FolderFeed
(
	UserId,
	FolderId,
	FeedId,
	SettingsID
)
VALUES
(
	@UserId,
	@FolderId,
	@NewFeedId,
	@SettingsID
)

SELECT @FeedId = @NewFeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_AddFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetAll
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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


CREATE PROC [dbo].cs_Feed_GetAll
(
	@SettingsID int
)
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetAll  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetAll_ModifiedSince
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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


CREATE PROC [dbo].cs_Feed_GetAll_ModifiedSince
(
	@Minutes int,
	@SettingsID int
)
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
Where DateAdd(mi, @Minutes, LastUpdateDate) <= GetDate() and SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetAll_ModifiedSince  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetFeed
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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

CREATE PROC [dbo].cs_Feed_GetFeed
	@FeedId INT
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE FeedId = @FeedId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetFeedPosts
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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


CREATE PROC [dbo].cs_Feed_GetFeedPosts
	@FeedId INT,
	@UserId INT,
	@SettingsID INT
AS

SELECT top 50 fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount, 
	HasRead = CASE WHEN urp.UserID 
			IS NULL THEN 0 ELSE 1 
		  END 
FROM 
	(SELECT DISTINCT UserID, FeedID FROM cs_FolderFeed) ff 
	INNER JOIN cs_Feed f ON
		ff.FeedId = f.FeedId
	INNER JOIN cs_FeedPost fp ON
		ff.FeedId = fp.FeedId
	LEFT OUTER JOIN cs_UserReadPost urp ON
		fp.FeedPostId	= urp.FeedPostId
	AND ff.UserID		= urp.UserID
WHERE
	ff.UserID = @UserId and f.SettingsID = @SettingsID
AND
  	ff.FeedId = @FeedId
ORDER BY fp.PubDate DESC


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetFeedPosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetProperties
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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

CREATE PROC [dbo].cs_Feed_GetProperties
	@FeedId INT
AS


SELECT 	cf.Url,
	cf.Title,
	cf.Link,
	cf.Language,
	cf.Generator,
	cf.SubscribeDate,
	cf.LastUpdateDate,
	cfs.StateName,
	cfs.Description,
	[SubscribeCount] = (SELECT COUNT(*) FROM cs_FolderFeed WHERE FeedId = cf.FeedId),
	[PostCount] = (SELECT COUNT(*) FROM cs_FeedPost WHERE FeedId = cf.FeedId)
FROM 	cs_Feed cf,
	cs_FeedState cfs
WHERE cf.FeedStateId = cfs.FeedStateId
  AND cf.FeedId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetProperties  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetUsers
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROC [dbo].cs_Feed_GetUsers
	@SettingsID INT
AS


	SELECT U.*
	FROM  cs_vw_Users_FullUser U
	WHERE U.SettingsID = @SettingsID 
		and U.cs_UserID in (select distinct UserID from cs_Folder where SettingsID = @SettingsID)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Feed_GetUsers]  TO [public]
GO


/***********************************************
* Sproc: cs_Feed_MoveFeed
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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

CREATE PROC [dbo].cs_Feed_MoveFeed
	@FolderFeedId INT,
	@NewFolderId INT = NULL
AS

UPDATE cs_FolderFeed
SET FolderId = @NewFolderId
WHERE FolderFeedId = @FolderFeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_MoveFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_Update
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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

CREATE PROC [dbo].cs_Feed_Update
	@FeedId INT,
	@Url NVARCHAR(255),
	@Title NVARCHAR(255),
	@Link NVARCHAR(255),
	@Language NVARCHAR(10),
	@Generator NVARCHAR(255),
	@SubscribeDate DATETIME,
	@LastUpdateDate DATETIME,
	@FeedStateId INT,
	@LastModified DATETIME,
	@ETag nvarchar(256) = NULL

AS

UPDATE cs_Feed
SET 	Url = @Url,
	Title = @Title,
	Link = @Link,
	Language = @Language,
	Generator = @Generator,
	SubscribeDate = @SubscribeDate,
	LastUpdateDate = @LastUpdateDate,
	FeedStateId = @FeedStateId,
	LastModified = @LastModified,
	ETag = @ETag
WHERE FeedId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_Update  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_UpdateFeedStatus
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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



CREATE PROC [dbo].cs_Feed_UpdateFeedStatus
	@FeedId INT,
	@FeedStateId INT
AS


UPDATE cs_Feed
SET	FeedStateId = @FeedStateId,
	LastUpdateDate = GetDate()
WHERE FeedId = @FeedId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_UpdateFeedStatus  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_AddFolder
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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


CREATE PROC [dbo].cs_Folder_AddFolder
	@UserID INT,
	@FolderName NVARCHAR(50),
	@ParentFolderId INT = NULL,
	@SettingsID INT,
	@FolderId INT OUTPUT
AS

INSERT INTO cs_Folder
(
	UserId,
	FolderName,
	ParentFolderId,
	SettingsID
	
)
VALUES
(
	@UserId,
	@FolderName,
	@ParentFolderId,
	@SettingsID
)

SELECT @FolderId = @@IDENTITY


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_AddFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_DeleteFolder
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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


CREATE PROC [dbo].cs_Folder_DeleteFolder
	@FolderId INT
AS

-- First, let's delete any associated feeds.
DELETE
FROM cs_FolderFeed
WHERE FolderId = @FolderId

-- Now, delete the folder.
DELETE
FROM cs_Folder
WHERE FolderId = @FolderId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_DeleteFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetFeeds
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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

CREATE PROC [dbo].cs_Folder_GetFeeds
	@UserId INT,
	@SettingsID int,
	@FolderId INT = NULL

AS


IF (@FolderId IS NULL)
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.Language,
	    cf1.Generator,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId IS NULL 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

  END

ELSE
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.Language,
	    cf1.Generator,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select  count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId = @FolderId 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetFolders
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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


CREATE PROC [dbo].cs_Folder_GetFolders
	@UserId INT,
	@SettingsID INT,
	@ParentFolderId INT = -1
AS
Begin


	Create Table #Temp ( FeedId int, FolderId int, CNT int )
	
	Insert #Temp (FeedId, FolderId, CNT)
	Select FeedId, cf.FolderId,
	(
		select count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cf.FeedId and urp.UserId IS NULL
	) as [CNT] FROM cs_FolderFeed cf, cs_Folder ff where cf.FolderId = ff.FolderId and  IsNull(ff.ParentFolderId, -1) = @ParentFolderId and cf.UserId = @UserId and cf.SettingsID = @SettingsID and ff.SettingsID = @SettingsID


	SELECT 	FolderId,
		UserId,
		FolderName,
		ParentFolderId
		,[UnreadCount] = (Select Sum(CNT) FROM #Temp where #Temp.FolderId = cs_Folder.FolderID)
	FROM cs_Folder
	WHERE UserId = @UserId
	  AND IsNull(ParentFolderId,-1) =  @ParentFolderId
          AND cs_Folder.SettingsID = @SettingsID
	ORDER BY FolderName



	DROP Table #Temp

  END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetFolders  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetSummary
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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

CREATE PROC [dbo].cs_Folder_GetSummary
	@UserId INT,
	@SettingsID INT,
	@FolderId INT = NULL

AS
BEGIN

IF (@FolderId IS NULL)
BEGIN
	SET @FolderId = -1
END

-- Give me the top 10 most active blog posts
SELECT 	TOP 10
	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_Feed f,
	cs_FeedPost fp,
	cs_FolderFeed ff
WHERE f.FeedId = fp.FeedId
  AND fp.CommentCount > 0
  AND fp.PubDate >= DATEADD(day, -30, GetDate())
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
  AND IsNull(ff.FolderId,-1) = @FolderId
  AND f.SettingsID = @SettingsID AND ff.SettingsID = @SettingsID
  ORDER BY fp.CommentCount DESC



SELECT top 100 	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_Feed f,
	cs_FeedPost fp,
	cs_FolderFeed ff
WHERE f.FeedId = fp.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
   AND IsNull(ff.FolderId,-1) = @FolderId
  AND f.SettingsID = @SettingsID AND ff.SettingsID = @SettingsID
  ORDER BY fp.PubDate DESC




  END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetSummary  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_MoveFolder
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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

CREATE PROC [dbo].cs_Folder_MoveFolder
	@FolderId INT,
	@NewParentFolderId INT = NULL
AS

UPDATE cs_Folder
SET ParentFolderId = @NewParentFolderId
WHERE FolderId = @FolderId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_MoveFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_RenameFolder
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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

CREATE PROC [dbo].cs_Folder_RenameFolder
	@FolderId INT,
	@FolderName NVARCHAR(50)
AS


UPDATE cs_Folder
SET FolderName = @FolderName
WHERE FolderId = @FolderId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_RenameFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_ForumPostActivityReportRecords_Get
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/* Most active forums for a given month: Forum, Total Posts, Replies */
CREATE PROC dbo.cs_ForumPostActivityReportRecords_Get
(
	@BegReportDate datetime,
	@EndReportDate datetime,
	@nRecordNumberStart int,
	@nRecordNumberEnd int,
	@Paged bit
)
AS

BEGIN
IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
	
		--------------------------------------------------------------------
	    	-- Define the table to do the filtering and paging
	    	--------------------------------------------------------------------
	    	DECLARE @tblTempData TABLE
	        (
	        	nID INT IDENTITY,
	        	SectionID int,
			ApplicationKey nvarchar(256),
			[Name] nvarchar(255),
			Threads int,
			Replies int,
			Users int
	        )
		INSERT INTO @tblTempData
		(
	        	SectionID, ApplicationKey, [Name], Threads, Replies, Users
	        )
		SELECT * FROM
		    	(SELECT DISTINCT 
			s.SectionID,
			s.ApplicationKey,
			s.[Name],
			(SELECT COUNT(*) FROM cs_Threads t WHERE t.SectionID = s.SectionID AND t.ThreadDate BETWEEN @BegReportDate AND @EndReportDate ) AS Threads,
			(SELECT COUNT(*) FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS Replies,
			(SELECT COUNT(*) FROM (SELECT DISTINCT UserID FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS u) AS Users
				FROM cs_Sections s
				WHERE s.ApplicationType = 0
			) AS tr
		WHERE tr.Threads > 0 or tr.Replies > 0
		ORDER BY tr.Replies DESC

		SET @totalRecords = @@rowcount
	        ---------------------------------------------------------------------------------------------------------------------------------------
		SELECT
	        	SectionID, ApplicationKey, [Name], Threads, Replies, Users
	    	FROM
			@tblTempData 
	    	WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
	    	ORDER BY 
	        	nID ASC
	
		-- Return totalRecords
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT * FROM
		    	(SELECT DISTINCT 
			s.SectionID,
			s.ApplicationKey,
			s.[Name],
			(SELECT COUNT(*) FROM cs_Threads t WHERE t.SectionID = s.SectionID AND t.ThreadDate BETWEEN @BegReportDate AND @EndReportDate ) AS Threads,
			(SELECT COUNT(*) FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS Replies,
			(SELECT COUNT(*) FROM (SELECT DISTINCT UserID FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS u) AS Users
				FROM cs_Sections s
				WHERE s.ApplicationType = 0
			) AS tr
		WHERE tr.Threads > 0 or tr.Replies > 0
		ORDER BY tr.Replies DESC
	END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ForumPostActivityReportRecords_Get] to public
go
/***********************************************
* Sproc: cs_forums_GetForumMessages
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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.cs_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: 8/8/2006 9:28:18 AM
***********************************************/
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 cs_UserID = @UserID and SettingsID = @SettingsID)

-- Is the Forum 0 (If so this is a private message and we need to verify the user can view it
IF @SectionID = 0
BEGIN
	IF NOT EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID AND ThreadID = @ThreadID)
		RETURN
END

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
BEGIN
	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)
END

/*
-- 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.cs_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.cs_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: 8/8/2006 9:28:22 AM
***********************************************/
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

-- Is the Forum 0 (If so this is a private message and we need to verify the user can view it
IF @SectionID = 0
BEGIN
	IF NOT EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID AND ThreadID = @ThreadID AND SettingsID = @SettingsID)
		RETURN
END

-- 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.cs_UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END

IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name], jP.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts jP ON jPI.PostID = jP.PostID
		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.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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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.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.cs_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_fourm_Feedback_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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_gallery_Post_GetSortOrder
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_gallery_Post_GetSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Post_GetSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Post_GetSortOrder]
GO


/***********************************************
* Sproc: cs_gallery_Search
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...cs_gallery_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Search]
GO
/***********************************************
* Sproc: cs_gallery_Search_PostReindex
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...cs_gallery_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_gallery_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Search_PostReindex]
GO

/***********************************************
* Sproc: cs_gallery_Threads_GetAllThreads
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
Print 'Creating...cs_gallery_Threads_GetAllThreads'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Threads_GetAllThreads]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Threads_GetAllThreads]
GO





/***********************************************
* Sproc: cs_gallery_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...cs_gallery_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_gallery_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Threads_GetThreadSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_GetAnonymousUserID
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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


Create Proc [dbo].cs_GetAnonymousUserID
(
	@SettingsID int,
	@UserID int output
)
as
SET Transaction Isolation Level Read UNCOMMITTED
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and IsAnonymous = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

GO

grant execute on [dbo].cs_GetAnonymousUserID to public
go
/***********************************************
* Sproc: cs_GetSectionSubscriptionType
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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.cs_UserID
FROM 
	cs_vw_Users_FullUser U (nolock)
WHERE 
	U.cs_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_Groups_Get
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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,
	@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
		)
	VALUES 
		(
			@Name,
			@Description,
			@SortOrder,
			@ApplicationType,
			@SettingsID
		)
	
	SET @GroupID = @@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
		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_guestbook_GetPosts
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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.cs_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: 8/8/2006 9:28:18 AM
***********************************************/
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 
		cs_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 = @@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 = @@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 = @@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: 8/8/2006 9:28:11 AM
***********************************************/
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_Image_CreateUpdateDelete
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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_Update
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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,
	@LicenseType nvarchar(50),
	@LicenseValue ntext
AS

if exists(select LicenseType from cs_Licenses where LicenseType = @LicenseType)
begin
	delete from cs_Licenses where LicenseType = @LicenseType
end

insert into cs_Licenses (LicenseID, LicenseType, LicenseValue) values (@LicenseID, @LicenseType, @LicenseValue)
GO


grant execute on [dbo].[cs_Licenses_Update] to public
go
/***********************************************
* Sproc: cs_LinkCategories_Get
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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_Message_CreateUpdateDelete
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
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_Moderate_ApprovePost
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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
	
	-- Is this a private message post (@SectionID = 0)?
	IF (@SectionID = 0)
	BEGIN
		-- Permanently delete the post and its replies
		EXEC cs_Post_Delete @SectionID, @SettingsID, @PostID, 0, @DeletedBy, @Reason

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
	END
	ELSE -- (@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: 8/8/2006 9:28:20 AM
***********************************************/
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.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, 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
FROM
	cs_Sections F
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: 8/8/2006 9:28:17 AM
***********************************************/
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
SELECT 
	R.RoleID,
	R.RoleName as [Name],
	Description 
FROM 
	cs_SectionPermissions P,
	aspnet_roles R
WHERE
	P.RoleID = R.RoleID AND
	P.allowmask & convert(bigint,0x0000100000000000) = convert(bigint,0x0000100000000000)  AND
	SectionID = @SectionID and P.SettingsID = @SettingsID







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: 8/8/2006 9:28:19 AM
***********************************************/
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,
    @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 EXISTS(
				SELECT
					A.UserId
				FROM
					aspnet_UsersInRoles A, cs_UserProfile U
				WHERE
					U.MembershipID = A.UserId and
					U.UserID = @MovedBy  and U.SettingsID = @SettingsID
					AND A.RoleId IN (
						SELECT 
							RoleID 
						FROM 
							cs_SectionPermissions
						WHERE 
							SectionID = @SectionID
							AND AllowMask & convert(bigint,0x0000100000000000) = convert(bigint,0x0000100000000000)  and SettingsID = @SettingsID
					)
			)
			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

				-- 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
				
				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

			-- 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
		
		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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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

-- 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: 8/8/2006 9:28:12 AM
***********************************************/
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 = @@IDENTITY
FROM
	cs_Threads


-- 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: 8/8/2006 9:28:17 AM
***********************************************/
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,
	ID int
)

CREATE INDEX page_index ON #TmpPageIndex(IndexID)

-- 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.cs_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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	ID int
)

CREATE INDEX page_index ON #TmpPageIndex(IndexID)

-- 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.cs_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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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)
)

-- 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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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 = cs_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 = cs_UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName

	-- Can't find the user
	IF @UserID IS NULL
	BEGIN

		EXEC cs_GetAnonymousUserID @SettingsID, @UserID output

	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_OverviewActivityReportRecords_Get
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




CREATE PROC dbo.cs_OverviewActivityReportRecords_Get
(
	@BegReportDate datetime,
	@EndReportDate datetime
)

AS

/* # of new users in given time period */
SELECT COUNT(*) FROM aspnet_Membership
WHERE CreateDate BETWEEN @BegReportDate AND @EndReportDate


/* # of new threads in a given time period */
SELECT COUNT(*)
FROM cs_Threads
WHERE ThreadDate BETWEEN @BegReportDate AND @EndReportDate


/* # of new posts in a given time period */
SELECT COUNT(*)
FROM cs_Posts
WHERE PostDate BETWEEN @BegReportDate AND @EndReportDate



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OverviewActivityReportRecords_Get] to public
go
/***********************************************
* Sproc: cs_PageViews_Add
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE    Proc [dbo].cs_PageViews_Add
(
	@URL nvarchar(512),
	@VisitCount int
)
AS

DECLARE @DTStamp AS DateTime
SET @DTStamp = GetDate()

IF EXISTS (SELECT URL FROM cs_PageViews WHERE URL = @URL AND DATEDIFF(HOUR, DateTimeStamp, @DTStamp) < 1)
	UPDATE cs_PageViews
	SET cs_PageViews.VisitCount = cs_PageViews.VisitCount + @VisitCount
        WHERE URL = @URL
ELSE
	INSERT INTO cs_PageViews
		(URL, VisitCount, DateTimeStamp)
	VALUES
		(@URL, @VisitCount, @DTStamp)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PageViews_Add] to public
go

/***********************************************
* Sproc: cs_PageViews_Get
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE      PROCEDURE [dbo].cs_PageViews_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)

AS
BEGIN

-- declare @Paged BIT
-- set @Paged = 1
-- declare @EndReportDate DateTime
-- set @EndReportDate = '1/1/2008'
-- declare @BegReportDate DateTime
-- set @BegReportDate = '1/1/1900'
-- declare @nRecordNumberStart INT
-- set @nRecordNumberStart = 1
-- declare @nRecordNumberEnd INT
-- set @nRecordNumberEnd = 100

IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
		--------------------------------------------------------------------
		-- Define the table to do the filtering and paging
		--------------------------------------------------------------------
		DECLARE @tblTempData TABLE
		(
			nID INT IDENTITY
			,URL varchar(512)
			,VisitCount INT
		)
		INSERT INTO @tblTempData
		(
			URL
			,VisitCount
		)
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
		SET @totalRecords = @@rowcount
		-------------------------------------------------------------------------------------
		
		SELECT
			URL
			,VisitCount
		FROM
			@tblTempData 
		WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
		ORDER BY 
			nID ASC
		
		--Return Record Count
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
	END
END                                                                                                                                                                                                                               


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PageViews_Get] to public
go

/***********************************************
* Sproc: cs_Page_Visits_Add
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_Page_Visits_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  Proc [dbo].cs_Page_Visits_Add
(
	@IP nvarchar(20),
	@VisitCount int
)
AS

DECLARE @DTStamp AS DateTime
SET @DTStamp = GetDate()

INSERT INTO cs_Visits
		(IP, VisitCount, DateTimeStamp)
	VALUES
		(@IP, @VisitCount, @DTStamp)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Page_Visits_Add to public
go

/***********************************************
* Sproc: cs_Points_CalculateForPost
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@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


	-- 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		files_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
				+ @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: 8/8/2006 9:28:13 AM
***********************************************/
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,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- recalculate post points
	EXECUTE cs_Points_CalculateForPost @SettingsID, @PostID, @PostFactor, @ReplyFactor, @ReplierFactor, @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


	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: 8/8/2006 9:28:11 AM
***********************************************/
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,
	@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	#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 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		files_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(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	#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	#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: 8/8/2006 9:28:11 AM
***********************************************/
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,
	@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 user's favorite count
	DECLARE		@FavoriteUserCount	int
	SELECT		@FavoriteUserCount = COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	WHERE		FU.UserID = @UserID
		AND		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites


	-- 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
					+ @FavoriteUserCount * @FavoriteUserFactor
					+ @RatingSum * @RaterFactor,
				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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@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	#FavoriteData	(UserID int, Value int)
	CREATE TABLE	#RatingData		(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 favorite count
	INSERT INTO	#FavoriteData
				(UserID, Value)
	SELECT		FU.UserID, COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	INNER JOIN	#UserSet US
		ON		FU.UserID = US.UserID
	WHERE		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites
	GROUP BY	FU.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(FD.Value, 0) * @FavoriteUserFactor
					+ ISNULL(RD.Value, 0) * @RaterFactor,
				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	#FavoriteData FD
		ON		UP.UserID = FD.UserID
	LEFT JOIN	#RatingData RD
		ON		UP.UserID = RD.UserID
	WHERE		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	-- clean up
	DROP TABLE	#RatingData
	DROP TABLE	#FavoriteData
	DROP TABLE	#PostData
	DROP TABLE	#UserSet


	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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@MetaOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	if(@MetaOnly = 0)
	Begin

		SELECT
			[PostID], [SectionID], [UserID], [Created], [FileName], [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [Height], [Width], [FriendlyFileName]
		FROM
			cs_PostAttachments
		WHERE
			PostID = @PostID
	End
	ELSE
	Begin
		SELECT
			[PostID], [SectionID], [UserID], [Created], [FileName], null as [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [Height], [Width], [FriendlyFileName]
		FROM
			cs_PostAttachments
		WHERE
			PostID = @PostID

	End
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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@Content image = 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,
			Content		= @Content,
			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],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			[Height],
			[Width]
		)
		VALUES
		(
			@PostID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@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: 8/8/2006 9:28:11 AM
***********************************************/
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_Temp_Create
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@Content image = 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],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			Created,
			[Height],
			[Width]
		)
		VALUES
		(
			@AttachmentID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@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: 8/8/2006 9:28:14 AM
***********************************************/
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

	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: 8/8/2006 9:28:20 AM
***********************************************/
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], [Content], 
			[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: 8/8/2006 9:28:12 AM
***********************************************/
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 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@ClearContent bit,
	@FriendlyFileName nvarchar(256),
	@AttachmentID uniqueidentifier,
	@SettingsID int,
	@DeleteTempOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

		SELECT
			@PostID as [PostID], [SectionID], [UserID], [Created], [FileName], [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [FriendlyFileName], [Height], [Width]
		FROM
			cs_PostAttachments_TEMP
		WHERE
			AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID

	if(@ClearContent = 1)
	Begin
		update cs_PostAttachments_TEMP
		Set Content = '0x'
  	        where AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID
	End

	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.Content = T.Content,
				cs_PostAttachments.ContentType = T.ContentType,
				cs_PostAttachments.Created = T.Created,
				cs_PostAttachments.UserID = T.UserID
			FROM cs_PostAttachments_TEMP T
			WHERE
				cs_PostAttachments.PostID = @PostID and
				cs_PostAttachments.SettingsID = @SettingsID and
				T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID and T.UserID = @UserID and T.SectionID = @SectionID
		END
		ELSE
		BEGIN
			INSERT INTO 
			cs_PostAttachments
			(
				PostID,
				SectionID,
				UserID,
				[FileName],
				[FriendlyFileName],
				Content,
				ContentType,
				ContentSize,
				IsRemote,
				SettingsID,
				Created,
				[Height],
				[Width]
			)
			Select @PostID,	T.SectionID,T.UserID,T.[Filename],IsNull(@FriendlyFileName,T.FriendlyFileName),T.Content, 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 and T.UserID = @UserID and T.SectionID = @SectionID
		END
	END

	DELETE FROM cs_PostAttachments_TEMP where AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID
	
	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: 8/8/2006 9:28:19 AM
***********************************************/
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,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@MetaDataOnly bit,
	@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	

		if(@MetaDataOnly = 0)
		Begin
			UPDATE cs_PostAttachments SET
			Content		= @Content
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
		End
	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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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 (@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: 8/8/2006 9:28:22 AM
***********************************************/
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 (@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: 8/8/2006 9:28:19 AM
***********************************************/
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),
		SectionID int not null,
		unique (CategoryID, UpLevelID))
	
	--Fix any orphaned categories
	UPDATE cs_Post_Categories SET ParentID = 0 WHERE CategoryID IN (SELECT CategoryID FROM cs_Post_Categories WHERE ParentID <> 0 AND ParentID NOT IN (SELECT CategoryID FROM cs_Post_Categories))

	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 cs_Post_Categories SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	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.PostID = jP.ParentID) 
		INNER JOIN @pathtable P ON PIC.CategoryID = P.CategoryID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID

	GROUP BY P.UpLevelID
	) QSUB ON cs_Post_Categories.CategoryID = QSUB.CategoryID

	INNER JOIN (
	SELECT C.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.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID

	--clear current table data for new values
	IF @SectionID IS NULL
		TRUNCATE TABLE cs_Post_Categories_Parents
	ELSE
		DELETE FROM cs_Post_Categories_Parents WHERE SectionID = @SectionID

	--Commit the path table for use in adding / deleting posts in categories
	INSERT INTO cs_Post_Categories_Parents (SectionID, CategoryID, UpLevelID) SELECT SectionID, CategoryID, UplevelID FROM @pathtable

	--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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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
)

as

Insert cs_posts_deleted_archive (PostID, UserID, SectionID, SettingsID, ApplicationType, Body, Subject, IPAddress, DeletedDate, ParentID, ThreadID, PostLevel, PostType)
Values (@PostID, @UserID, @SectionID, @SettingsID, @ApplicationType, @Body, @Subject, @IPAddress, getdate(), @ParentID, @ThreadID, @PostLevel, @PostType)


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: 8/8/2006 9:28:12 AM
***********************************************/
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	P.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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:14 AM
***********************************************/
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_ReindexByUser
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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
	-- first, reset post to be indexed
	UPDATE	cs_Posts
	SET		IsIndexed =  0
	WHERE	UserID = @UserID

	-- step 2, add post to reindex table
	INSERT INTO	cs_es_Search_RemoveQueue (PostID, SettingsID)
	SELECT		PostID, SettingsID
	FROM		cs_Posts
	WHERE		UserID = @UserID
		AND		PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)
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: 8/8/2006 9:28:19 AM
***********************************************/
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  Proc [dbo].cs_Posts_UpdatePostsInCategories
(
	@CategoryList nvarchar(4000) = null,
	@SectionID int,
	@PostID int,
	@SettingsID int = null,
	@UpdateStats bit = 1
)
as

DELETE FROM cs_Posts_InCategories where PostID = @PostID

-- 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>"

	EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList

	DECLARE @CategoryIDList TABLE
	(
		CategoryID Int
	)

	--Insert Missing Categories
	INSERT INTO cs_Post_Categories (SectionID, [Name], IsEnabled, ParentID, [Description], SettingsID)
		Select 	DISTINCT
			@SectionID, CONVERT(nvarchar(255), X.[text]), 1, 0, null, @SettingsID
		FROM 
			OPENXML(@idoc, '/Categories/Category/', 2) X
		where 
			X.[text] is not null  
			and CONVERT(nvarchar(255), X.[text]) not in (
				Select [Name] FROM cs_Post_Categories where SectionID = @SectionID
			) 
	IF @@ROWCOUNT > 0
		exec [cs_PostCategories_Parents_RebuildIndex] @SectionID

	Insert Into @CategoryIDList (CategoryID) 
	SELECT DISTINCT C.CategoryID 
		FROM OPENXML(@idoc, '/Categories/Category/', 2) X
		inner join cs_Post_Categories C on C.[Name] = Convert(nvarchar(256),X.[text]) collate database_default
				and C.SectionID = @SectionID

		--Insert Entry Categories
		INSERT INTO cs_Posts_InCategories 
			( PostID, CategoryID, SettingsID)
		Select 
			@PostID, C.CategoryID, @SettingsID
		FROM 
			@CategoryIDList C
	
	EXEC sp_xml_removedocument @idoc
END

if(@UpdateStats = 1) --for changes we need to rebuild the entire section stats
Begin
	UPDATE cs_Post_Categories SET
		TotalSubThreads = IsNull(QSUB.posts, 0),
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = IsNull(QCURR.posts, 0),
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	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.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories_Parents P ON PIC.CategoryID = P.CategoryID and P.SectionID = @SectionID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY P.UpLevelID
	) QSUB ON cs_Post_Categories.CategoryID = QSUB.CategoryID

	LEFT  JOIN (
	SELECT C.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.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID
	WHERE cs_Post_Categories.SectionID = @SectionID
End

if(@UpdateStats = 3) --this code is only good for additions
Begin

	UPDATE cs_Post_Categories SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories JOIN
	(
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		@CategoryIDList cid
		inner join cs_Post_Categories C on C.CategoryID = cid.CategoryID
		Inner Join cs_Post_Categories_Parents P on C.CategoryID = P.CategoryID
		INNER JOIN cs_Posts_InCategories PIC on PIC.CategoryID = P.CategoryID
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
	WHERE jP.IsApproved = 1
		Group By P.UplevelID
	) QSUB on cs_Post_Categories.CategoryID = QSUB.CategoryID

	JOIN
	(
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		@CategoryIDList cid
		inner join cs_Post_Categories C on C.CategoryID = cid.CategoryID
		INNER JOIN cs_Posts_InCategories PIC on C.CategoryID  =  PIC.CategoryID
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID)
	WHERE jP.IsApproved = 1
		Group By C.CategoryID
	) QCURR on cs_Post_Categories.CategoryID = QCURR.CategoryID

End


/* This code has been replaced by the update statements above DanB 7-19-2005 */
if(@UpdateStats = 2)
Begin

	-- Update the most recent post dates and total thread stuff for the categories
	declare @UpCategoryID int
	declare @UpPath nvarchar(256)
	DECLARE Categories_Cursor CURSOR FOR
		SELECT CategoryID FROM cs_Post_Categories WHERE SectionID = @SectionID
	
	OPEN Categories_Cursor
	FETCH NEXT FROM Categories_Cursor INTO @UpCategoryID
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		set @UpPath = (select Path from cs_Post_Categories where CategoryID = @UpCategoryID)
	
		UPDATE cs_Post_Categories SET
			TotalThreads = IsNull((SELECT COUNT(PIC.PostID) FROM cs_Posts_InCategories PIC INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) WHERE PIC.CategoryID = @UpCategoryID AND jP.IsApproved = 1), 0),
			TotalSubThreads = IsNull((SELECT COUNT(P.PostID) FROM cs_Posts P INNER JOIN cs_Post_Categories jC ON (jC.CategoryID = @UpCategoryID OR jC.Path LIKE @UpPath + convert(nvarchar, @UpCategoryID) + '/%') INNER JOIN cs_Posts_InCategories jPIC ON (jPIC.CategoryID = jC.CategoryID) WHERE P.PostID = P.ParentID AND P.PostID = jPIC.PostID AND P.IsApproved = 1), 0),
			MostRecentPostDate = (SELECT MAX(PostDate) FROM cs_Posts_InCategories PIC INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) WHERE PIC.CategoryID = @UpCategoryID and jP.IsApproved = 1),
			MostRecentSubPostDate = (SELECT MAX(PostDate) FROM cs_Posts P INNER JOIN cs_Post_Categories jC ON (jC.CategoryID = @UpCategoryID OR jC.Path LIKE @UpPath + convert(nvarchar, @UpCategoryID) + '/%') INNER JOIN cs_Posts_InCategories jPIC ON (jPIC.CategoryID = jC.CategoryID) WHERE P.PostID = P.ParentID AND P.PostID = jPIC.PostID AND P.IsApproved = 1)
		WHERE CategoryID = @UpCategoryID
	
		FETCH NEXT FROM Categories_Cursor INTO @UpCategoryID
	END
	
	CLOSE Categories_Cursor
	DEALLOCATE Categories_Cursor
	
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: 8/8/2006 9:28:11 AM
***********************************************/
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
)

as
SET Transaction Isolation Level Read UNCOMMITTED

Update cs_Posts
Set 
	TotalViews = TotalViews + @WebCount,
	AggViews = AggViews + @AggCount
Where 
	PostID = @PostID

declare @ThreadID int
set @ThreadID = (select ThreadID from cs_Posts where PostID = @PostID)

update cs_Threads
set
	TotalViews = TotalViews + @WebCount
where
	ThreadID = @ThreadID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_Views_Add] to public
go
/***********************************************
* Sproc: cs_Post_CreateUpdate
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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,
	@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)

-- 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 
		cs_UserID = @UserID and SettingsID = @SettingsID

-- Check if this is an anonymous post (value = 1)
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Anonymous ID
	SELECT @ContextUserID = cs_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 )
	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 )

	-- Get the new ThreadID
	SELECT 
		@ThreadID = @@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 = @@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 = @@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 = @@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

-- Is this a private post
IF @SectionID = 0
	EXEC cs_PrivateMessages_CreateDelete @UserID, @ThreadID, @SettingsID, 0

-- 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: 8/8/2006 9:28:18 AM
***********************************************/
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_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_GetAuthorID
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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


CREATE PROCEDURE dbo.cs_Post_GetRandomPostID
	@SettingsID int,
	@CategoryID int=-1,
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @CategoryID = -1
begin
	select top 1 PostID
		from cs_Posts
		where PostID = ParentID
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			order by newid()
end
else
begin
	select P.PostID
		from cs_Posts P
		join cs_Posts_InCategories C on C.PostID = P.PostID
		where P.PostID = P.ParentID
			and P.SettingsID = @SettingsID
			and P.SectionID = @SectionID
			and C.CategoryID = @CategoryID
			order by newid()
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_GetRandomPostID] to public
go
/***********************************************
* Sproc: cs_Post_GetRating
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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
)
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
	
	-- 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: 8/8/2006 9:28:18 AM
***********************************************/
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

CREATE  procedure [dbo].cs_PrivateMessages_CreateDelete
(
	@UserID int,
	@ThreadID int,
	@SettingsID int,
	@Action int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF (@Action = 0)
BEGIN
	-- Does the user already have the ability to see this thread?
	IF EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID and ThreadID = @ThreadID and SettingsID = @SettingsID)
		RETURN
	
	INSERT INTO
		cs_PrivateMessages
	VALUES
	(
		@UserID,
		@ThreadID,
		@SettingsID
	)
	
	RETURN
END
	
IF (@Action = 2)
BEGIN
	-- This is a thread level delete operation ... and it works like this:
	-- as long as one of the pairs has the message in its list we don't want to delete 
	-- thread related data but only its link to that message. 
	
	-- The SectionID for any PM thread is 0
	DECLARE @SectionID INT
	SET @SectionID = 0
	 
	-- Delete user's link to this PM thread
	DELETE
		cs_PrivateMessages
	WHERE
		UserID = @UserID AND
		ThreadID = @ThreadID AND 
		SettingsID = @SettingsID
	
	-- Find out if there are any other pair that are bound to this PM thread.
	-- If no one is found then we may delete thread related data
	IF NOT EXISTS( SELECT UserID FROM cs_PrivateMessages WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID )
	BEGIN
		-- Delete thread related data
		EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, 0, @UserID, ''
	END
END
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_PrivateMessages_CreateDelete] to public
go
/***********************************************
* Sproc: cs_PrivateMessages_Recipients
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
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


CREATE procedure [dbo].cs_PrivateMessages_Recipients (
	@ThreadID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	SELECT 
		PM.UserID,
		U.UserName
	FROM 
		cs_vw_Users_FullUser U,
		cs_PrivateMessages PM
	WHERE 
		PM.ThreadID = @ThreadID AND
		PM.SettingsID = @SettingsID AND
		PM.UserID = U.cs_UserID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PrivateMessages_Recipients] to public
go
/***********************************************
* Sproc: cs_PrivateMessages_UnreadCount
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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


create procedure [dbo].[cs_PrivateMessages_UnreadCount] (
	@SettingsID	int,
	@UserID		int
)
AS
BEGIN
	-- Ensure data integrity
	DELETE
		cs_PrivateMessages
	WHERE
		ThreadID not in (SELECT ThreadID from cs_Threads)

	SELECT ThreadID  FROM cs_PrivateMessages WHERE  SettingsID = @SettingsID AND UserID = @UserID
	exec dbo.cs_forums_threads_ThreadsRead 0, @UserID, @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_PrivateMessages_UnreadCount]  to public
GO
/***********************************************
* Sproc: cs_Ranks_Get
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:21 AM
***********************************************/
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.cs_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.cs_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: 8/8/2006 9:28:20 AM
***********************************************/
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
)
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
	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
	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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Get existing rating
	DECLARE @CurrentRating	int
	EXECUTE cs_Rating_Get @RatingType, @ItemID, @UserID, @SettingsID, @CurrentRating OUTPUT
	
	-- Rating hasn't changed
	IF @Rating = @CurrentRating
		RETURN

	-- User has previously rated this item
	IF @CurrentRating >= 0

		-- Update the rating
		EXECUTE cs_Rating_Update @RatingType, @ItemID, @UserID, @Rating, @SettingsID, @CurrentRating

	ELSE

		-- Add the rating
		EXECUTE cs_Rating_Add @RatingType, @ItemID, @UserID, @Rating, @SettingsID

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: 8/8/2006 9:28:19 AM
***********************************************/
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
)
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
	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
	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: 8/8/2006 9:28:20 AM
***********************************************/
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 Proc [dbo].cs_referrals_Add
(
	@UrlID int,
	@Url nvarchar(512),
	@SettingsID int,
	@SectionID int,
	@PostID int	
)

as
SET Transaction Isolation Level Read UNCOMMITTED

exec cs_Urls_Add @UrlID, @Url

Declare @ReferralID int

Select @ReferralID = ReferralID FROM cs_Referrals where SettingsID = @SettingsID and SectionID = @SectionID and UrlID = @UrlID

if(@ReferralID is null)
Begin
	Insert cs_Referrals (SettingsID, SectionID, PostID, UrlID, Hits, LastDate)
	Values (@SettingsID, @SectionID, @PostID, @UrlID, 1, getdate())
End
Else
Begin
	Update cs_Referrals
	Set 
		Hits = Hits + 1,
		LastDate = getdate()
	Where ReferralID = @ReferralID
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: 8/8/2006 9:28:13 AM
***********************************************/
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
		R.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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:17 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROCEDURE [dbo].cs_report_GetBlogPostReplies
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Replies To Forum Posts --
SELECT
	p.PostID, t.Replies, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select COUNT(p2.ThreadID) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostID != p2.ParentID AND p2.PostDate between @BegReportDate and @EndReportDate) AS Replies
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 1
	GROUP BY
		posts.ThreadID
	ORDER BY
		Replies DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetBlogPostReplies] to public
go

/***********************************************
* Sproc: cs_report_GetBlogPostViews
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROCEDURE [dbo].cs_report_GetBlogPostViews
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Viewed Blog Posts --
SELECT
	p.PostID, t.TViews, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select SUM(p2.TotalViews) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostDate between @BegReportDate and @EndReportDate) AS TViews
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 1
	GROUP BY
		posts.ThreadID
	ORDER BY
		TViews DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetBlogPostViews] to public
go

/***********************************************
* Sproc: cs_report_GetForumPostReplies
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE [dbo].cs_report_GetForumPostReplies
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Replies To Forum Posts --
SELECT
	p.PostID, t.Replies, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select COUNT(p2.ThreadID) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostID != p2.ParentID AND p2.PostDate between @BegReportDate and @EndReportDate) AS Replies
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 0
	GROUP BY
		posts.ThreadID
	ORDER BY
		Replies DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetForumPostReplies] to public
go

/***********************************************
* Sproc: cs_report_GetForumPostViews
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE [dbo].cs_report_GetForumPostViews
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Viewed Forum Posts --
SELECT
	p.PostID, t.TViews, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select SUM(p2.TotalViews) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostDate between @BegReportDate and @EndReportDate) AS TViews
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 0
	GROUP BY
		posts.ThreadID
	ORDER BY
		TViews DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetForumPostViews] to public
go

/***********************************************
* Sproc: cs_ReverseTrackingOption
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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_CreateUpdateDelete
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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







-- sp_helptext cs_Roles_CreateUpdateDelete


CREATE PROCEDURE [dbo].cs_Roles_CreateUpdateDelete
(
	@RoleID	uniqueidentifier out,
	@DeleteRole	bit = 0,
	@Name		nvarchar(256) = '',
	@Description	nvarchar(512) = '',
	@SettingsID int

)
AS
DECLARE	@ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

if(@ApplicationId IS NULL)
RETURN
 

IF @RoleID is not null
Begin

	--validate application/role context
	IF NOT EXISTS(Select RoleId FROM aspnet_Roles where RoleId = @RoleID  and ApplicationId = @ApplicationId)
	RETURN


	-- Are we deleting the role?
	IF @DeleteRole = 1
	BEGIN
	
		-- delete all users in the role
		DELETE 
			aspnet_UsersInRoles
		WHERE 
			RoleId = @RoleID

		-- delete all product permissions using the role
		DELETE 
			cs_ProductPermissions
		WHERE 
			RoleID = @RoleID and SettingsID = @SettingsID
	
		-- delete all section permissions using the role
		DELETE 
			cs_SectionPermissions
		WHERE 
			RoleID = @RoleID and SettingsID = @SettingsID
	
	
		-- finally we can delete the actual role
		DELETE 
			aspnet_Roles
		WHERE 
			RoleId = @RoleID
	
	END
	ELSE
	BEGIN -- Are we updating a forum
		-- Update the role
		UPDATE 
			aspnet_Roles
		SET
			RoleName = @Name,
			LoweredRoleName = Lower(@Name),
			Description = @Description
		WHERE 
			RoleId = @RoleID
	END
END
ELSE
BEGIN

	-- Create a new Forum
	INSERT INTO 
		aspnet_Roles (
			RoleName, 
			LoweredRoleName,
			Description
			)
		VALUES (
			@Name,
			Lower(@Name),
			@Description
			)
	
	Select @RoleID = RoleId FROM aspnet_Roles where LoweredRoleName = Lower(@Name) and ApplicationId = @ApplicationId

END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Roles_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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
(
@UserID int = 0,
@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Declare @ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName


	IF (@UserID = 0)
		SELECT
			RoleId, RoleName as [Name], Description
		FROM
			aspnet_Roles where ApplicationId = @ApplicationId
	ELSE
		SELECT DISTINCT
			R.RoleId, RoleName as [Name], Description
		FROM 
			aspnet_UsersInRoles U,
			aspnet_Roles R,
			cs_UserProfile P
		WHERE
			U.RoleId = R.RoleId AND
			P.UserID = @UserID AND
			P.MembershipID = U.UserId and P.SettingsID = @SettingsID and R.ApplicationId = @ApplicationId
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_Get] to public
go
/***********************************************
* Sproc: cs_Role_Get
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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,
	@SettingsID int
	
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


	Declare @ApplicationName nvarchar(256)
	Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID
	
	
	select RoleId, 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 r.RoleId = @RoleID ) or @RoleID is null ) and
		((@RoleName is not null and r.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_RollerBlog_AddFeed
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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 = @@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,
	    @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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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


CREATE PROC [dbo].cs_Roller_AddFeed
	@UserId INT,
	@FeedId INT
AS


INSERT INTO cs_FolderFeed
(
	UserId,
	FolderId,
	FeedId
)
VALUES
(
	@UserId,
	NULL,
	@FeedId
)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_AddFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetFeeds
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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

CREATE PROC [dbo].cs_Roller_GetFeeds
	@UserId INT
AS


SELECT 	f.FeedId,
	f.Title,
	f.Url,
	f.Link
FROM 	cs_Feed f,
	cs_FolderFeed ff
WHERE f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
ORDER BY Title


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetPosts
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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


CREATE PROC [dbo].cs_Roller_GetPosts
	@UserID INT,
	@PageIndex int = 0, 
	@PageSize int = 25,
	@TotalRecords int output
AS

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 TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	FeedPostId int
)

Insert #PageIndex (FeedPostId)
Select fp.FeedPostId
FROM cs_FeedPost fp,
	cs_Feed f,
	cs_FolderFeed ff
WHERE fp.FeedId = f.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
ORDER BY fp.FeedPostId DESC 
-- changed this to Id instead of date. 
-- Do all feeds return acurate dates, do we care? 
-- My guess is users want to see what was most recently added to the site.

SET @TotalRecords = @@rowcount

SELECT 	f.Title AS 'FeedTitle',
	f.Link AS 'FeedLink',
	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM cs_FeedPost fp,
	cs_Feed f,
	cs_FolderFeed ff,
	#PageIndex fPI
WHERE fp.FeedId = f.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
  AND fPI.FeedPostID = fp.FeedPostID
  AND fPI.IndexID > @PageLowerBound
  AND fPI.IndexID < @PageUpperBound
ORDER BY fPI.IndexID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetPosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetUnaggregatedFeeds
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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


CREATE PROC [dbo].cs_Roller_GetUnaggregatedFeeds
	@UserID INT
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE FeedId NOT IN (
	SELECT FeedId
	FROM cs_FolderFeed
	WHERE UserId = @UserId
	AND FolderId IS NULL
)
ORDER BY Title ASC



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetUnaggregatedFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_SearchBarrel_Search
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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,
	--@RecordCountSQL nvarchar(4000),
	@PageIndex int = 0,
	@PageSize int = 25,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @StartTime datetime
	DECLARE @RowsToReturn int
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @Count int
	DECLARE @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,
		PostID int,
		SectionID int,
		Weight int,
		PostDate datetime
	)

	-- Fill the temp table
	INSERT INTO #SearchResults (PostID, SectionID, Weight, PostDate)
	exec (@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,
		AttachmentFilename =  ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		S.ApplicationKey, S.GroupID, S.ApplicationType, S.Name as SectionName

	FROM 
		cs_Posts P,
		cs_Sections S,
		#SearchResults R
	WHERE
		P.PostID = R.PostID AND
		P.SectionID = S.SectionID AND
		R.IndexID > @PageLowerBound AND
		R.IndexID < @PageUpperBound AND
		P.SettingsID = @SettingsID
	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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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_Sections_Get
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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 = 0,
	@AllowInactive			bit = 0,
	@IncludePostTypeCounts	bit = 0
)
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.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, 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.DiskUsage

FROM
	cs_Sections F
WHERE
	SettingsID = @SettingsID AND
	--(IsActive = 1 OR 1 = @AllowInactive) AND
	 ApplicationType = @ApplicationType

--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 
		cs_Sections F
		JOIN cs_Posts P on F.SectionID = P.SectionID
	WHERE
		F.SettingsID = @SettingsID AND
		F.ApplicationType = @ApplicationType
	GROUP BY F.ApplicationKey, P.ApplicationPostType
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: 8/8/2006 9:28:13 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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(3000) = '',
	@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,
	@EnableAutoDelete bit = 0,
	@EnableAnonymousPosting bit = 0,
	@AutoDeleteThreshold int = 90,
	@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
)
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,
		EnableAutoDelete = @EnableAutoDelete,
		EnableAnonymousPosting = @EnableAnonymousPosting,
		AutoDeleteThreshold = @AutoDeleteThreshold,
		SortOrder = @SortOrder,
		ApplicationKey = @ApplicationKey,
		ApplicationType = @ApplicationType,
		ForumType = @ForumType,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		DefaultLanguage = @DefaultLanguage
	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,
			EnableAutoDelete,
			AutoDeleteThreshold,
			SortOrder,
			ApplicationKey,
			ApplicationType,
			ForumType,
			PropertyNames,
			PropertyValues,
			DefaultLanguage
			)
		VALUES (
			@Name,
			@Url,
			@Description,
			@ParentID,
			@SettingsID,
			@GroupID,
			@IsModerated,
			@DisplayPostsOlderThan,
			@IsActive,
			@IsSearchable,
			@EnablePostStatistics,
			@EnablePostPoints,
			@EnableAutoDelete,
			@AutoDeleteThreshold,
			@SortOrder,
			@ApplicationKey, 
			@ApplicationType,
			@ForumType,
			@PropertyNames,
			@PropertyValues,
			@DefaultLanguage
			)
	
	SET @SectionID = @@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: 8/8/2006 9:28:14 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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



CREATE Procedure [dbo].cs_Section_Get
(
	@SettingsID int,
	@SectionID int,
	@ApplicationKey nvarchar(512) = null,
	@ApplicationType smallint
)

as
SET Transaction Isolation Level Read UNCOMMITTED

if(@ApplicationKey is not null)
Begin
	Select @SectionID = SectionID FROM cs_Sections where ApplicationKey = @ApplicationKey and ApplicationType = @ApplicationType
End

SELECT 
	SectionID, SettingsID, IsActive, ParentID, GroupID, [Name], NewsgroupName, [Description], 
	DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, 
	EnablePostStatistics, EnablePostPoints, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, 
	MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostSubject, 
	MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, ForumType, 
	IsSearchable, ApplicationType, ApplicationKey, PropertyNames as SectionPropertyNames, PropertyValues as SectionPropertyValues, Path, DefaultLanguage
FROM 
	cs_Sections 
Where SectionID = @SectionID and ApplicationType = @ApplicationType

exec cs_Section_Permissions_Get @SettingsID, @SectionID, @ApplicationType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Section_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Section_GetRandomSectionID
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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_MarkRead
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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
)
AS


SET Transaction Isolation Level Read UNCOMMITTED

IF ( @SectionID = 0 ) 
	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		ApplicationKey = null,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID AND
		P.SectionID = F.SectionID AND
		F.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

ELSE IF (@SectionID > 0)
 
	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		ApplicationKey = null,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

	UNION
	
	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID  AND
		P.SectionID = @SectionID  AND
		P.SectionID = F.SectionID AND
		F.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID
	
ELSE

	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		R.RoleName, 
		R.RoleId, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM		
		aspnet_Roles R
		inner join aspnet_Applications A on R.ApplicationId = A.ApplicationId
		inner join cs_SiteSettings ss on A.ApplicationName = ss.ApplicationName
		left outer join cs_ProductPermissions P on P.RoleID = R.RoleId and P.ApplicationType = @ApplicationType and P.SettingsID = @SettingsID
	WHERE 
		
		ss.SettingsID = @SettingsID


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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@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, @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 )
	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 )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		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 )
	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, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		else
			UPDATE
				cs_ProductPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end

	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
END
ELSE IF @Action = 2
BEGIN
	if( @SectionID <> -1 )
		DELETE cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID
	else
	begin
		DELETE cs_SectionPermissions where RoleID = @RoleID and SettingsID = @SettingsID
		DELETE cs_ProductPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end
	
	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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



CREATE PROCEDURE [dbo].cs_security_ValidateUserPasswordAnswer
(
	@UserID int,
	@PasswordAnswer nvarchar(256)
)
AS
BEGIN
	SELECT 
		COUNT(cs_Users.UserID) 
	FROM 
		aspnet_membership, cs_Users
	WHERE
		aspnet_membership.UserID = cs_Users.MembershipID and cs_Users.UserID = @UserID
		AND (PasswordAnswer = @PasswordAnswer OR PasswordAnswer = NULL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_security_ValidateUserPasswordAnswer] to public
go
/***********************************************
* Sproc: cs_Services_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@UserID int,
	@IncludeCategories bit,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
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,
	PostID int
)
 

--CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

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
	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.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	--AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate


SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN

	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

End

If @IncludePageIndex = 1
BEGIN
	SELECT IndexID, PostID from #PageIndex ORDER BY IndexID
END

DROP TABLE #PageIndex

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: 8/8/2006 9:28:17 AM
***********************************************/
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
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

ELSE 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
	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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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
DECLARE @ApplicationId uniqueidentifier
DECLARE @ModeratorRoleID AS uniqueidentifier

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
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 cs_UserID = S.MostActiveUserID and SettingsID = @SettingsID),''),
	NewestUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE cs_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.cs_UserID AND
	U.EnableDisplayInMemberList = 1 AND
	U.cs_UserID > 0 and U.SettingsID = @SettingsID and S.SettingsID = @SettingsID
ORDER BY
	S.TotalPosts DESC

-- SELECT top 10 Moderators
SELECT TOP 10
	U.*,
	M.PostsModerated
FROM
	cs_vw_Users_FullUser U,
	aspnet_UsersInRoles R,
	cs_Moderators M
WHERE
	U.UserId = R.UserId AND
	R.RoleId = @ModeratorRoleID AND
	U.cs_UserID = M.UserID AND
	M.PostsModerated > 0 AND 
	U.SettingsID = @SettingsID AND 
	M.SettingsID = @SettingsID
ORDER BY
	PostsModerated 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: 8/8/2006 9:28:11 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:17 AM
***********************************************/
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_Styles_Get
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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 = @@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_System_AddNewUrl.sql
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
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 = @@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_CleanForumsRead
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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
)

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 = @@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 = @@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', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'javascript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'jscript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'vbscript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'expression\(*.\)', 'BLOCKED EXPRESSION')

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 = @@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, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, 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, 0, 1, 90, 0, 0, 0, '', 0, '1977-01-01', 0,  0
	)
Select @ReportingSectionID = @@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, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, 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, 90, 0, 0, 0, '', 0, '1977-01-01', 0, 0
	)
Select @DeletedSectionID = @@Identity



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'GalleryAdministrator', N'galleryadministrator', N'Administration role for Galleries.')
	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'ReaderAdministrator', N'readeradministrator', N'Administration role for the Feed Reader')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ReaderUser', N'readeruser', N'Users who are allowed to use the Feed Reader')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'FileAdministrator', N'fileadministrator', N'Administration role for Files')
	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')

	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,   N'DVZTktxeMzDtXR7eik7Cdw==', NULL,       @AdminEmail,    NULL,            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])
		VALUES(@UserID, 0,1, null, getdate(), '')


		Set @cs_UserID = @@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)
		
		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',    NULL,            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])
	VALUES(@UserID, 0,1, null, getdate(), '')

	Set @cs_UserID = @@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])
	SELECT aspnet.UserId, 0,1, null, getdate(), '' from dbo.vw_aspnet_MembershipUsers aspnet LEFT OUTER JOIN dbo.cs_vw_Users_FullUser cs on aspnet.UserId = cs.UserId WHERE aspnet.ApplicationId = @ApplicationID and cs.UserId 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, 2, @Perm_RoleID, 0x0000000000000089, 0xFFFFFFFFFFFFFF76 ) -- Gallery Permission
	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, 6, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 ) -- File Permission >> Allow  View, Read, Replay, Deny Post, Moderate, Vote, Delete, Edit
	-- 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, 2, @Perm_RoleID, 0x00000000000000B9, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 ) -- File Permission

	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- GuestBook Permission  >> Allow View, Reply  Deny Post
	-- 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 = '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, 6, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 ) -- File 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, 0x0000100F00000FFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 ) -- File Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'GalleryAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x01001000000000BD, 0 ) -- Gallery Permission
	
		Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'FileAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x01001008000002FF, 0 ) -- File 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, 0x0100100F00000FFF, 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, 0x4100100F00000FFF, 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, 2, @Perm_RoleID, 0x41001000000000BD, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x41001008000002FF, 0 ) -- File 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, 2, @Perm_RoleID, 0x41001000000000BD, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x01001008000002FF, 0 ) -- File Permission


---Return New Data	

if @CreateSamples = 1
Begin
	exec cs_system_SampleGallery @SettingsID, @AdminUserName
	exec cs_system_SampleWeblog @SettingsID, @AdminUserName
	exec cs_system_SampleForum @SettingsID, @AdminUserName
	exec cs_system_SampleDownload @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_DeletePostAndAdoptChildren
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:19 AM
***********************************************/
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
	
	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 = @@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: 8/8/2006 9:28:17 AM
***********************************************/
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 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)
			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_ModerationAction_AuditEntry
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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 @AutoDelete bit
DECLARE @AutoDeleteThreshold int
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
    
	-- Finally, perform any auto-delete
	SELECT 
		@AutoDelete = EnableAutoDelete, 
		@AutoDeleteThreshold = AutoDeleteThreshold 
	FROM 
		cs_Sections
	WHERE
		SectionID = @SectionID
	
	-- Do we need to cleanup the forum?
	IF @AutoDelete = 1
	BEGIN

		DECLARE @ThreadIDToDelete int

		DECLARE ThreadDelete_Cursor CURSOR FOR
			SELECT ThreadID FROM cs_Threads WHERE ThreadDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND LastViewedDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND StickyDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND SectionID = @SectionID	

		OPEN ThreadDelete_Cursor
		FETCH NEXT FROM ThreadDelete_Cursor INTO @ThreadIDToDelete
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- delete corresponding posts first
			DELETE cs_Posts WHERE ThreadID = @ThreadIDToDelete
			DELETE cs_Threads WHERE ThreadID = @ThreadIDToDelete
			FETCH NEXT FROM ThreadDelete_Cursor INTO @ThreadIDToDelete
		END
	
		CLOSE ThreadDelete_Cursor
		DEALLOCATE ThreadDelete_Cursor

		exec sp_recompile 'cs_Threads'
		exec sp_recompile 'cs_Posts'
		exec sp_recompile 'cs_SearchBarrel'
	END

	-- 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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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 = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @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, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @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', @Content = 0x, @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: 8/8/2006 9:28:17 AM
***********************************************/
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 = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @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, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 0, @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @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: 8/8/2006 9:28:18 AM
***********************************************/
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 = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @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, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 2, @ApplicationKey = N'sample', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID


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', @Content = 0x, @ContentType = N'image/pjpeg', @ContentSize = 20558, @SettingsID = @SettingsID, @FriendlyFileName = 'Cheetah', @IsRemote = 0, @Width= 425, @Height=283


declare @ptr varbinary(16)
select @ptr = textptr(Content) from cs_PostAttachments where PostID = @PicPostID
writetext cs_PostAttachments.Content @ptr [encoded data, 41118 characters]

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_SampleWeblog
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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 = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @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, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 1, @ApplicationKey = N'sample_weblog', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID



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_UpdateForum
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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


-- 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

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = cs_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
	
		-- 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
	
			-- 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: 8/8/2006 9:28:17 AM
***********************************************/
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.cs_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.cs_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.cs_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: 8/8/2006 9:28:17 AM
***********************************************/
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
)
AS

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
DECLARE @DateWindow datetime
DECLARE @ApplicationId uniqueidentifier
DECLARE @ModeratorRoleID AS uniqueidentifier

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
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 @TotalModerators 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
	-- ***********************************************
	SET @TotalModerators = ISNULL(
					(
						SELECT 
							COUNT(*) 
						FROM 
							aspnet_UsersInRoles jUR
							JOIN aspnet_Roles jR ON jR.RoleID = jUR.RoleID
							JOIN aspnet_applications jA on jR.ApplicationId = jA.ApplicationId			
						WHERE 
							jR.LoweredRoleName = 'moderator' and LOWER(@ApplicationName) = jA.LoweredApplicationName
					), 0)

	-- 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_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId 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_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId 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_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId 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_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId 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_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId 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 
							--jU.cs_UserID
							jP.UserID
						FROM 
							--cs_vw_Users_FullUser jU JOIN 
							cs_UserProfile jP --ON jP.UserID = jU.cs_UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 and jP.SettingsID = @SettingsID
						ORDER BY 
							jP.TotalPosts DESC
					), 0)
	-- Newest user
	-- ***********************************************
	SET @NewestUserID = ISNULL(
					(
						SELECT Max(ju.cs_UserID) 

						FROM 
							cs_vw_Users_FullUser jU
							JOIN cs_UserProfile jP ON jP.UserID = jU.cs_UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 AND
							jU.cs_UserAccountStatus = 1 and jP.SettingsID = @SettingsID
						--ORDER BY jU.CreateDate DESC
					), 0)


	-- Total Users
	-- ***********************************************
	SET @TotalUsers = ISNULL( 
					(
						SELECT 
							COUNT(UserID) 
						FROM 
							cs_UserProfile 
						WHERE 
							--EnableDisplayInMemberList = 1 and SettingsID = @SettingsID
							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(IsApproved) FROM aspnet_Membership WHERE ApplicationId = @ApplicationId and 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_UpdateSubscriptions
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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

CREATE PROCEDURE [dbo].cs_system_UpdateSubscriptions
(
	@RoleID uniqueidentifier,
	@SectionID int,
	@SettingsID int
)
AS
/*
	Remove users subscriptions based on provided role ID.
*/
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @UserID int
	DECLARE @HasAccess bit
	
	DECLARE users_cursor CURSOR FOR 
	SELECT UserID FROM cs_vw_UsersInRoles WHERE RoleId = @RoleID

	OPEN users_cursor

	FETCH NEXT FROM users_cursor 
	INTO @UserID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- Get user's view & read access permissions status
		EXEC @HasAccess = cs_system_UserCanReadSection @UserID, @SectionID, @SettingsID
		
		-- If no access then clean up subscriptions
		IF @HasAccess = 0
		BEGIN
			-- Remove forum subscriptions
			EXEC cs_RemoveAllSectionTracking @UserID, @SectionID, @SettingsID

			-- Remove thread subscriptions
			EXEC cs_RemoveAllPostTracking @UserID, @SectionID, @SettingsID
		END

		FETCH NEXT FROM users_cursor
		INTO @UserID
	END

	CLOSE users_cursor
	DEALLOCATE users_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateSubscriptions] to public


/***********************************************
* Sproc: cs_system_UpdateThread
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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 = cs_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
	PostLevel = 1,
	SortOrder = 1
WHERE
	ThreadID = @ThreadID
	AND PostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostID ASC)

UPDATE
	cs_Posts
SET
	PostLevel = 2,
	SortOrder = SortOrder + 1
WHERE
	ThreadID = @ThreadID
	AND PostID > @ReplyPostID and SettingsID = @SettingsID

-- 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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @Usercount int
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
		P.TotalPosts DESC

	-- How many users did we select?
	SELECT @Usercount = count(*) FROM #PostRank


	-- 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: 8/8/2006 9:28:19 AM
***********************************************/
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

CREATE PROCEDURE [dbo].cs_system_UpdateUserSubscriptions
(
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @SectionID int
	DECLARE @HasAccess bit
	
	DECLARE sections_cursor CURSOR FOR
	SELECT T.SectionID
	FROM cs_TrackedThreads TT INNER JOIN cs_Threads T ON TT.ThreadID = T.ThreadID
	WHERE TT.UserID = @UserID AND TT.SettingsID = @SettingsID
	UNION
	SELECT TS.SectionID
	FROM cs_TrackedSections TS
	WHERE TS.UserID = @UserID AND TS.SettingsID = @SettingsID
	
	OPEN sections_cursor

	FETCH NEXT FROM sections_cursor 
	INTO @SectionID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- Get user's view & read access permissions status
		EXEC @HasAccess = cs_system_UserCanReadSection @UserID, @SectionID, @SettingsID
		
		-- If no access then clean up subscriptions
		IF @HasAccess = 0
		BEGIN
			-- Remove forum subscriptions
			EXEC cs_RemoveAllSectionTracking @UserID, @SectionID, @SettingsID

			-- Remove thread subscriptions
			EXEC cs_RemoveAllPostTracking @UserID, @SectionID, @SettingsID
		END

		FETCH NEXT FROM sections_cursor
		INTO @SectionID
	END

	CLOSE sections_cursor
	DEALLOCATE sections_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserSubscriptions] to public


/***********************************************
* Sproc: cs_system_UserCanReadSection
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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

CREATE PROCEDURE [dbo].cs_system_UserCanReadSection
(
	@UserID int,
	@SectionID int,
	@SettingsID int
)
AS
/*
Figure out if an user has View or Read access permissions on provided Section ID.
*/
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @HasAccess bit
 
-- Set default values
SET @HasAccess = 0

-- Has view & read access permission?
IF EXISTS(
	SELECT TOP 1 
		UserID
	FROM
		cs_vw_UsersInRoles ur
		INNER JOIN cs_SectionPermissions sp ON ur.RoleId = sp.RoleID AND sp.SettingsID = @SettingsID
	WHERE
		ur.UserID = @UserID AND 
		sp.SectionID = @SectionID AND
		sp.AllowMask & convert(bigint, 0x0000000000000001) = convert(bigint, 0x0000000000000001) AND
    sp.AllowMask & convert(bigint, 0x0000000000000002) = convert(bigint, 0x0000000000000002)
)	
	SET @HasAccess = 1

RETURN @HasAccess

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UserCanReadSection] to public


/***********************************************
* Sproc: cs_system_UserIsOnline
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Update cs_Users table
	UPDATE 
		cs_Users 
	SET 
		LastActivity = GetDate(),
		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: 8/8/2006 9:28:18 AM
***********************************************/
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] 
	@SectionQuerySQL ntext,
	@SettingsID int,
	@CategoryList nvarchar(4000) = null
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC (@SectionQuerySQL)

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
	where C.SettingsID = @SettingsID
		and C.SectionID in (select SectionID from #Sections)
		and C.IsEnabled = 1
	group by [Name]
	order by [Name]

end else begin

	declare @idoc int
	EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList

	CREATE TABLE #Tags
	(
		[Name] nvarchar(255) collate database_default
	)

	insert into #Tags ([Name])
	select CONVERT(nvarchar(255), [text])
	from OPENXML(@idoc, '/Categories/Category/', 2)
	where [text] is not null

	declare @categoryCount int
	set @categoryCount = (select count(*) from #Tags)

	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 SectionID from #Sections)
		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 SectionID from #Sections)
				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 [Name] from #Tags)
	order by [Name]

	DROP TABLE #Tags

	EXEC sp_xml_removedocument @idoc

end

DROP TABLE #Sections
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Tags_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
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 (@sqlPopulate)

SELECT
	jT.*, U.*,
	HasRead = 0,
	jP.PostID,
	jP.Subject,
	jP.Body,
	jP.FormattedBody,
	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.cs_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
ORDER BY
	jPI.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 (@sqlCount)

-- Return the users that the message is to if this
-- is a private message
IF @SectionID = 0
	SELECT 
		U.*,
		P2.ThreadID 
	FROM
		cs_PrivateMessages P1, 
		cs_PrivateMessages P2,
		cs_vw_Users_FullUser U
		
	WHERE 
		P1.UserID = @UserID AND 
		P2.UserID <> @UserID AND 
		P2.UserID = U.cs_UserID AND
		P1.ThreadID = P2.ThreadID and U.SettingsID = @SettingsID and P1.SettingsID = @SettingsID and P2.SettingsID = @SettingsID

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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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_Delete
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
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_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_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

-- 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_IsTracked
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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
		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_UpdateForumGroupSortOrder
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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 = @@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: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:12 AM
***********************************************/
Print 'Creating...cs_UserActivityNightlyJob'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE     PROCEDURE [dbo].cs_UserActivityNightlyJob

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	declare @RangeDate datetime
	declare @JobRunDate datetime
	set @JobRunDate = getdate()
	set @RangeDate = dateadd(d, -1, convert(datetime, (convert(varchar(10), @JobRunDate, 101))))
	
	insert into [cs_VisitsDaily]
	select
		v.IP
		,VisitCount  = (select sum(v1.VisitCount) from cs_Visits v1 where (v1.IP = v.IP) and (v1.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)) group by v1.IP)
		,VisitDate = @RangeDate
		,JobDate = @JobRunDate
	from
		cs_Visits v
	where
		v.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)
	group by
		v.IP

	---------------------------------------------
	
	DELETE cs_Visits WHERE cs_Visits.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_UserActivityNightlyJob to public
go

/***********************************************
* Sproc: cs_UserActivityReportRecords_Get
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...cs_UserActivityReportRecords_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE      PROCEDURE [dbo].cs_UserActivityReportRecords_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)
AS
BEGIN
IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
	
		--------------------------------------------------------------------
	    	-- Define the table to do the filtering and paging
	    	--------------------------------------------------------------------
	    	DECLARE @tblTempData TABLE
	        (
	        	nID INT IDENTITY
	        	,IP nvarchar(20)
	        	,VisitCount INT
	        )
		INSERT INTO @tblTempData
		(
	        	IP
	        	,VisitCount
	        )
	    	SELECT  IP, SUM(VisitCount) as VisitCount
		FROM     cs_VisitsDaily AS v
		WHERE 
			v.VisitDate between @BegReportDate and @EndReportDate
		GROUP BY
			v.IP
		ORDER BY
			VisitCount DESC
		SET @totalRecords = @@rowcount
	        ---------------------------------------------------------------------------------------------------------------------------------------
		SELECT
	        	IP
	        	,VisitCount
	    	FROM
			@tblTempData 
	    	WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
	    	ORDER BY 
	        	nID ASC
	
		-- Return totalRecords
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT  IP as IP_Address, SUM(VisitCount) as Number_Page_Visits
		FROM     cs_VisitsDaily AS v
		WHERE 
			v.VisitDate between @BegReportDate and @EndReportDate
		GROUP BY
			v.IP
		ORDER BY
			Number_Page_Visits DESC
	END
END




GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserActivityReportRecords_Get] to public
go

/***********************************************
* Sproc: cs_UserFeed_DeleteFeed
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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


CREATE PROC [dbo].cs_UserFeed_DeleteFeed
 @UserId INT,  
 @FeedId INT,
 @SettingsID INT  
AS  
  
DELETE  
FROM cs_UserReadPost  
WHERE UserId = @UserId  
  AND FeedPostId IN (SELECT FeedPostId FROM cs_FeedPost WHERE FeedId = @FeedId)  
  
DELETE  
FROM cs_FolderFeed  
WHERE FolderFeedId IN (
  SELECT FolderFeedId
  FROM cs_FolderFeed
  WHERE UserId = @UserId
    AND FeedId = @FeedId
) 



if not exists(Select FolderFeedId FROM cs_FolderFeed where FeedId = @FeedID and SettingsID = @SettingsID)
BEGIN
	Delete FROM cs_FeedPost where FeedID = @FeedID
	Delete FROM cs_Feed where FeedID = @FeedId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserFeed_DeleteFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_UserHasPostsAwaitingModeration
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:20 AM
***********************************************/
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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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


CREATE PROC [dbo].cs_UserReadPost_MarkPostRead
	@UserId INT,
	@FeedPostId INT
AS

INSERT INTO cs_UserReadPost
(
	UserId,
	FeedPostId
)
VALUES
(
	@UserId,
	@FeedPostId
)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserReadPost_MarkPostRead  TO PUBLIC
GO

/***********************************************
* Sproc: cs_users_BackPort
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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 = UserId FROM cs_vw_Users_FullUser where UserName = @UserName and SettingsID = @SettingsID
	
	Update aspnet_Membership
	Set Password = @Password, PasswordSalt = @PasswordSalt, PasswordFormat = @PasswordFormat
	Where UserId = @UserID
		
End

go


grant execute on [dbo].[cs_users_BackPort] to public
go
/***********************************************
* Sproc: cs_users_count_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_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: 8/8/2006 9:28:18 AM
***********************************************/
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,
	@SearchText nvarchar(256),
	@ReturnModerationCounters bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

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,
	UserID int
)	

DECLARE @ParmDefinition NVARCHAR(500)
SET @ParmDefinition = N'@SearchText nvarchar(256)'

INSERT INTO #PageIndexForUsers (UserID)
Exec sp_executesql @sqlPopulate, @ParmDefinition, @SearchText



SET @TotalUsers = @@rowcount

-- Get the user details
IF @ReturnModerationCounters = 1
	SELECT
		U.*,
		ApprovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 1 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		EditPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 2 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		MovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 3 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		DeletePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 4 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		LockPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 5 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnlockPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 6 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		MergePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 7 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		SplitPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 8 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		EditUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 9 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnmoderateUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 10 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ModerateUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 11 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		BanUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 12 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnbanUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 13  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ResetPassword = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 14  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ChangePassword = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 15  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		PostIsAnnouncement = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 16  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		PostIsNotAnnoucement = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 17  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnApprovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 18  AND UserID = U.cs_UserID AND SettingsID = @SettingsID)	
		-- (we do not see to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID)
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.cs_UserID = #PageIndexForUsers.UserID AND
		#PageIndexForUsers.IndexID > @PageLowerBound AND
		#PageIndexForUsers.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		#PageIndexForUsers.IndexID
ELSE
	SELECT
		U.*
		-- (we do not see to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID)
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.cs_UserID = #PageIndexForUsers.UserID AND
		#PageIndexForUsers.IndexID > @PageLowerBound AND
		#PageIndexForUsers.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		#PageIndexForUsers.IndexID

END

-- Return the record count
SELECT @TotalUsers

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: 8/8/2006 9:28:20 AM
***********************************************/
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	UP.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: 8/8/2006 9:28:18 AM
***********************************************/
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.cs_LastActivity  > DateAdd(minute, -@PastMinutes, GetDate()) AND
		U.SettingsID = @SettingsID
	ORDER BY U.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: 8/8/2006 9:28:19 AM
***********************************************/
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


CREATE PROCEDURE [dbo].cs_users_UsersInRole_Get
(
	@PageIndex int,
	@PageSize int,
	@SortBy int = 0,
	@SortOrder int = 0,
	@RoleID uniqueidentifier,
	@UserAccountStatus smallint = 1,
	@ReturnRecordCount bit = 0,
	@SettingsID int
)
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,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(*) FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserId = U.UserId AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleId = @RoleID and U.SettingsID = @SettingsID)

-- Special case depending on what the user wants and how they want it ordered by
-- *************************************

-- Sort by Date Joined
IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID ORDER BY CreateDate
ELSE IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY CreateDate DESC

-- Sort by username
IF @SortBy = 1 AND @SortOrder = 1
	INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY UserName DESC
ELSE IF @SortBy = 1 AND @SortOrder = 0
	INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY UserName

-- Sort by Last Active
IF @SortBy = 3 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY cs_LastActivity DESC
ELSE IF @SortBy = 3 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY cs_LastActivity

-- Sort by TotalPosts
IF @SortBy = 4 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY TotalPosts DESC
ELSE IF @SortBy = 4 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY TotalPosts

-- Get the user details
SELECT
	*,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID and SettingsID = @SettingsID)
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.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_UsersInRole_Get] to public
go
/***********************************************
* Sproc: cs_users_ValidateAnswer
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
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







--cs_users_ValidateAnswereAnswer 0, 10, 0, 0, null, 0, 1, 0, 0, 3
CREATE          PROCEDURE [dbo].cs_users_ValidateAnswereAnswer
(
	@UserId uniqueidentifier,
	@PasswordAnswer nvarchar(128),
	@IsValid bit output
)
as

if exists (Select UserId from aspnet_membership where Lower(PasswordAnswer) = Lower(@PasswordAnswer))
Begin
	Set @IsValid = 1
End
Else
Begin
	Set @IsValid = 0
End




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_users_ValidateAnswereAnswer] to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Count
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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_Avatar
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...cs_User_Avatar'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Avatar]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Avatar]
GO


CREATE procedure [dbo].[cs_User_Avatar]
(
	@UserID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		SELECT
			UserID,
			Length,
			ContentType,
			Content,
			DateLastUpdated
		FROM
			cs_UserAvatar
		WHERE
			UserID = @UserID and SettingsID = @SettingsID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Avatar] to public
go
/***********************************************
* Sproc: cs_User_Avatar_CreateUpdateDelete
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_User_Avatar_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_Avatar_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
GO



CREATE procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
(
    @UserID  int,
    @Content image,
    @ContentType nvarchar(64),
    @ContentSize int,
    @Action  int,
    @SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
    -- Remove if already exists from tables: cs_Images, cs_UserAvatar
    DELETE cs_UserAvatar WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

    IF @Action = 0 OR @Action = 1 --If the action is 2 (delete) we can skip this part
    BEGIN

        -- Add new entry
        INSERT INTO cs_UserAvatar(UserID, SettingsID, Length, ContentType, [Content], DateLastUpdated) 
			SELECT @UserID, SettingsID, @ContentSize, @ContentType, @Content, GetDate() 
			FROM cs_UserProfile where UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
    END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Avatar_CreateUpdateDelete] to public 
go
/***********************************************
* Sproc: cs_user_CreateUpdateDelete
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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) = '',
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '',
	@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,
	@FavoritesShared int = 0,
	@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
*/

-- 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 = cs_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])
		VALUES(@UserID, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '')

		Select @cs_UserID = @@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], [FavoritesShared], [AllowSiteToContact], [AllowSitePartnersToContact])
		Select @cs_UserID, @TimeZone, 0, @PostSortOrder, @PostRank, @IsAvatarApproved, @ModerationLevel, @EnableThreadTracking,  @EnableDisplayUnreadThreadsOnly,  @EnableAvatar,   @EnableDisplayInMemberList, @EnablePrivateMessages,   @EnableOnlineStatus,  @EnableEmail, @EnableHtmlEmail, @IsIgnored,  @UserID, SettingsID, @PropertyNames, @PropertyValues, @FavoritesShared, @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,
		FavoritesShared = @FavoritesShared,
		AllowSiteToContact = @AllowSiteToContact,
		AllowSitePartnersToContact = @AllowSitePartnersToContact,
		IsIgnored = @IsIgnored
	WHERE
		UserID = @cs_UserID
		AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
	

	-- Update the user's anonymous settings passed in, as well.
	UPDATE aspnet_Users
	SET IsAnonymous = @IsAnonymous
	WHERE UserId = @UserID
  
	-- 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
		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: 8/8/2006 9:28:20 AM
***********************************************/
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_PrivateMessages
	SET		UserID = @ReassignUserID
	WHERE	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		MostRecentArticleAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentArticleAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		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_FavoriteUsers
	WHERE	OwnerID = @UserID OR UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FolderFeed
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Folder
	WHERE	UserID = @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	files_Downloads
	WHERE	UserID = @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: 8/8/2006 9:28:19 AM
***********************************************/
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) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @UserIDGUID as uniqueidentifier

	
	-- Are we looking up the user by username or ID?
	IF @Username is not null
	BEGIN
		
		SELECT
			@UserIDGUID = U.UserId
		FROM
			aspnet_Users U,
			cs_SiteSettings S,
			aspnet_Applications A
		WHERE
			S.SettingsID = @SettingsID AND
			A.ApplicationName = S.ApplicationName AND
			A.ApplicationId = U.ApplicationId AND
			U.UserName = @Username

		SELECT
			@UserID = UserID
		FROM
			cs_Users M
		WHERE
			M.MembershipID = @UserIDGUID

		SELECT
			U.*
		FROM
			cs_vw_Users_FullUser U (nolock)
		WHERE 
			UserId = @UserIDGUID AND U.SettingsID = @SettingsID


	END
	ELSE BEGIN
		-- Looking up the user by ID
		
		if(@UserID = 0)
		Begin
			exec cs_GetAnonymousUserID @SettingsID, @UserID output
		End
	
		-- Get the user details
		SELECT
			U.*
		FROM 
			cs_vw_Users_FullUser U (nolock)
		WHERE 
			U.cs_UserID = @UserID and U.SettingsID = @SettingsID
	END

	IF @IsOnline = 1
	BEGIN
		EXEC cs_system_UserIsOnline @UserID, @LastAction, @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: 8/8/2006 9:28:18 AM
***********************************************/
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 
	cs_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: 8/8/2006 9:28:11 AM
***********************************************/
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


CREATE PROC [dbo].cs_User_GetOpmlFeedsFolders
	@UserId INT
AS

SELECT 	cfo.FolderName,
	cfe.Title,
	cfe.Url,
	cfe.Link
FROM 	cs_Folder cfo
RIGHT OUTER JOIN cs_FolderFeed cff
  ON cff.FolderId = cfo.FolderId
INNER JOIN cs_Feed cfe
  ON cff.FeedId = cfe.FeedId
  AND cff.UserId = @UserId
ORDER BY cfo.FolderName, cfe.Title


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_User_GetOpmlFeedsFolders  TO PUBLIC
GO

/***********************************************
* Sproc: cs_User_PasswordAnswer_Change
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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



CREATE PROCEDURE [dbo].cs_User_PasswordAnswer_Change
(
	@UserID int,
	@SettingsID int,
	@PasswordQuestion  nvarchar(256),
	@PasswordAnswer  nvarchar(256)
)
AS

Declare @UID uniqueidentifier
Select @UID = MembershipID FROM cs_UserProfile where UserID = @UserID and SettingsID = @SettingsID

BEGIN
	UPDATE
		aspnet_membership
	SET
		PasswordQuestion = @PasswordQuestion,
		PasswordAnswer = @PasswordAnswer
	WHERE
		UserID = @UID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_PasswordAnswer_Change] to public
go
/***********************************************
* Sproc: cs_User_Rename
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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 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: 8/8/2006 9:28:12 AM
***********************************************/
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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:19 AM
***********************************************/
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_weblog_DeleteStaleSpamComments
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
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 = 30
)
AS

SET Transaction Isolation Level Read UNCOMMITTED


DECLARE	@CommentsToDelete TABLE
		(PostID int)

-- temporarily store posts to delete
INSERT	@CommentsToDelete
		(PostID)
SELECT	P.PostID
FROM	cs_Posts P INNER JOIN cs_Sections S ON P.SectionID = S.SectionID
WHERE	S.ApplicationType = 1									-- only posts in blogs
	AND	P.ApplicationPostType IN (4, 8)							-- only comments/trackbacks
	AND	(P.PostStatus & 2) = 2									-- only posts marked as spam
	AND	P.PostDate < dateadd(d, -@ExpirationDays, getdate())	-- only posts that have been around for a while

-- archive deleted posts
INSERT	cs_posts_deleted_archive
		(PostID, UserID, SectionID, SettingsID, ApplicationType, Body, Subject, IPAddress, DeletedDate, ParentID, ThreadID, PostLevel, PostType)
SELECT	P.PostID, P.UserID, P.SectionID, P.SettingsID, 1, P.Body, P.Subject, P.IPAddress, getdate(), P.ParentID, P.ThreadID, P.PostLevel, P.PostType
FROM	cs_Posts P INNER JOIN @CommentsToDelete D ON P.PostID = D.PostID

-- actually delete posts
DELETE	P
FROM	cs_Posts P INNER JOIN @CommentsToDelete D ON P.PostID = D.PostID


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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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

SET Transaction Isolation Level Read UNCOMMITTED


Select @Month as [Month], @Year as [Year], Day(p.UserTime) as [Day], Count(*) as [Count] 
From cs_Posts p
where p.SectionID = @SectionID and p.IsApproved = 1 and P.ApplicationPostType = 1 and p.PostLevel = 1 and Month(p.UserTime) = @Month and Year(p.UserTime) = @Year and p.PostDate <= getdate()
Group by Day(p.UserTime) order by  [Day]




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: 8/8/2006 9:28:19 AM
***********************************************/
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

SET Transaction Isolation Level Read UNCOMMITTED

Select Month(p.UserTime) as [Month], Year(p.UserTime) as [Year], 1 as Day, Count(*) as [Count] 
From cs_Posts p
where p.SectionID = @SectionID and p.IsApproved = 1 and p.ApplicationPostType = 1 and p.PostDate <= getdate()
Group by Year(p.UserTime), Month(p.UserTime) order by [Year] desc, [Month] desc




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: 8/8/2006 9:28:11 AM
***********************************************/
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.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
		P.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: 8/8/2006 9:28:18 AM
***********************************************/
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: 8/8/2006 9:28:17 AM
***********************************************/
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()

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		cs_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

-- 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 = @@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 = @@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

	-- 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

	-- 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 = @@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
		-- Moderated Posts: get the new PostID
		SELECT @PostID = @@IDENTITY 
	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: 8/8/2006 9:28:11 AM
***********************************************/
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 and SectionID = SectionID

End


-- exec cs_weblog_UpdateContentHistory @SectionID = @SectionID, @BlogPostTypeFilter = @BlogPostType
exec cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID

-- Update thread statistics
exec cs_system_ResetThreadStatistics @ThreadID



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: 8/8/2006 9:28:19 AM
***********************************************/
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.cs_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.cs_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: 8/8/2006 9:28:21 AM
***********************************************/
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

	-- 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
	


	-- 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: 8/8/2006 9:28:21 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:22 AM
***********************************************/
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: 8/8/2006 9:28:13 AM
***********************************************/
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.cs_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: 8/8/2006 9:28:19 AM
***********************************************/
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 P.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 P.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: 8/8/2006 9:28:21 AM
***********************************************/
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 cs_weblog_weblogs
Set 
	MostRecentPostID = P.PostID, 
	MostRecentPostDate = P.UserTime, 
	MostRecentPostName = P.PostName, 
	MostRecentPostAuthorID = P.UserID, 
	MostRecentPostAuthor = P.PostAuthor, 
	MostRecentPostSubject = P.Subject
FROM
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where p.ApplicationPostType = 1 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID



--We may be able to can the articles part
Update cs_weblog_weblogs
Set 
	MostRecentArticleID = P.PostID , 
	MostRecentArticleDate = P.UserTime, 
	MostRecentArticleName = P.PostName, 
	MostRecentArticleAuthorID = P.UserID, 
	MostRecentArticleAuthor = P.PostAuthor, 
	MostRecentArticleSubject = P.Subject
FROM 
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where  p.ApplicationPostType = 2 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where 
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID

--Update Count Items
update cs_Weblog_Weblogs
Set
	PostCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 1 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	ArticleCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 2 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	CommentCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 4 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	TrackBackCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 8 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID)
where 
	cs_Weblog_Weblogs.SettingsID = @SettingsID


-- Update Weblog Section records. 
-- NOTE: Other applications update the Section table stats via cs_system_UpdateForum, called from cs_Post_CreateUpdate
UPDATE cs_Sections
SET
	TotalPosts = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1), 0),
	TotalThreads = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1 and p.PostLevel = 1), 0),
	-- For weblogs, only count feedback that is not approved (ignore posts/articles)
	PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = cs_Sections.SectionID AND p.IsApproved = 0 and p.PostLevel > 1), 0)
WHERE
	cs_Sections.SettingsID = @SettingsID
	and cs_Sections.ApplicationType = 1



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: 8/8/2006 9:28:14 AM
***********************************************/
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.[EnableAutoDelete], F.[EnableAnonymousPosting], F.[AutoDeleteThreshold], F.[MostRecentThreadID], F.[MostRecentThreadReplies], F.[PostsToModerate], F.[ForumType], F.[IsSearchable], F.[ApplicationType], F.[ApplicationKey], 
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.[DefaultLanguage], W.*,
	null as	LastUserActivity
		
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
/*
SELECT
	P.*, F.ApplicationKey
FROM
	cs_SectionPermissions P,
	cs_Sections F,
	cs_UserProfile U,
	aspnet_UsersInRoles R
	
WHERE
	P.RoleID = R.RoleId AND
	U.MembershipID = R.UserId and
	(U.UserID = @UserID )--OR U.UserID = 0) 
	and F.ApplicationType = 1 and F.SectionID = P.SectionID
*/









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Weblogs_Get] to public
go
/***********************************************
* Sproc: files_Comments_GetComments
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...files_Comments_GetComments'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_comments_getComments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_comments_getComments]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  PROCEDURE [dbo].[files_comments_getComments]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate ntext,
	@UserID int,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
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,
	PostID int
)

--CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

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, 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.PostConfiguration, jP.UserTime, jP.ApplicationPostType, jP.PostName, jP.PostStatus, jP.SpamScore,
	jP.Points as PostPoints, jP.RatingSum as PostRatingSum, jP.TotalRatings as PostTotalRatings,
	HasRead = 1,
	jT.*, jU.*,
	Username = jP.PostAuthor,
	ThreadStarterAuthor = jT.PostAuthor,
	ThreadStartDate = jT.PostDate,	
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = jP.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = jP.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
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	JOIN cs_vw_Users_FullUser jU ON jU.cs_UserID = jP.UserID
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 and jU.SettingsID = @SettingsID 
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

If @IncludePageIndex = 1
BEGIN
	SELECT IndexID, PostID from #PageIndex ORDER BY IndexID
END

DROP TABLE #PageIndex
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_Comments_GetComments] to public
go

/***********************************************
* Sproc: files_Downloads_Log
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...files_Downloads_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Downloads_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Downloads_Log]
GO

CREATE PROCEDURE [dbo].files_Downloads_Log
	@PostID int,
	@UserID int
AS

INSERT INTO files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Downloads_Log to public
go
/***********************************************
* Sproc: files_Entries_GetEntries
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...files_Entries_GetEntries'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entries_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entries_GetEntries]
GO

CREATE PROCEDURE dbo.files_Entries_GetEntries
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate nText,
	@UserID int,
	@IncludeCategories bit,
	@SettingsID int,
	@TotalRecords int output
)
AS


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
)


INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET ROWCOUNT @RowsToReturn

SELECT 
	jT.*,
	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.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),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_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.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	AND jp.SettingsID = @SettingsID and jT.SettingsID = @SettingsID
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

Select @TotalRecords = Count(*) FROM #PageIndex

IF @IncludeCategories = 1
Begin

Select 
	Cats.[Name], jP.PostID
FROM 
	#PageIndex jPI
	JOIN cs_Posts jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jT.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 jT.SettingsID = @SettingsID and jP.SettingsID = @SettingsID


End

DROP TABLE #PageIndex
GO

grant execute on [dbo].[files_Entries_GetEntries] to public
go

/***********************************************
* Sproc: files_Entry_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...files_Entry_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entry_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entry_Get]
GO







CREATE        PROCEDURE [dbo].files_Entry_Get
/*

	Procedure for getting basic information on a single post.

*/
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int
) AS
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 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

-- 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
	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

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.Points as PostPoints,
	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, 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),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_Downloads fD (nolock) WHERE fD.PostID = P.PostID),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T
WHERE 
	P.PostID = @PostID AND
	P.ThreadID = T.ThreadID AND
	P.SettingsID = @SettingsID



SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Entry_Get to public
go
/***********************************************
* Sproc: files_PostAttachment_Get
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...files_PostAttachment_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_PostAttachment_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_PostAttachment_Get]
GO







create procedure [dbo].files_PostAttachment_Get
(
	@PostID int,
	@UserID int=0,
	@LogDownload bit=0
)
AS

if @LogDownload = 1
begin
	INSERT files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())
end

SELECT
	*
FROM
	cs_PostAttachments
WHERE
	PostID = @PostID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_PostAttachment_Get] to public
go
/***********************************************
* Sproc: files_Post_GetSortOrder
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...files_Post_GetSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Post_GetSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Post_GetSortOrder]
GO

CREATE PROCEDURE [dbo].files_Post_GetSortOrder
	@PostID int,
	@sqlPopulate nvarchar(4000),
	@SettingsID int
AS

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ThreadID int
)

CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (ThreadID)
EXEC (@sqlPopulate)

SELECT IndexID
	FROM #PageIndex I
	LEFT JOIN cs_Posts P ON P.ThreadID = I.ThreadID
	WHERE P.PostID = @PostID
		AND P.SettingsID = @SettingsID

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Post_GetSortOrder to public
go
/***********************************************
* Sproc: files_Search_PostReindex
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...files_Search_PostReindex'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Search_PostReindex]
GO



/***********************************************
* Sproc: files_users_WhoDownloadedFile
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...files_users_WhoDownloadedFile'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_users_WhoDownloadedFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_users_WhoDownloadedFile]
GO

CREATE PROCEDURE [dbo].files_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.cs_UserId) FROM cs_vw_Users_FullUser U, files_Downloads D WHERE D.UserId = U.cs_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.cs_UserID, Max(D.DownloadDate), count(*)
FROM cs_vw_Users_FullUser U, files_Downloads D 
WHERE D.UserId = U.cs_UserId 
	and D.PostID = @PostID 
	and U.SettingsID = @SettingsID 
	and D.DownloadDate between @StartDate and @EndDate
GROUP BY U.cs_UserID
ORDER BY Max(D.DownloadDate)

-- Get the user details
SELECT
	*, @PostID as PostID
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.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].files_users_WhoDownloadedFile  to public
go
/***********************************************
* Sproc: forums_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
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: 8/8/2006 9:28:11 AM
***********************************************/
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: spam_GetRecentPostCountFromIP
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
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(50),
	@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

