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: 4/14/2008 11:35:01 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



/***********************************************
* Sproc: cs_Post_GetRating
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_PrivateMessages_Recipients
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_PrivateMessages_UnreadCount
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_Profile_GetPropertiesForUsers
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Profile_GetPropertiesForUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Profile_GetPropertiesForUsers]
    @ApplicationName       NVARCHAR(256),
    @UserNames         NTEXT

AS
BEGIN

	SET NOCOUNT ON

    DECLARE @ApplicationId UNIQUEIDENTIFIER
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0

	DECLARE @tbNames	table(Name nvarchar(256) collate database_default NOT NULL PRIMARY KEY) --Has to be removed until we can ensure uniqueness
	DECLARE @tbUsers	table(UserId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

    DECLARE @textpos  int --our chunks position in the ntext
    DECLARE @chunklen smallint
    DECLARE @UserNamesChunk   nvarchar(4000)
	DECLARE @delimiter nvarchar(1)
    DECLARE @leftover nvarchar(4000)

	SET @delimiter = N','
	SET @Num = 0
	SET @textpos = 1
	SET @leftover = ''

	WHILE @textpos <= DATALENGTH(@UserNames) /2
	BEGIN

		SET @chunklen = 4000 - DATALENGTH(@leftover) /2
		SET @UserNamesChunk = ltrim(@leftover + substring(@UserNames, @textpos, @chunklen))
		SET @textpos = @textpos + @chunklen

		SET @Pos = 1 

		WHILE(@Pos <= DATALENGTH(@UserNamesChunk))
		BEGIN
			SELECT @NextPos = CHARINDEX(@delimiter, @UserNamesChunk,  @Pos)
			IF (@NextPos = 0 OR @NextPos IS NULL)
			BEGIN
				--break us from the loop
				SELECT @NextPos = DATALENGTH(@UserNamesChunk) + 1
				--set the leftover string to use again in next iter
				SET @leftover = SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos)
			END
			ELSE
			BEGIN
				SELECT @Name = LOWER(RTRIM(LTRIM(SUBSTRING(@UserNamesChunk, @Pos, @NextPos - @Pos))))
			
				INSERT INTO @tbNames VALUES (@Name)
			
				SET @Num = @Num + 1
			END

			SELECT @Pos = @NextPos+1
		END
		
		IF(@Pos = DATALENGTH(@UserNamesChunk))
			SET @leftover = ''
	END

	INSERT INTO @tbNames VALUES (@leftover)

	INSERT INTO @tbUsers
	  SELECT UserId
	  FROM   dbo.aspnet_Users ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @ApplicationId


    SELECT u.UserName, p.PropertyNames, p.PropertyValuesString, p.PropertyValuesBinary
    FROM         dbo.aspnet_Profile p
			JOIN dbo.aspnet_Users u ON u.UserId = p.UserId
			JOIN @tbUsers t ON u.UserId = t.UserId
    ORDER BY u.UserName

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Profile_GetPropertiesForUsers] to public
go
/***********************************************
* Sproc: cs_Ranks_Get
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()
END

RETURN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Rank_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Ratings_Get
* File Date: 4/14/2008 11:35:03 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.UserID AND
			R.PostID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID

	ELSE IF @RatingType = 1		-- Thread

		SELECT
			U.*,
			'Thread' AS RatingType,
			R.ThreadID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_ThreadRating R
		WHERE
			R.UserID = U.UserID AND
			R.ThreadID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Rating_Add
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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 procedure [dbo].[cs_referrals_Add]
(
	@UrlID int,
	@Url nvarchar(512),
	@SettingsID int,
	@SectionID int,
	@PostID int	
)
as
begin
	set transaction isolation level read uncommitted
	
	exec cs_Urls_Add @UrlID, @Url
	
	-- update the hit count for the SettingsID, SectionID, UrlID and PostID
	update r
	set 
		r.Hits = r.Hits + 1,
		r.LastDate = getdate()
	from
		cs_Referrals r
	where
		r.SettingsID = @SettingsID
		and r.SectionID = @SectionID
		and r.UrlID = @UrlID
		and r.PostID = @PostID
	
	if(@@ROWCOUNT = 0)
	begin
		-- insert the first hit count for the SettingsID, SectionID, UrlID and PostID
		insert cs_Referrals (SettingsID, SectionID, PostID, UrlID, Hits, LastDate)
		values (@SettingsID, @SectionID, @PostID, @UrlID, 1, getdate())
	end
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_referrals_Add] to public
go
/***********************************************
* Sproc: cs_referrals_Get
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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 = SCOPE_IDENTITY()
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Report_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_report_GetBlogPostReplies
* File Date: 4/14/2008 11:35:01 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
/***********************************************
* Sproc: cs_report_GetBlogPostViews
* File Date: 4/14/2008 11:35:01 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
/***********************************************
* Sproc: cs_report_GetForumPostReplies
* File Date: 4/14/2008 11:35:01 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
/***********************************************
* Sproc: cs_report_GetForumPostViews
* File Date: 4/14/2008 11:35:02 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
/***********************************************
* Sproc: cs_report_ThreadViewsByDay
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_report_ThreadViewsByDay'

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

create procedure [dbo].cs_report_ThreadViewsByDay
(
	@SectionID int = -1,
	@PostID int = -1,
	@ApplicationType smallint = -1,
	@Days int
)	
as
begin
	declare @StartDate as datetime

	set @StartDate = (select convert(char(10), dateadd(day, -@Days, getdate()), 120 ))

	if (@PostID > 0)
	begin
		declare @ThreadID as int

		set @ThreadID = (SELECT ThreadID from cs_Posts where PostID = @PostID)

		select
			S.SectionID,
			S.[Day],
			S.ThreadID,
			S.ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.SectionID = @SectionID and
			S.ThreadID = @ThreadID and
			S.[Day] > @StartDate
		order by
			S.[Day]
	end
	else if (@SectionID > 0)
		select
			S.SectionID,
			S.[Day],
			S.ThreadID,
			S.ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.SectionID = @SectionID and
			S.[Day] > @StartDate
		order by
			S.[Day]
	else if (@ApplicationType > -1)
		select
			-1 as SectionID,
			S.[Day],
			-1 as ThreadID,
			sum(S.ViewCount) as ViewCount
		from
			cs_Thread_Daily_Stats S
			inner join cs_Sections SS on SS.SectionID = S.SectionID
		where
			SS.ApplicationType = @ApplicationType and
			S.[Day] > @StartDate
		group by
			S.[Day]		
		order by 
			S.[Day]
	else
		select
			-1 as SectionID,
			S.[Day],
			-1 as ThreadID,
			sum(S.ViewCount) as ViewCount
		from
			cs_Thread_Daily_Stats S
		where
			S.[Day] > @StartDate
		group by
			S.[Day]		
		order by 
			S.[Day]
end
	


/***********************************************
* Sproc: cs_ReverseTrackingOption
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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_CreateRole
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Roles_CreateRole'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.cs_Roles_CreateRole
    @ApplicationName  NVARCHAR(256),
    @RoleName         NVARCHAR(256),
    @Description      NVARCHAR(256) = NULL
AS
BEGIN

    DECLARE @ErrorCode     INT
    SET @ErrorCode = 0

    DECLARE @TranStarted   BIT
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0


    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	DECLARE @ApplicationId uniqueidentifier
	SELECT	@ApplicationId = ApplicationId
	FROM	aspnet_Applications
	WHERE	ApplicationName = @ApplicationName

    IF (EXISTS(SELECT RoleId FROM dbo.aspnet_Roles WHERE LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId))
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    INSERT INTO dbo.aspnet_Roles
                (ApplicationId, RoleName, LoweredRoleName, Description)
         VALUES (@ApplicationId, @RoleName, LOWER(@RoleName), @Description)

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Roles_CreateUpdateDelete
* File Date: 4/14/2008 11:35:01 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


/***********************************************
* Sproc: cs_Roles_Get
* File Date: 4/14/2008 11:35:02 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
(
	@UserName NVARCHAR(256) = NULL,
	@ApplicationName NVARCHAR(256)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF (@UserName IS NULL OR LEN(@UserName) = 0)
		SELECT
			R.RoleId,
			R.RoleName as [Name],
			R.Description
		FROM
			aspnet_Roles R
			INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
		WHERE
			A.LoweredApplicationName = LOWER(@ApplicationName)
	ELSE
	BEGIN
		DECLARE @UserId UNIQUEIDENTIFIER
		SELECT
			@UserId = U.UserId
		FROM
			aspnet_Users U
			INNER JOIN aspnet_Applications A ON U.ApplicationId = A.ApplicationId
		WHERE
			U.LoweredUserName = LOWER(@UserName)
			AND A.LoweredApplicationName = LOWER(@ApplicationName)

		SELECT DISTINCT
			R.RoleId,
			R.RoleName as [Name],
			R.Description
		FROM 
			aspnet_UsersInRoles UIR
			INNER JOIN aspnet_Roles R ON UIR.RoleId = R.RoleId
			INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
		WHERE
			UIR.UserId = @UserId AND
			A.LoweredApplicationName = LOWER(@ApplicationName)
	END
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_Get] to public
go
/***********************************************
* Sproc: cs_Roles_GetRoleIdsForUsers
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Roles_GetRoleIdsForUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cs_Roles_GetRoleIdsForUsers]
	@ApplicationName	nvarchar(256),
    @UserNamesXml         NTEXT

AS
BEGIN


DECLARE @idoc int
	
EXEC sp_xml_preparedocument @idoc OUTPUT, @UserNamesXml


	SELECT DISTINCT
		U.UserName,
		UIR.UserId,
		UIR.RoleId
	FROM
		aspnet_Applications A
		INNER JOIN dbo.aspnet_Users U ON A.ApplicationId = U.ApplicationId
		INNER JOIN dbo.aspnet_UsersInRoles UIR ON U.UserId = UIR.UserId
		INNER JOIN OPENXML(@idoc, '/UserNames/UserName', 2) WITH (UserName nvarchar(256) '.') X on U.LoweredUserName = LOWER(X.UserName)
	WHERE
		A.LoweredApplicationName = LOWER(@ApplicationName)
	ORDER BY U.UserName

EXEC sp_xml_removedocument @idoc

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_GetRoleIdsForUsers] to public
go
/***********************************************
* Sproc: cs_Roles_UpdateRole
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Roles_UpdateRole'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.cs_Roles_UpdateRole
    @ApplicationName  NVARCHAR(256),
    @RoleID           UNIQUEIDENTIFIER,
    @RoleName         NVARCHAR(256),
    @Description      NVARCHAR(256) = NULL
AS
BEGIN

    DECLARE @ErrorCode     INT
    SET @ErrorCode = 0

    DECLARE @TranStarted   BIT
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	DECLARE @ApplicationId uniqueidentifier
	SELECT	@ApplicationId = ApplicationId
	FROM	aspnet_Applications
	WHERE	ApplicationName = @ApplicationName

    UPDATE	aspnet_Roles
    SET		RoleName = @RoleName,
		LoweredRoleName = LOWER(@RoleName),
		Description = @Description
	WHERE	RoleId = @RoleID AND ApplicationId = @ApplicationId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Role_Get
* File Date: 4/14/2008 11:35:01 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,
	@ApplicationName NVARCHAR(256)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT
		R.RoleId,
		R.RoleName as [Name],
		R.Description
	FROM
		aspnet_Roles R
		INNER JOIN aspnet_Applications A ON R.ApplicationId = A.ApplicationId
	WHERE
		((@RoleID IS NOT NULL AND RoleId = @RoleID) OR @RoleID IS NULL) AND
		((@RoleName IS NOT NULL AND RoleName = @RoleName) OR @RoleName IS NULL) AND
		(A.LoweredApplicationName = LOWER(@ApplicationName))

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Role_Get] to public
go
/***********************************************
* Sproc: cs_Role_sprocs
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Role_sprocs'


/***********************************************
* Sproc: cs_RollerBlog_AddFeed
* File Date: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()

  END

-- Let's see if this feed is already part of cs_RollerBlogFeeds based on the SectionID and UrlId.
SET @RecCount = (SELECT COUNT(SectionID) FROM cs_RollerBlogFeeds WHERE UrlID = @AUrlId AND SectionID = @SectionID)

IF (@RecCount = 0)
BEGIN
        -- Add the feed to cs_RollerBlogFeeds based on SectionID (users blog).
	INSERT INTO cs_RollerBlogFeeds
	(
		SectionID,
		UrlID,
		SettingsID,
		SiteUrl,
        IntervalMinutes,
		Title,
		SubscribeDate,
		LastUpdateDate,
		LastModifiedDate,
		PostFullArticle,
		ExerptSize,
		IsBlogAggregated,
		IsBlogRollAggregated,
		Enabled,
		State
	)
	VALUES
	(
		@SectionID,
		@AUrlId,
		@SettingsID,
		@SiteUrl,
		@IntervalMin,
		@Title,
	    @CurrentDateTime,
	    DateAdd(mi, -@IntervalMin, @CurrentDateTime),
	    @CurrentDateTime,
		@PostFullText,
		@ExerptSize,
		@IsBlogAggregated,
		@IsBlogRollAggregated,
		@Enabled,
		@State
	)
END
ELSE
BEGIN
        -- Enable the already existing feed.
	UPDATE cs_RollerBlogFeeds
	SET 
		Enabled = 1, 
		IntervalMinutes = @IntervalMin, 
		Title = @Title,
		PostFullArticle = @PostFullText, 
		ExerptSize = @ExerptSize,
        IsBlogAggregated = @IsBlogAggregated, 
		IsBlogRollAggregated = @IsBlogRollAggregated, 
		SiteUrl = @SiteUrl
	WHERE UrlID = @AUrlId AND SectionID = @SectionID
END

SELECT @NewUrlID = @AUrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_RollerBlog_AddPost
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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

/***********************************************
* Sproc: cs_Roller_GetFeeds
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_Roller_GetPosts
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_Roller_GetUnaggregatedFeeds
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_SearchBarrel_Search
* File Date: 4/14/2008 11:35:01 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,
	@PageIndex int = 0,
	@PageSize int = 25,
	@SettingsID int
)
AS
BEGIN

	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @StartTime datetime
		, @RowsToReturn int
		, @PageLowerBound int
		, @PageUpperBound int
		, @Count int
		, @TotalRecords int

	-- Used to calculate cost of query
	SET @StartTime = GetDate()

	-- Set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	--SET ROWCOUNT @RowsToReturn

	-- Calculate the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the results in
	CREATE TABLE #SearchResults
	(
		IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
		PostID int not null,
		SectionID int not null,
		Weight int,
		PostDate datetime
	)

	-- Fill the temp table
	INSERT INTO #SearchResults (PostID, SectionID, Weight, PostDate)
	exec sp_executesql @SearchSQL

	SET @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- SELECT actual search results from this table
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.Subject, P.PostDate,
		P.FormattedBody, P.IPAddress, P.PostType, P.SettingsID, P.UserTime,
		P.ApplicationPostType, P.PostName, P.UserTime,
		COALESCE(pa.[FileName], '') AS AttachmentFilename,
		S.ApplicationKey, S.GroupID, S.ApplicationType, S.[Name] as SectionName, S.HubSectionID
	FROM 
		cs_Posts P
	INNER JOIN
		cs_Sections S ON P.SettingsID = S.SettingsID AND P.SectionID = S.SectionID
	INNER JOIN
		#SearchResults R ON R.PostID = P.PostID
	LEFT OUTER JOIN
		cs_PostAttachments pa ON pa.PostID = P.PostID
	WHERE
		S.SettingsID = @SettingsID AND
		R.IndexID > @PageLowerBound AND
		R.IndexID < @PageUpperBound
	Order By R.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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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_SectionMembers_Add
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SectionMembers_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_SectionMembers_Add
(
	@SectionID			int,
	@UserID				int,
	@MembershipType		int,
	@DateAdded datetime OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


			UPDATE cs_SectionMembers
				Set MembershipType = @MembershipType
			WHERE
				SectionID = @SectionID AND UserID = @UserID

      IF @@ROWCOUNT = 0
      BEGIN
        INSERT INTO cs_SectionMembers
          (SectionID, UserID, MembershipType)
        VALUES
          (@SectionID, @UserID, @MembershipType)
      END
			SELECT @DateAdded = [DateAdded] from cs_SectionMembers WHERE SectionID = @SectionID AND UserID = @UserID AND MembershipType = @MembershipType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_SectionMembers_Delete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SectionMembers_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_SectionMembers_Delete
(
	@SectionID			int = NULL,
	@UserID				int = NULL,
	@MembershipType		int = NULL
)
AS

--Must pass either a sectionid or userid or a bad programmer could use this to delete all records

IF @SectionID is NULL and @UserID is NULL
	RETURN


		DELETE
		FROM	cs_SectionMembers
		WHERE	
		(SectionID = @SectionID OR @SectionID IS NULL) AND
		(UserID = @UserID OR @UserID IS NULL) AND
		(MembershipType = @MembershipType OR @MembershipType IS NULL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_SectionMembers_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_SectionMembers_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_SectionMembers_Get
(
	@SectionID			int = NULL,
	@UserID				int = NULL,
	@MembershipType		int = NULL
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


		SELECT
			SM.SectionID,
			SM.UserID,
			SM.MembershipType,
			SM.DateAdded,
			S.ApplicationType
		FROM
			cs_SectionMembers SM
			join cs_Sections S on S.SectionID = SM.SectionID
		WHERE
		(SM.SectionID = @SectionID OR @SectionID IS NULL) AND
		(SM.UserID = @UserID OR @UserID IS NULL) AND
		(SM.MembershipType & @MembershipType = SM.MembershipType OR @MembershipType IS NULL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Sections_Get
* File Date: 4/14/2008 11:35:01 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 = null,
	@AllowInactive			bit = 0,
	@IncludePostTypeCounts	bit = 0,
	@sqlPopulate			ntext = null,
	@PageIndex				int = 0, 
	@PageSize				int = 2147483646,
	@IncludePageIndex		bit = 0,
	@IncludeMembers			bit = 0,
	@HubSectionID			int = 0,
	@TotalRecords			int = null output

)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalThreads int
	
	-- First set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	
	
	
	
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndex 
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		SectionID int not null
	)
	 
	
	if @sqlPopulate is not null
	BEGIN
		INSERT INTO #PageIndex (SectionID)
		EXEC sp_executesql @sqlPopulate
	END
	ELSE
	BEGIN
		IF @ApplicationType = 11 AND @HubSectionID = 0
		BEGIN
			INSERT INTO #PageIndex (SectionID)
			SELECT SectionID from cs_Sections where SettingsID = @SettingsID AND (ApplicationType = @ApplicationType OR @ApplicationType is null)
		END
		ELSE
		BEGIN
			INSERT INTO #PageIndex (SectionID)
			SELECT SectionID from cs_Sections where SettingsID = @SettingsID AND (ApplicationType = @ApplicationType OR @ApplicationType is null) AND HubSectionID = @HubSectionID
		END
	END
	
	SET @TotalRecords = @@rowcount
	
	-- if an index is to be created, it should come after the insertion
	--CREATE INDEX page_index ON #PageIndex(IndexID)
	
	SET ROWCOUNT @RowsToReturn
	
	
	-- Return all the forums
	SELECT  
		F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
		F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnablePostPoints, F.EnableAnonymousPosting,
		F.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, F.IsPublic, F.HubSectionID, F.IsCommunityAggregated, W.*
	
	FROM
		#PageIndex jPI
		INNER JOIN cs_Sections F on F.SettingsID = @SettingsID AND F.SectionID = jPI.SectionID
		LEFT OUTER JOIN cs_weblog_Weblogs W on F.SectionID = W.SectionID
	WHERE
		--(IsActive = 1 OR 1 = @AllowInactive) AND
		(ApplicationType = @ApplicationType or @ApplicationType is null) AND
		jPI.IndexID > @PageLowerBound AND 
		jPI.IndexID < @PageUpperBound
	ORDER BY
		jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate
	
	
	--Clear the rowcount
	SET ROWCOUNT 0
	
	--Declare @AnonID int
	--exec cs_GetAnonymousUserID @SettingsID, @AnonID output
	
	exec cs_Section_Permissions_Get @SettingsID, 0, @ApplicationType
	
	--Return the counts of each post type
	IF @IncludePostTypeCounts > 0
	BEGIN
		
		SELECT 
			F.ApplicationKey, P.ApplicationPostType, Count(*) as PostCount
		FROM 
			#PageIndex jPI
			INNER JOIN cs_Sections F on F.SettingsID = @SettingsID AND F.SectionID = jPI.SectionID
			INNER JOIN cs_Posts P on F.SettingsID = P.SettingsID AND F.SectionID = P.SectionID
		WHERE 
			jPI.IndexID > @PageLowerBound AND 
			jPI.IndexID < @PageUpperBound AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		GROUP BY 
			F.ApplicationKey, P.ApplicationPostType, jPI.IndexID
		ORDER BY
			jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate
		
	END
	
	SET ROWCOUNT 0
	
  IF @IncludeMembers = 1
  BEGIN

	SELECT
		SM.SectionID,
		SM.UserID,
		SM.MembershipType,
		SM.DateAdded,
		S.ApplicationType
	FROM
		#PageIndex jPI
		INNER JOIN dbo.cs_SectionMembers SM on SM.SectionID = jPI.SectionID
		INNER JOIN cs_Sections S on S.SettingsID = @SettingsID AND S.SectionID = jPI.SectionID
	WHERE
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
	ORDER BY
		SM.SectionID, SM.MembershipType

  End
	
	If @IncludePageIndex = 1 
	BEGIN
		SELECT IndexID, SectionID from #PageIndex ORDER BY IndexID
	END
	
	DROP TABLE #PageIndex
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Sections_GetRead
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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 = SCOPE_IDENTITY()



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Add to public
go
/***********************************************
* Sproc: cs_SectionTokens_Delete
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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(1000) = '',
	@ParentID	int = 0,
	@SettingsID	int,
	@GroupID	int = 0,
	@IsModerated	bit = 1,
	@IsSearchable   bit = 1,
	@DisplayPostsOlderThan	int = 0,
	@IsActive 	bit = 0,
	@EnablePostStatistics bit = 1,
	@EnablePostPoints bit = 1,
	@EnableAnonymousPosting bit = 0,
	@SortOrder int = 0,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ApplicationKey nvarchar(256) = null,
	@ApplicationType smallint = 0,
	@ForumType int = 0,
	@UserID int,
	@DefaultLanguage nvarchar(32) = null,
	@IsPublic 	bit = null,
	@IsCommunityAggregated 	bit = 1,
	@HubSectionID int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting the forum?
IF @DeleteForum = 1
BEGIN

	Select @ApplicationKey = 'Deleted Section ' + ApplicationKey FROM cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

	exec cs_system_ModerationAction_AuditEntry 19, @UserID, null, @UserID, @SectionID, @SettingsID,  @ApplicationKey


           DECLARE @SectionToDeleteParentID int
           SET @SectionToDeleteParentID = (SELECT ParentID FROM cs_Sections WHERE SectionID = @SectionID)

	-- delete the specified forum and all of its posts
	-- first we must remove all the thread tracking rows
	DELETE 
		cs_TrackedThreads
	WHERE 
		ThreadID IN (SELECT DISTINCT ThreadID FROM cs_Threads WHERE SectionID = @SectionID and SettingsID = @SettingsID)

	-- we must remove all of the moderators for this forum
	DELETE 
		cs_Moderators
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	-- we must remove all roller blog related data
	DELETE
		cs_RollerBlogPost
	FROM
		cs_RollerBlogPost RBP INNER JOIN cs_RollerBlogFeeds RBF ON  RBP.SectionID = RBF.SectionID AND RBP.UrlID = RBF.UrlID
	WHERE
		RBF.SectionID = @SectionID AND RBF.SettingsID = @SettingsID

	DELETE
		cs_RollerBlogFeeds
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- now we must remove all of the posts
	DELETE 
		cs_Posts
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE cs_weblog_Weblogs Where SectionID = @SectionID and SettingsID = @SettingsID

	-- remove all the explicit forum permissions
	DELETE
		cs_SectionPermissions
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- finally we can delete the actual forum
	DELETE 
		cs_Sections
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE 
		cs_Posts_InCategories
	WHERE
		CategoryID in (Select CategoryID FROM cs_Post_Categories where SectionID = @SectionID and SettingsID = @SettingsID)

	DELETE 
		cs_Post_Categories
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID		

	-- Clean up an child sectoins
       UPDATE
		cs_Sections
	SET 
		ParentID = @SectionToDeleteParentID
        WHERE
                ParentID = @SectionID


	RETURN
END

-- Are we updating a forum
IF @SectionID > 0
BEGIN
	-- if we are making the forum non-moderated, remove all forum moderators for this forum
	IF @IsModerated = 0
		DELETE 
			cs_Moderators
		WHERE 
			SectionID = @SectionID and SettingsID = @SettingsID

	-- Update the forum information
	UPDATE 
		cs_Sections 
	SET
		Name = @Name,
		Url = @Url,
		Description = @Description,
		ParentID = @ParentID,
		SettingsID = @SettingsID,
		GroupID = @GroupID,
		IsModerated = @IsModerated,
		IsActive = @IsActive,
		IsSearchable = @IsSearchable,
		DaysToView = @DisplayPostsOlderThan,
		EnablePostStatistics = @EnablePostStatistics,
		EnablePostPoints = @EnablePostPoints,
		EnableAnonymousPosting = @EnableAnonymousPosting,
		SortOrder = @SortOrder,
		ApplicationKey = @ApplicationKey,
		ApplicationType = @ApplicationType,
		ForumType = @ForumType,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		DefaultLanguage = @DefaultLanguage,
		IsPublic = @IsPublic,
		IsCommunityAggregated = @IsCommunityAggregated,
		HubSectionID = @HubSectionID
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID
END
ELSE
BEGIN

	if( @SortOrder = 0 ) 
	begin
		select @SortOrder = coalesce(max(SortOrder) + 1, 1) from cs_Sections where GroupID = @GroupID

		if(@SortOrder is null)
		Begin
			Select @SortOrder = 1
		End
	end

	-- Create a new Forum
	INSERT INTO 
		cs_Sections (
			Name, 
			Url,
			Description, 
			ParentID, 
			SettingsID, 
			GroupID, 
			IsModerated, 
			DaysToView, 
			IsActive,
			IsSearchable,
			EnablePostStatistics,
			EnablePostPoints,
			SortOrder,
			ApplicationKey,
			ApplicationType,
			ForumType,
			PropertyNames,
			PropertyValues,
			DefaultLanguage,
			IsPublic,
			IsCommunityAggregated,
			HubSectionID
			)
		VALUES (
			@Name,
			@Url,
			@Description,
			@ParentID,
			@SettingsID,
			@GroupID,
			@IsModerated,
			@DisplayPostsOlderThan,
			@IsActive,
			@IsSearchable,
			@EnablePostStatistics,
			@EnablePostPoints,
			@SortOrder,
			@ApplicationKey, 
			@ApplicationType,
			@ForumType,
			@PropertyNames,
			@PropertyValues,
			@DefaultLanguage,
			@IsPublic,
			@IsCommunityAggregated,
			@HubSectionID
			)
	
	SET @SectionID = scope_identity()

	If @ApplicationType = 1
	Begin
		Insert cs_weblog_Weblogs (SectionID, SettingsID) Values (@SectionID, @SettingsID)
	End

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Section_DiskUsage_Update
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_Section_GetRandomSectionID
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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_IsPublic_Update
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Section_IsPublic_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Section_IsPublic_Update
(
	@SectionID int,
	@SettingsID int,
	@IsPublic bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	UPDATE cs_Sections SET IsPublic = @IsPublic
	WHERE SettingsID = @SettingsID AND SectionID = @SectionID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Section_IsPublic_UpdateAll
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Section_IsPublic_UpdateAll'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Section_IsPublic_UpdateAll
(
	@SettingsID int,
	@RoleID uniqueidentifier,
	@ApplicationType int,
	@Reset bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

--SET @SettingsID = 1000
--SET @ApplicationType = 0
--SET @Reset = 1

--Select @RoleID = RoleID from aspnet_Roles where LoweredRoleName = 'everyone'

Update [dbo].[cs_Sections] set IsPublic = P.AllowViewBit FROM
	(
	SELECT
		F.SettingsID, 
		DefaultPermission = convert(bit, coalesce(P.AllowMask*0,1)), 
		F.SectionID, 
		F.ApplicationKey,
		AllowViewBit = coalesce(P.AllowMask, PP.AllowMask) & 1 --CONVERT(bigint, 0x0000000000000001)
	FROM 
		cs_Sections F
		LEFT OUTER JOIN cs_ProductPermissions PP on F.ApplicationType = PP.ApplicationType and PP.RoleID = @RoleID
		LEFT OUTER JOIN cs_SectionPermissions P on P.SectionID = F.SectionID and P.RoleID = @RoleID

	WHERE
		F.SettingsID = @SettingsID
		AND F.ApplicationType = @ApplicationType
		AND (F.IsPublic is null or @Reset = 1)

	) P JOIN cs_Sections F  ON P.SectionID = F.SectionID
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Section_IsPublic_UpdateGroup
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Section_IsPublic_UpdateGroup'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].[cs_Section_IsPublic_UpdateGroup]
(
	@SettingsID int,
	@RoleID uniqueidentifier,
	@GroupID int,
	@ApplicationType int,
	@Reset bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Update cs_Sections set IsPublic = P.AllowViewBit FROM
	(
	SELECT
		F.SettingsID, 
		DefaultPermission = convert(bit, coalesce(P.AllowMask*0,1)), 
		F.SectionID, 
		F.ApplicationKey,
		AllowViewBit = coalesce(P.AllowMask, GP.AllowMask, PP.AllowMask) & 1
	FROM 
		cs_Sections F
		LEFT OUTER JOIN cs_GroupPermissions GP on F.GroupID = GP.GroupID and GP.RoleID = @RoleID
		LEFT OUTER JOIN cs_ProductPermissions PP on F.ApplicationType = PP.ApplicationType and PP.RoleID = @RoleID
		LEFT OUTER JOIN cs_SectionPermissions P on P.SectionID = F.SectionID and P.RoleID = @RoleID

	WHERE
		F.SettingsID = @SettingsID
		AND F.GroupID = @GroupID
		AND F.ApplicationType = @ApplicationType
		AND (F.IsPublic is null or @Reset = 1)

	) P JOIN cs_Sections F ON P.SectionID = F.SectionID
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Section_MarkRead
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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,
	@AllRoles ntext = NULL
)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	
	IF ( @SectionID = 0 )
	begin
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID
	
		UNION ALL
	
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			P.GroupID, 
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			G.ApplicationType 
		FROM 
			cs_GroupPermissions P
		INNER JOIN
			cs_Groups G
			ON P.GroupID = G.GroupID AND P.SettingsID = G.SettingsID
		WHERE
			G.SettingsID = @SettingsID AND
			(G.ApplicationType = @ApplicationType or @ApplicationType is null)
		
		UNION ALL
	
		-- Return section permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 0), 
			P.SectionID,
			GroupID = -1, 
			F.ApplicationKey,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			F.ApplicationType
		FROM 
			cs_SectionPermissions P
		INNER JOIN
			cs_Sections F
			ON P.SectionID = F.SectionID AND P.SettingsID = F.SettingsID
		WHERE
			F.SettingsID = @SettingsID AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		order by Implied asc, SectionID, GroupID desc
	
	end
	ELSE IF (@SectionID > 0)
	begin
		
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			P.ApplicationType 
		FROM
			cs_ProductPermissions P
		WHERE 
			(P.ApplicationType = @ApplicationType or @ApplicationType is null) AND
			P.SettingsID = @SettingsID
	
		UNION ALL

		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			P.GroupID,
			ApplicationKey = null,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)), 
			S.ApplicationType 
		FROM
			cs_GroupPermissions P
			INNER JOIN cs_Sections S on S.SectionID = @SectionID AND S.GroupID = P.GroupID
		WHERE 
			P.SettingsID = @SettingsID

		UNION ALL
		
		-- Return section permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 0), 
			P.SectionID,
			F.GroupID,
			F.ApplicationKey,
			P.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),  
			F.ApplicationType 
		FROM 
			cs_SectionPermissions P
		INNER JOIN
			cs_Sections F
			ON P.SectionID = F.SectionID AND P.SettingsID = F.SettingsID
		WHERE
			F.SettingsID = @SettingsID AND
			F.SectionID = @SectionID  AND
			(F.ApplicationType = @ApplicationType or @ApplicationType is null)
		order by Implied asc, SectionID, GroupID DESC
	END 
    ELSE BEGIN
	
	    DECLARE @Roles		table(RoleID uniqueidentifier NOT NULL PRIMARY KEY)
	    DECLARE @Num		int
	    DECLARE @Pos		int
	    DECLARE @NextPos	int
	    DECLARE @guid		nvarchar(256)
	
	    DECLARE @textpos  int --our chunks position in the ntext
	    DECLARE @chunklen smallint
	    DECLARE @chunk   nvarchar(4000)
	    DECLARE @delimiter nvarchar(1)
	    DECLARE @leftover nvarchar(4000)
	
		SET @delimiter = N','
		SET @Num = 0
		SET @textpos = 1
		SET @leftover = ''
	
		WHILE @textpos <= DATALENGTH(@AllRoles) /2
		BEGIN
	
			SET @chunklen = 4000 - DATALENGTH(@leftover) /2
			SET @chunk = ltrim(@leftover + substring(@AllRoles, @textpos, @chunklen))
			SET @textpos = @textpos + @chunklen
	
			SET @Pos = 1 
	
			WHILE(@Pos <= DATALENGTH(@chunk))
			BEGIN
				SELECT @NextPos = CHARINDEX(@delimiter, @chunk,  @Pos)
				IF (@NextPos = 0 OR @NextPos IS NULL)
				BEGIN
					--break us from the loop
					SELECT @NextPos = DATALENGTH(@chunk) + 1
					--set the leftover string to use again in next iter
					SET @leftover = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
				END
				ELSE
				BEGIN
					SELECT @guid = LOWER(RTRIM(LTRIM(SUBSTRING(@chunk, @Pos, @NextPos - @Pos))))
	
					INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @guid))
	
					SET @Num = @Num + 1
				END
	
				SELECT @Pos = @NextPos+1
			END
	
			IF(@Pos = DATALENGTH(@chunk))
				SET @leftover = ''
		END
	
		INSERT INTO @Roles VALUES (CONVERT(uniqueidentifier, @leftover))
	
	
		-- Return product permissions
		SELECT
			P.SettingsID, 
			Implied = convert(bit, 1), 
			SectionID = -1,
			GroupID = -1,
			R.RoleID, 
			AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
			DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)),
			P.ApplicationType 
		FROM
			@Roles R
			left outer join cs_ProductPermissions P on R.RoleID = P.RoleID and (P.ApplicationType = @ApplicationType or @ApplicationType is null)and P.SettingsID = @SettingsID
	END
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_Permissions_Get] to public
go
/***********************************************
* Sproc: cs_Section_Permission_CreateUpdateDelete
* File Date: 4/14/2008 11:35:01 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,
	@GroupID 	int,
	@RoleID		uniqueidentifier,
	@Action		int,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@ApplicationType smallint
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

-- Create
IF @Action = 0
BEGIN

	IF( @SectionID <> -1) 
	begin
		-- Check if an entry already exists
		IF EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
	
		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		select @GroupID = GroupID from cs_Sections S where S.SectionID = @SectionID and S.SettingsID = @SettingsID
			
		if not exists( select * from cs_GroupPermissions where SettingsID = @SettingsID and RoleID = @RoleID and GroupID = @GroupID)
			insert into cs_GroupPermissions ( SettingsID, RoleID, AllowMask, DenyMask, GroupID )
				values( @SettingsID, @RoleID, 0x0, 0x0, @GroupID )
				
		--reindex the posts
		exec cs_Posts_ReindexBySection @SectionID, @SettingsID
	end
	ELSE IF (@GroupID <> -1)
	begin
		IF EXISTS (SELECT GroupID FROM cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_GroupPermissions (SettingsID, GroupID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@GroupID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		--reindex the posts
		exec cs_Posts_ReindexByGroup @GroupID, @SettingsID
	end
	ELSE
	begin
		insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
			values( @SettingsID, @RoleID, @AllowMask, @DenyMask, @ApplicationType )
	end
END
-- UPDATE
ELSE IF @Action = 1
BEGIN
	
	IF ( @SectionID <> -1 ) 
	begin
		IF NOT EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID )
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
		ELSE
			UPDATE
				cs_SectionPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				SectionID = @SectionID AND
				RoleID = @RoleID AND SettingsID = @SettingsID

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )

		select @GroupID = GroupID from cs_Sections S where S.SectionID = @SectionID and S.SettingsID = @SettingsID
			
		if not exists( select * from cs_GroupPermissions where SettingsID = @SettingsID and RoleID = @RoleID and GroupID = @GroupID)
			insert into cs_GroupPermissions ( SettingsID, RoleID, AllowMask, DenyMask, GroupID )
				values( @SettingsID, @RoleID, 0x0, 0x0, @GroupID )
	end
	ELSE IF (@GroupID <> -1)
	begin
		IF NOT EXISTS (SELECT GroupID FROM cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID )
			INSERT INTO 
				cs_GroupPermissions (SettingsID, GroupID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@GroupID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)
		ELSE
			UPDATE
				cs_GroupPermissions
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				GroupID = @GroupID AND
				RoleID = @RoleID AND
				SettingsID = @SettingsID

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )	
	end
	ELSE
	begin
		if not exists( select * from cs_ProductPermissions where RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @GroupID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		else
			UPDATE
				cs_ProductPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end

END
ELSE IF @Action = 2
BEGIN
	IF( @SectionID <> -1 )
		DELETE cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID
	ELSE IF (@GroupID <> -1)
		DELETE cs_GroupPermissions WHERE GroupID = @GroupID AND RoleID = @RoleID AND SettingsID = @SettingsID
	ELSE
	begin
		DELETE cs_SectionPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID
		DELETE cs_GroupPermissions WHERE RoleID = @RoleID AND SettingsID = @SettingsID
		DELETE cs_ProductPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end
	
END

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Section_Permission_CreateUpdateDelete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Section_RssPingback_Update
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_Services_Get
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()

END

RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Service_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_SetForumSubscriptionType
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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,
	@sqlPopulateCount ntext,
	@UserID int,
	@IncludeCategories bit,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int

	/* First set the rowcount */
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)

	/* Set the page bounds */
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	/* Create a temp table to store the select results */
	CREATE TABLE #PageIndex
	(
		IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
		PostID int NOT NULL
	)

	exec sp_executesql @sqlPopulateCount, N'@recordCount int output', @recordCount = @TotalRecords output

	/* this is the number of records to page from */
	SET ROWCOUNT @RowsToReturn

	INSERT INTO #PageIndex (PostID)
	exec sp_executesql @sqlPopulate

	/* this is the size of the page */
	SET ROWCOUNT @PageSize

	SELECT
		SortOrder = jPI.IndexID,
		jP.PostID,
		jP.ThreadID,
		jP.ParentID,
		jP.PostAuthor,
		jP.UserID,
		jP.SectionID,
		jP.PostLevel,
		jP.SortOrder,
		jP.Subject,
		jP.PostDate,
		jP.IsApproved,
		jP.IsLocked as IsLocked,
		jP.IsIndexed,
		jP.TotalViews as PostTotalViews,  /* Conflicts with the Threads table which has precidence */
		jP.Body,
		jP.FormattedBody,
		jP.IPAddress,
		jP.PostType,
		jP.PostMedia,
		jP.EmoticonID,
		jP.SettingsID,
		jP.AggViews,
		jP.PostPropertyNames,
		jP.PostPropertyValues,
		jP.PostConfiguration,
		jP.Points AS PostPoints,
		jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created, jP.Height, jP.Width,
		jP.PostName,
		jP.ApplicationPostType,
		jP.UserTime,
		HasRead = 1,
		EditNotes = null, /*(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),*/

		jT.PostAuthor as UserName,
		jT.TotalReplies as Replies, /* (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1) */

	        jT.UserID as ThreadUserID,
	        jT.PostAuthor as ThreadPostAuthor,
	        jT.PostDate as ThreadPostDate,
	        jT.ThreadDate,
	        jT.LastViewedDate,
	        jT.StickyDate,
	        jT.TotalViews as TotalViews,
	        jT.TotalReplies,
	        jT.MostRecentPostAuthorID,
	        jT.MostRecentPostAuthor,
	        jT.MostRecentPostID,
	        jT.IsLocked as ThreadIsLocked,
	        jT.IsSticky,
	        jT.IsApproved as ThreadIsApproved,
	        jT.RatingSum,
	        jT.TotalRatings,
	        jT.ThreadEmoticonID,
	        jT.ThreadStatus,
	        jT.SettingsID
		, jP.PostStatus, jP.SpamScore
	FROM
		#PageIndex jPI
		INNER JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
		INNER JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	WHERE
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		/*AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,*/
		/*AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID*/
	ORDER BY
		jPI.IndexID	/* this is the ordering system we're using populated from the @sqlPopulate */

	SET ROWCOUNT 0

	IF @IncludeCategories = 1
	BEGIN
		declare @P table(PostID int not null primary key)

		insert into @P
		select jPI.PostID from #PageIndex jPI
		where jPI.IndexID > @PageLowerBound
			AND jPI.IndexID < @PageUpperBound

		SELECT
			Cats.[Name], PIC.PostID
		FROM
			@P jPI
			INNER JOIN cs_Posts_InCategories PIC ON jPI.PostID = PIC.PostID
			INNER JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	End

	DROP TABLE #PageIndex

	If @IncludePageIndex = 1
	BEGIN
		/* Create a temp table to store the select results */
		CREATE TABLE #PageIndex2
		(
			IndexID int IDENTITY (1, 1) NOT NULL primary key clustered,
			PostID int NOT NULL
		)

		/* this is the number of records to page from */
		SET ROWCOUNT 0

		INSERT INTO #PageIndex2 (PostID)
		exec sp_executesql @sqlPopulate

		SELECT IndexID, PostID from #PageIndex2 ORDER BY IndexID

		DROP TABLE #PageIndex2
	END
end
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

grant execute on [dbo].[cs_shared_Threads_GetThreadSet] to public
go
/***********************************************
* Sproc: cs_SiteSettings_Get
* File Date: 4/14/2008 11:35:01 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
	IF @SiteUrl is null
	Begin
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
			FROM 
				cs_SiteSettings ss
			LEFT OUTER JOIN 
				cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
			LEFT OUTER JOIN 
				cs_Sites s ON s.SiteID = sm.SiteID
			Where
				ss.SettingsID = @SettingsID
	End
	else
	begin
		select
			top 1 ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
			FROM 
				cs_SiteSettings ss
			LEFT OUTER JOIN 
				cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
			LEFT OUTER JOIN 
				cs_Sites s ON s.SiteID = sm.SiteID
			ORDER BY ss.SettingsID asc
	end
End
Else
Begin
	IF @SiteUrl = '*'
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
	
	ELSE IF NOT EXISTS (SELECT * FROM cs_Sites WHERE SiteUrl = @SiteUrl OR SiteUrl = @SiteUrl + '/')
		RETURN
	ELSE
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			(s.SiteUrl = @SiteUrl OR s.SiteUrl = @SiteUrl + '/')
End

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SiteSettings_Get to public
go
/***********************************************
* Sproc: cs_SiteSettings_Save
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')


-- SELECT current statistics
SELECT 
	S.*,
	CurrentAnonymousUsers = (SELECT Count(*) FROM cs_AnonymousUsers where SettingsID = @SettingsID),
	MostReadSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostReadPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostViewsSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostViewsPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostActivePostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE UserID = S.MostActiveUserID and SettingsID = @SettingsID),''),
	NewestUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE UserID = S.NewestUserID and SettingsID = @SettingsID),'')
FROM
	cs_statistics_Site S
WHERE
	DateCreated = @LastUpdate  and SettingsID = @SettingsID

-- SELECT TOP 100 Users
SELECT TOP 100
	S.TotalPosts,
	U.*
FROM
	cs_statistics_User S,
	cs_vw_Users_FullUser U
WHERE
	S.UserID = U.UserID AND
	U.EnableDisplayInMemberList = 1 AND
	U.UserID > 0 and U.SettingsID = @SettingsID and S.SettingsID = @SettingsID
ORDER BY
	S.TotalPosts DESC

-- SELECT Moderator actions
SELECT
	Description,
	TotalActions
FROM
	cs_ModerationAction
WHERE
	TotalActions > 0
ORDER BY
	TotalActions DESC 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Smiley_CreateUpdateDelete
* File Date: 4/14/2008 11:35:02 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 = SCOPE_IDENTITY()
END
RETURN









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Smiley_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Smilies_Get
* File Date: 4/14/2008 11:35:01 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_SpamPostArchive
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SpamPostArchive'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

CREATE PROCEDURE [dbo].[cs_SpamPostArchive]
(
	@SourceProcedure nvarchar(128)
	/* from cs_Post_CreateUpdate */
	, @SectionID int
	, @ParentID int
	, @AllowDuplicatePosts bit
	, @DuplicateIntervalInMinutes int
	, @Subject nvarchar(256)
	, @UserID int
	, @PostAuthor nvarchar(64)
	, @Body ntext
	, @FormattedBody ntext
	, @EmoticonID int
	, @IsLocked bit
	, @IsSticky bit
	, @IsApproved bit
	, @StickyDate datetime
	, @PostType int
	, @PostMedia int
	, @PostDate datetime
	, @UserHostAddress nvarchar(32)
	, @PropertyNames ntext
	, @PropertyValues ntext
	, @SettingsID int
	, @IsTracked bit
	, @PostID int
	, @ThreadID int
	, @PostConfiguration int
	, @UpdateSectionStatistics bit
	, @UserTime datetime
	, @ApplicationPostType int
	, @PostName nvarchar(256)
	, @ThreadStatus int
	, @Points int
	, @PostDisplayName nvarchar(64)
	, @AutoApprove bit

	/* from cs_weblog_Post_Create */
	, @TitleUrl nvarchar(256)
	, @PostConfig int
	, @BlogPostType tinyint
	, @Categories nvarchar(4000)
	, @SpamScore int
	, @PostStatus int
)
AS
begin
	SET NOCOUNT ON

	if @SourceProcedure IS NULL
	begin
		raiserror ( 'The parameter @SourceProcedure should not be NULL.', 16, 1 )
		return 1
	end
	
	if OBJECT_ID( @SourceProcedure ) IS NULL
	begin
		raiserror ( 'The parameter @SourceProcedure contains [%s] which is not currently a valid object in the database.', 16, 1, @SourceProcedure )
		return 2
	end
	
	select
		@PostDate = COALESCE( @PostDate, getdate() )
		, @UserTime = COALESCE( @UserTime, @PostDate )

	INSERT INTO [dbo].[cs_SpamPosts] (
		[SourceProcedure]
		, [SectionID], [ParentID], [AllowDuplicatePosts], [DuplicateIntervalInMinutes], [Subject], [UserID], [PostAuthor]
		, [Body], [FormattedBody], [EmoticonID], [IsLocked], [IsSticky], [IsApproved], [StickyDate]
		, [PostType], [PostMedia], [PostDate], [UserHostAddress], [PropertyNames], [PropertyValues], [SettingsID]
		, [IsTracked], [ThreadID], [PostConfiguration], [UpdateSectionStatistics], [UserTime], [ApplicationPostType]
		, [PostName], [ThreadStatus], [Points], [PostDisplayName], [AutoApprove], [TitleUrl], [PostConfig]
		, [BlogPostType], [Categories], [SpamScore], [PostStatus]
	) VALUES (
		@SourceProcedure
		, @SectionID, @ParentID, @AllowDuplicatePosts, @DuplicateIntervalInMinutes, @Subject, @UserID, @PostAuthor
		, @Body, @FormattedBody, @EmoticonID, @IsLocked, @IsSticky, @IsApproved, @StickyDate
		, @PostType, @PostMedia, @PostDate, @UserHostAddress, @PropertyNames, @PropertyValues, @SettingsID
		, @IsTracked, @ThreadID, @PostConfiguration, @UpdateSectionStatistics, @UserTime, @ApplicationPostType
		, @PostName, @ThreadStatus, @Points, @PostDisplayName, @AutoApprove, @TitleUrl, @PostConfig
		, @BlogPostType, @Categories, @SpamScore, @PostStatus
	)

end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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


/***********************************************
* Sproc: cs_SpamPostDelete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SpamPostDelete'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

CREATE PROCEDURE [dbo].[cs_SpamPostDelete]
(
	@SpamPostID bigint = null
	, @SettingsID int = null
	, @SectionID int = null
	, @ThreadID int = null
	, @RowCount int = null output
)
AS
begin
	SET NOCOUNT ON
	
    --	We will allow movement at a SpamPostID level, a SettingsID, SectionID, ThreadID level, and SettingsID, SectionID
    --	The default is SpamPostID - if that is set, it overrides any thing else

	if @SpamPostID IS NOT NULL
	begin
	
		/* Remove a single spam post */
		delete p from [dbo].[cs_SpamPosts] p
		where p.[SpamPostID] = @SpamPostID
		
		set @RowCount = @@ROWCOUNT
	
	end
	else if @SettingsID IS NOT NULL AND @SectionID IS NOT NULL
	begin
	
		if @ThreadID IS NOT NULL
		begin
		
			/* Remove spam posts by Thread */
			delete p from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID AND p.[ThreadID] = @ThreadID
			
			set @RowCount = @@ROWCOUNT
		
		end
		else
		begin
		
			/* Remove spam posts by Section */
			delete p from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID
			
			set @RowCount = @@ROWCOUNT
		
		end
	end
	
	return 0
end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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


/***********************************************
* Sproc: cs_SpamPostRevive
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_SpamPostRevive'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

CREATE PROCEDURE [dbo].[cs_SpamPostRevive]
(
	@SettingsID int = null
	, @SectionID int = null
	, @ThreadID int = null
	, @RowCount int = null output
)
AS
begin

	SET NOCOUNT ON
	
	declare @ID bigint, @SpamPostID bigint, @TotalRowCount bigint

	declare @SpamPosts table (
		ID bigint identity(1, 1) not null primary key
		, SpamPostID bigint not null
		)

	select @ID = 1, @TotalRowCount = 0

	--We will allow movement at a SpamPostID level and a SettingsID, SectionID, ThreadID level.
	--The default is SpamPostID - if that is set, it overrides any thing else

	if @SettingsID IS NOT NULL AND @SectionID IS NOT NULL
	begin
	
		if @ThreadID IS NOT NULL
		begin
		
			/* Revive spam posts by Thread */
			insert into @SpamPosts ( [SpamPostID] )
			select p.[SpamPostID] from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID AND p.[ThreadID] = @ThreadID
		
		end
		else
		begin
		
			/* Revive spam posts by Section */
			insert into @SpamPosts ( [SpamPostID] )
			select p.[SpamPostID] from [dbo].[cs_SpamPosts] p
			where p.[SettingsID] = @SettingsID AND p.[SectionID] = @SectionID
		
		end
		
		while 1=1
		begin
			select @SpamPostID = (select p.[SpamPostID] from @SpamPosts p where p.[ID] = @ID)
			
			if @SpamPostID IS NULL break
			
			execute [dbo].[cs_SpamPostReviveOne] @SpamPostID = @SpamPostID, @RowCount = @RowCount output
			
			select
				@TotalRowCount = @TotalRowCount + @RowCount
				, @ID = @ID + 1
		end
	end
	
	set @RowCount = @TotalRowCount
	
	return 0

end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_SpamPostReviveOne
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SpamPostReviveOne'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

CREATE PROCEDURE [dbo].[cs_SpamPostReviveOne]
(
	@SpamPostID bigint = null
	, @RowCount int = null output
)
AS
begin
	SET NOCOUNT ON
	
	declare
		@return_value int
		, @SourceProcedure nvarchar(128)
		/* from cs_Post_CreateUpdate */
		, @SectionID int
		, @ParentID int
		, @AllowDuplicatePosts bit
		, @DuplicateIntervalInMinutes int
		, @Subject nvarchar(256)
		, @UserID int
		, @PostAuthor nvarchar(64)
		, @Body nvarchar(4000) --ntext
		, @FormattedBody nvarchar(4000) --ntext
		, @EmoticonID int
		, @IsLocked bit
		, @IsSticky bit
		, @IsApproved bit
		, @StickyDate datetime
		, @PostType int
		, @PostMedia int
		, @PostDate datetime
		, @UserHostAddress nvarchar(32)
		, @PropertyNames nvarchar(4000) --ntext
		, @PropertyValues nvarchar(4000) --ntext
		, @SettingsID int
		, @IsTracked bit
		, @PostID int
		, @ThreadID int
		, @PostConfiguration int
		, @UpdateSectionStatistics bit
		, @UserTime datetime
		, @ApplicationPostType int
		, @PostName nvarchar(256)
		, @ThreadStatus int
		, @Points int
		, @PostDisplayName nvarchar(64)
		, @AutoApprove bit
	
		/* from cs_weblog_Post_Create */
		, @TitleUrl nvarchar(256)
		, @PostConfig int
		, @BlogPostType tinyint
		, @Categories nvarchar(4000)
		, @SpamScore int
		, @PostStatus int
	
	if @SpamPostID IS NOT NULL
	begin

		select
			@SourceProcedure = p.[SourceProcedure]
			, @SectionID = p.[SectionID]
			, @ParentID = p.[ParentID]
			, @AllowDuplicatePosts = p.[AllowDuplicatePosts]
			, @DuplicateIntervalInMinutes = p.[DuplicateIntervalInMinutes]
			, @Subject = p.[Subject]
			, @UserID = p.[UserID]
			, @PostAuthor = p.[PostAuthor]
			, @Body = p.[Body]
			, @FormattedBody = p.[FormattedBody]
			, @EmoticonID = p.[EmoticonID]
			, @IsLocked = p.[IsLocked]
			, @IsSticky = p.[IsSticky]
			, @IsApproved = p.[IsApproved]
			, @StickyDate = p.[StickyDate]
			, @PostType = p.[PostType]
			, @PostMedia = p.[PostMedia]
			, @PostDate = p.[PostDate]
			, @UserHostAddress = p.[UserHostAddress]
			, @PropertyNames = p.[PropertyNames]
			, @PropertyValues = p.[PropertyValues]
			, @SettingsID = p.[SettingsID]
			, @IsTracked = p.[IsTracked]
			, @ThreadID = p.[ThreadID]
			, @PostConfiguration = p.[PostConfiguration]
			, @UpdateSectionStatistics = p.[UpdateSectionStatistics]
			, @UserTime = p.[UserTime]
			, @ApplicationPostType = p.[ApplicationPostType]
			, @PostName = p.[PostName]
			, @ThreadStatus = p.[ThreadStatus]
			, @Points = p.[Points]
			, @PostDisplayName = p.[PostDisplayName]
			, @AutoApprove = p.[AutoApprove]
			, @TitleUrl = p.[TitleUrl]
			, @PostConfig = p.[PostConfig]
			, @BlogPostType = p.[BlogPostType]
			, @Categories = p.[Categories]
			, @SpamScore = p.[SpamScore]
			, @PostStatus = p.[PostStatus]
			, @PostID = NULL /* resetting the PostID */
		from
			[dbo].[cs_SpamPosts] p
		where
			p.[SpamPostID] = @SpamPostID

		if @SourceProcedure = N'cs_Post_CreateUpdate'
		begin

			select
				@IsApproved = 1 /* @IsApproved will be set to 1.  If someone is moving a post, it should be approved.  Perhaps there should be a flag to set this,  */

			execute @return_value = [dbo].[cs_Post_CreateUpdate]
				@SectionID = @SectionID
				, @ParentID = @ParentID
				, @AllowDuplicatePosts = @AllowDuplicatePosts
				, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
				, @Subject = @Subject
				, @UserID = @UserID
				, @PostAuthor = @PostAuthor
				, @Body = @Body
				, @FormattedBody = @FormattedBody
				, @EmoticonID = @EmoticonID
				, @IsLocked = @IsLocked
				, @IsSticky = @IsSticky
				, @IsApproved = @IsApproved
				, @StickyDate = @StickyDate
				, @PostType = @PostType
				, @PostMedia = @PostMedia
				, @PostDate = @PostDate
				, @UserHostAddress = @UserHostAddress
				, @PropertyNames = @PropertyNames
				, @PropertyValues = @PropertyValues
				, @SettingsID = @SettingsID
				, @IsTracked = @IsTracked
					, @PostID = @PostID output
				, @ThreadID = @ThreadID
				, @PostConfiguration = @PostConfiguration
				, @UpdateSectionStatistics = @UpdateSectionStatistics
				, @UserTime = @UserTime
				, @ApplicationPostType = @ApplicationPostType
				, @PostName = @PostName
				, @ThreadStatus = @ThreadStatus
				, @Points = @Points
				, @PostDisplayName = @PostDisplayName
				, @AutoApprove = @AutoApprove

		end
		else if @SourceProcedure = N'cs_weblog_Post_Create'
		begin

			select
				@IsApproved = 1 /* @IsApproved will be set to 1.  If someone is moving a post, it should be approved.  Perhaps there should be a flag to set this,  */
				, @PostStatus = @PostStatus & 0x7ffffffd /* ensure that PostStatus=2 (spam) is not set since this is how a post gets here */

			execute @return_value = [dbo].[cs_weblog_Post_Create]
				@SectionID = @SectionID
				, @ParentID = @ParentID
				, @AllowDuplicatePosts = @AllowDuplicatePosts
				, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
				, @Subject = @Subject
				, @UserID = @UserID
				, @PostAuthor = @PostAuthor
				, @Body = @Body
				, @FormattedBody = @FormattedBody
				, @EmoticonID = @EmoticonID
				, @IsLocked = @IsLocked
				, @IsSticky = @IsSticky
				, @IsApproved = @IsApproved
				, @IsTracked = @IsTracked
				, @StickyDate = @StickyDate
				, @PostType = @PostType
				, @PostMedia = @PostMedia
				, @PostDate = @PostDate
				, @UserTime = @UserTime
				, @UserHostAddress = @UserHostAddress
				, @PostName = @PostName
				, @TitleUrl = @TitleUrl
				, @PostConfig = @PostConfig
				, @BlogPostType = @BlogPostType
				, @Categories = @Categories
				, @PropertyNames = @PropertyNames
				, @PropertyValues = @PropertyValues
				, @SettingsID = @SettingsID
				, @SpamScore = @SpamScore
				, @PostStatus = @PostStatus
					, @PostID = @PostID output
			
		end
	end
	
	if @return_value = 0
	begin
	
		delete p from [dbo].[cs_SpamPosts] p
		where
			p.[SpamPostID] = @SpamPostID
	
	end
	
	return @return_value
end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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


/***********************************************
* Sproc: cs_SpamPosts_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SpamPosts_Get'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

CREATE PROCEDURE [dbo].[cs_SpamPosts_Get]
(
	@SectionID int,
	@SpamStatus int,
	@PageIndex int,
	@PageSize int,
	@TotalRecords int out
)
AS
begin

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @RowsToReturn int
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- Create a temp table to store the select results
DECLARE @PageTable TABLE
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	SpamPostID bigint not null
)

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	
-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

INSERT INTO @PageTable(SpamPostID)
SELECT P.SpamPostID 
FROM cs_SpamPosts P (nolock)
WHERE (P.SectionID = @SectionID) AND (@SpamStatus = -1 OR P.PostStatus & @SpamStatus = @SpamStatus)
ORDER BY P.PostDate DESC

Set @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

SELECT 
	Convert(int, P.[SpamPostID]) as PostID, [SectionID], [ParentID], [AllowDuplicatePosts], [DuplicateIntervalInMinutes], [Subject], [UserID], [PostAuthor]
	, [Body], [FormattedBody], [EmoticonID], [IsLocked], [IsSticky], [IsApproved], [StickyDate]
	, [PostType], [PostMedia], [PostDate], [UserHostAddress] as IPAddress, [PropertyNames] as PostPropertyNames, [PropertyValues] as PostPropertyValues, [SettingsID]
	, [IsTracked], [ThreadID], [PostConfiguration], [UpdateSectionStatistics], [UserTime], [ApplicationPostType]
	, [PostName], [ThreadStatus], [Points] as PostPoints, [PostDisplayName], [AutoApprove], [TitleUrl], [PostConfig]
	, [BlogPostType], [Categories], [SpamScore], [PostStatus],
	[PostDate] as ThreadDate,
	Replies = 0, PostLevel = 1,
	TotalViews = 0, AggViews = 0,
	RatingSum = 0, TotalRatings = 0

FROM 
	cs_SpamPosts P (nolock),
	@PageTable pt
WHERE 
	P.SpamPostID = pt.SpamPostID AND
	pt.IndexID > @PageLowerBound AND
	pt.IndexID < @PageUpperBound
ORDER BY
	pt.IndexID


end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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


/***********************************************
* Sproc: cs_split_varchar
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_split_varchar'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[cs_split_varchar]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[cs_split_varchar]
GO

CREATE PROCEDURE [dbo].[cs_split_varchar]
    @str varchar(8000)
AS  
	CREATE TABLE #SplitItems
	(
		[Item] nvarchar(500) collate database_default NOT NULL
	)

    declare @frommarker tinyint, @tomarker tinyint, @strlen tinyint, @item varchar(500)

    select @frommarker=1, @tomarker=1
    
    while (@tomarker > 0)
    begin 
        set @tomarker = CHARINDEX (',', @str, @frommarker)
    
        if @tomarker > 0 
            set @strlen = @tomarker - @frommarker
        else
            set @strlen = LEN(@str) - @frommarker + 1

        set @item = ltrim(rtrim(SUBSTRING (@str, @frommarker, @strlen)))
        
		if not exists (select null from #SplitItems where Item = @item)
			insert into #SplitItems values(@item)
        
        set @frommarker = @tomarker + 1
    end

	select Item from #SplitItems



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_split_varchar] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Styles_Get
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Style_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_SubscribedSection_Confirm
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SubscribedSection_Confirm'

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_SubscribedSection_Confirm]
(
	@SectionID int OUTPUT,
	@SubscriptionId uniqueidentifier
)
AS
	UPDATE [cs_SectionSubscriptions]
	SET IsConfirmed = 1, DateUnsubscribed = NULL
	WHERE	SubscriptionID = @SubscriptionId AND IsConfirmed = 0
	
	SELECT @SectionID = SectionID FROM [cs_SectionSubscriptions]
	WHERE SubscriptionID = @SubscriptionId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_SubscribedSection_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SubscribedSection_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_SubscribedSection_Get
(
	@SectionID int,
	@Email nvarchar(256),
	@SettingsID int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT DateSubscribed, 
		SubscriptionFrequency as Frequency,
		IsConfirmed, DateUnsubscribed
	FROM cs_SectionSubscriptions
	WHERE
		SectionID = @SectionID AND Email = @Email AND SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_SubscribeToSection
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_SubscribeToSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_SubscribeToSection
(
	@UserID int,
	@SectionID int,
	@SettingsID int,
	@Email nvarchar(256),
	@SubscriptionType int,
	@SubscriptionID uniqueidentifier OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @counter int

	-- check to see if the user is currently subscribed to the section
	IF NOT EXISTS (SELECT SubscriptionID FROM cs_SectionSubscriptions
					WHERE SectionID = @SectionID AND
							SettingsID = @SettingsID AND Email = @Email)
		BEGIN
			SET @SubscriptionID = NEWID()
			-- this user isn't subscribed to the section, so add them
			INSERT INTO cs_SectionSubscriptions (SubscriptionID, SectionID, Email, SubscriptionType, UserID, SettingsID, DateSubscribed, DateUnsubscribed, SubscriptionFrequency)
			VALUES(@SubscriptionID, @SectionID, @Email, @SubscriptionType, @UserID, @SettingsID, GetDate(), NULL, 1)		
		END
	ELSE IF EXISTS (SELECT SubscriptionID FROM cs_SectionSubscriptions
						WHERE	SectionID = @SectionID AND
							SettingsID = @SettingsID AND Email = @Email)
		BEGIN
			-- the subscription exists but is unsubscribed, so subscribe it
			SELECT @counter = SubscriptionFrequency, @SubscriptionID = SubscriptionID 
				FROM cs_SectionSubscriptions 
				WHERE	SectionID = @SectionID AND
					SettingsID = @SettingsID AND Email = @Email AND
					DateUnsubscribed IS NOT NULL
			SET @counter = @counter + 1
		
			UPDATE cs_SectionSubscriptions
			SET DateUnsubscribed = NULL,
				DateSubscribed = GetDate(),
				SubscriptionFrequency = @counter
			WHERE	SectionID = @SectionID AND
					SettingsID = @SettingsID AND Email = @Email AND
					DateUnsubscribed IS NOT NULL
		END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_System_AddNewUrl.sql
* File Date: 4/14/2008 11:35:02 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 = SCOPE_IDENTITY()

if @NewSiteID is null
Return -4 -->> Insert of new site failed

Insert cs_SiteMappings Values (@SettingsID, @NewSiteID)
Return 1

GO

grant execute on [dbo].[cs_System_AddNewUrl] to public
go
/***********************************************
* Sproc: cs_system_CleanForumsRead
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()

--Get or Create the Application ID.
--An ApplicationName/ID can exist in more than one site, so it does not need to be unique
Set @ApplicationID = null
Select @ApplicationID = ApplicationId FROM aspnet_Applications where  LoweredApplicationName = Lower(@ApplicationName)

if(@ApplicationID is  null)
BEGIN
	exec aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId = @ApplicationID OUTPUT
	Set @IsApplicationCreated = 1
	Print 'Created New Application ' + @ApplicationName + '(' + Convert(varchar(36),@ApplicationID) + ')'

END
ELSE
BEGIN
	SET @IsApplicationCreated = 0
END

--Insert a record into the SiteSettings table
INSERT cs_SiteSettings (Disabled, Version, SettingsKey, ApplicationName)
VALUES (0,@Version,newID(),@ApplicationName)

--Get the SettingsID
Select @SettingsID = SCOPE_IDENTITY()
Print 'Created new SettingsID ' + Convert(varchar(5),@SettingsID)

--Site Mappings bind a specific Url to a SiteSetting (and ApplicationName/ID)
Insert cs_SiteMappings (SettingsID, SiteID) Values (@SettingsID, @SiteID)
Print 'SettingsID and ApplicationID Mapped'




print 'Creating moderation actions...'
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (1, 'ApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (2, 'EditPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (3, 'MovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (4, 'DeletePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (5, 'LockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (6, 'UnlockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (7, 'MergePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (8, 'SplitPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (9, 'EditUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (10, 'UnmoderateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (11, 'ModerateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (12, 'BanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (13, 'UnbanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (14, 'ResetPassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (15, 'ChangePassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (16, 'PostIsAnnouncement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (17, 'PostIsNotAnnoucement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (18, 'UnApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (19, 'DeleteSection', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (20, 'IgnoreUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (21, 'UnignoreUser', 0, @SettingsID)


----------------------------------------------------------
--WORD CENSORS (default list)
----------------------------------------------------------
print 'Creating a default list of censored words...'
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dyke', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'amcik', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'arse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'asshole', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'assramer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'atouche', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ayir', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b17ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b1tch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bastard', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bi7ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bitch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'boiolas', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bollock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'breast', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'c0ck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cabron', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cazzo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chink', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chraa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chuj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cipa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cunt', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'd4mn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dago', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'daygo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dego', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dildo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dirsa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dupa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dziwka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekrem', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'enculer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'faen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fag', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fancul', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fatass', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fcuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'feces', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ficken', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitte', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'flikker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fotze', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'futkretzn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fux0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'guiena', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h4x0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'helvete', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hoer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'honkey', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Huevon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hui', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'injun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kike', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ootzak', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'knulle', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kraut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuksuger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Kurac', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kurwa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kusi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kyrp', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbian', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mamhoon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'masturbat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merd', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merde', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mibun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'monkleigh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'motherfucker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mouliewop', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muie', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mulkku', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muschi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nazis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nepesaurio', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigga', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nutsack', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'orospu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'paska', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pendejo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'penisperse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'phuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'picka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pierdol', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pillu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimmel', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimpis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pizdapoontsee', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pr0n', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preteen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preud', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'prick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pula', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pule', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pusse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pussy', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qaHbeh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qweef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'rautenbergschaffer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheiss', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheisse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schlampe', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schmuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scrotum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmuta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmute', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shemale', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shipal', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Skribz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'skurwysyn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'slut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'smut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sphencter', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spic', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spierdalaj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'splooge', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'suka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'tits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'twatty', '***')
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 = SCOPE_IDENTITY()
Print 'Created Admin ForumGroup'

--Reporting Forum of Reporting Forum Type
Print 'Created Reporting Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAnonymousPosting, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 60, 1, 0, @GroupID, 'Reporting Forums', 'Reporting_Forums-' + convert(nvarchar(10), @GroupID), 'When problems are reported they go in this forum.', GetDate(), '', 0, 7, 3, 0, 0, 0x0, 0, 0, 1, 0, 0, 0, '', 0, '1977-01-01', 0,  0
	)
Select @ReportingSectionID = SCOPE_IDENTITY()

Print 'Created Deleted Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAnonymousPosting, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 50, 1, 0, @GroupID, 'Deleted Posts', 'Deleted_Posts-' + convert(nvarchar(10), @GroupID), 'Deleted posts are archived in this forum.', GetDate(), '', 0, 7, 4, 0, 0, 0x0, 0, 0, 0, 0, 0, 0, '', 0, '1977-01-01', 0, 0
	)
Select @DeletedSectionID = SCOPE_IDENTITY()

declare @CategoryGroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @CategoryGroupID output, @ParentGroupID = 0, @Name = N'Sample Category', @Action = 0, @ApplicationType = 11, @SettingsID = @SettingsID
Print 'Created Default Group Category'

if(@IsApplicationCreated = 1)
Begin

	print 'Created default roles...'

	declare @EveryoneRoleID uniqueidentifier
	Set @EveryoneRoleID = newID()
	

	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (@EveryoneRoleID, @ApplicationID, N'Everyone', N'everyone', N'Do not add users to this role. This role exists only for permission mapping. All anonymous and registered users are automatically part of this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Registered Users', N'registered users', N'Users who create accounts are automatically added to this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Trusted Users', N'trusted users', N'Trusted users are given more permissions within the site.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Editor', N'editor', N'')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Moderator', N'moderator', N'Moderators are allowed to approve content.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ForumsAdministrator', N'forumsadministrator', N'Administration role for Forums.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'BlogAdministrator', N'blogadministrator', N'Administration role for Blogs')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'MediaGalleryAdministrator', N'mediagalleryadministrator', N'Administration role for Media Galleries')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'GroupAdministrator', N'groupadministrator', N'Administration role for Groups')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'MembershipAdministrator', N'membershipadministrator', N'Administration role for Member Management')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'SystemAdministrator', N'systemadministrator', N'Global Administration role.')	
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Owners', N'owners', N'Owners are the role used for bloggers and photogallery owners')

	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,	LOWER(@AdminEmail),	NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,                 '1753-01-01',                              0,                               '1753-01-01',                       0,                          '1753-01-01',      0)
		
		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
		VALUES(@UserID, 0,1, null, getdate(), '', @AdminUserName, @AdminEmail, 1, 0, getdate())


		Set @cs_UserID = SCOPE_IDENTITY()
		
		INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
		VALUES (@cs_UserID, 0, 0, 0, 0x01, 1, 0, 0, 0, 1, 0, 0, 1, 1, @UserID, @SettingsID, 'EnableDisplayName:S:0:4:EnableUserAvtars:S:4:4', 'TrueTrue')
		
		Print 'Created Admin User'
		
		Insert aspnet_UsersInRoles (UserId, RoleId) 
		Select @UserID, RoleId FROM aspnet_Roles where ApplicationId = @ApplicationID
	
	End
	
	
	Set @UserID = newid()
	
	Print 'Create Anonymous User'
	INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
	      VALUES (@UserID, @ApplicationID, 'Anonymous', Lower('Anonymous'), NULL, 1, getdate())
	--Do we need to make Salt configurable?
	INSERT INTO [aspnet_Membership] ([ApplicationId],[UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email],						[LoweredEmail],						[PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment],	[FailedPasswordAnswerAttemptWindowStart], [FailedPasswordAnswerAttemptCount],	[FailedPasswordAttemptWindowStart], [FailedPasswordAttemptCount],	[LastLockoutDate],	[IsLockedOut])
	                         VALUES (@ApplicationID, @UserID,  @UserID,         0,               N'DVZTktxeMzDtXR7eik7Cdw==', NULL,        'anonymous@localhost.com',    LOWER('anonymous@localhost.com'),  NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,			'1753-01-01',                              0,									'1753-01-01',                       0,								'1753-01-01',		0)
	
	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
	VALUES(@UserID, 0,1, null, getdate(), '', 'Anonymous', 'anonymous@localhost.com', 1, 1, getdate())

	Set @cs_UserID = SCOPE_IDENTITY()
	
	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	VALUES                          (@cs_UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, @UserID, @SettingsID, NULL, NULL)

	-- add the anonymous user to the everyone role
	INSERT INTO aspnet_UsersInRoles ([UserId], [RoleId]) VALUES( @UserID, @EveryoneRoleID )
END
ELSE
BEGIN
	Print 'Copied CS_UserProfile'
	--Import ApplicationID specific users from aspnet_Users if they dont already exists

	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsApproved], [IsAnonymous], [CreateDate])
	SELECT aspnet.UserId, 0,1, null, getdate(), '', aspnet.UserName, aspnet.Email, aspnet.IsApproved, aspnet.IsAnonymous, getdate() from dbo.vw_aspnet_MembershipUsers aspnet LEFT OUTER JOIN dbo.cs_vw_Users_FullUser cs on aspnet.UserId = cs.MembershipID WHERE aspnet.ApplicationId = @ApplicationID and cs.MembershipID is null

	--Create cs_UserProfile records for any cs_Users without Profiles

	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	SELECT cs_Users.UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, cs_Users.MembershipID, @SettingsID, NULL, NULL FROM cs_Users LEFT OUTER JOIN cs_UserProfile on cs_Users.UserID = cs_UserProfile.UserID and cs_UserProfile.SettingsID = @SettingsID Where cs_UserProfile.UserID is null and cs_Users.MembershipID in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)

END

Declare @Perm_RoleID uniqueidentifier

	-- These items need to be set outside the if(@IsApplicationCreated = 1) since they need to be created based on the SettingsID and not ApplicationID


	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Everyone'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x000000000000000F, 0x00001007000000F0 ) -- Forum Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000001, 0x000000000000000C ) -- GuestBook Permission  >> Allow View,  Deny Post, Reply
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 ) -- Media Gallery Permission >> Allow  View, Read, Replay, Deny Post, Moderate, Vote, Delete, Edit
	-- SET SPECIFIC DELETED adn Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Registered Users'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x00000000000000BF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 ) -- Media Gallery Permission

	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- GuestBook Permission  >> Allow View, Reply  Deny Post
	-- 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, 13, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 ) -- Media Gallery Permission

	-- SET SPECIFIC DELETED Forums Permission
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Moderator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000100F00000BFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'MediaGalleryAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'ForumsAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0100100F00000BFF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'BlogAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission  >> Allow View, Reply, Post

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'SystemAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x4100100F00000BFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x41001008000002FF, 0 ) -- Media Gallery Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Owners'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post, and Attachments
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 ) -- Media Gallery Permission


-- removed because its causing an issue with ThemePath defaults
	-- Set Public Only Aggregation for blogs
	-- INSERT INTO [cs_ApplicationConfigurationSettings] (SettingsID, ApplicationType, Settings) VALUES (@SettingsID, 1, N'<?xml version="1.0" encoding="utf-16"?><WeblogConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><AggPublicOnly>true</AggPublicOnly></WeblogConfiguration>')

	-- Set Public Only Aggregation for Galleries
    -- INSERT INTO [cs_ApplicationConfigurationSettings] (SettingsID, ApplicationType, Settings) VALUES (@SettingsID, 2, N'<GalleryConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><AggPublicOnly>true</AggPublicOnly></GalleryConfiguration>')

---Return New Data	

if @CreateSamples = 1
Begin
	exec cs_system_SampleMediaGallery @SettingsID, @AdminUserName
	exec cs_system_SampleWeblog @SettingsID, @AdminUserName
	exec cs_system_SampleForum @SettingsID, @AdminUserName
	exec cs_system_SampleGroups @SettingsID, @CategoryGroupID, @AdminUserName
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_dbreindex
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_system_dbreindex'

IF object_id( '[dbo].[cs_system_dbreindex]', N'P' ) IS NOT NULL
	drop procedure [dbo].[cs_system_dbreindex]
go

CREATE PROCEDURE [dbo].[cs_system_dbreindex]
as
begin

	declare @sql nvarchar(1000), @id int, @full_name sysname, @table_count int

	declare @t table (
		id int identity(1, 1) not null
		, full_name sysname collate database_default not null
	)

	set nocount on

	insert into @t ( full_name )
	select t.FULL_NAME from (
		select
			quotename(tx.TABLE_SCHEMA) + N'.' + quotename(tx.TABLE_NAME) as FULL_NAME
		from
			INFORMATION_SCHEMA.TABLES tx
	) as t
	where
		objectproperty( OBJECT_ID( t.FULL_NAME ), N'TableHasClustIndex' ) = 1
		and objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsMSShipped' ) = 0
	order by
		t.FULL_NAME

	set @table_count = @@ROWCOUNT

	print 'Beginning to perform a DBREINDEX on all ' + cast(@table_count as varchar) + ' tables at ' + convert(char(19), getdate(), 120)

	while 1=1
	begin
		select @id = t.id, @full_name = t.full_name from (
			select top 1 tx.* from @t tx order by tx.id
		) as t
		
		if @id is null break
		
		print 'Doing a DBREINDEX on table ' + @full_name + ' at ' + convert(char(19), getdate(), 120)
		
		set @sql = N'dbcc dbreindex(''' + @full_name + N''')' -- with no_infomsgs
		exec sp_executesql @sql
		
		delete from @t where id = @id
		
		set @id = null
	end

	print 'Done with DBREINDEX at ' + convert(char(19), getdate(), 120)
end
go

/***********************************************
* Sproc: cs_system_DeletePostAndAdoptChildren
* File Date: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()
	END

	-- First delete this post which is a parent post and should have its children adopted
	------------------------------------------------------------------------------------------
	-- Posts related updates
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID

	UPDATE
		cs_Posts
	SET
		SectionID = @DeletedSectionID,
		PostLevel = 1,
		ThreadID = @NewThreadID,
		ParentID = @PostID,
		SortOrder = 1
	WHERE
		PostID = @PostID AND
		SettingsID = @SettingsID

	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are there children to be adopted?
	------------------------------------------------------------------------------------------
	IF (@HasReplies > 0)
	BEGIN

print 'adopt children'
		-- Adopt children (by grandparent)
		UPDATE	cs_Posts
		SET		ParentID = @ParentID,
				PostLevel = @OldPostLevel
		WHERE	ParentID = @PostID AND
				ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		-- Get max post level (used for looping)
		DECLARE	@MaxPostLevel	INT
		SELECT	@MaxPostLevel = MAX(PostLevel)
		FROM	cs_Posts
		WHERE	ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		DECLARE	@level	int
		SET		@level = @OldPostLevel

		-- loop thru posting levels and recalculate (should just be a decrement)
		WHILE (@level <= @MaxPostLevel)
		BEGIN
			print 'reset levels'
			UPDATE	P
			SET		P.PostLevel = PP.PostLevel + 1
			FROM	cs_Posts P INNER JOIN cs_Posts PP ON P.ParentID = PP.PostID
			WHERE	P.PostLevel = @level AND
					P.ThreadID = @OldThreadID AND
					P.SectionID = @SectionID AND
					P.SettingsID = @SettingsID

			SET	@level = @level + 1
		END
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
	-- Decrease the TotalPosts on the user's profile.
--	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
--		UPDATE 
--			cs_UserProfile
--		SET 
--			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
--		WHERE 
--			UserID = @UserID and SettingsID = @SettingsID


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndAdoptChildren] to public
go
/***********************************************
* Sproc: cs_system_DeletePostAndChildren
* File Date: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()		
	END
	------------------------------------------------------------------------------------------
		
	-- Calculate Post Level, Parent ID & Sort Order values
	------------------------------------------------------------------------------------------
	IF (@NewPostLevel IS NULL)
	BEGIN
		-- We have an unknown post level, so we have to figure out its values
		IF (NOT EXISTS(SELECT PostID FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID))
		BEGIN
			-- Set this post as a tread starter post
			SET @NewPostLevel = 1					
			SET @ParentID = @PostID
			SET @SortOrder = 1
		END
		ELSE
		BEGIN				
			-- Bind this post to the thread starter post
			SET @NewPostLevel = 2
			SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
		END
		
		-- Set children's post level
		SET @PostLevel = (@NewPostLevel + 1)
	END
	ELSE
	BEGIN
		--SET @PostLevel = 2
		SET @PostLevel = (@NewPostLevel + 1)
		SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
	END
	------------------------------------------------------------------------------------------

	-- First delete this post which is a parent post and should have its children removed
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID
		
	UPDATE 
		cs_Posts 
	SET 
		SectionID = @DeletedSectionID, 
		PostLevel = @NewPostLevel, 
		ThreadID = @NewThreadID,
		ParentID = @ParentID,
		SortOrder = @SortOrder
	WHERE 
		PostID = @PostID AND 
		SettingsID = @SettingsID
		
	-- TODO: Threads related updates?!
		
	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID
		
	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'
		
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are we allowed to delete children and there are some?
	------------------------------------------------------------------------------------------
	IF (@DeleteChildren = 1 AND @HasReplies > 0)
	BEGIN
		DECLARE @CurrentPostID INT

		-- Delete replying posts through a cursor loop
		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @OldThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID
	
		OPEN Posts_Cursor
			
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
	
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call
			EXEC cs_system_DeletePostAndChildren @CurrentPostID, @DeleteChildren, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, @PostLevel
	
			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END
	
		CLOSE Posts_Cursor
	
		DEALLOCATE Posts_Cursor		
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
	-- Decrease the TotalPosts on the user's profile.
--	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
--		UPDATE 
--			cs_UserProfile
--		SET 
--			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
--		WHERE 
--			UserID = @UserID and SettingsID = @SettingsID


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndChildren] to public
go
/***********************************************
* Sproc: cs_system_DuplicatePost
* File Date: 4/14/2008 11:35:01 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 escape('[') AND PostDate > DateAdd(minute, -@IntervalInMinutes, GetDate()) )
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0
        ELSE
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body escape('['))
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_DuplicatePost] to public
go
/***********************************************
* Sproc: cs_system_GenerateWeblogYearMonthDayList
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_system_GenerateWeblogYearMonthDayList'

if object_id( 'dbo.cs_system_GenerateWeblogYearMonthDayList', N'P' ) IS NOT NULL
	drop procedure dbo.cs_system_GenerateWeblogYearMonthDayList
go

create procedure dbo.cs_system_GenerateWeblogYearMonthDayList
as
begin

--	this is the start of main step 1.  We would need to store the tblSuffix to know where the process is
--	so subsequent steps can continue on from this procedure
	declare
		@tblSuffix nvarchar(5)
		, @tblSuffixOld nvarchar(5)
		, @sql nvarchar(4000)

	/*	if table 1 is full, operate on table 2 and vice-versa */
	set @tblSuffix = case when exists (select 1 from dbo.cs_weblog_PostByYearMonth_tbl01)
		then N'tbl02' else N'tbl01' end
	
	/*	if tbl01 is the target table, the old table is tbl02 and vice-versa */
	set @tblSuffixOld = case @tblSuffix when N'tbl01' then N'tbl02' else N'tbl01' end

	print 'Using ['+@tblSuffix+'] for this data run.'

	print 'Truncate table: ' + convert(char(19), getdate(), 120)

	set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
	exec sp_executesql @sql

	print 'Removing PK from table: ' + convert(char(19), getdate(), 120)

	set @sql = case when exists (
		select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
		where
			c.CONSTRAINT_NAME = N'PK_cs_weblog_PostByYearMonth_' + @tblSuffix
			and c.TABLE_SCHEMA = N'dbo'
			and c.TABLE_NAME = N'cs_weblog_PostByYearMonth_' + @tblSuffix
			and c.CONSTRAINT_TYPE = N'PRIMARY KEY'
		)
		then N'alter table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' drop constraint PK_cs_weblog_PostByYearMonth_' + @tblSuffix
		else null end

	if @sql IS NOT NULL
		exec sp_executesql @sql

	print 'Insert base day data: ' + convert(char(19), getdate(), 120)
	
--		this could *possibly* reduce locks by only calculating the posts that have
--		been 'added' today ( getdate() ) and then filling in the previous data from the 'other'
--		table.  But, that doesn't consider if someone changes a PostDate from a previous day
--		on extremely high volume sites, I think it would be beneficial to only calculate the
--		previous day's numbers either once a day, or even calculate that once a week.
	set @sql = N'
	insert into dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' ([SectionID], [Year], [Month], [Day], [PostCount])
	Select
		p.SectionID
		, Year( coalesce(p.UserTime, p.PostDate) )
		, Month( coalesce(p.UserTime, p.PostDate) )
		, Day( coalesce(p.UserTime, p.PostDate) )
		, count(*)
	From
		cs_Posts p (nolock)
	where
		p.IsApproved = 1
		and p.ApplicationPostType = 1
		and p.PostDate <= getdate()
	group by
		p.SectionID
		, Year( coalesce(p.UserTime, p.PostDate) )
		, Month( coalesce(p.UserTime, p.PostDate) )
		, Day( coalesce(p.UserTime, p.PostDate) )'

	exec sp_executesql @sql

	if @@ERROR <> 0
	begin
		print 'Error occurred while inserting base data.  Truncating table: ' + convert(char(19), getdate(), 120)

		set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
		exec sp_executesql @sql
		return
	end

	print 'Insert base month data: ' + convert(char(19), getdate(), 120)

--		we could possibly add the constraint here and do this in two steps
--		this would be if we had extended times for this particular step
--		since there is no other process hitting this table at this time,
--		we shouldn't have issues with locking
	set @sql = N'insert into dbo.cs_weblog_PostByYearMonth_' + @tblSuffix + N' ([SectionID], [Year], [Month], [Day], [PostCount])
	Select
		p.SectionID, p.[Year], p.[Month], 255 as [Day], sum( p.[PostCount] ) as [PostCount]
	From
		cs_weblog_PostByYearMonth_' + @tblSuffix + N' p
	group by
		p.SectionID, p.[Year], p.[Month]'

	exec sp_executesql @sql

	print 'Add constraint: ' + convert(char(19), getdate(), 120)

	set @sql = N'ALTER TABLE [dbo].[cs_weblog_PostByYearMonth_' + @tblSuffix + N']
		ADD CONSTRAINT [PK_cs_weblog_PostByYearMonth_' + @tblSuffix + N'] PRIMARY KEY CLUSTERED
	(
		[SectionID] ASC,
		[Year] DESC,
		[Month] DESC,
		[Day] DESC
	)
	WITH FILLFACTOR = 100 ON [PRIMARY]'

	exec sp_executesql @sql

	print 'Compute stats on new table: ' + convert(char(19), getdate(), 120)

	set @sql = N'dbcc dbreindex(''[dbo].[cs_weblog_PostByYearMonth_' + @tblSuffix + N']'')'

--		this is the start of main step 2.  We would need to store the tblSuffix to know where the process is
--		if this was to be split from the main stored procedure
	exec sp_executesql @sql

	print 'Alter view: ' + convert(char(19), getdate(), 120)

	/*	if the view doesn't exist, make it create instead of alter */
	set @sql = case when object_id(N'[dbo].[cs_vw_weblog_PostByYearMonth]', N'V') IS NOT NULL then N'alter' else 'create' end
		+ N' view dbo.cs_vw_weblog_PostByYearMonth as select * from cs_weblog_PostByYearMonth_' + @tblSuffix

	exec sp_executesql @sql

	if @@ERROR <> 0
	begin
		print 'Error occurred altering view.  Truncating table: ' + convert(char(19), getdate(), 120)

		set @sql = N'truncate table dbo.cs_weblog_PostByYearMonth_' + @tblSuffix
		exec sp_executesql @sql
		return
	end

--		this is the start of main step 3.  We would need to store the tblSuffix to know where the process is
--		if this was to be split from the main stored procedure
	print 'Clear old table: ' + convert(char(19), getdate(), 120)

	set @sql = N'truncate table cs_weblog_PostByYearMonth_' + @tblSuffixOld

	exec sp_executesql @sql

	print 'Compute stats on old table: ' + convert(char(19), getdate(), 120)

	set @sql = N'dbcc dbreindex(''[dbo].[cs_weblog_PostByYearMonth_' + @tblSuffixOld + N']'')'

	exec sp_executesql @sql

end
go

-- now to attempt to populate the table initially
if object_id(N'dbo.cs_vw_weblog_PostByYearMonth') IS NOT NULL
	exec [dbo].[cs_system_GenerateWeblogYearMonthDayList]

go

/***********************************************
* Sproc: cs_system_ModerationAction_AuditEntry
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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 @ThreadID int
DECLARE @PostID int

IF @SectionID = 0
BEGIN
	-- Reset the statistics on all of the forums.

	DECLARE ForumCount_Cursor CURSOR FOR
		SELECT SectionID FROM cs_Sections

	OPEN ForumCount_Cursor
	FETCH NEXT FROM ForumCount_Cursor INTO @SectionID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
		FETCH NEXT FROM ForumCount_Cursor INTO @SectionID
	END

	CLOSE ForumCount_Cursor
	DEALLOCATE ForumCount_Cursor
	
END
ELSE BEGIN

	DECLARE @SettingsID int

	Select @SettingsID = SettingsID FROM cs_Sections where SectionID = @SectionID

	-- Select the most recent post from the forum.
	SELECT TOP 1
		@ThreadID = ThreadID,
		@PostID = PostID
	FROM 
		cs_Posts
	WHERE 
		SectionID = @SectionID AND
		IsApproved = 1
	ORDER BY
		PostID DESC
   
	-- If the thread is null, reset the forum statistics.
	IF @ThreadID IS NULL
		UPDATE
			cs_Sections
		SET
			TotalThreads = 0,
			TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID),
			MostRecentPostID = 0,
			MostRecentThreadID = 0,
			MostRecentPostDate = '1/01/1797',
			MostRecentPostAuthorID = 0,
			MostRecentPostSubject = '',
			MostRecentPostAuthor = ''
		WHERE
			SectionID = @SectionID
	ELSE
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ResetForumStatistics] to public
go
/***********************************************
* Sproc: cs_system_ResetThreadStatistics
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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 = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Downloads', @Action = 0, @ApplicationType = 6, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 6, @ApplicationKey = N'sample_files', @PropertyNames = N'EnableExternalLinks:S:0:4:EnableDisclaimer:S:4:5:', @PropertyValues = N'TrueFalse', @SettingsID = @SettingsID, @UserID = @UserID


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Downloads', @IsEnabled = 1, @ParentID = 0, @Description = N'Files to download', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'The Latest Community Server Licensing Guide', @IsLocked = 0, @PostType = 1, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'This guide provides an overview of licensing for Community Server', @IsApproved = 1, @FormattedBody = N'This guide provides an overview of licensing for Community Server ', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ImageSize:S:0:6:', @PropertyValues = N'243742', @ApplicationPostType = 2, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'http://communityserver.org/r.ashx?D', @ContentType = N'application/pdf', @ContentSize = 243742, @SettingsID = @SettingsID, @FriendlyFileName = 'The Latest Community Server Licensing Guide', @IsRemote = 1, @Width= 425, @Height=283

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Downloads</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_SampleForum
* File Date: 4/14/2008 11:35:01 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 = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Forums', @Action = 0, @ApplicationType = 0, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @ForumType=0, @IsActive = 1, @ParentID = 0, @GroupID = @GroupID, @Name = N'Sample Forum', @ApplicationKey = N'sample_forum', @Description = N'', @IsModerated = 0, @DisplayPostsOlderThan = 7, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 0, @PropertyNames = null, @PropertyValues = null, @SettingsID = @SettingsID, @UserID = @UserID



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Sample Forum Posts', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is for forum posts', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



declare @ForumPostID int
declare @ForumThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)

exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Sample Forum Post', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'
		<p>sample forum post content</p>
', @IsApproved = 1, @FormattedBody = N'
		<p>sample forum post content</p>
', @UserHostAddress = N'127.0.0.1', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'', @PropertyValues = N'', @ApplicationPostType = 0, @PostID = @ForumPostID output, @ThreadID = @ForumThreadID output

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @ForumPostID, @CategoryList = N'<Categories><Category>Sample Forum Posts</Category></Categories>', @SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_SampleGallery
* File Date: 4/14/2008 11:35:02 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 = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Photo Galleries', @Action = 0, @ApplicationType = 2, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 2, @ApplicationKey = N'sample', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Wildlife', @IsEnabled = 1, @ParentID = 0, @Description = N'Interesting Wildlife Pictures', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Ready for the chase', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'A picture from my backyard!', @IsApproved = 1, @FormattedBody = N'A picture from my backyard!', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ContentType:S:0:11:Width:S:11:3:Height:S:14:3:EXIF-DateTime:S:17:22:EXIF-Model:S:39:13:EXIF-ExposureTime:S:52:5:EXIF-FocalLength:S:57:1:EXIF-ApertureValue:S:58:5:EXIF-ISOSpeedRatings:S:63:3:EXIF-Flash:S:66:1:', @PropertyValues = N'image/pjpeg42528307/15/2004 09:08:18 AMCanon EOS 10D1/5008f/4.54000', @ApplicationPostType = 64, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'Cheetah.jpg', @ContentType = N'image/pjpeg', @ContentSize = 20558, @SettingsID = @SettingsID, @FriendlyFileName = 'Cheetah', @IsRemote = 0, @Width= 425, @Height=283


--	Commenting for now until CFS is worked out for this
--
--declare @ptr varbinary(16)
--select @ptr = textptr(Content) from cs_PostAttachments where PostID = @PicPostID
--writetext cs_PostAttachments.Content @ptr 0x[encoded data, 41116 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_SampleGroups
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_system_SampleGroups'

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

Create Proc [dbo].cs_system_SampleGroups
(
	@SettingsID int,
	@CategoryGroupID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @UserID = @UserID, @SettingsID = @SettingsID

exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID, @UserID = @UserID, @SettingsID = @SettingsID, @HubSectionID = @SectionID, @Name = N'Sample Group', @Description = N'', @ParentID = 0, @GroupID = @CategoryGroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 11, @ApplicationKey = N'sample_group', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @IsPublic = 1

declare @DateAdded datetime
exec dbo.cs_SectionMembers_Add @SectionID = @SectionID, @UserID = @UserID, @MembershipType = 1, @DateAdded = @DateAdded output

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_SampleMediaGallery
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_system_SampleMediaGallery'


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

Create Proc [dbo].cs_system_SampleMediaGallery
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Media Galleries', @Action = 0, @ApplicationType = 13, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample Media', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 13, @ApplicationKey = N'samplemedia', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Downloads', @IsEnabled = 1, @ParentID = 0, @Description = N'Files to download', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Community Server Documentation', @IsLocked = 0, @PostType = 1, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'', @IsApproved = 1, @FormattedBody = N'', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'', @PropertyValues = N'', @ApplicationPostType = 2, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'http://communityserver.org/r.ashx?S', @ContentType = N'text/html; charset=utf-8', @ContentSize = 50000, @SettingsID = @SettingsID, @FriendlyFileName = 'Community Server Documentation', @IsRemote = 1, @Width= 425, @Height=283

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Downloads</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_SampleWeblog
* File Date: 4/14/2008 11:35:01 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 = UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @ParentGroupID = 0, @Name = N'Sample Weblogs', @Action = 0, @ApplicationType = 1, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample Weblog', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAnonymousPosting = 0, @SortOrder = 0, @ApplicationType = 1, @ApplicationKey = N'sample_weblog', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID, @IsPublic = 1



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Blogging', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is about blogging', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



Declare @PostID int
Declare @Date datetime
Set @Date = GetDate()
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)
exec dbo.cs_weblog_Post_Create @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 1, @Subject = N'Welcome to Community Server Blogs!', @IsLocked = 0, @IsApproved = 1, @IsTracked = 0, @PostType = 1, @EmoticonID = 0, @UserID = @UserID, @Body = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>
', @FormattedBody = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>', @UserHostAddress = N'127.0.0.1', @PostDate = @Date, @UserTime = @Date, @PropertyNames = N'EnableRatings:S:0:4:EnableTrackBacks:S:4:4:', @PropertyValues = N'TrueTrue', @SettingsID = @SettingsID, @IsSticky = 0, @StickyDate = @PostStickyDate, @PostName = N'My First Post', @PostConfig = 11, @BlogPostType = 1, @Categories = N'<Categories><Category>Blogging</Category></Categories>', @PostID = @PostID output

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_UpdateForum
* File Date: 4/14/2008 11:35:01 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
DECLARE @HubSectionID int


-- Set default
SET @PostConfiguration = 0

-- Get values necessary to update the forum statistics
SELECT
	@IsApproved = P.IsApproved,
	@UserID = P.UserID,
	@PostDate = PostDate,
	@TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 1 and SettingsID = @SettingsID),
	@TotalThreads = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.SectionID = @SectionID AND P2.IsApproved=1 AND P2.PostLevel=1 and P2.SettingsID = @SettingsID),
	@PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID),
	@Subject = P.Subject,
	@User = PostAuthor,
	@PostConfiguration = P.PostConfiguration
FROM
	cs_Posts P
WHERE
	PostID = @PostID and P.SettingsID = @SettingsID and P.SectionID = @SectionID

SELECT
	@HubSectionID = S.HubSectionID
FROM
	cs_Sections S
WHERE
	S.SectionID = @SectionID and S.SettingsID = @SettingsID

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1	
	SET @User = null
	SET @PostDisplayName = null
	
END

IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the post is not flagged as ignored. 
BEGIN 
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	-- Always update counters
	UPDATE 
		cs_Sections
	SET
		TotalPosts = isnull(@TotalPosts,0),
		TotalThreads = isnull(@TotalThreads,0),
		PostsToModerate = isnull(@PostsToModerate,0)
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- Only update Post-specific info if the current post is approved
	IF @IsApproved = 1
	BEGIN
		UPDATE 
			cs_Sections
		SET
			MostRecentPostID = isnull(@PostID,0),
			MostRecentThreadID = isnull(@ThreadID,0),
			MostRecentPostAuthorID = isnull(@UserID,0),
			MostRecentPostSubject = isnull(@Subject,''),
			MostRecentPostAuthor = isnull(@PostDisplayName,isnull(@User,'')),
			MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
		WHERE
			SectionID = @SectionID and SettingsID = @SettingsID
	
		IF @UpdateThreadDate = 1
			UPDATE 
				cs_Sections
			SET
				MostRecentPostDate = isnull(@PostDate,'1/01/1797')
			WHERE
				SectionID = @SectionID and SettingsID = @SettingsID

		-- If section has a hub, the update the hub's most recent post info
		if @HubSectionID > 0
		begin
			UPDATE 
				cs_Sections
			SET
				MostRecentPostID = isnull(@PostID,0),
				MostRecentThreadID = isnull(@ThreadID,0),
				MostRecentPostAuthorID = isnull(@UserID,0),
				MostRecentPostSubject = isnull(@Subject,''),
				MostRecentPostAuthor = isnull(@PostDisplayName,isnull(@User,'')),
				MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
			WHERE
				SectionID = @HubSectionID and SettingsID = @SettingsID

			IF @UpdateThreadDate = 1
				UPDATE 
					cs_Sections
				SET
					MostRecentPostDate = isnull(@PostDate,'1/01/1797')
				WHERE
					SectionID = @HubSectionID and SettingsID = @SettingsID
		end
	
		-- UPDATE Parent
		DECLARE @ParentID int
		SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @SectionID
	
		WHILE @ParentID > 0
		BEGIN
			UPDATE 
				cs_Sections
			SET
				MostRecentPostID = isnull(@PostID,0),
				MostRecentThreadID = isnull(@ThreadID,0),
				MostRecentPostAuthorID = isnull(@UserID,0),
				MostRecentPostSubject = isnull(@Subject,''),
				MostRecentPostAuthor = isnull(@User,''),
				MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
			WHERE
				SectionID = @ParentID and SettingsID = @SettingsID
			
			IF @UpdateThreadDate = 1
				UPDATE 
					cs_Sections
				SET
					MostRecentPostDate = isnull((SELECT top 1 MostRecentPostDate FROM cs_Sections WHERE SectionID = @ParentID and SettingsID = @SettingsID AND MostRecentPostDate > @PostDate), @PostDate)
				WHERE
					SectionID = @ParentID and SettingsID = @SettingsID
		
			-- Get the next ParentID
			SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @ParentID
		END
	
	END

END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_UpdateMostActiveUsers
* File Date: 4/14/2008 11:35:01 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.UserID,
		TotalPosts = ISNULL( (SELECT count(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SectionID = cs_Posts.SectionID and cs_Sections.SettingsID = @SettingsID AND UserID = U.UserID AND PostDate > DateAdd(day, -1, GetDate())), 0),
		@SettingsID
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.IsIgnored = 0   AND
		U.UserAccountStatus = 1 and U.SettingsID = @SettingsID
	ORDER BY
		TotalPosts DESC

	SET NOCOUNT OFF
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateMostActiveUsers] to public
go
/***********************************************
* Sproc: cs_system_UpdateSite
* File Date: 4/14/2008 11:35:01 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,
	@EveryoneRoleID uniqueidentifier,
	@ModeratorRoleID uniqueidentifier,
	@TotalModerators int
)
AS

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
DECLARE @DateWindow datetime

SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')
SET @DateWindow = DATEADD(hh, -@UpdateWindow, GetDate())

if (@LastUpdate <  @DateWindow)
BEGIN


	-- Get summary information - Total Users, Total Posts, TotalTopics, DaysPosts, and DaysTopics
	DECLARE @LastDateTimeUpdate datetime
	DECLARE @TotalUsers int
	DECLARE @TotalPosts int
	DECLARE @TotalTopics int
	DECLARE @TotalModeratedPosts int
	DECLARE @NewThreadsInPast24Hours int
	DECLARE @NewPostsInPast24Hours int
	DECLARE @NewUsersInPast24Hours int
	DECLARE @MostViewsPostID int
    DECLARE @ViewCount int
	DECLARE @MostActivePostID int
	DECLARE @ReplyCount int
	DECLARE @MostReadPostID int
	DECLARE @TotalAnonymousUsers int
	DECLARE @NewestUserID int
	DECLARE @MostActiveUserID int
	DECLARE @ApplicationName  NVARCHAR(256)

	SET @ApplicationName  = (Select Lower(ApplicationName) FROM cs_SiteSettings where SettingsID = @SettingsID)

	SET NOCOUNT ON

	SET @LastDateTimeUpdate = ISNULL( 
					(
						SELECT TOP 1
							DateCreated 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID
					), '1/1/1979 12:00:00')

	-- Reset top posters
	IF @UpdateUserPostRank = 1
		exec cs_system_UpdateUserPostRank @SettingsID

	IF @UpdateMostActiveUserList = 1
		exec cs_system_UpdateMostActiveUsers @SettingsID

	-- Total Anonymous Users
	-- ***********************************************
	SET @TotalAnonymousUsers = 0-- ISNULL((SELECT COUNT(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID), 0 )

	-- Total Moderators, for this site only
	-- ***********************************************


	-- Total Moderated Posts
	-- ***********************************************
	SET @TotalModeratedPosts  = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalModeratedPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
					ISNULL( 
					(
						SELECT 
							COUNT(ModerationAction) 
						FROM 
							cs_ModerationAudit 
						WHERE 
							ModeratedOn >= @LastDateTimeUpdate AND
							SettingsID = @SettingsID AND
							ModerationAction = 1
					), 0)
	IF @TotalModeratedPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalModeratedPosts = (SELECT COUNT(ModerationAction) FROM cs_ModerationAudit WHERE SettingsID = @SettingsID AND ModerationAction = 1)
	END

	-- Most "Viewed" thread, by grabbing the first post
	-- ***********************************************
	SET @MostViewsPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY 
							jT.TotalViews DESC
					), 0)

        -- "ViewCount" thread, by grabbing the first post
	-- ***********************************************
	SET @ViewCount = ISNULL(
					(
						SELECT TOP 1 
							jP1.TotalViews
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY
							jT.TotalViews DESC
					), 0)


	-- Most "Active" Thread, by grabbing the first post
	-- ***********************************************
	SET @MostActivePostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

        -- "ReplyCount" on a Thread, by grabbing the first post
	-- ***********************************************
	SET @ReplyCount = ISNULL(
					(
						SELECT TOP 1 
							jT.TotalReplies
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

	-- Most "Read" thread, by grabbing the first post
	-- ***********************************************
	SET @MostReadPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_ProductPermissions jP ON (jP.RoleID = @EveryoneRoleID and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = @EveryoneRoleID and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jF.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							( SELECT count(jTR.ThreadID) FROM cs_ThreadsRead jTR WHERE jP1.ThreadID = jTR.ThreadID ) DESC
					), 0)


	-- Most active user
	-- ***********************************************
	SET @MostActiveUserID = ISNULL(
					(
						SELECT TOP 1 
							jP.UserID
						FROM 
							cs_UserProfile jP
						WHERE
							jP.EnableDisplayInMemberList = 1 and jP.SettingsID = @SettingsID
						ORDER BY 
							jP.TotalPosts DESC
					), 0)
	-- Newest user
	-- ***********************************************
	SET @NewestUserID = ISNULL(
					(
						SELECT Max(jU.UserID) 

						FROM 
							cs_vw_Users_FullUser jU
							JOIN cs_UserProfile jP ON jP.UserID = jU.UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 AND
							jU.UserAccountStatus = 1 and jP.SettingsID = @SettingsID
					), 0)


	-- Total Users
	-- ***********************************************
	SET @TotalUsers = ISNULL( 
					(
						SELECT 
							COUNT(UserID) 
						FROM 
							cs_UserProfile 
						WHERE 
							SettingsID = @SettingsID
					) ,0) 


	-- Total Posts
	-- ***********************************************
	SET @TotalPosts = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) +
				 ISNULL( 
					(
						SELECT 
							COUNT(PostID) 
						FROM 
							cs_Posts, cs_Sections
						WHERE 
							ForumType = 0 and cs_Posts.SectionID = cs_Sections.SectionID and 
						PostDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SettingsID = @SettingsID)
	END


	-- Total Topics
	-- ***********************************************
	SET @TotalTopics = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalTopics 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
				ISNULL( 
					(
						SELECT 
							COUNT(ThreadID) 
						FROM 
							cs_Threads, cs_Sections 
						WHERE 
							ForumType = 0 AND cs_Threads.SectionID = cs_Sections.SectionID and 
							ThreadDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalTopics = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalTopics = (SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.SectionID = cs_Threads.SectionID and cs_Sections.ApplicationType = 0)
	END

	-- Total Posts in past 24 hours
	-- ***********************************************
	SET @NewPostsInPast24Hours = ISNULL( 
					(SELECT COUNT(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SettingsID = @SettingsID And cs_Sections.SectionID = cs_Posts.SectionID and ForumType = 0 and PostDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Users in past 24 hours
	-- ***********************************************
	SET @NewUsersInPast24Hours = ISNULL(
						(SELECT COUNT(U.IsApproved) FROM cs_Users U INNER JOIN cs_UserProfile UP ON U.UserID = UP.UserID WHERE UP.SettingsID = @SettingsID and U.CreateDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Topics in past 24 hours
	-- ***********************************************
	SET @NewThreadsInPast24Hours = ISNULL(
						(SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SectionID = cs_Threads.SectionID AND cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.ApplicationType = 0 AND PostDate > DATEADD(dd,-1,getdate())
					), 0)

	INSERT INTO cs_statistics_Site
	SELECT 
		DateCreated = GetDate(),
		TotalUsers = @TotalUsers,
		TotalPosts = @TotalPosts,
		TotalModerators = @TotalModerators,
		TotalModeratedPosts = @TotalModeratedPosts,
		TotalAnonymousUsers = @TotalAnonymousUsers,
		TotalTopics = @TotalTopics,
		DaysPosts = @NewPostsInPast24Hours, -- TODO remove
		DaysTopics = @NewThreadsInPast24Hours, -- TODO remove
		NewPostsInPast24Hours = @NewPostsInPast24Hours,
		NewThreadsInPast24Hours = @NewThreadsInPast24Hours,
		NewUsersInPast24Hours = @NewUsersInPast24Hours,
		MostViewsPostID = @MostViewsPostID,
		MostActivePostID = @MostActivePostID,
		MostActiveUserID = @MostActiveUserID,
		MostReadPostID = @MostReadPostID,
		NewestUserID = @NewestUserID,	
		SettingsID = @SettingsID,
        	ViewCount = @ViewCount,
        	ReplyCount = @ReplyCount
END

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_updatestatistics
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_system_updatestatistics'

IF object_id( '[dbo].[cs_system_updatestatistics]', N'P' ) IS NOT NULL
	drop procedure [dbo].[cs_system_updatestatistics]
go

CREATE PROCEDURE [dbo].[cs_system_updatestatistics]
as
begin

	declare @sql nvarchar(1000), @id int, @full_name sysname, @table_count int
		,@dbsid varbinary(85)

	declare @t table (
		id int identity(1, 1) not null
		, full_name sysname collate database_default not null
	)

	set nocount on
	
	select
		@dbsid = d.sid
	from
		master..sysdatabases d
	where
		d.name = db_name()
	
	-- Check the user sysadmin
	if not is_srvrolemember(N'sysadmin') = 1 and suser_sid() <> @dbsid
	begin
		raiserror( 15247, -1, -1 )
		return (1)
	end
	
	if DATABASEPROPERTYEX( db_name(), N'Updateability' ) = N'READ_ONLY'
	begin
		raiserror( 15635, -1, -1, N'cs_system_updatestatistics' )
		return (1)
	end
	
	insert into @t ( full_name )
	select t.FULL_NAME from (
		select
			quotename(tx.TABLE_SCHEMA) + N'.' + quotename(tx.TABLE_NAME) as FULL_NAME
		from
			INFORMATION_SCHEMA.TABLES tx
	) as t
	where
		objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsIndexed' ) = 1
		and objectproperty( OBJECT_ID( t.FULL_NAME ), N'IsMSShipped' ) = 0
	order by
		t.FULL_NAME

	set @table_count = @@ROWCOUNT

	print 'Beginning to perform an UPDATE STATISTICS on all ' + cast(@table_count as varchar) + ' tables at ' + convert(char(19), getdate(), 120)

	while 1=1
	begin
		select @id = t.id, @full_name = t.full_name from (
			select top 1 tx.* from @t tx order by tx.id
		) as t
		
		if @id is null break
		
		print 'Performing an UPDATE STATISTICS on table/view ' + @full_name + ' at ' + convert(char(19), getdate(), 120)
		
		set @sql = 'update statistics ' + @full_name -- with no_infomsgs
		exec sp_executesql @sql
		
		delete from @t where id = @id
		
		set @id = null
	end

	print 'Done with UPDATE STATISTICS at ' + convert(char(19), getdate(), 120)
end
go

/***********************************************
* Sproc: cs_system_UpdateSubscriptions
* File Date: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_system_UpdateThread
* File Date: 4/14/2008 11:35:01 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 = UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1
	SET @PostAuthor = ''
END

SELECT 
	@StickyDate = StickyDate 
FROM 
	cs_Threads 
WHERE 
	ThreadID = @ThreadID and SettingsID = @SettingsID

IF @StickyDate < @ThreadDate
	SET @StickyDate = @ThreadDate

-- do the mass updates.
IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the most recent post hasn't been flagged as ignored. 
BEGIN
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	UPDATE 
		cs_Threads
	SET
		TotalReplies = (SELECT Count(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
		MostRecentPostAuthorID = @UserID,
		MostRecentPostAuthor = @PostAuthor,
		MostRecentPostID = @ReplyPostID
	WHERE
		ThreadID = @ThreadID and SettingsID = @SettingsID
	
	IF @UpdateThreadDate = 1	
		UPDATE 
			cs_Threads
		SET
			ThreadDate = @ThreadDate,
			StickyDate = @StickyDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- find any lingering ParentIDs that don't match any posts in
-- our thread (from a merge or split action)
SET @FirstPostID = (	
	SELECT TOP 1 
		PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate ASC 
	)

UPDATE
	cs_Posts
SET
	ParentID = @FirstPostID
WHERE
	ParentID NOT IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID)
	AND ThreadID = @ThreadID and SettingsID = @SettingsID


-- fix the PostLevel and SortOrder ordering, by date
-- this could be done better, as it's on a MassScale now.
UPDATE
	cs_Posts
SET
	SortOrder = SortOrder + 1
WHERE
	ThreadID = @ThreadID
	AND PostID > @ReplyPostID and SettingsID = @SettingsID

UPDATE p set p.PostLevel = 0
FROM cs_Posts p where p.ThreadID = @ThreadID
 
-- set initial post level
UPDATE p set p.PostLevel = 1
FROM cs_Posts p where p.PostID = p.ParentID and p.ThreadID = @ThreadID
 
-- reset all other post levels
while 1=1
begin
    UPDATE p set p.PostLevel = pp.PostLevel + 1
    FROM cs_Posts p
    inner join cs_Posts pp on p.ParentID = pp.PostID
    WHERE p.ThreadID = @ThreadID and p.PostLevel = 0 and pp.PostLevel > 0

    if @@ROWCOUNT = 0 BREAK
end


-- update the EmoticonID, if it's the first post
IF @ReplyPostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate ASC)
	UPDATE
		cs_Threads
	SET
		ThreadEmoticonID = (SELECT EmoticonID FROM cs_Posts WHERE PostID = @ReplyPostID and SettingsID = @SettingsID)
	WHERE
		ThreadID = @ThreadID	 and SettingsID = @SettingsID

SET NOCOUNT OFF

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



grant execute on [dbo].[cs_system_UpdateThread] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserPostCount
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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
BEGIN

	SET Transaction Isolation Level Read UNCOMMITTED
	DECLARE @LoopCounter int

	SET NOCOUNT ON

	CREATE Table #PostRank (
	  Rank int IDENTITY (1, 1) NOT NULL,
	  UserID int
	)

	-- Select into temp table
	INSERT INTO #PostRank (UserID)
	SELECT TOP 500
		P.UserID
	FROM
		cs_UserProfile P
	Where SettingsID = @SettingsID
	ORDER BY
		P.TotalPosts DESC

	-- First clear all the users
	UPDATE 
		cs_UserProfile
	SET 
		PostRank = 0x0
	WHERE 
		PostRank > 0 and SettingsID = @SettingsID

	-- Top 10
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x01
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank < 11 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 25
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x02
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 10 AND Rank < 26 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 50
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x04
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 25 AND Rank < 51 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 75
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x08
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 50 AND Rank < 76 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 100
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x10
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 75 AND Rank < 101 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 150
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x20
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 100 AND Rank < 151 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 200
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x40
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 150 AND Rank < 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 500
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x80
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID

END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserPostRank] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserSubscriptions
* File Date: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_system_UserCanReadSection
* File Date: 4/14/2008 11:35:01 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


/***********************************************
* Sproc: cs_system_UserIsOnline
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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] 
	@SectionXML ntext = null,
	@CategoryList nvarchar(4000) = null,
	@sqlPopulate ntext = null,
	@SettingsID int
AS
begin
	SET Transaction Isolation Level Read UNCOMMITTED
	DECLARE @Sections TABLE 
	(
		SectionID int
	)
	--DECLARE @FilterSections TABLE 
	--(
	--	SectionID int
	--)
	-- Create a temp table to store the select results
	CREATE TABLE #FilterSections 
	(
		SectionID int  NOT NULL
	)
	
	
	DECLARE @ret int, @iXml int
	
	IF @SectionXML IS NOT NULL
	BEGIN
	
		EXECUTE @ret = [master].[dbo].[sp_xml_preparedocument] @iXml OUTPUT, @SectionXML
	
		INSERT INTO #FilterSections (SectionID)
			SELECT
		    		a.sectionID
			FROM
		    		OPENXML(@iXml, '/xml/SectionIDs/i', 2) -- use element-centric mapping
			WITH ( sectionID int '.') AS a
	
		-- clean up the sqlxml object
		EXEC sp_xml_removedocument @iXml
	END
	
	--SQL POPULATE WAS ADDED TO SUPPORT THE ISPUBLIC FLAG AS AN OPTIONAL ALTERNATE WAY TO POPULATE THE SECTION LIST
	IF @sqlPopulate IS NOT NULL
	BEGIN
	
		INSERT INTO #FilterSections (SectionID)
		EXEC sp_executesql @sqlPopulate
	
	END   
	
	
	INSERT INTO @Sections (SectionID)
			SELECT
			    s.SectionID 
			FROM 
			   #FilterSections fs JOIN cs_Sections s on
			   	s.SettingsID = @SettingsID
			   	and fs.SectionID = s.SectionID
			   	and s.IsActive = 1
	
	DROP TABLE #FilterSections
	
	if @CategoryList is null begin
	
		select [Name], count(*) as TotalCount
		from cs_Post_Categories C
		inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
		inner join cs_Posts P on PiC.PostID = P.PostID
		where C.SettingsID = @SettingsID
			and C.SectionID IN (select sx.SectionID from @Sections sx)
			and P.IsApproved = 1
			and C.IsEnabled = 1
		group by [Name]
		order by [Name]
	
	end else begin
	
		declare @idoc int
		declare @categoryCount int
	
		declare @Tags TABLE
		(
			[Name] nvarchar(255) collate database_default
		)
	
		EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList
		
		insert into @Tags ([Name])
		select CONVERT(nvarchar(255), [text])
		from OPENXML(@idoc, '/Categories/Category/', 2)
		where [text] is not null
	
		set @categoryCount = @@ROWCOUNT
	
		-- clean up the sqlxml object
		EXEC sp_xml_removedocument @idoc
	
		select [Name], count(*) as TotalCount
		from cs_Post_Categories C
		inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
		where C.SettingsID = @SettingsID
			and C.SectionID in (select sx.SectionID from @Sections sx)
			and C.IsEnabled = 1
			and PiC.PostID in (
				select P2.PostID
				from @Tags X
				inner join cs_Post_Categories C2 on X.[Name] = C2.Name
				inner join cs_Posts_InCategories PiC2 on PiC2.CategoryID = C2.CategoryID
				inner join cs_Posts P2 on PiC2.PostID = P2.PostID
				where C2.SettingsID = @SettingsID
					and C2.SectionID in (select sx.SectionID from @Sections sx)
					and C2.IsEnabled = 1
					and P2.SettingsID = @SettingsID
					and P2.IsApproved = 1
				group by P2.PostID
				having count(*) = @categoryCount
				)
		group by [Name]
		having [Name] not in (select tx.[Name] from @Tags tx)
		order by [Name]
	
	end
end
go

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_TemporaryUserTokens_Expire
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_TemporaryUserTokens_Expire'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


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


create procedure [dbo].cs_TemporaryUserTokens_Expire
AS
SET Transaction Isolation Level Read UNCOMMITTED


DELETE
	cs_TemporaryUserTokens
WHERE
	ExpirationDate < getdate()


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserTokens_Expire] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Create
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Create'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


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


create procedure [dbo].cs_TemporaryUserToken_Create
(
	@UserID			int,
	@SettingsID		int,
	@ExpirationDate	datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @Token uniqueidentifier
SET @Token = newid()

INSERT INTO
	cs_TemporaryUserTokens
	(
		UserID,
		SettingsID,
		Token,
		ExpirationDate
	)
VALUES
	(
		@UserID,
		@SettingsID,
		@Token,
		@ExpirationDate
	)

SELECT @Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Create] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Delete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


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


create procedure [dbo].cs_TemporaryUserToken_Delete
(
	@UserID		int,
	@SettingsID	int,
	@Token		uniqueidentifier
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


DELETE
	cs_TemporaryUserTokens
WHERE
	UserID = @UserID
	AND SettingsID = @SettingsID
	AND Token = @Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Delete] to public
go
/***********************************************
* Sproc: cs_TemporaryUserToken_Validate
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_TemporaryUserToken_Validate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


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


create procedure [dbo].cs_TemporaryUserToken_Validate
(
	@UserID		int,
	@SettingsID	int,
	@Token		uniqueidentifier
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


IF EXISTS (SELECT * FROM cs_TemporaryUserTokens WHERE UserID = @UserID AND SettingsID = @SettingsID AND Token = @Token AND ExpirationDate > getdate())
	SELECT 1
ELSE
	SELECT 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_TemporaryUserToken_Validate] to public
go
/***********************************************
* Sproc: cs_ThemeConfigurationData_Delete
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Delete
	@ThemeName nvarchar(255) = null,
	@SettingsID int,
	@SectionID int = null,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if (@ThemeName is null and @SectionID is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end 
	
	if (@SectionID is null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end
	
	if (@SectionID is not null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end
end else begin
	if (@ThemeName is null and @SectionID is not null) begin
		delete from cs_ThemeConfigurationData
		where SettingsID = @SettingsID
			and SectionID = @SectionID
	end 
	
	if (@SectionID is null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
	end
	
	if (@SectionID is not null and @ThemeName is not null) begin
		delete from cs_ThemeConfigurationData
		where ThemeName = @ThemeName 
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_ThemeConfigurationData_ExpireTemp
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_ExpireTemp'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_ExpireTemp
	@HoursOld int,
	@SettingsID int
AS

declare @ExpireBefore datetime
set @ExpireBefore = dateadd(hour, -@HoursOld, getdate())

delete from cs_ThemeConfigurationData_TEMP
where LastModified < @ExpireBefore
	and SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_ThemeConfigurationData_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Get
	@ThemeName nvarchar(255),
	@SettingsID int,
	@SectionID int,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if (exists(select ThemeName from cs_ThemeConfigurationData_TEMP	where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID)) begin
		select *
		from cs_ThemeConfigurationData_TEMP
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end else begin
		select *
		from cs_ThemeConfigurationData
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end
end else begin
	select *
	from cs_ThemeConfigurationData
	where ThemeName = @ThemeName
		and SettingsID = @SettingsID
		and SectionID = @SectionID
end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_ThemeConfigurationData_Update
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ThemeConfigurationData_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_ThemeConfigurationData_Update
	@ThemeName nvarchar(255),
	@SettingsID int,
	@SectionID int,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ThemeConfigurationDataTempID uniqueidentifier = null
AS

if (@ThemeConfigurationDataTempID is not null) begin
	if exists(select ThemeName from cs_ThemeConfigurationData_TEMP where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID)
	begin
		update cs_ThemeConfigurationData_TEMP
		set PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues,
			LastModified = getdate()
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			and ThemeConfigurationDataTempID = @ThemeConfigurationDataTempID
	end else begin
		insert into cs_ThemeConfigurationData_TEMP (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues, ThemeConfigurationDataTempID, LastModified) 
		values (@ThemeName, @SettingsID, @SectionID, @PropertyNames, @PropertyValues, @ThemeConfigurationDataTempID, getdate())
	end
end else begin
	if exists(select ThemeName from cs_ThemeConfigurationData where ThemeName = @ThemeName and SettingsID = @SettingsID and SectionID = @SectionID)
	begin
		update cs_ThemeConfigurationData
		set PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues
		where ThemeName = @ThemeName
			and SettingsID = @SettingsID
			and SectionID = @SectionID
	end else begin
		insert into cs_ThemeConfigurationData (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues) 
		values (@ThemeName, @SettingsID, @SectionID, @PropertyNames, @PropertyValues)
	end
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Threads_GetThreadSet
* File Date: 4/14/2008 11:35:01 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 sp_executesql @sqlPopulate

SELECT
	jT.*, U.*,
	HasRead = 0,
	jP.PostID,
	jP.Subject,
	jP.Body,
	jP.FormattedBody,
	jP.PostMedia,
	jP.PostType,
	UserName = jT.PostAuthor,
	jP.PropertyNames as PostPropertyNames, jP.PropertyValues as PostPropertyValues,
	jP.PostConfiguration
FROM 
	#PageIndex jPI
	JOIN cs_Threads jT ON jPI.ThreadID = jT.ThreadID
	JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.UserID and U.SettingsID = @SettingsID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter
	AND (U.IsIgnored = 0 OR U.UserID = @UserID)	-- Ensure that you are not getting threads by ignored users unless the ignored user is requesting them
ORDER BY
	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 sp_executesql @sqlCount


END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Threads_ThreadSet
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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_Daily_Stats_Increment
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Thread_Daily_Stats_Increment'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

Create PROCEDURE [dbo].[cs_Thread_Daily_Stats_Increment]
(
	@SectionID as int,
	@ThreadID as int,
	@ViewCount as int
)
AS
BEGIN
	SET Transaction Isolation Level Read UNCOMMITTED

	DECLARE @day datetime

	Set @day = convert( char(10), GetDate(), 120 )

	-- update daily stats
	UPDATE
		tds
	SET
		tds.ViewCount = tds.ViewCount + @ViewCount
	FROM
		cs_Thread_Daily_Stats tds
	WHERE
		tds.SectionID = @SectionID
		AND tds.ThreadID = @ThreadID
		AND tds.[Day] = @day

	-- if there was nothing to update, add it to the table
	IF @@ROWCOUNT = 0
		-- new stats record
		INSERT INTO cs_Thread_Daily_Stats ([SectionID], [ThreadID], [Day], [ViewCount])
		VALUES (@SectionID, @ThreadID, @day, @ViewCount)

END



grant execute on [dbo].[cs_Thread_Daily_Stats_Increment] to public
go
/***********************************************
* Sproc: cs_Thread_Delete
* File Date: 4/14/2008 11:35:02 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

-- 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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_UnsubscribeFromSection
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_UnsubscribeFromSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_UnsubscribeFromSection
(
	@SubscriptionID uniqueidentifier,
	@SectionID int OUTPUT
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Include the check for DateUnsubscribed so that a user can only be unsubscribed once
	UPDATE [cs_SectionSubscriptions]
	SET DateUnsubscribed = GetDate(), IsConfirmed = 0
	WHERE SubscriptionID = @SubscriptionID AND DateUnsubscribed IS NULL
	
	SELECT @SectionID = SectionID FROM [cs_SectionSubscriptions] 
	WHERE SubscriptionID = @SubscriptionID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_UnsubscribeFromThread
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_UnsubscribeFromThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

	DECLARE @ThreadID INT
	
	-- First get the post info
	SELECT 
		@ThreadID = ThreadID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID
		
	IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		-- the user is tracking this thread, delete this row
		DELETE FROM cs_TrackedThreads
		WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_UpdateForumGroupSortOrder
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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 = SCOPE_IDENTITY()
END
--Update
ELSE IF @Action = 1
BEGIN
	UPDATE cs_UrlRedirects SET
		Description = @Description,
		Url = @Url
	WHERE
		UrlID = @UrlID
END
--Delete
ELSE IF @Action = 2
BEGIN
	DELETE FROM
		cs_UrlRedirects
	WHERE
		UrlID = @UrlID
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UrlRedirect_CreateUpdateDelete] to public
GO
/***********************************************
* Sproc: cs_Urls_Add
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_UserActivityNightlyJob'

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

/***********************************************
* Sproc: cs_UserActivityReportRecords_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_UserActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_UserFeed_DeleteFeed
* File Date: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_UserHasPostsAwaitingModeration
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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: 4/14/2008 11:35:02 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

/***********************************************
* Sproc: cs_users_BackPort
* File Date: 4/14/2008 11:35:02 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 = MembershipId FROM cs_vw_Users_FullUser where UserName = @UserName and SettingsID = @SettingsID
--	
--	Update aspnet_Membership
--	Set Password = @Password, PasswordSalt = @PasswordSalt, PasswordFormat = @PasswordFormat
--	Where MembershipId = @UserID
--		
--End

go


-- grant execute on [dbo].[cs_users_BackPort] to public
go
/***********************************************
* Sproc: cs_users_count_Get
* File Date: 4/14/2008 11:35:01 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(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND (UserName LIKE @UsernameFilter OR Email LIKE @UsernameFilter))



END




  SELECT @TotalUsers
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_users_Get
* File Date: 4/14/2008 11:35:02 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,
	@sqlPopulateCount ntext,
	@SearchText nvarchar(256),
	@ReturnModerationCounters bit = 0,
	@SettingsID int
)
AS
BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1
SET @RowsToReturn = @PageSize * (@PageIndex + 1)

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	UserID int not null
)

Exec sp_executesql @sqlPopulateCount, N'@SearchText nvarchar(256), @recordCount int output', @SearchText = @SearchText, @recordCount = @TotalUsers output

/* First set the rowcount to the total possible rows to return */
SET ROWCOUNT @RowsToReturn

INSERT INTO #PageIndexForUsers (UserID)
Exec sp_executesql @sqlPopulate, N'@SearchText nvarchar(256)', @SearchText = @SearchText

/* now set it to the page size */
SET ROWCOUNT @PageSize

/* Get the user details */
IF @ReturnModerationCounters = 1
begin
	/* I don't want to see the null removed from the aggregate message */
	set ANSI_WARNINGS OFF

	SELECT
		U.*
		, coalesce(mod.ApprovePost, 0) AS ApprovePost
		, coalesce(mod.EditPost, 0) AS EditPost
		, coalesce(mod.MovePost, 0) AS MovePost
		, coalesce(mod.DeletePost, 0) AS DeletePost
		, coalesce(mod.LockPost, 0) AS LockPost
		, coalesce(mod.UnlockPost, 0) AS UnlockPost
		, coalesce(mod.MergePost, 0) AS MergePost
		, coalesce(mod.SplitPost, 0) AS SplitPost
		, coalesce(mod.EditUser, 0) AS EditUser
		, coalesce(mod.UnmoderateUser, 0) AS UnmoderateUser
		, coalesce(mod.ModerateUser, 0) AS ModerateUser
		, coalesce(mod.BanUser, 0) AS BanUser
		, coalesce(mod.UnbanUser, 0) AS UnbanUser
		, coalesce(mod.ResetPassword, 0) AS ResetPassword
		, coalesce(mod.ChangePassword, 0) AS ChangePassword
		, coalesce(mod.PostIsAnnouncement, 0) AS PostIsAnnouncement
		, coalesce(mod.PostIsNotAnnoucement, 0) AS PostIsNotAnnoucement
		, coalesce(mod.UnApprovePost, 0) AS UnApprovePost
		/* (we do not seem to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID) */
	FROM
		cs_vw_Users_FullUser U (nolock)
	INNER JOIN
		#PageIndexForUsers jPI ON U.UserID = jPI.UserID
	LEFT OUTER JOIN (
		SELECT
			ma.UserID
			, count(case ma.ModerationAction when 1  then ma.UserID end) as [ApprovePost]
			, count(case ma.ModerationAction when 2  then ma.UserID end) as [EditPost]
			, count(case ma.ModerationAction when 3  then ma.UserID end) as [MovePost]
			, count(case ma.ModerationAction when 4  then ma.UserID end) as [DeletePost]
			, count(case ma.ModerationAction when 5  then ma.UserID end) as [LockPost]
			, count(case ma.ModerationAction when 6  then ma.UserID end) as [UnlockPost]
			, count(case ma.ModerationAction when 7  then ma.UserID end) as [MergePost]
			, count(case ma.ModerationAction when 8  then ma.UserID end) as [SplitPost]
			, count(case ma.ModerationAction when 9  then ma.UserID end) as [EditUser]
			, count(case ma.ModerationAction when 10 then ma.UserID end) as [UnmoderateUser]
			, count(case ma.ModerationAction when 11 then ma.UserID end) as [ModerateUser]
			, count(case ma.ModerationAction when 12 then ma.UserID end) as [BanUser]
			, count(case ma.ModerationAction when 13 then ma.UserID end) as [UnbanUser]
			, count(case ma.ModerationAction when 14 then ma.UserID end) as [ResetPassword]
			, count(case ma.ModerationAction when 15 then ma.UserID end) as [ChangePassword]
			, count(case ma.ModerationAction when 16 then ma.UserID end) as [PostIsAnnouncement]
			, count(case ma.ModerationAction when 17 then ma.UserID end) as [PostIsNotAnnoucement]
			, count(case ma.ModerationAction when 18 then ma.UserID end) as [UnApprovePost]
		FROM cs_ModerationAudit ma
		WHERE
			ma.SettingsID = @SettingsID
		GROUP BY
			ma.UserID
	) as mod ON U.UserID = mod.UserID
	WHERE
		jPI.IndexID > @PageLowerBound AND jPI.IndexID < @PageUpperBound
		and U.SettingsID = @SettingsID
	ORDER BY
		jPI.IndexID

	set ANSI_WARNINGS ON

end ELSE begin

	SELECT
		U.*
		/* (we do not seem to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.UserID) */
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.UserID = #PageIndexForUsers.UserID AND
		#PageIndexForUsers.IndexID > @PageLowerBound AND
		#PageIndexForUsers.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		#PageIndexForUsers.IndexID

end

set rowcount 0

/* Return the record count */
SELECT @TotalUsers

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Users_GetUserIDByFilter
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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.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: 4/14/2008 11:35:01 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

/***********************************************
* Sproc: cs_users_ValidateAnswer
* File Date: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_Users_WhoDownloadedPost
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Users_WhoDownloadedPost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].cs_Users_WhoDownloadedFile
(
	@PageIndex int,
	@PageSize int,
	@PostID int,
	@ReturnRecordCount bit = 0,
	@SettingsID int,
	@StartDate datetime,
	@EndDate datetime
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	LatestDownloadDate datetime,
	TotalDownloads int,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(distinct U.UserID) FROM cs_vw_Users_FullUser U, cs_Posts_Downloads D WHERE D.UserID = U.UserID and D.PostID = @PostID and U.SettingsID = @SettingsID and D.DownloadDate between @StartDate and @EndDate)

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

INSERT INTO #PageIndexForUsers (UserID, LatestDownloadDate, TotalDownloads)
SELECT U.UserID, Max(D.DownloadDate), count(*)
FROM cs_vw_Users_FullUser U, cs_Posts_Downloads D 
WHERE D.UserID = U.UserID 
	and D.PostID = @PostID 
	and U.SettingsID = @SettingsID 
	and D.DownloadDate between @StartDate and @EndDate
GROUP BY U.UserID
ORDER BY Max(D.DownloadDate)

-- Get the user details
SELECT
	*, @PostID as PostID
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.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_WhoDownloadedFile  to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Count
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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_CreateUpdateDelete
* File Date: 4/14/2008 11:35:02 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) = '',
	@Email nvarchar(256) = '',
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '',
	@CreateDate	datetime = null,
	@IsApproved bit = 1,
	@ForumView   int = 0,
	@TimeZone   float = 0.0,
	@PostRank   binary(1) = 0x0,
	@PostSortOrder   int = 0,
	@IsAvatarApproved   smallint  = 0,
	@ForceLogin   bit   = 0,
	@ModerationLevel  smallint  = 0,
	@EnableThreadTracking  smallint  = 0,
	@EnableDisplayUnreadThreadsOnly smallint  = 0,
	@EnableAvatar    smallint  = 0,
	@EnableDisplayInMemberList  smallint  = 1,
	@EnablePrivateMessages  smallint  = 1,
	@EnableOnlineStatus smallint  = 1,
	@EnableEmail smallint  = 1,
	@EnableHtmlEmail   smallint  = 1,
	@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


IF @CreateDate is null
	SET @CreateDate = GetDate()
-- first, we need to check if the username is a dup

-- Are we creating a user?
IF @Action = 0
BEGIN
	IF (@IsAnonymous = 1)
	BEGIN
		SELECT @cs_UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName AND IsAnonymous = 1 AND SettingsID = @SettingsID
		
		-- Check if the anonymous user already exists
		IF @cs_UserID IS NOT NULL
		Begin
			SELECT 1
			RETURN
		End
		
	END
	ELSE
	BEGIN
		--A WSHA User can exist in multiple sites. We need to find all the site's this user will have access to
		-- and create the coresponding records
		Declare @ApplicationName nvarchar(256)
		Select @ApplicationName = ApplicationName FROM cs_SiteSettings where SettingsID = @SettingsID

		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction], [UserName], [Email], [IsAnonymous], [CreateDate], [IsApproved])
		VALUES(@UserID, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '', @UserName, @Email, @IsAnonymous, @CreateDate, @IsApproved)
		IF (@@ERROR <> 0)
		BEGIN
			Select 0
			RETURN
		END

		Select @cs_UserID = SCOPE_IDENTITY()

		INSERT INTO cs_UserProfile ( [UserID], [TimeZone], [TotalPosts], 	[PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableEmail], [EnableHtmlEmail], [IsIgnored], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues], [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)
	

  
	-- Some properties will be created/defaulted by SHS Create User.
	-- These values will be updated by Membership.UpdateUser as well. 
	-- Here we just update the properties which fall outside of MembershipUser
	-- First Update the cs_vw_forums_Users table

	UPDATE
		cs_Users
	SET
		Email = @Email,
		IsAnonymous = @IsAnonymous,
		IsApproved = @IsApproved,
		AppUserToken = @AppUserToken,
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		MembershipID = @UserID

	SELECT 6
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_user_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_User_Delete
* File Date: 4/14/2008 11:35:02 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_Sections
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		UserID = @ReassignUserID,
			PostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentArticleAuthorID = @ReassignUserID,
			MostRecentArticleAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentArticleAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure
    
	-- delete content
	DELETE
	FROM	cs_FavoritePosts
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

	DELETE
	FROM	cs_FavoriteUsers
	WHERE	OwnerID = @UserID OR 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	cs_Posts_Downloads
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

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

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

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

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

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

    -- Deleting user announcements has to occur before
    -- other messages are reassigned
    EXEC cs_Messaging_DeleteProfileAnnouncementsForUser @UserID  
    IF (@@ERROR <> 0) GOTO Failure

    -- Deleting user activity messages has to occur before
    -- other messages are reassigned
    EXEC cs_Messaging_DeleteActivityMessagesForUser @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
    UPDATE cs_Messaging_ProfileMessages
    SET    UserId = @ReassignUserID
    WHERE  UserId = @UserID
    IF (@@ERROR <> 0) GOTO Failure

    UPDATE cs_Messaging_ConversationParticipants
    SET    ParticipantId = @ReassignUserID
    WHERE  ParticipantId = @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
    UPDATE cs_Messaging_Messages
    SET    AuthorId = @ReassignUserID
    WHERE  AuthorId = @UserID
    IF (@@ERROR <> 0) GOTO Failure
    
	-- delete user
	DELETE
	FROM	cs_Moderators
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

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

	DELETE
	FROM	aspnet_UsersInRoles
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Profile
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Membership
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Users
	WHERE	UserId = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Delete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_user_Get
* File Date: 4/14/2008 11:35:02 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 @MembershipID uniqueidentifier

	-- Looking up by UserName?
	IF @UserName IS NOT NULL
	BEGIN

		SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName AND SettingsID = @SettingsID

		SELECT
			U.*
		FROM
			cs_vw_Users_FullUser U (nolock)
		WHERE
			U.UserName = @UserName AND U.SettingsID = @SettingsID
	END

	-- Looking up the user by ID
	ELSE
	BEGIN

		IF (@UserID = 0)
			SELECT @UserID = UserID FROM cs_vw_Users_FullUser WHERE UserName = 'Anonymous' and SettingsID = @SettingsID

		-- Get the user details
		SELECT
			U.*
		FROM 
			cs_vw_Users_FullUser U (nolock)
		WHERE 
			U.UserID = @UserID and U.SettingsID = @SettingsID
	END

	IF @IsOnline = 1
	BEGIN
		EXEC cs_system_UserIsOnline @UserID, @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: 4/14/2008 11:35:02 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 
	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: 4/14/2008 11:35:02 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

/***********************************************
* Sproc: cs_User_PasswordAnswer_Change
* File Date: 4/14/2008 11:35:02 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


/***********************************************
* Sproc: cs_User_Rename
* File Date: 4/14/2008 11:35:01 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 users
	UPDATE	cs_Users
	SET	UserName = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle posts
	UPDATE	cs_Posts
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle post archive
	UPDATE	cs_PostsArchive
	SET	UserName = @DesiredUserName
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle sections
	UPDATE	cs_Sections
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle threads
	UPDATE	cs_Threads
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_Threads
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle blogs
	UPDATE	cs_weblog_Weblogs
	SET	MostRecentArticleAuthor = @DesiredUserName
	WHERE	MostRecentArticleAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_weblog_Weblogs
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- be sure posts are reindexed
	EXECUTE cs_Posts_ReindexByUser @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Rename] TO PUBLIC
GO
/***********************************************
* Sproc: cs_User_ToggleSettings
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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 = 2,
	@Increment int = 250 /* new parameter that is default */
)
AS
BEGIN

	/* temporarily store posts to delete */
	set nocount on

	declare @curdate datetime
		, @purgeDate datetime
		, @bottom int
		, @top int
		, @possibleSpamPurgeDate datetime
		, @PossibleSpamExpirationDays int
		, @rc int

	create table #Posts (
		id int identity(1, 1) not null primary key clustered
		, PostID int not null
	)

	select
		@curdate = GETDATE()
		/* ensuring @ExpirationDays has a value */
		, @ExpirationDays = COALESCE( @ExpirationDays, 2 )
		/* set a purgedate based on the days in the past to truncate from */
		, @purgeDate = dateadd(day, -1 * @ExpirationDays, @curdate )
		/* ensuring @Increment has a value */
		, @Increment = COALESCE( @Increment, 250 )
		/*	seed the top at zero.  This is so logic for determining the next 'top' is cleaner */
		, @top = 0
		/* initial rowcount */
		, @rc = 0
		/* range checking.  If ExpirationDays exceeds half of the max value of INT, then make it the max value of INT */
		, @PossibleSpamExpirationDays = case when @ExpirationDays >= cast(0x7fffffff as int) / 2
			then cast(0x7fffffff as int) else @ExpirationDays * 2 end
		/* set a purgedate based on the days in the past to truncate from */
		, @possibleSpamPurgeDate = dateadd(day, -1 * @PossibleSpamExpirationDays, @curdate )

	print 'Calculating spam posts to be deleted: ' + convert(char(19), getdate(), 120)

	/* inserting for definite spam */
	INSERT INTO #Posts (PostID)
	SELECT P.PostID FROM cs_Posts P (nolock)
	INNER JOIN
		cs_Sections S (nolock) on P.SettingsID = S.SettingsID and P.SectionID = S.SectionID
	WHERE
		S.SettingsID = @SettingsID
		AND (
			( S.ApplicationType = 1	/* only weblogs */
            AND P.ApplicationPostType IN (4, 8)	) /* only comments/trackbacks */
			OR
			( S.ApplicationType = 13 /* only media gallery */
            AND P.ApplicationPostType = 1 ) /* only comments */
		)
		AND	(P.PostStatus & 2) = 2			/* only posts marked as DEFINITE spam */
		AND P.IsApproved = 0				/* make sure they are not approved */
		AND P.PostLevel > 1					/* ensure they are replies only */
		AND	P.PostDate < @purgeDate			/* only posts that have been around for a while */

	set @rc = @rc + @@ROWCOUNT

	/* inserting possible spam from weblog posts */
	INSERT INTO #Posts (PostID)
	SELECT P.PostID FROM cs_Posts P (nolock)
	INNER JOIN
		cs_Sections S (nolock) on P.SettingsID = S.SettingsID and P.SectionID = S.SectionID
	WHERE
		S.SettingsID = @SettingsID
		AND (
			( S.ApplicationType = 1	/* only weblogs */
            AND P.ApplicationPostType IN (4, 8)	) /* only comments/trackbacks */
			OR
			( S.ApplicationType = 13 /* only media gallery */
            AND P.ApplicationPostType = 1 ) /* only comments */
		)
		AND	(P.PostStatus & 4) = 4			/* only posts marked as POSSIBLE spam */
		AND P.IsApproved = 0				/* make sure they are not approved */
		AND P.PostLevel > 1					/* ensure they are replies only */
		AND	P.PostDate < @possibleSpamPurgeDate	/* only posts that have been around for a while */

	set @rc = @rc + @@ROWCOUNT

	print 'Total number of spam posts that will be deleted: ' + cast(@rc as varchar) + ': ' + convert(char(19), getdate(), 120)

	while ( 1 = 1 )
	begin

		select
			@top = @top + @Increment
			, @bottom = @top + 1 - @Increment
		
		print 'Deleting from index ' + cast(@bottom as varchar) + ' to ' + cast(@top as varchar) + ': ' + convert(char(19), getdate(), 120)

		delete p
		from cs_Posts P
		inner join
			#Posts px on P.PostID = px.PostID
		where
			px.id between @bottom and @top

		if @@ROWCOUNT < @Increment begin break end

	end

	drop table #Posts

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/***********************************************
* Sproc: cs_weblog_Feedback_Get
* File Date: 4/14/2008 11:35:02 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: 4/14/2008 11:35:01 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
begin

	SET Transaction Isolation Level Read UNCOMMITTED
	declare @tYear smallint, @tMonth tinyint

	-- let's convert to make sure these are in the right range
	select @tYear = convert(smallint, @Year), @tMonth = convert(tinyint, @Month)

	select
		@Month as [Month], @Year as [Year], cast(t.[Day] as int) as [Day], t.[PostCount] as [Count]
	from
		dbo.cs_vw_weblog_PostByYearMonth t
	where
		t.[SectionID] = @SectionID
		and t.[Year] = @tYear
		and t.[Month] = @tMonth
		and t.[Day] < 255 -- we store the month level data where Day == 255
	order by t.[Day] asc

end

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonth] to public
go
/***********************************************
* Sproc: cs_weblog_PostsByMonthList
* File Date: 4/14/2008 11:35:01 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
begin

	SET Transaction Isolation Level Read UNCOMMITTED

	select
		CAST(t.[Month] as int) as [Month], cast(t.[Year] as int) as [Year], 1 as [Day], t.[PostCount] as [Count]
	from
		dbo.cs_vw_weblog_PostByYearMonth t
	where
		t.[SectionID] = @SectionID
		and t.[Year] > 0
		and t.[Month] > 0
		and t.[Day] = 255
	order by t.[Year] desc, t.[Month] desc

end
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonthList] to public
go
/***********************************************
* Sproc: cs_weblog_PostSet
* File Date: 4/14/2008 11:35:02 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.ApplicationPostType, P.UserTime,
		P.Points as PostPoints,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		#PageIndex.*,
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0,
		IsModerator = 0, 
		HasRead = 0 -- not used
		, P.PostStatus, P.SpamScore
	FROM 
		cs_Posts P (nolock),
		cs_Threads T,
		#PageIndex
	WHERE 
		P.PostID = #PageIndex.PostID AND
		T.ThreadID = P.ThreadID AND
		#PageIndex.IndexID > @PageLowerBound AND
		#PageIndex.IndexID < @PageUpperBound
	ORDER BY
		IndexID

	--SELECT @TotalRecords = count(*) FROM #PageIndex  

	DROP TABLE #PageIndex
END
ELSE --No Paging, just get all of the comments/trackbacks
BEGIN
	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.ApplicationPostType, P.UserTime,
		P.Points as PostPoints, P.PostStatus, P.SpamScore,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0, 
		IsModerator = 0, 
		HasRead = 0 -- not used
	FROM 
		cs_Posts P,
		cs_Threads T
	WHERE 
		P.ThreadID = T.ThreadID AND
		T.ThreadID = @ThreadID AND P.PostLevel > 1 AND P.IsApproved = 1 
		AND P.PostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY
		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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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()

If @UserTime IS NULL
	-- ensuring UserTime is not null
	SET @UserTime = COALESCE( @PostDate, GETDATE() )

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		UserID = @UserID

-- Do we care about duplicates?
IF @AllowDuplicatePosts = 0 and @IsComment = 1
BEGIN
	DECLARE @IsDuplicate bit
	exec cs_system_DuplicatePost @UserID, @Body, @DuplicateIntervalInMinutes, @SettingsID, @IsDuplicate output

	IF @IsDuplicate = 1
	BEGIN
		SET @PostID = -1	
		RETURN 1-- Exit with error code.
	END
END

-- we need to get the SectionID, if the ParentID is not null (there should be a SectionID)
IF @SectionID = 0 AND @ParentID <> 0
	SELECT 
		@SectionID = SectionID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @ParentID

--Set @ModeratedForum = (@PostConfig & 16)
SELECT 
	@EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID


IF @ParentID <> 0
BEGIN

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID


	IF @PostStatus & 2 = 2 /* This is spam */
	begin

		execute [dbo].[cs_SpamPostArchive]
			@SourceProcedure = N'cs_weblog_Post_Create'
			/* from cs_Post_CreateUpdate */
			, @SectionID = @SectionID
			, @ParentID = @ParentID
			, @AllowDuplicatePosts = @AllowDuplicatePosts
			, @DuplicateIntervalInMinutes = @DuplicateIntervalInMinutes
			, @Subject = @Subject
			, @UserID = @UserID
			, @PostAuthor = @PostAuthor
			, @Body = @Body
			, @FormattedBody = @FormattedBody
			, @EmoticonID = @EmoticonID
			, @IsLocked = @IsLocked
			, @IsSticky = @IsSticky
			, @IsApproved = @IsApproved
			, @StickyDate = @StickyDate
			, @PostType = @PostType
			, @PostMedia = @PostMedia
			, @PostDate = @PostDate
			, @UserHostAddress = @UserHostAddress
			, @PropertyNames = @PropertyNames
			, @PropertyValues = @PropertyValues
			, @SettingsID = @SettingsID
			, @IsTracked = @IsTracked
			, @PostID = @PostID
			, @ThreadID = @ThreadID
			, @PostConfiguration = @PostConfig
			, @UpdateSectionStatistics = NULL /* @UpdateSectionStatistics */
			, @UserTime = @UserTime
			, @ApplicationPostType = @PostType
			, @PostName = @PostName
			, @ThreadStatus = NULL /* @ThreadStatus */
			, @Points = 0 /* @Points */
			, @PostDisplayName = NULL /* @PostDisplayName */
			, @AutoApprove = NULL /* @AutoApprove */
		
			/* from cs_weblog_Post_Create */
			, @TitleUrl = @TitleUrl
			, @PostConfig = @PostConfig
			, @BlogPostType = @BlogPostType
			, @Categories = @Categories
			, @SpamScore = @SpamScore
			, @PostStatus = @PostStatus

		return 3 -- error to indicate this was spam so we can do something with it
	end
END



-- Determine if this post will be approved.
-- If the forum is NOT moderated, then the post will be approved by default.
SET NOCOUNT ON
BEGIN TRAN

IF @ParentID = 0	-- parameter indicating this is a top-level post (for a new thread)
BEGIN
	-- First we create a new ThreadID.

	-- check the StickyDate to ensure it's not null
	IF @StickyDate < @PostDate
		SET @StickyDate = @PostDate

	INSERT cs_Threads 	
		( SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID, 
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID )
	VALUES
		( @SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@PostAuthor,
		@UserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		@IsLocked,
		@IsApproved,
		@IsSticky,
		@StickyDate,
		@EmoticonID,
		@SettingsID )

	-- Get the new ThreadID
	SELECT @ThreadID = SCOPE_IDENTITY()
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore
		
	        )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore )
		

	-- Get the new PostID
	SELECT 
		@PostID = SCOPE_IDENTITY()


	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = SCOPE_IDENTITY() 


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1 
	BEGIN		
		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			--MostRecentPostAuthor = @PostAuthor, << We do not track comments
			--MostRecentPostAuthorID = @UserID, << We do not track comments
			--MostRecentPostID = @PostID, << We do not track Comments
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE  p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
			--IsLocked = @IsLocked,
			--StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			--ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID
	END
	ELSE
	BEGIN
		-- Recalculate the number of moderated posts for this blog
		UPDATE cs_Sections
		SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
		WHERE SectionID = @SectionID AND SettingsID = @SettingsID

	END

	-- Clean up ThreadsRead (this should work very well now)
	-- Not tracking in blogs
--	DELETE
--		cs_ThreadsRead
--	WHERE
--		ThreadID = @ThreadID 
--		AND UserID <> @UserID

END

--Increments posts totals ignoring settings id
IF @EnablePostStatistics = 1 AND @UserID > 0 AND @IsApproved = 1
BEGIN
	EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
END

IF(@BlogPostType = 1 OR @BlogPostType = 2)
BEGIN
	IF @IsTracked = 1
		BEGIN
		INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
		VALUES	( @ThreadID, @UserID, @SettingsID )
	END
	
	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
END

--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

	
COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_weblog_Post_Delete
* File Date: 4/14/2008 11:35:01 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

End


exec cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID

-- Update thread statistics
exec cs_system_ResetThreadStatistics @ThreadID

-- Recalculate the number of moderated posts for this blog
UPDATE cs_Sections
SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
WHERE SectionID = @SectionID AND SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/***********************************************
* Sproc: cs_weblog_Post_Get
* File Date: 4/14/2008 11:35:02 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.UserID),
	Replies = T.TotalReplies, -- (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = 0,
	IsTracked = Convert(bit,0) -- Convert(bit, (Select Count(*) FROM cs_TrackedThreads where UserID = @UserID and ThreadID = P.ThreadID))
	, P.PostStatus, P.SpamScore
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND P.SettingsID = @SettingsID and T.SettingsID = @SettingsID AND
	U.SettingsID = @SettingsID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.UserID AND
	P.IsApproved <> case @IsApprovedFilter when 1 then 0 else -1 END

	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_weblog_Post_Update
* File Date: 4/14/2008 11:35:01 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

	If @UserTime IS NULL
		-- ensuring UserTime is not null
		SET @UserTime = COALESCE( @PostDate, GETDATE() )

	-- this sproc updates a post (called from the moderate/admin page)
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		IsApproved = @IsApproved,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostDate = @PostDate,
		PostName = @PostName,
		UserTime = @UserTime,
		PostConfiguration = @PostConfig,
		ApplicationPostType = @BlogPostType,
		PostMedia = @PostMedia,
		PostStatus = @PostStatus,
		SpamScore = @SpamScore
		
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID


	IF(@PostID = @ParentID)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	ELSE 
	BEGIN
		-- This is a comment being updated. Recalculate the number of moderated posts for this blog
		UPDATE cs_Sections
		SET PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = @SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (p.PostStatus & 2) <> 2), 0)
		WHERE SectionID = @SectionID AND SettingsID = @SettingsID
	END


	-- Allow thread to update sticky properties.
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		-- Get the thread and postdate this applies to
		SELECT 
			@ThreadID = ThreadID,
			@PostDate = PostDate 
		FROM 
			cs_Posts 
		WHERE 
			PostID = @PostID and SettingsID = @SettingsID

		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @PostDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID		
		END
	END

	IF(@BlogPostType = 1 OR @BlogPostType = 2)
	BEGIN


		IF @IsTracked = 1
		BEGIN
			-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
			IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @EditedBy )
				INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
			VALUES	( @ThreadID, @EditedBy, @SettingsID)
		END
		Else
		Begin
			DELETE FROM cs_TrackedThreads where ThreadID = @ThreadID and UserID = @EditedBy and SettingsID = @SettingsID
		End


	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
	END


		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
		WHERE
			ThreadID = @ThreadID

	--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_weblog_Search
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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.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: 4/14/2008 11:35:01 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: 4/14/2008 11:35:02 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 w
Set
	w.MostRecentPostID = P.PostID,
	w.MostRecentPostDate = P.UserTime,
	w.MostRecentPostName = P.PostName,
	w.MostRecentPostAuthorID = P.UserID,
	w.MostRecentPostAuthor = P.PostAuthor,
	w.MostRecentPostSubject = P.Subject
FROM
	cs_weblog_Weblogs w
inner join (
		Select Max(px.PostID) as PostID, px.SectionID
		FROM cs_Posts px
		where px.ApplicationPostType = 1 and px.IsApproved = 1 and px.UserTime <= getdate() and px.SettingsID = @SettingsID
		Group by px.SectionID
	) sub
	ON w.SectionID = sub.SectionID
inner join
	cs_Posts P on P.PostID = sub.PostID
where
	w.SettingsID = @SettingsID



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


--Update Count Items
update w
set
	w.PostCount = p.[PostCount]
	, w.ArticleCount = p.[ArticleCount]
	, w.CommentCount = p.[CommentCount]
	, w.TrackbackCount = p.[TrackbackCount]
from
	cs_weblog_Weblogs w
inner join (
	Select
		px.SectionID
		, sum(case when px.ApplicationPostType = 1 then 1 else 0 end) [PostCount]
		, sum(case when px.ApplicationPostType = 2 then 1 else 0 end) [ArticleCount]
		, sum(case when px.ApplicationPostType = 4 then 1 else 0 end) [CommentCount]
		, sum(case when px.ApplicationPostType = 8 then 1 else 0 end) [TrackbackCount]
	FROM
		cs_Posts px
	where
		px.SettingsID = @SettingsID
		AND px.IsApproved = 1
	group by
		px.SectionID
) as p
ON
	w.SectionID = p.SectionID
where
	w.SettingsID = @SettingsID


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


-- Update any hubs that have weblogs
UPDATE
	H
SET
	H.MostRecentPostID = W.MostRecentPostID,
	H.MostRecentPostAuthorID = W.MostRecentPostAuthorID,
	H.MostRecentPostSubject = W.MostRecentPostSubject,
	H.MostRecentPostAuthor = W.MostRecentPostAuthor,
	H.MostRecentPostDate = W.MostRecentPostDate
FROM
	cs_Sections H
inner join (
		Select S.HubSectionID, S.SectionID FROM cs_Sections S
		where S.ApplicationType = 1 and S.HubSectionID > 0 and S.SettingsID = @SettingsID
		Group by S.SectionID, S.HubSectionID
	) sub ON H.SectionID = sub.HubSectionID
inner join
	cs_weblog_Weblogs W
	ON W.SectionID = sub.SectionID
where
	H.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_weblog_Weblogs_Get
* File Date: 4/14/2008 11:35:02 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.[EnableAnonymousPosting], F.[MostRecentThreadID], F.[MostRecentThreadReplies], F.[PostsToModerate], F.[ForumType], F.[IsSearchable], F.[ApplicationType], F.[ApplicationKey], 
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.[DefaultLanguage], F.[DiskUsage], W.*,
	null as	LastUserActivity, F.IsPublic, F.HubSectionID
		
FROM
	cs_Sections F, cs_weblog_Weblogs W
WHERE
	F.SettingsID = @SettingsID AND
	 ApplicationType = 1 AND F.SectionID = W.SectionID


exec cs_Section_Permissions_Get @SettingsID, 0, 1









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Weblogs_Get] to public
go
/***********************************************
* Sproc: forums_Threads_GetThreadSet
* File Date: 4/14/2008 11:35:01 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: 4/14/2008 11:35:01 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: mg_EmailQueue_Delete
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...mg_EmailQueue_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON dbo.mg_EmailQueue_Delete TO public
GO
/***********************************************
* Sproc: mg_EmailQueue_Failure
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...mg_EmailQueue_Failure'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

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

GRANT EXECUTE on dbo.mg_EmailQueue_Failure TO public
GO
/***********************************************
* Sproc: mg_Emails_Dequeue
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...mg_Emails_Dequeue'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



CREATE    PROCEDURE [dbo].mg_Emails_Dequeue
(
  @MessageLimit int=1000,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

  if @MessageLimit > 0
  begin
    SET ROWCOUNT @MessageLimit
  end

	SELECT * FROM mg_EmailQueue Where SettingsID = @SettingsID and NextTryTime < getdate() order by NextTryTime asc
	
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].mg_Emails_Dequeue to public
go
/***********************************************
* Sproc: mg_Emails_Enqueue
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...mg_Emails_Enqueue'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

	INSERT INTO
		mg_EmailQueue
		(
			EmailXml,
			SettingsID,
			NextTryTime
		)
	VALUES
		(
			@EmailXml,
			@SettingsID,
			getdate()
		)		
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].mg_Emails_Enqueue to public
go
/***********************************************
* Sproc: spam_GetRecentPostCountFromIP
* File Date: 4/14/2008 11:35:01 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(64),
	@Duration	int,
	@SettingsID	int
)
AS
	SELECT	COUNT(*)
	FROM	cs_Posts
	WHERE	SettingsID = @SettingsID AND
			IPAddress = @IPAddress AND
			PostDate > DATEADD(s, -@Duration, GETDATE())

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[spam_GetRecentPostCountFromIP] TO PUBLIC
GO
