	CREATE TABLE	#PostSet		(PostID int)
	CREATE TABLE	#ReplyData		(PostID int, ReplyCount int, ReplierCount int)
	CREATE TABLE	#RatingData		(PostID int, RatingSum int)
	CREATE TABLE	#DownloadData	(PostID int, DownloadCount int, DownloaderCount int)
	CREATE TABLE	#FavoriteData	(PostID int, Value int)


	-- get working post set
	INSERT INTO	#PostSet
				(PostID)
	EXECUTE		cs_Posts_GetPostIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get post's reply statistics
	INSERT INTO	#ReplyData
				(PostID, ReplyCount, ReplierCount)
	SELECT		PP.PostID, COUNT(P.PostID), COUNT(DISTINCT(P.UserID))
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.PostID = P.ParentID
	INNER JOIN	#PostSet PS
		ON		PP.PostID = PS.PostID
	WHERE		PP.SettingsID = @SettingsID
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
	GROUP BY	PP.PostID


	-- get post's rating statistics
	INSERT INTO	#RatingData
				(PostID, RatingSum)
	SELECT		PR.PostID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		PR.PostID = PS.PostID
	WHERE		PR.SettingsID = @SettingsID
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.PostID


	-- get post's download statistics
	INSERT INTO	#DownloadData
				(PostID, DownloadCount, DownloaderCount)
	SELECT		D.PostID, COUNT(D.PostID), COUNT(DISTINCT(D.UserID))
	FROM		files_Downloads D
	INNER JOIN	cs_Posts P
		ON		D.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		D.PostID = PS.PostID
	WHERE		P.SettingsID = @SettingsID
		AND		D.UserID <> P.UserID		-- ignore self-downloads
	GROUP BY	D.PostID


	-- get post's favorite count
	INSERT INTO	#FavoriteData
				(PostID, Value)
	SELECT		FP.PostID, COUNT(FP.PostID)
	FROM		cs_FavoritePosts FP
	INNER JOIN	cs_Posts P
		ON		FP.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		FP.PostID = PS.PostID
	WHERE		FP.SettingsID = @SettingsID
		AND		FP.OwnerID <> P.UserID
	GROUP BY	FP.PostID


	-- disable triggers (nntp triggers make this update deathly SLOW!)
	ALTER TABLE cs_posts DISABLE TRIGGER ALL


	-- update post points
	UPDATE		P
	SET			Points =
				1 * @PostFactor
				+ ISNULL(RPD.ReplyCount, 0) * @ReplyFactor
				+ ISNULL(RPD.ReplierCount, 0) * @ReplierFactor
				+ ISNULL(RTD.RatingSum, 0) * @RatingFactor
				+ ISNULL(DD.DownloadCount, 0) * @DownloadFactor
				+ ISNULL(DD.DownloaderCount, 0) * @DownloaderFactor
				+ ISNULL(FD.Value, 0) * @FavoritePostFactor,
				PointsUpdated = GETDATE()
	FROM		cs_Posts P
	INNER JOIN	#PostSet PS
		ON		P.PostID = PS.PostID
	LEFT JOIN	#ReplyData RPD
		ON		P.PostID = RPD.PostID
	LEFT JOIN	#RatingData RTD
		ON		P.PostID = RTD.PostID
	LEFT JOIN	#DownloadData DD
		ON		P.PostID = DD.PostID
	LEFT JOIN	#FavoriteData FD
		ON		P.PostID = FD.PostID
	WHERE		P.SettingsID = @SettingsID


	-- enable triggers
	ALTER TABLE cs_posts ENABLE TRIGGER ALL


	-- clean up
	DROP TABLE	#FavoriteData
	DROP TABLE	#DownloadData
	DROP TABLE	#RatingData
	DROP TABLE	#ReplyData
	DROP TABLE	#PostSet


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

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

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser
--	Calculates the points for a user
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser]
(
	@SettingsID			int,
	@UserID				int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- get user's post points
	DECLARE		@PostPoints		int
	SELECT		@PostPoints = ISNULL(SUM(P.Points), 0)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		P.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- get user's favorite count
	DECLARE		@FavoriteUserCount	int
	SELECT		@FavoriteUserCount = COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	WHERE		FU.UserID = @UserID
		AND		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites


	-- get user's rating sum
	DECLARE		@RatingSum	int
	SELECT		@RatingSum = ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		PR.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating


	-- update user points
	UPDATE		UP
	SET			Points =
					1 * @PostPoints
					+ @FavoriteUserCount * @FavoriteUserFactor
					+ @RatingSum * @RaterFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	WHERE		UP.UserID = @UserID
		AND		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_Points_CalculateForUser_Set
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForUser_Set'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser_Set]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser_Set]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser_Set
--	Calculates the points for a user set
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser_Set]
(
	@SettingsID			int,
	@FilterType			int,
	@FilterValue		varchar(255),
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- declare temp structures
	CREATE TABLE	#UserSet		(UserID int)
	CREATE TABLE	#PostData		(UserID int, Value int)
	CREATE TABLE	#FavoriteData	(UserID int, Value int)
	CREATE TABLE	#RatingData		(UserID int, Value int)


	-- get working user set
	INSERT INTO	#UserSet
				(UserID)
	EXECUTE		cs_Users_GetUserIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get user's post points
	INSERT INTO	#PostData
				(UserID, Value)
	SELECT		P.UserID, SUM(P.Points)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		P.UserID = US.UserID
	WHERE		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
	GROUP BY	P.UserID


	-- get user's favorite count
	INSERT INTO	#FavoriteData
				(UserID, Value)
	SELECT		FU.UserID, COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	INNER JOIN	#UserSet US
		ON		FU.UserID = US.UserID
	WHERE		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites
	GROUP BY	FU.UserID


	-- get user's rating sum
	INSERT INTO	#RatingData
				(UserID, Value)
	SELECT		PR.UserID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		PR.UserID = US.UserID
	WHERE		(PR.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.UserID


	-- update user points
	UPDATE		UP
	SET			Points =
					ISNULL(PD.Value, 0)	* 1
					+ ISNULL(FD.Value, 0) * @FavoriteUserFactor
					+ ISNULL(RD.Value, 0) * @RaterFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	INNER JOIN	#UserSet US
		ON		UP.UserID = US.UserID
	LEFT JOIN	#PostData PD
		ON		UP.UserID = PD.UserID
	LEFT JOIN	#FavoriteData FD
		ON		UP.UserID = FD.UserID
	LEFT JOIN	#RatingData RD
		ON		UP.UserID = RD.UserID
	WHERE		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


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


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_PostAttachment
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_PostAttachment'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create procedure [dbo].cs_PostAttachment
(
	@PostID int,
	@MetaOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	if(@MetaOnly = 0)
	Begin

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

	End
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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











CREATE procedure dbo.cs_PostAttachment_Add 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			Content		= @Content,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height] 	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
	end
	else
	begin
		INSERT INTO 
			cs_PostAttachments
		(
			PostID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			[Height],
			[Width]
		)
		VALUES
		(
			@PostID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			@Height,
			@Width
		)
	end
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.cs_PostAttachment_Delete
(
	@PostID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @SettingsID int
	DECLARE @SectionID int

	SELECT @SettingsID = SettingsID, @SectionID = SectionID FROM cs_PostAttachments WHERE PostID = @PostID

	DELETE FROM cs_PostAttachments WHERE PostID = @PostID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_PostAttachment_Temp_Create
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE Procedure [dbo].cs_PostAttachment_Temp_Create
(
	@UserID int,
	@SettingsID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@AttachmentID uniqueidentifier,
	@Height int = 0,
	@Width int = 0
)

as
SET Transaction Isolation Level Read UNCOMMITTED

		INSERT INTO 
		cs_PostAttachments_TEMP
		(
			AttachmentID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			Created,
			[Height],
			[Width]
		)
		VALUES
		(
			@AttachmentID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			getdate(),
			@Height,
			@Width
		)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_PostAttachment_Temp_Expire
* File Date: 8/8/2006 9:28:14 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Expire'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.cs_PostAttachment_Temp_Expire
(
	@Date datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DELETE FROM cs_PostAttachments_TEMP WHERE Created < @Date

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE procedure [dbo].[cs_PostAttachment_Temp_Get] 
(
	@UserID int,
	@SectionID int,
	@AttachmentID uniqueidentifier,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

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

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE procedure dbo.cs_PostAttachment_ToggleTemporary 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@ClearContent bit,
	@FriendlyFileName nvarchar(256),
	@AttachmentID uniqueidentifier,
	@SettingsID int,
	@DeleteTempOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

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

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

	IF(@DeleteTempOnly = 0)
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
		BEGIN
			UPDATE cs_PostAttachments SET
				cs_PostAttachments.[FileName] 	= T.[Filename],
				cs_PostAttachments.[FriendlyFileName] = IsNull(@FriendlyFileName,T.FriendlyFileName),
				cs_PostAttachments.ContentSize	= T.ContentSize,
				cs_PostAttachments.IsRemote	= T.IsRemote,
				cs_PostAttachments.Height	= T.Height,
				cs_PostAttachments.Width	= T.Width,
				cs_PostAttachments.Content = T.Content,
				cs_PostAttachments.ContentType = T.ContentType,
				cs_PostAttachments.Created = T.Created,
				cs_PostAttachments.UserID = T.UserID
			FROM cs_PostAttachments_TEMP T
			WHERE
				cs_PostAttachments.PostID = @PostID and
				cs_PostAttachments.SettingsID = @SettingsID and
				T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID and T.UserID = @UserID and T.SectionID = @SectionID
		END
		ELSE
		BEGIN
			INSERT INTO 
			cs_PostAttachments
			(
				PostID,
				SectionID,
				UserID,
				[FileName],
				[FriendlyFileName],
				Content,
				ContentType,
				ContentSize,
				IsRemote,
				SettingsID,
				Created,
				[Height],
				[Width]
			)
			Select @PostID,	T.SectionID,T.UserID,T.[Filename],IsNull(@FriendlyFileName,T.FriendlyFileName),T.Content, T.ContentType,
				T.ContentSize,	T.IsRemote, T.SettingsID,T.Created, T.Height, T.Width
			FROM cs_PostAttachments_TEMP T
			WHERE T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID and T.UserID = @UserID and T.SectionID = @SectionID
		END
	END

	DELETE FROM cs_PostAttachments_TEMP where AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

create procedure [dbo].cs_PostAttachment_Update 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@MetaDataOnly bit,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height]	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	

		if(@MetaDataOnly = 0)
		Begin
			UPDATE cs_PostAttachments SET
			Content		= @Content
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
		End
	end
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_PostCategories_Get
	@SectionID int=0,
	@ApplicationKey nvarchar(256)=null
AS

SET Transaction Isolation Level Read UNCOMMITTED


if @ApplicationKey Is Not Null
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	LEFT JOIN cs_Sections F ON F.SectionID = C.SectionID
	WHERE F.ApplicationKey = @ApplicationKey
end
else
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	WHERE C.SectionID = @SectionID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_PostCategories_Get_ByName
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
Print 'Creating...cs_PostCategories_Get_ByName'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

CREATE PROCEDURE dbo.cs_PostCategories_Get_ByName
	@Name nvarchar(256),
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

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

SELECT
	C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
	C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.[Name] = @Name
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_PostCategories_Get_WithoutPosts
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
Print 'Creating...cs_PostCategories_Get_WithoutPosts'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

CREATE PROCEDURE dbo.cs_PostCategories_Get_WithoutPosts
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

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

SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.CategoryID not in (
		select CategoryID
		from cs_Posts_InCategories PiC
		inner join cs_Posts P on P.PostID = PiC.PostID
		where P.SectionID in (select SectionID from #Sections)
			and P.SettingsID = @SettingsID
		)
	and C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.CategoryID not in (
		select UpLevelID
		from cs_Post_Categories_Parents
		where SectionID in (select SectionID from #Sections)
			and UpLevelID <> CategoryID
		)	

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

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].[cs_PostCategories_Parents_RebuildIndex] @SectionID INT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Create some temporary storage for the update
	DECLARE @pathtable TABLE(
		CategoryID int not null,
		UpLevelID int not null,
		[path] varchar(255),
		SectionID int not null,
		unique (CategoryID, UpLevelID))
	
	--Fix any orphaned categories
	UPDATE cs_Post_Categories SET ParentID = 0 WHERE CategoryID IN (SELECT CategoryID FROM cs_Post_Categories WHERE ParentID <> 0 AND ParentID NOT IN (SELECT CategoryID FROM cs_Post_Categories))

	IF @SectionID IS NULL
	BEGIN

		--every post category is at least in itself
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/' FROM cs_Post_Categories
		
		--Get all the non parents parents
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0
	

		--Recurse until we have reached the root for all
		WHILE @@Rowcount > 0
		BEGIN
			
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT  C.SectionID, P.CategoryID, C.ParentID,  RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL

		END
	

	END
	ELSE
	BEGIN
		--every post category is at least in itself (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE SectionID = @SectionID

		--Get all the non parents parents (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0 AND SectionID = @SectionID

		--Recurse until we have reached the root for all (for this section)
		WHILE @@Rowcount > 0
		BEGIN
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT C.SectionID, P.CategoryID, C.ParentID,   RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL AND C.SectionID = @SectionID
		END
	END

	--Recalculate category stats for selected section
	UPDATE cs_Post_Categories SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	INNER JOIN (
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN @pathtable P ON PIC.CategoryID = P.CategoryID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID

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

	INNER JOIN (
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID

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

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

	--Rebuild the path (for legacy support, this value is not currently used by the galleries)

	SELECT P.CategoryID, P.[Path] from @pathtable P JOIN cs_Post_Categories C on P.UplevelID = C.CategoryID and C.ParentID = 0

	--Commit the new path to the Categoies table
	UPDATE cs_Post_Categories SET cs_Post_Categories.[Path] = NewPath.[path] from cs_Post_Categories 
		JOIN 
			(SELECT P.CategoryID, P.[Path] FROM @pathtable P 
				JOIN cs_Post_Categories C ON P.UplevelID = C.CategoryID AND C.ParentID = 0
			) NewPath ON cs_Post_Categories.CategoryID = NewPath.CategoryID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE PROCEDURE [dbo].[cs_PostCategory_CreateUpdateDelete]
	@DeleteCategory bit=0,
	@SectionID int=0,
	@Name nvarchar(256)='',
	@IsEnabled bit=1,
	@ParentID int=0,
	@Description nvarchar(2000)=null,
	@SettingsID int,
	@FeaturedPostID int = null,
	@CategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting?
if @DeleteCategory = 1
begin
	DELETE FROM cs_Posts_InCategories WHERE CategoryID = @CategoryID
	DELETE FROM [cs_Post_Categories_Parents] WHERE CategoryID = @CategoryID
	DELETE FROM cs_Post_Categories WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID
	RETURN
end

-- Find out the new path
declare @Path nvarchar(255)
set @Path = isnull((select Path + convert(nvarchar, CategoryID) + '/' from cs_Post_Categories where CategoryID = @ParentID and SectionID = @SectionID and SettingsID = @SettingsID), '/')

-- Are we updating?
if @CategoryID > 0
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID AND CategoryID <> @CategoryID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	UPDATE cs_Post_Categories SET
		Name = @Name,
		IsEnabled = @IsEnabled,
		ParentID = @ParentID,
		Description = @Description,
		Path = @Path,
		FeaturedPostID = @FeaturedPostID
	WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	INSERT INTO cs_Post_Categories (SectionID, Name, IsEnabled, ParentID, [Description], [Path], SettingsID, FeaturedPostID)
		VALUES (@SectionID, @Name, @IsEnabled, @ParentID, @Description, @Path, @SettingsID, @FeaturedPostID)
	set @CategoryID = SCOPE_IDENTITY()
end
EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID

GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_PostMetadata_Get
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_PostMetadata_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.cs_PostMetadata_Get
	@PostID int,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

select MetaKey, MetaType, MetaValue from cs_PostMetadata where PostID = @PostID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.cs_PostMetadata_Update
	@PostID int,
	@MetadataList ntext,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
delete from cs_PostMetadata where PostID = @PostID

if @MetadataList is null --or len(ltrim(rtrim(@MetadataList))) = 0
return

declare @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @MetadataList

insert into cs_PostMetaData (PostID, MetaKey, MetaType, MetaValue)
	select @PostID, M.[key], M.[type], M.[value]
	from openxml(@idoc, '/entries/entry', 1)
		with ([key] nvarchar(100), [type] nvarchar(100), [value] nvarchar(100)) as M

EXEC sp_xml_removedocument @idoc
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


Create Proc [dbo].cs_posts_AddAuditDeletedPostContent
(
	@PostID int = -1,
	@UserID int  = -1,
	@SectionID int = -1,
	@SettingsID int = -1,
	@ApplicationType int = 9999,
	@ParentID int = -1,
	@ThreadID int = -1,
	@PostType int = -1,
	@PostLevel int = -1,
	@Body ntext = null,
	@Subject nvarchar(500) = null,
	@IPAddress nvarchar(50) = null
)

as

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_posts_AddAuditDeletedPostContent to public
GO
/***********************************************
* Sproc: cs_Posts_GetPostIDByFilter
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
Print 'Creating...cs_Posts_GetPostIDByFilter'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Posts_GetPostIDByFilter
--	Returns a list of filtered PostIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Posts_GetPostIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@PostSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of post set
		SET @PostSetSize = CONVERT(int, @FilterValue)

		-- limit number of posts to work with (non-positive = ALL)
		IF @PostSetSize > 0
			SET ROWCOUNT @PostSetSize

		-- get posts to work with
		SELECT		P.PostID
		FROM		cs_Posts P
		INNER JOIN	cs_Sections S				-- exclude private messages
			ON		P.SectionID = S.SectionID
		WHERE		P.SettingsID = @SettingsID
			AND		S.EnablePostPoints = 1		-- ignore excluded sections
			AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		ORDER BY	P.PointsUpdated				-- start with "stalest" posts

		-- limit has been used; reset to default
		IF @PostSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE PROCEDURE dbo.cs_Posts_GetPostInCategories
	@PostID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	C.*
FROM cs_Posts_InCategories P
RIGHT JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
WHERE P.PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_Posts_GetPostsInNoCategories
* File Date: 8/8/2006 9:28:14 AM
***********************************************/
Print 'Creating...cs_Posts_GetPostsInNoCategories'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE PROCEDURE dbo.cs_Posts_GetPostsInNoCategories
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues
FROM cs_Posts P
WHERE P.SectionID = @SectionID
	AND P.ParentID = P.PostID
	AND P.PostID NOT IN ( SELECT PostID FROm cs_Posts_InCategories )
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByUser]
(
	@UserID	int
)
AS
	-- first, reset post to be indexed
	UPDATE	cs_Posts
	SET		IsIndexed =  0
	WHERE	UserID = @UserID

	-- step 2, add post to reindex table
	INSERT INTO	cs_es_Search_RemoveQueue (PostID, SettingsID)
	SELECT		PostID, SettingsID
	FROM		cs_Posts
	WHERE		UserID = @UserID
		AND		PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  Proc [dbo].cs_Posts_UpdatePostsInCategories
(
	@CategoryList nvarchar(4000) = null,
	@SectionID int,
	@PostID int,
	@SettingsID int = null,
	@UpdateStats bit = 1
)
as

DELETE FROM cs_Posts_InCategories where PostID = @PostID

-- If the post is not in any categories, we have to rebuild the index incase we are deleting a post or removing categories
IF @CategoryList Is Not Null AND LEN(LTRIM(RTRIM(@CategoryList))) > 0
BEGIN
	DECLARE @idoc int
	-- declare @CategoryList nvarchar(4000)
	-- select @CategoryList = "<?xml version=""1.0"" ?><Categories><Category>Test</Category></Categories>"

	EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList

	DECLARE @CategoryIDList TABLE
	(
		CategoryID Int
	)

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

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

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

if(@UpdateStats = 1) --for changes we need to rebuild the entire section stats
Begin
	UPDATE cs_Post_Categories SET
		TotalSubThreads = IsNull(QSUB.posts, 0),
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = IsNull(QCURR.posts, 0),
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	LEFT  JOIN (
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories_Parents P ON PIC.CategoryID = P.CategoryID and P.SectionID = @SectionID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY P.UpLevelID
	) QSUB ON cs_Post_Categories.CategoryID = QSUB.CategoryID

	LEFT  JOIN (
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID
	WHERE cs_Post_Categories.SectionID = @SectionID
End

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

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

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

End


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

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

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

Create Proc [dbo].cs_Posts_Views_Add
(
	@PostID int,
	@AggCount int,
	@WebCount int
)

as
SET Transaction Isolation Level Read UNCOMMITTED

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

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

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




CREATE  PROCEDURE [dbo].cs_Post_CreateUpdate
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
 	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime = null,
	@UserHostAddress nvarchar(32),
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int, 
	@IsTracked bit = 0,
	@PostID int out,
	@ThreadID int=0 out,
	@PostConfiguration int = 0,
	@UpdateSectionStatistics bit = 1,
	@UserTime datetime = null,
	@ApplicationPostType int,
	@PostName nvarchar(256) =  null,
	@ThreadStatus int = 0,
	@Points int = 0,
	@PostDisplayName nvarchar(64) = null,
	@AutoApprove bit = 0
) 
AS
/*
	stored procedure cs_Post_CreateUpdate
	* Procedure now creates new threads here, from an identity column in cs_Threads.
	* To update a Post, ParentID must not equal 0.
	* To delete a post, use forums_Moderate_Posts_Move to move it to the Deleted Forum
  * Default value for ThreadStatus is Not Set (0)
*/

SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @ModeratedForum bit
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @ContextUserID int
DECLARE @ContextPostAuthor nvarchar(64)

-- Set 'not set' for Sticky and Anouncement posts
IF ((@IsSticky = 1) OR ((@IsLocked = 1) AND ( @StickyDate > DATEADD( Year, 2, getdate() ) )))
	SET @ThreadStatus = 0 -- not set value

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

IF @UserTime IS NULL
	SET @UserTime = GetDate()

-- Get the real username for poster
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser  
	WHERE 
		cs_UserID = @UserID and SettingsID = @SettingsID

-- Check if this is an anonymous post (value = 1)
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Anonymous ID
	SELECT @ContextUserID = cs_UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1

	-- Set the username
	IF(@PostAuthor is not null)
	begin
		SET @ContextPostAuthor = @PostAuthor
	end
	else
	begin
		SET @ContextPostAuthor = ''
	end
END
ELSE
BEGIN
	-- Set the real user ID
	SET @ContextUserID = @UserID

	IF(@PostDisplayName is not null)
	Begin
		-- Set the real username
		SET @ContextPostAuthor = @PostDisplayName
	END
	ELSE
	BEGIN
		SET @ContextPostAuthor = @PostAuthor
	END
END

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

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

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

-- Is this forum moderated?
SELECT 
	@ModeratedForum = IsModerated, @EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID

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

IF @AutoApprove = 1
BEGIN
	SET @IsApproved = 1
END
ELSE IF @IsApproved = 1 AND @ModeratedForum = 1 AND @SectionID <> 0
BEGIN
	-- ok, this is a moderated forum.  Is this user trusted?  If he is, then the post is approved ; else it is not
	SET @IsApproved = ( 
		SELECT
			ModerationLevel
		FROM
			cs_UserProfile (nolock)
		WHERE
			UserID = @UserID and SettingsID = @SettingsID )
END


-- EAD: Modifying this sproc to insert directly into cs_Threads.  We are no longer keying
-- cs_Threads.ThreadID to be same number as the top PostID for the thread.  This is to allow
-- for the FKs to be put into place.

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

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

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

	-- Get the new ThreadID
	SELECT 
		@ThreadID = @@IDENTITY
	--FROM
		--cs_Threads
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 

		Body, 

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

	-- Get the new PostID
	SELECT 
		@PostID = @@IDENTITY
--	FROM
--		cs_Posts

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

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

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

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

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

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

		SET @MaxSortOrder = @NextSortOrder

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

	END 

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


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1
	BEGIN		
		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = @@IDENTITY 
--		FROM 
--			cs_Posts

		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		Select @StickyDate = StickyDate FROM cs_Threads where ThreadID = @ThreadID and SettingsID = @SettingsID

		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			MostRecentPostAuthor = @ContextPostAuthor,
			MostRecentPostAuthorID = @ContextUserID,
			MostRecentPostID = @PostID,
			TotalReplies = TotalReplies + 1, -- (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
			IsLocked = @IsLocked,
			StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
	END
	ELSE
	BEGIN
		-- Moderated Posts: get the new PostID
		SELECT @PostID = @@IDENTITY 
	END

	-- Clean up ThreadsRead (this should work very well now)
	DELETE
		cs_ThreadsRead
	WHERE
		ThreadID = @ThreadID 
		AND UserID != @UserID and SettingsID = @SettingsID
END


-- Update the users tracking for the new post (if needed)
SELECT 
	@TrackThread = EnableThreadTracking 
FROM 
	cs_UserProfile (nolock) 
WHERE 
	UserID = @UserID and SettingsID = @SettingsID

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

COMMIT TRAN
BEGIN TRAN

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

-- Update the forum statitics
IF @SectionID > 0 AND @UserID > 0
BEGIN
	IF @IsApproved = 1 AND @EnablePostStatistics = 1
	BEGIN
		EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
	END

	IF @UpdateSectionStatistics = 1
	BEGIN
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 1, @PostDisplayName
	END
END


COMMIT TRAN
SET NOCOUNT OFF

SELECT @PostID = @PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Post_Delete
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_Post_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

CREATE PROCEDURE dbo.cs_Post_Delete
(
	@SectionID int,
	@SettingsID int,
	@PostID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
-- Permanently deletes one post at a time and eventually its thread.
-- If the post has some replies then subsequent calls are made till all the tree's nodes and leafs are removed.
-- Also if the post is level 1 then we can delete the thread itself without any other checkings.

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostLevel INT
DECLARE @ThreadID INT
DECLARE @HasReplies INT

-- Figure out if this is a thread starter post, who is its thread and if it has some replies
--------------------------------------------------------------------------------
SELECT 
	@PostLevel = PostLevel,
	@ThreadID = ThreadID	
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID AND
	SectionID = @SectionID AND
	SettingsID = @SettingsID

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SectionID = @SectionID AND SettingsID = @SettingsID)
--------------------------------------------------------------------------------

-- Is a starter thread post?
IF (@PostLevel = 1)
BEGIN
	-- Easy job: delete the thread and its content with statistics update
	--------------------------------------------------------------------------------
	EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, @ResetStatistics, @DeletedBy, ''

	RETURN 1
	--------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- This is not a thread starter post, so we have to delete it carefully

	-- Delete parent post
	--------------------------------------------------------------------------------	
	DELETE FROM cs_PostAttachments WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_PostEditNotes WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts_InCategories WHERE PostID = @PostID AND SettingsID = @SettingsID
		
	DELETE FROM cs_PostsArchive WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID  AND ThreadID = @ThreadID AND PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts WHERE PostID = @PostID AND ThreadID = @ThreadID AND SectionID = @SectionID AND SettingsID = @SettingsID
	
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been permanently deleted on request.'

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

	-- Do we have some replies?
	--------------------------------------------------------------------------------	
	IF (@HasReplies > 0)
	BEGIN
		-- There should be some replies/children bound to this post.
		-- Get replying posts one by one through a local cursor and call its removal.

		DECLARE @CurrentPostID INT

		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @ThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID

		OPEN Posts_Cursor
		
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID

		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call with no statistics update
			EXEC cs_Post_Delete @SectionID, @SettingsID, @CurrentPostID, 0, @DeletedBy, @Reason

			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END

		CLOSE Posts_Cursor

		DEALLOCATE Posts_Cursor		
	END
	--------------------------------------------------------------------------------	
	
	-- Update statistics?
	--------------------------------------------------------------------------------	
	IF (@ResetStatistics = 1)
	BEGIN
		EXEC cs_system_ResetThreadStatistics @ThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	--------------------------------------------------------------------------------	

	RETURN 1
END

END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetAuthorID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetAuthorID]
GO
--------------------------------------------------------------------------------
--	cs_Post_GetAuthorID
--	Returns a post author's userID
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Post_GetAuthorID]
(
	@SettingsID	int,
	@PostID		int,
	@UserID		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- lookup author for post
	SELECT	@UserID = P.UserID
	FROM	cs_Posts P
	WHERE	P.PostID = @PostID
		AND	P.SettingsID = @SettingsID


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_Post_GetPageIndex
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_Post_GetPageIndex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE   PROCEDURE dbo.cs_Post_GetPageIndex
(
	@PostID int,
	@PageSize int,
	@SortBy int,
	@SortOrder bit,
	@AllowUnapproved bit = 0,
	@SettingsID int
)
AS

DECLARE @ThreadID int
SELECT @ThreadID = ThreadID FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

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

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY PostDate DESC

-- Sort by Author
IF @SortBy = 1 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID

ELSE IF @SortBy = 1 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID DESC

-- Sort by SortOrder
IF @SortBy = 2 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder

ELSE IF @SortBy = 2 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder DESC

SELECT (IndexID / @PageSize) + 1 AS PageIndex FROM #PageIndex WHERE PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/***********************************************
* Sproc: cs_Post_ToggleSettings
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_Post_ToggleSettings'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE   procedure [dbo].cs_Post_ToggleSettings
(
	@PostID int,
	@IsAnnouncement bit,
	@IsLocked bit,
	@ModeratorID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @CurrentLockState bit
	DECLARE @CurrentAnnouncementState bit
	
	DECLARE @ThreadID int
	DECLARE @PostLevel int
	SELECT 
		@ThreadID = ThreadID, 
		@PostLevel = PostLevel 
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

-- Is this a thread
IF @PostLevel =1
BEGIN
	print 'Toggling settings on a thread.'

	-- Get the current state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Threads 
	WHERE 
		ThreadID = @ThreadID

	-- Get current is announcement state of the thread
	IF EXISTS (	SELECT 
				ThreadID 
			FROM 
				cs_Threads
			WHERE
				ThreadID = @ThreadID 
				AND IsSticky = 1
				AND StickyDate > DateAdd( y, 20, GetDate() )
			)

		SET @CurrentAnnouncementState = 1
	ELSE
		SET @CurrentAnnouncementState = 0
		

	-- Is the Post getting locked?
	IF @CurrentLockState != @IsLocked
	BEGIN
		UPDATE
			cs_Threads
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		UPDATE
			cs_Posts
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		IF @IsLocked = 0
		BEGIN
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
		END
        		ELSE
		BEGIN
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
		END
	END


	-- Is the post an Annoucement
	IF @CurrentAnnouncementState != @IsAnnouncement
		IF @IsAnnouncement = 1
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 1,
				StickyDate = DateAdd(y, 25, ThreadDate)
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 16, @ModeratorID, @PostID, null, null, @SettingsID
	
		END
		ELSE
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 0,
				StickyDate = ThreadDate
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 17, @ModeratorID, @PostID, null, null, @SettingsID
		END
END
ELSE
	print 'Toggling settings on a post.'

	-- Get the current lock state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

	-- UPDATE The child posts
	UPDATE
	   	cs_Posts
	SET
		IsLocked = @IsLocked
	WHERE
		ParentID = @PostID
	
	IF @IsLocked != @CurrentLockState
		IF @IsLocked = 0
		  exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
	        ELSE
		  exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].cs_Post_Update
(
	@SectionID	int = null,
	@PostID	int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsAnnouncement bit,
	@EditedBy	int,
	@EditNotes	ntext = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@PostConfiguration int = 0,
	@PostName nvarchar(256) =  null,
	@IsApproved bit = null,
	@Points int = 0,
	@PostMedia int = null,
	@PostDate datetime = null,
	@PostStatus int = null,
	@SpamScore int = null
)
AS
	-- This sproc updates a post

	DECLARE @ThreadID int
	DECLARE @CurrentStickyDate datetime
	DECLARE @ParentID int
	--DECLARE @CurrentIsSticky BIT
	--DECLARE @CurrentSubject NVARCHAR(256)
	--DECLARE @StickyHasRemoved BIT
	--DECLARE @SubjectHasChanged BIT
	
	-- Get the thread and postdate this applies to
	SELECT 
		@ThreadID = P.ThreadID,
		@CurrentStickyDate = T.StickyDate,
		@ParentID = P.ParentID,
		@SectionID = P.SectionID
		--@CurrentIsSticky = T.IsSticky,
		--@CurrentSubject = P.Subject
	FROM 
		cs_Posts P
	LEFT JOIN
		cs_Threads T ON T.ThreadID = P.ThreadID
	WHERE 
		P.PostID = @PostID AND P.SettingsID = @SettingsID
	
	-- Check if subject has changed or stickiness has been removed.
	--SET @StickyHasRemoved = 0
	--SET @SubjectHasChanged = 0

	--IF (@IsSticky IS NOT NULL) AND (@IsSticky = 0) AND (@CurrentIsSticky = 1)
	--	SET @StickyHasRemoved = 1		
	
	--IF (@CurrentSubject <> @Subject)		
	--	SET @SubjectHasChanged = 1

	-- Update post's details
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostConfiguration = @PostConfiguration,
		PostName = @PostName,
		Points = @Points,
		IsApproved = IsNull(@IsApproved, IsApproved),
		PostMedia = IsNull(@PostMedia, PostMedia),
		PostStatus = IsNull(@PostStatus, PostStatus),
		SpamScore = IsNull(@SpamScore, SpamScore)
	WHERE 
		PostID = @PostID AND SettingsID = @SettingsID

	if(@PostID = @ParentID AND @IsApproved is not null)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	
	/*
	-- We need not to trigger thread and section stats rebuild if sticky has been 
	-- removed or subject has been changed.
	-- If something else has changed then we will trigger stats rebuild of info 
	-- but not the dates (is the meaning of 0, a new param).

	-- Update most recent info in cs_Threads but not any date
	IF (@ThreadID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0) 
		EXEC cs_system_UpdateThread @ThreadID, @PostID, @SettingsID, 0
	
	-- Update most recent info in cs_Sections but not any date
	IF (@SectionID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0)
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 0
	*/

	IF (@PostStatus IS NOT NULL)
		EXEC cs_Thread_Status_Update @ThreadID, null, @SettingsID

	-- Allow thread to update sticky properties.
	-- Also if this post got locked, then mark the thread locked too
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		DECLARE @ThreadIsLocked BIT
		SET @ThreadIsLocked = (@IsAnnouncement | @IsLocked)
	 
		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID  AND SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @CurrentStickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID AND SettingsID = @SettingsID 		
		END
	END

	IF @EditNotes IS NOT NULL
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostEditNotes WHERE PostID = @PostID)
			UPDATE 
				cs_PostEditNotes
			SET
				EditNotes = @EditNotes
			WHERE	
				PostID = @PostID AND SettingsID = @SettingsID
		ELSE
			INSERT INTO
				cs_PostEditNotes
			VALUES
				(@PostID, @EditNotes, @SettingsID)
	END
	
	IF @PostDate IS NOT NULL
	BEGIN
			UPDATE cs_Posts	SET	PostDate = @PostDate WHERE PostID = @PostID AND SettingsID = @SettingsID
			
			if(@PostID = @ParentID)
			Begin
				Update cs_Threads Set PostDate = @PostDate Where ThreadID = @ThreadID AND SettingsID = @SettingsID
			End
	END

	-- update thread emoticon if this is a thread starter
	IF (@PostID = @ParentID)
	BEGIN
		UPDATE cs_Threads SET ThreadEmoticonID = @EmoticonID WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID
	END
	
	-- Mark thread as not read for anyone but the editor
	DELETE cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID AND UserID <> @EditedBy 

	-- We want to track what happened
	exec cs_system_ModerationAction_AuditEntry 2, @EditedBy, @PostID, NULL, NULL, @SettingsID, @EditNotes

	EXEC cs_system_ResetThreadStatistics @ThreadID
	IF @SectionID > 0	-- passing in "0" will recalculate stats for ALL sections (timeout on large sites)
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = null
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_PrivateMessages_CreateDelete
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_PrivateMessages_CreateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

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

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

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

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_PrivateMessages_UnreadCount]  to public
GO
/***********************************************
* Sproc: cs_Ranks_Get
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_Ranks_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create proc [dbo].cs_Ranks_Get
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT r.*
	FROM
		cs_Ranks r where SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE proc [dbo].cs_Rank_CreateUpdateDelete
(
	@RankID				int out,
	@DeleteRank			bit	= 0,
	@RankName			nvarchar(60),
	@PostingCountMin	int,
	@PostingCountMax	int,	
	@RankIconUrl		nvarchar(512),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the rank
IF( @DeleteRank = 1 )
BEGIN

	DELETE cs_Ranks
	WHERE
		RankID	= @RankID and SettingsID = @SettingsID

	RETURN
END

-- are we updating the rank
IF( @RankID >  0 )
BEGIN

	UPDATE cs_Ranks SET
		  RankName			= @RankName
		, PostingCountMin	= @PostingCountMin
		, PostingCountMax	= @PostingCountMax
		, RankIconUrl		= @RankIconUrl
	WHERE
		  RankID	= @RankID and SettingsID = @SettingsID
		

END
ELSE
BEGIN
	INSERT INTO cs_Ranks (
		RankName, PostingCountMin, PostingCountMax, RankIconUrl, SettingsID
	)
	VALUES( 
		@RankName, @PostingCountMin, @PostingCountMax, @RankIconUrl, @SettingsID
	)

	SET @RankID = @@identity
END

RETURN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_Ratings_Get
(
	@RatingType	int,
	@ItemID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType = 0			-- Post

		SELECT
			U.*,
			'Post' AS RatingType,
			R.PostID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_PostRating R
		WHERE
			R.UserID = U.cs_UserID AND
			R.PostID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID

	ELSE IF @RatingType = 1		-- Thread

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Rating_Add
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_PostRating
			(UserID, PostID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID
	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_ThreadRating
			(UserID, ThreadID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Rating_Get
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@SettingsID	int,
	@Rating		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Setup default value (signifies not rated)
	SET	@Rating	= -1

	IF @RatingType = 0			--Post

		SELECT	@Rating = Rating
		FROM	cs_PostRating
		WHERE	UserID = @UserID
		AND		PostID = @ItemID
		AND		SettingsID = @SettingsID

	ELSE IF @RatingType = 1		--Thread

		SELECT	@Rating = Rating
		FROM	cs_ThreadRating
		WHERE	UserID = @UserID
		AND		ThreadID = @ItemID
		AND		SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure dbo.cs_Rating_Rate
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@Rating		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

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

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

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

	ELSE

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Rating_Update
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int,
	@CurrentRating	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Update the rating
		UPDATE
			cs_PostRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			PostID = @ItemID and SettingsID = @SettingsID

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID
	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Update the rating
		UPDATE
			cs_ThreadRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			ThreadID = @ItemID and SettingsID = @SettingsID

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE Proc [dbo].cs_referrals_Add
(
	@UrlID int,
	@Url nvarchar(512),
	@SettingsID int,
	@SectionID int,
	@PostID int	
)

as
SET Transaction Isolation Level Read UNCOMMITTED

exec cs_Urls_Add @UrlID, @Url

Declare @ReferralID int

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

if(@ReferralID is null)
Begin
	Insert cs_Referrals (SettingsID, SectionID, PostID, UrlID, Hits, LastDate)
	Values (@SettingsID, @SectionID, @PostID, @UrlID, 1, getdate())
End
Else
Begin
	Update cs_Referrals
	Set 
		Hits = Hits + 1,
		LastDate = getdate()
	Where ReferralID = @ReferralID
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE Proc [dbo].cs_referrals_Get
(
	@SettingsID int,
	@SectionID int,
	@PostID int,
	@PageSize int,
	@PageIndex int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


-- are we getting referrals for a single post
IF (@PostID <> -1)
BEGIN

	-- return all referrals (no paging)
	SELECT
		P.Subject,
		R.ReferralID,
		R.SettingsID,
		R.SectionID,
		P.PostID,
		U.Url,
		R.Hits,
		R.LastDate
	FROM
		cs_Referrals R
		INNER JOIN cs_Urls U ON R.UrlID = U.UrlID
		INNER JOIN cs_Posts P ON R.PostID = P.PostID
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID
	ORDER BY
		R.LastDate DESC	

	-- return record count
	SELECT
		@TotalRecords = COUNT(*)
	FROM
		cs_Referrals R
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID

	-- exit immediately
	RETURN
END


-- we are getting referrals for multiple posts (use paging)
DECLARE @RowsToReturn int
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ReferralID int
)

Insert #PageIndex (ReferralID)
Select ReferralID FROM cs_Referrals where SettingsID = @SettingsID and  SectionID = @SectionID order by LastDate desc

-- Reset rowcount and get count of total records
SET ROWCOUNT 0
Select @TotalRecords = count(*) From cs_Referrals Where SettingsID = @SettingsID and SectionID = @SectionID

Select  cs_Posts.Subject,  cs_Referrals.ReferralID, cs_Referrals.SettingsID,  cs_Referrals.SectionID, cs_Posts.PostID, Url, Hits, LastDate
FROM cs_Referrals, cs_Urls, #PageIndex, cs_Posts
Where
	cs_Referrals.ReferralID = #PageIndex.ReferralID and
	cs_Urls.UrlID = cs_Referrals.UrlID and 
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound AND 
	cs_Posts.PostID = cs_Referrals.PostID
Order by IndexID

DROP Table #PageIndex


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



CREATE PROCEDURE [dbo].cs_RemoveAllPostTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.UserID = @UserID AND 
			tt.SettingsID = @SettingsID
				
	ELSE
		DELETE FROM cs_TrackedThreads WHERE UserID = @UserID AND SettingsID = @SettingsID	
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.SettingsID = @SettingsID

	ELSE
		DELETE FROM cs_TrackedThreads WHERE SettingsID = @SettingsID	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE PROCEDURE [dbo].cs_RemoveAllSectionTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)			
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SettingsID = @SettingsID			
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE FROM cs_TrackedSections WHERE SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create proc [dbo].cs_Reports_Get
(
	@ReportID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	FROM
		cs_Reports
	WHERE
		ReportID = @ReportID or
		( 
			@ReportID = 0 AND
			1=1
		) and SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

create proc [dbo].cs_Report_CreateUpdateDelete
(
	  @ReportID			int out
	, @DeleteReport		bit		= 0
	, @ReportName		varchar(20)
	, @Active			bit
	, @ReportCommand	varchar(6500)
	, @ReportScript		ntext
	, @SettingsID 		int
)
AS

IF( @DeleteReport > 0 )
BEGIN
	DELETE cs_Reports
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
	RETURN
END

IF( @ReportID > 0 )
BEGIN
	UPDATE cs_Reports SET
		  ReportName	= @ReportName
		, Active		= @Active
		, ReportCommand	= @ReportCommand
		, ReportScript	= @ReportScript
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
END
ELSE
BEGIN	
	INSERT INTO cs_Reports ( 
		ReportName, Active, ReportCommand, ReportScript, SettingsID 
	) VALUES (
		@ReportName, @Active, @ReportCommand, @ReportScript, @SettingsID
	)	

	SET @ReportID = @@identity
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



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

AS
BEGIN

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

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



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



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

AS
BEGIN

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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_report_GetForumPostReplies
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_report_GetForumPostReplies'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

AS
BEGIN

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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

AS
BEGIN

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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


create procedure [dbo].cs_ReverseTrackingOption 
(
	@UserID int,
	@ThreadID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- reverse the user's tracking options for a particular thread
	-- first get the threadID of the Post

	IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		-- the user is tracking this thread, delete this row
		DELETE FROM cs_TrackedThreads
		WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID
	ELSE
		-- this user isn't tracking the thread, so add her
		INSERT INTO cs_TrackedThreads (ThreadID, UserID, DateCreated, SettingsID)
		VALUES(@ThreadID, @UserID, GetDate(), @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_RoleQuotas_Get
(
	@SettingsID int
)

AS
	/* SET NOCOUNT ON */
	SELECT RoleID, DiskQuota, ImageQuota
	FROM cs_RoleQuotas
	WHERE SettingsID = @SettingsID
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_RoleQuota_CreateUpdateDelete
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_RoleQuota_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_RoleQuota_CreateUpdateDelete
(
	@RoleID uniqueidentifier,
	@DiskQuota bigint = -1,
	@ImageQuota int = -1,
	@SettingsID int
)

AS
	IF @DiskQuota = -1 AND @ImageQuota = -1
		DELETE FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	ELSE
	BEGIN
		DECLARE @Exists bit
	
		SELECT @Exists = COUNT(*) FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
		IF @Exists = 0
			INSERT INTO cs_RoleQuotas (RoleID, DiskQuota, ImageQuota, SettingsID) VALUES (@RoleID, @DiskQuota, @ImageQuota, @SettingsID)
		ELSE
			UPDATE cs_RoleQuotas SET DiskQuota = @DiskQuota, ImageQuota = @ImageQuota WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	END
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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







-- sp_helptext cs_Roles_CreateUpdateDelete


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

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

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

if(@ApplicationId IS NULL)
RETURN
 

IF @RoleID is not null
Begin

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


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

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

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

END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE   procedure [dbo].cs_Roles_Get
(
@UserID int = 0,
@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

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

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


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








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


--We will need to filter all by application name

create procedure [dbo].cs_Role_Get
(
	@RoleID uniqueidentifier = null,
	@RoleName nvarchar(256) = null,
	@SettingsID int
	
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


	Declare @ApplicationName nvarchar(256)
	Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID
	
	
	select RoleId, RoleName as [Name], r.Description
	from aspnet_Roles r
		inner join aspnet_Applications a on 
			r.ApplicationId = a.ApplicationId
	where
		((@RoleID is not null and r.RoleId = @RoleID ) or @RoleID is null ) and
		((@RoleName is not null and r.RoleName = @RoleName ) or @RoleName is null ) and
		a.LoweredApplicationName = lower(@ApplicationName);


END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE        PROC [dbo].cs_RollerBlog_AddFeed
	@SectionID INT,
	@SettingsID INT,
	@FeedUrl NVARCHAR(512),
	@SiteUrl NVARCHAR(512),
    @Title NVARCHAR(512),
	@IntervalMin INT,
	@ExerptSize INT,
	@PostFullText BIT,
	@IsBlogAggregated BIT,
	@IsBlogRollAggregated BIT,
	@Enabled BIT,
	@State INT,
	@NewUrlID INT OUTPUT
AS

-- -- *** Test Data ***
-- DECLARE @SectionID INT
-- DECLARE @Url NVARCHAR(512)
-- DECLARE @Title NVARCHAR(512)
-- DECLARE @UrlId INT
-- 
-- SET @SectionID = 4 -- Sample Weblog
-- SET @Url = 'http://communityserver.org/roller/rss.ashx'
-- SET @Title = 'Community Server'
-- -- *** End Test Data ***

DECLARE @AUrlId INT
DECLARE @RecCount INT
DECLARE @CurrentDateTime DateTime
SET @CurrentDateTime = GetDate()

--Settings ID is now coming from the data layer
--DECLARE @SettingsID INT
--SET @SettingsID = (Select SettingsID FROM cs_Sections WHERE SectionID = @SectionID)

-- First, let's see if the url is already int cs_RollerBlogUrls.
SELECT @AUrlId = UrlID
FROM cs_RollerBlogUrls
WHERE Url = @FeedUrl --'http://communityserver.org/roller/rss.ashx'

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

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

  END

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

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

SELECT @NewUrlID = @AUrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_AddPost
	@PostID INT,
	@SectionID INT,
	@URlId INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

INSERT INTO cs_RollerBlogPost
(
	PostID,
	SectionID,
	UrlId,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
)

VALUES
(
	@PostID,
	@SectionID,
	@URlId,
	@PermaLink,
	@CommentsUrl,
	@CommentsCount,
	@GuidName,
	@GuidIsPermaLink
)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROC [dbo].cs_RollerBlog_DeleteFeed
	@SectionID INT,
	@UrlId INT
AS

UPDATE cs_RollerBlogFeeds
SET 	LastUpdateDate = GetDate(), Enabled = 0
WHERE SectionID = @SectionID AND UrlId = @UrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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


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

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


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

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


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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].[cs_RollerBlog_GetFeeds]
(
	@SettingsID int,
	@EnabledOnly bit = 0,
	@UpdateNeededOnly bit = 0,
	@SectionID int = 0
)
AS

SELECT
	SectionID
	,rbf.UrlId
    ,rollerUrls.Url
    ,rbf.SiteUrl
	,rbf.SettingsID
	,rbf.Enabled
    ,rbf.IntervalMinutes
	,rbf.Title
	,rbf.SubscribeDate
	,rbf.LastUpdateDate
	,rbf.LastModifiedDate
	,rbf.PostFullArticle
	,rbf.ExerptSize
	,rbf.ETag
	,rbf.IsBlogAggregated
	,rbf.IsBlogRollAggregated

FROM
	cs_RollerBlogFeeds rbf
	INNER JOIN cs_RollerBlogUrls rollerUrls on rollerUrls.UrlID = rbf.UrlId
WHERE
	SettingsID = @SettingsID
	AND (rbf.Enabled = @EnabledOnly or @EnabledOnly = 0)
	AND (SectionID = @SectionID or @SectionID = 0)
	AND (DateAdd(mi, rbf.IntervalMinutes, LastUpdateDate) <= GetDate() or @UpdateNeededOnly = 0)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_RollerBlog_GetPosts
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetPosts'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROC [dbo].cs_RollerBlog_GetPosts
	@SectionID INT,
	@UrlId INT

AS

SELECT
	SectionID,
	UrlId,
	PostID,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
FROM
	cs_RollerBlogPost
WHERE
	SectionID = @SectionID AND UrlId = @UrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




CREATE   PROC [dbo].cs_RollerBlog_UpdateFeed
	@SectionID INT,
	@UrlId INT,
    @FeedState INT,
   	@LastUpdateDate DateTime OUTPUT

AS

SELECT @LastUpdateDate = GetDate();
UPDATE cs_RollerBlogFeeds
SET 	
	-- we need to use the sql servers time for this
	LastUpdateDate = @LastUpdateDate, 
	State = @FeedState
WHERE SectionID = @SectionID AND UrlId = @UrlId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_RollerBlog_UpdatePost
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
Print 'Creating...cs_RollerBlog_UpdatePost'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_UpdatePost
	@PostID INT,
	@SectionID INT,
	@URlId INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

UPDATE cs_RollerBlogPost

SET
	SectionID = SectionID,
	UrlId = @URlId,
	PermaLink = @PermaLink,
	CommentUrl = @CommentsUrl,
	CommentCount = @CommentsCount,
	GuidName = @GuidName,
	GuidIsPermaLink = @GuidIsPermaLink

WHERE
	PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_AddFeed  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROC [dbo].cs_Roller_GetFeeds
	@UserId INT
AS


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetFeeds  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

SET Transaction Isolation Level Read UNCOMMITTED

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

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


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

CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	FeedPostId int
)

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

SET @TotalRecords = @@rowcount

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetPosts  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROC [dbo].cs_Roller_GetUnaggregatedFeeds
	@UserID INT
AS

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



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetUnaggregatedFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_SearchBarrel_Search
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_SearchBarrel_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





CREATE procedure dbo.cs_SearchBarrel_Search (
	@SearchSQL NText,
	--@RecordCountSQL nvarchar(4000),
	@PageIndex int = 0,
	@PageSize int = 25,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

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

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

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

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

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

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

	SET @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- SELECT actual search results from this table
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.Subject, P.PostDate,
		P.FormattedBody, P.IPAddress, P.PostType, P.SettingsID, P.UserTime,
		P.ApplicationPostType, P.PostName, P.UserTime,
		AttachmentFilename =  ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		S.ApplicationKey, S.GroupID, S.ApplicationType, S.Name as SectionName

	FROM 
		cs_Posts P,
		cs_Sections S,
		#SearchResults R
	WHERE
		P.PostID = R.PostID AND
		P.SectionID = S.SectionID AND
		R.IndexID > @PageLowerBound AND
		R.IndexID < @PageUpperBound AND
		P.SettingsID = @SettingsID
	Order By IndexID

	DROP Table #SearchResults

	Select @TotalRecords

	SELECT Duration = GetDate() - @StartTime
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE  procedure [dbo].cs_Search_Add (
	@WordHash int,
	@Word nvarchar(64),
	@Weight float,
	@PostID int,
	@ThreadID int,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	IF EXISTS (SELECT WordHash FROM cs_SearchBarrel WHERE PostID = @PostID AND WordHash = @WordHash)
		UPDATE 
			cs_SearchBarrel 
		SET
			Weight = @Weight
		WHERE
			WordHash = @WordHash AND
			PostID = @PostID and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_SearchBarrel
			(WordHash, Word, PostID, ThreadID, SectionID, Weight, SettingsID)
		VALUES
			(@WordHash, @Word, @PostID, @ThreadID, @SectionID, @Weight, @SettingsID)

	IF EXISTS (SELECT PostID From cs_Posts WHERE PostID = @PostID AND IsIndexed = 0 and SettingsID = @SettingsID)
		UPDATE cs_Posts SET IsIndexed = 1 WHERE PostID = @PostID and SettingsID = @SettingsID

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




CREATE   procedure [dbo].cs_Search_IgnoreWords
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		SELECT
			WordHash,
			Word
		FROM
			cs_SearchIgnoreWords
		WHERE
			SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create procedure [dbo].cs_Search_IgnoreWords_CreateDelete
(
	@WordHash int,
	@Word nvarchar (64),
	@Action int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
IF NOT EXISTS(SELECT * FROM cs_SearchIgnoreWords WHERE WordHash = @WordHash)
	INSERT INTO 
		cs_SearchIgnoreWords
	VALUES
		(@WordHash, @Word, @SettingsID)
END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE 
		cs_SearchIgnoreWords 
	WHERE 
		WordHash = @WordHash and SettingsID = @SettingsID

	DELETE
		cs_SearchBarrel
	WHERE
		WordHash = @WordHash and SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/***********************************************
* Sproc: cs_Search_UpdatePostIndexStatus
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_Search_UpdatePostIndexStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE  procedure [dbo].cs_Search_UpdatePostIndexStatus (
	@PostID int,
	@SettingsID int,
	@Status bit = 1
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	UPDATE cs_Posts SET IsIndexed = @Status WHERE PostID = @PostID and SettingsID = @SettingsID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].cs_Sections_Get
(
	@SettingsID				int,
	@ApplicationType        smallint = 0,
	@AllowInactive			bit = 0,
	@IncludePostTypeCounts	bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Return all the forums
SELECT  
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnablePostPoints, F.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.DefaultLanguage, F.DiskUsage

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

--Declare @AnonID int
--exec cs_GetAnonymousUserID @SettingsID, @AnonID output

exec cs_Section_Permissions_Get @SettingsID, 0, @ApplicationType

--Return the counts of each post type
IF @IncludePostTypeCounts > 0
BEGIN
	SELECT 
		F.ApplicationKey, P.ApplicationPostType, Count(*) as PostCount
	FROM 
		cs_Sections F
		JOIN cs_Posts P on F.SectionID = P.SectionID
	WHERE
		F.SettingsID = @SettingsID AND
		F.ApplicationType = @ApplicationType
	GROUP BY F.ApplicationKey, P.ApplicationPostType
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Sections_GetRead
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_Sections_GetRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


create procedure [dbo].cs_Sections_GetRead (
	@UserID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	SectionID,
	LastActivity
FROM
	cs_SectionsRead
WHERE
	UserID = @UserID AND 
	SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

Create Proc [dbo].cs_Sections_MoveOrReOrder
(
	@NewGroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Declare @OldGroupId int
Select @OldGroupId = GroupID from cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

if(@NewGroupID <> @OldGroupId) -- move from one group to another
Begin
	--Move the group, mark order at the end
	update cs_Sections
	Set GroupID = @NewGroupID, SortOrder = 9999999 where SectionID = @SectionID and SettingsID = @SettingsID

	--Update Old Group
	exec cs_Sections_ResetOrder @OldGroupId, @SettingsID
End

--Reset the Section
exec cs_Section_MoveSection @NewGroupID, @SectionID, @SectionIndex, @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

Create Proc [dbo].cs_Sections_ResetOrder
(
	@GroupID int,
	@SettingsID int
)
as

Declare @Sort int
Set @Sort = 0
Declare @SectionID int
DECLARE section_Cursor CURSOR FOR
SELECT SectionID FROM cs_Sections where GroupID = @GroupID and SettingsID = @SettingsID order by SortOrder

OPEN section_Cursor

FETCH NEXT FROM section_Cursor Into @SectionID
WHILE (@@FETCH_STATUS = 0)
Begin
	Update cs_Sections Set SortOrder = @Sort where SectionID = @SectionID
	Set @Sort = @Sort + 1
   FETCH NEXT FROM section_Cursor Into @SectionID
End

CLOSE section_Cursor
DEALLOCATE section_Cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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

Create Proc [dbo].[cs_SectionTokens_Add]
(
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int,
	@TokenID int output
)

as

Insert cs_SectionTokens (Token, Link, [Text], SettingsID, SectionID)
Values (@Token, @Link, @Text, @SettingsID, @SectionID)

Select @TokenID = @@Identity



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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


Create Proc [dbo].[cs_SectionTokens_Delete]
(
	@TokenID int,
	@SectionID int,
	@SettingsID int
)
as
Delete FROM cs_SectionTokens where TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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

Create Proc [dbo].[cs_SectionTokens_Get]
(
	@SectionID int,
	@SettingsID int
)
as
Select TokenID, Token, Link, [Text], SectionID FROM cs_SectionTokens where SettingsID = @SettingsID and SectionID = @SectionID Order by Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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

Create Proc [dbo].[cs_SectionTokens_Update]
(
	@TokenID int,
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int
)

as

update cs_SectionTokens
Set 
	Token = @Token,
	Link = @Link,
	[Text] = @Text
where
	TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- sp_helptext cs_Section_CreateUpdateDelete


CREATE PROCEDURE [dbo].cs_Section_CreateUpdateDelete
(
	@SectionID	int out,
	@DeleteForum	bit = 0,
	@Name		nvarchar(256) = '',
	@Url		nvarchar(512) = '',
	@Description	nvarchar(3000) = '',
	@ParentID	int = 0,
	@SettingsID	int,
	@GroupID	int = 0,
	@IsModerated	bit = 1,
	@IsSearchable   bit = 1,
	@DisplayPostsOlderThan	int = 0,
	@IsActive 	bit = 0,
	@EnablePostStatistics bit = 1,
	@EnablePostPoints bit = 1,
	@EnableAutoDelete bit = 0,
	@EnableAnonymousPosting bit = 0,
	@AutoDeleteThreshold int = 90,
	@SortOrder int = 0,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ApplicationKey nvarchar(256) = null,
	@ApplicationType smallint = 0,
	@ForumType int = 0,
	@UserID int,
	@DefaultLanguage nvarchar(32) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting the forum?
IF @DeleteForum = 1
BEGIN

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

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


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

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

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

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

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

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

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

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

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

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

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

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


	RETURN
END

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

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

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

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

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

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

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Section_DiskUsage_Update
* File Date: 8/8/2006 9:28:14 AM
***********************************************/
Print 'Creating...cs_Section_DiskUsage_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

	UPDATE cs_Sections SET DiskUsage = (SELECT COALESCE(SUM(Convert(bigint, ContentSize)),0) AS DiskUsage FROM cs_PostAttachments WHERE SectionID = @SectionID AND SettingsID = @SettingsID)
	WHERE SettingsID = @SettingsID AND SectionID = @SectionID
	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



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

as
SET Transaction Isolation Level Read UNCOMMITTED

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

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

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

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Section_GetRandomSectionID
	@SettingsID int,
	@ApplicationType smallint,
	@AllowEmpty bit = 0
AS
SET Transaction Isolation Level Read UNCOMMITTED
select top 1 SectionID
	from cs_Sections
	where ApplicationType = @ApplicationType
		and SettingsID = @SettingsID
		and IsActive = 1
		and (TotalThreads > 0 OR 1 = @AllowEmpty)
	order by newid()

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









CREATE PROCEDURE [dbo].cs_Section_GetSectionIDByPostID
(
	@PostID			int = 0,
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Loop up the forum by PostID

SELECT SectionID FROM cs_Posts WHERE PostID = @PostID and SettingsID = @SettingsID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE    procedure [dbo].cs_Section_MarkRead
(
	@UserID int,
	@SectionID int = 0,
	@SettingsID int,
	@GroupID int = 0,
	@MarkAllThreadsRead bit = 0

)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @LastReadThread int

	SET NOCOUNT ON

	IF @UserID = 0
		RETURN

	-- Are we marking all forums as read?
	IF @GroupID = 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID and SettingsID = @SettingsID

		-- 2. INSERT into cs_SectionsRead
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking a particular forum group as read?
	IF @GroupID > 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID

		-- 2. Insert into cs_Sections Read
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE GroupID = @GroupID and SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking an individual forum as read?
	IF @SectionID > 0
	BEGIN
		IF @MarkAllThreadsRead = 1
			IF EXISTS (SELECT UserID FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID)
				UPDATE 
					cs_SectionsRead 
				SET 
					NewPosts = 0,
					MarkReadAfter = (SELECT (MostRecentPostID + 1) FROM cs_Sections F WHERE SectionID = @SectionID),
					LastActivity = GetDate()
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID  and SettingsID = @SettingsID
			ELSE
				INSERT INTO 
					cs_SectionsRead
				SELECT GroupID, SectionID, @UserID, (MostRecentPostID + 1), 0, GetDate(), SettingsID FROM cs_Sections F WHERE SectionID = @SectionID  and SettingsID = @SettingsID
		ELSE
			IF (SELECT NewPosts FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID) = 1
				UPDATE
					cs_SectionsRead							
				SET 
					NewPosts = 0
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID

	END
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

Create Proc [dbo].cs_Section_MoveSection
(
	@GroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Set NoCount On

--Set Order
exec cs_Sections_ResetOrder @GroupID, @SettingsID

--Update all items at or below the updatedindex
update cs_Sections
Set SortOrder = SortOrder + 1 where SortOrder >= @SectionIndex and GroupID = @GroupID and SettingsID = @SettingsID

--Set the item we are updating
update cs_Sections
Set SortOrder = @SectionIndex where SectionID = @SectionID and SettingsID = @SettingsID

-- Make sure everything is sorted correctly
exec cs_Sections_ResetOrder @GroupID, @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

create procedure [dbo].cs_Section_Permissions_Get
(
	@SettingsID int,
	@SectionID int = 0,
	@ApplicationType smallint
)
AS


SET Transaction Isolation Level Read UNCOMMITTED

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

	UNION

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

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

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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  procedure [dbo].cs_Section_Permission_CreateUpdateDelete
(
	@SettingsID 	int,
	@SectionID 	int,
	@RoleID		uniqueidentifier,
	@Action		int,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@ApplicationType smallint
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

-- Create
IF @Action = 0
BEGIN

	if( @SectionID <> -1 ) 
	begin
		-- Check if an entry already exists
		IF EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)


		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )
	end
	else
	begin
		insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
			values( @SettingsID, @RoleID, @AllowMask, @DenyMask, @ApplicationType )
	end
END
-- UPDATE
ELSE IF @Action = 1
BEGIN
	
	if( @SectionID <> -1 ) 
	begin
		IF NOT EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			UPDATE
				cs_SectionPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				SectionID = @SectionID AND
				RoleID = @RoleID and SettingsID = @SettingsID

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

	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
END
ELSE IF @Action = 2
BEGIN
	if( @SectionID <> -1 )
		DELETE cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID
	else
	begin
		DELETE cs_SectionPermissions where RoleID = @RoleID and SettingsID = @SettingsID
		DELETE cs_ProductPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end
	
	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
END

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Section_Permission_CreateUpdateDelete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Section_RssPingback_Update
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...cs_Section_RssPingback_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






create procedure [dbo].cs_Section_RssPingback_Update (
	@SectionID int,
	@Pingback nvarchar(512),
	@Count int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT SectionID FROM cs_ForumPingback WHERE SectionID = @SectionID AND Pingback = @Pingback)
		UPDATE
			cs_ForumPingback
		SET
			[Count] = [Count] + @Count,
			LastUpdated = GetDate()
		WHERE
			SectionID = @SectionID AND
			Pingback = @Pingback and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_ForumPingback
		VALUES
			(@SectionID, @Pingback, @Count, GetDate(), @SettingsID)
			

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_UpdateSortOrder]
GO
/***********************************************
* Sproc: cs_security_ValidateUserPasswordAnswer
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_security_ValidateUserPasswordAnswer'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create proc [dbo].cs_Services_Get
(
	@ServiceID int = 0,
	@SettingsID int
)
as 
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT
		*
	FROM
		cs_Services
	WHERE
		ServiceID = @ServiceID or
		(@ServiceID = 0 and 1=1) and SettingsID = @SettingsID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








create proc [dbo].cs_Service_CreateUpdateDelete
(
	  @ServiceID				int out
	, @DeleteService			bit = 0
	, @ServiceName				nvarchar(60)
	, @ServiceTypeCode			int
	, @ServiceAssemblyPath		nvarchar(512)
	, @ServiceFullClassName		nvarchar(512)
	, @ServiceWorkingDirectory	nvarchar(512)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the service
IF ( @DeleteService > 0 )
BEGIN

	DELETE cs_Services
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

	RETURN
END

IF( @ServiceID > 0 )
BEGIN

	UPDATE cs_Services SET
		  ServiceName				= @ServiceName
		, ServiceTypeCode			= @ServiceTypeCode
		, ServiceAssemblyPath		= @ServiceAssemblyPath
		, ServiceFullClassName		= @ServiceFullClassName
		, ServiceWorkingDirectory	= @ServiceWorkingDirectory
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

END
ELSE
BEGIN

	INSERT INTO cs_Services (
		ServiceName, ServiceTypeCode, ServiceAssemblyPath, ServiceFullClassName, ServiceWorkingDirectory, SettingsID
	) VALUES (
		@ServiceName, @ServiceTypeCode, @ServiceAssemblyPath, @ServiceFullClassName, @ServiceWorkingDirectory, @SettingsID
	)

	SET @ServiceID = @@identity

END

RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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





CREATE procedure [dbo].cs_SetSectionSubscriptionType
(
	@UserID int,
	@SectionID int,
	@subType int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
if (@subType=0)
	DELETE from cs_TrackedSections where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
IF Exists (select SubscriptionType from cs_TrackedSections (nolock) where UserID=@UserID AND SectionID=@SectionID and SettingsID = @SettingsID)
	UPDATE cs_TrackedSections Set SubscriptionType=@subType where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
	INSERT INTO cs_TrackedSections (UserID, SectionID, SubscriptionType, SettingsID) values (@UserID, @SectionID, @subType, @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE  PROCEDURE [dbo].cs_SettingsIDs_Get
AS
SET Transaction Isolation Level Read UNCOMMITTED

Select 
	sm.SettingsID, 
	s.SiteUrl 
FROM 
	cs_SiteMappings sm,
	cs_Sites s
Where
	s.SiteID = sm.SiteID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  PROCEDURE [dbo].[cs_shared_Threads_GetThreadSet]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate ntext,
	@UserID int,
	@IncludeCategories bit,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

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

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


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



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

--CREATE INDEX page_index ON #PageIndex(IndexID)

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

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

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

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

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


SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN

	SELECT 
		Cats.[Name], jPI.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts_InCategories PIC ON jPI.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound

End

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

DROP TABLE #PageIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE  PROCEDURE [dbo].cs_SiteSettings_Get
(
	@SiteUrl nvarchar(512) = null,
	@SettingsID int = 0,
	@ReturnAll bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

If @ReturnAll = 0
Begin
Select 
		top 1 ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		ORDER BY ss.SettingsID asc

End

ELSE IF @SiteUrl is null
Begin
Select 
		ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			ss.SettingsID = @SettingsID
End
Else
Begin
	IF @SiteUrl = '*'
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
	
	ELSE IF NOT EXISTS (SELECT * FROM cs_Sites WHERE SiteUrl = @SiteUrl OR SiteUrl = @SiteUrl + '/')
		RETURN
	ELSE
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			(s.SiteUrl = @SiteUrl OR s.SiteUrl = @SiteUrl + '/')
End

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE procedure [dbo].cs_SiteSettings_Save
(
	@Disabled		smallint,
	@SettingsXML	 	ntext = null,
	@ApplicationName	nvarchar(256),
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		UPDATE
			cs_SiteSettings
		SET
			Disabled = @Disabled,
			SettingsXML = @SettingsXML,
			ApplicationName = @ApplicationName
		WHERE
			SettingsID  = @SettingsID
END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE    procedure [dbo].cs_Site_GetSiteUrls
AS

select
 lower(SS.ApplicationName) as ApplicationName, S.SiteUrl
from cs_SiteSettings SS
left join cs_SiteMappings SM on (SM.SettingsID = SS.SettingsID)
left join cs_Sites S on (S.SiteID = SM.SiteID)

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




CREATE PROCEDURE [dbo].cs_Site_Statistics
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

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

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')



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

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

-- SELECT top 10 Moderators
SELECT TOP 10
	U.*,
	M.PostsModerated
FROM
	cs_vw_Users_FullUser U,
	aspnet_UsersInRoles R,
	cs_Moderators M
WHERE
	U.UserId = R.UserId AND
	R.RoleId = @ModeratorRoleID AND
	U.cs_UserID = M.UserID AND
	M.PostsModerated > 0 AND 
	U.SettingsID = @SettingsID AND 
	M.SettingsID = @SettingsID
ORDER BY
	PostsModerated DESC

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



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE proc [dbo].cs_Smiley_CreateUpdateDelete
(
	  @SmileyID		int out
	, @DeleteSmiley	bit = 0
	, @SmileyCode	nvarchar(20)
	, @SmileyUrl	nvarchar(512)
	, @SmileyText	nvarchar(512)
	, @BracketSafe	bit = 0
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED

IF( @DeleteSmiley > 0 ) 
BEGIN

	DELETE cs_Smilies
	WHERE
		SmileyID = @SmileyID and SettingsID = @SettingsID

	RETURN
END

IF( @SmileyID > 0 ) 
BEGIN
	UPDATE cs_Smilies SET
		  SmileyCode	= @SmileyCode
		, SmileyUrl		= @SmileyUrl
		, SmileyText	= @SmileyText
		, BracketSafe	= @BracketSafe
	WHERE
		SmileyID	= @SmileyID and SettingsID = @SettingsID
END
ELSE
BEGIN

	INSERT INTO cs_Smilies (
		SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID
	) VALUES (
		@SmileyCode, @SmileyUrl, @SmileyText, @BracketSafe, @SettingsID
	)

	SET @SmileyID = @@identity
END
RETURN









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create proc [dbo].cs_Smilies_Get
(
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Smilies
	WHERE
		SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








create proc [dbo].cs_Styles_Get
(
	@StyleID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Styles
	WHERE
		StyleID = @StyleID OR
		(
			@StyleID = 0 AND
			1=1
		) and SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







create proc [dbo].cs_Style_CreateUpdateDelete
(
	  @StyleID				int out
	, @DeleteStyle			bit = 0
	, @StyleName			varchar(30)
	, @StyleSheetTemplate	varchar(30)
	, @BodyBackgroundColor	int
	, @BodyTextColor		int
	, @LinkVisited			int
	, @LinkHover			int
	, @LinkActive			int
	, @RowColorPrimary		int
	, @RowColorSecondary	int
	, @RowColorTertiary		int
	, @RowClassPrimary		varchar(30)
	, @RowClassSecondary	varchar(30)
	, @RowClassTertiary		varchar(30)
	, @HeaderColorPrimary	int
	, @HeaderColorSecondary	int
	, @HeaderColorTertiary	int
	, @HeaderStylePrimary	varchar(30)
	, @HeaderStyleSecondary	varchar(30)
	, @HeaderStyleTertiary	varchar(30)
	, @CellColorPrimary		int
	, @CellColorSecondary	int
	, @CellColorTertiary	int
	, @CellClassPrimary		varchar(30)
	, @CellClassSecondary	varchar(30)
	, @CellClassTertiary	varchar(30)
	, @FontFacePrimary		varchar(30)	
	, @FontFaceSecondary	varchar(30)
	, @FontFaceTertiary		varchar(30)
	, @FontSizePrimary		smallint
	, @FontSizeSecondary	smallint
	, @FontSizeTertiary		smallint
	, @FontColorPrimary		int
	, @FontColorSecondary	int
	, @FontColorTertiary	int
	, @SpanClassPrimary		varchar(30)
	, @SpanClassSecondary	varchar(30)
	, @SpanClassTertiary	varchar(30)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF( @DeleteStyle = 1 ) 
BEGIN
	
	DELETE cs_Styles
	WHERE
		StyleID	= @StyleID and SettingsID = @SettingsID

	RETURN
END

IF( @StyleID > 0 )
BEGIN

	UPDATE cs_Styles SET
		  StyleName 			= @StyleName
		, StyleSheetTemplate 	= @StyleSheetTemplate
		, BodyBackgroundColor 	= @BodyBackgroundColor
		, BodyTextColor 		= @BodyTextColor
		, LinkVisited 			= @LinkVisited
		, LinkHover 			= @LinkHover
		, LinkActive 			= @LinkActive
		, RowColorPrimary 		= @RowColorPrimary
		, RowColorSecondary 	= @RowColorSecondary
		, RowColorTertiary 		= @RowColorTertiary
		, RowClassPrimary 		= @RowClassPrimary
		, RowClassSecondary 	= @RowClassSecondary
		, RowClassTertiary 		= @RowClassTertiary
		, HeaderColorPrimary 	= @HeaderColorPrimary
		, HeaderColorSecondary	= @HeaderColorSecondary
		, HeaderColorTertiary 	= @HeaderColorTertiary
		, HeaderStylePrimary 	= @HeaderStylePrimary
		, HeaderStyleSecondary 	= @HeaderStyleSecondary
		, HeaderStyleTertiary 	= @HeaderStyleTertiary
		, CellColorPrimary 		= @CellColorPrimary
		, CellColorSecondary	= @CellColorSecondary
		, CellColorTertiary 	= @CellColorTertiary
		, CellClassPrimary 		= @CellClassPrimary
		, CellClassSecondary 	= @CellClassSecondary
		, CellClassTertiary 	= @CellClassTertiary
		, FontFacePrimary 		= @FontFacePrimary
		, FontFaceSecondary 	= @FontFaceSecondary
		, FontFaceTertiary 		= @FontFaceTertiary
		, FontSizePrimary 		= @FontSizePrimary
		, FontSizeSecondary 	= @FontSizeSecondary
		, FontSizeTertiary 		= @FontSizeTertiary
		, FontColorPrimary 		= @FontColorPrimary
		, FontColorSecondary 	= @FontColorSecondary
		, FontColorTertiary 	= @FontColorTertiary
		, SpanClassPrimary 		= @SpanClassPrimary
		, SpanClassSecondary 	= @SpanClassSecondary
		, SpanClassTertiary 	= @SpanClassTertiary
	WHERE
		StyleID = @StyleID and SettingsID = @SettingsID


END
ELSE
BEGIN

	INSERT INTO cs_Styles (
		  StyleName				, StyleSheetTemplate		, BodyBackgroundColor		, BodyTextColor
		, LinkVisited			, LinkHover					, LinkActive				, RowColorPrimary
		, RowColorSecondary		, RowColorTertiary			, RowClassPrimary			, RowClassSecondary
		, RowClassTertiary		, HeaderColorPrimary		, HeaderColorSecondary		, HeaderColorTertiary
		, HeaderStylePrimary	, HeaderStyleSecondary		, HeaderStyleTertiary		, CellColorPrimary
		, CellColorSecondary	, CellColorTertiary			, CellClassPrimary			, CellClassSecondary
		, CellClassTertiary		, FontFacePrimary			, FontFaceSecondary			, FontFaceTertiary
		, FontSizePrimary		, FontSizeSecondary			, FontSizeTertiary			, FontColorPrimary
		, FontColorSecondary	, FontColorTertiary			, SpanClassPrimary			, SpanClassSecondary
		, SpanClassTertiary, SettingsID
	) VALUES (
		  @StyleName			, @StyleSheetTemplate		, @BodyBackgroundColor		, @BodyTextColor		, @LinkVisited			, @LinkHover				, @LinkActive				, @RowColorPrimary
		, @RowColorSecondary	, @RowColorTertiary			, @RowClassPrimary			, @RowClassSecondary
		, @RowClassTertiary		, @HeaderColorPrimary		, @HeaderColorSecondary		, @HeaderColorTertiary
		, @HeaderStylePrimary	, @HeaderStyleSecondary		, @HeaderStyleTertiary		, @CellColorPrimary
		, @CellColorSecondary	, @CellColorTertiary		, @CellClassPrimary			, @CellClassSecondary
		, @CellClassTertiary	, @FontFacePrimary			, @FontFaceSecondary		, @FontFaceTertiary
		, @FontSizePrimary		, @FontSizeSecondary		, @FontSizeTertiary			, @FontColorPrimary
		, @FontColorSecondary	, @FontColorTertiary		, @SpanClassPrimary			, @SpanClassSecondary
		, @SpanClassTertiary, @SettingsID
	)

	SELECT @StyleID = @@IDENTITY
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Style_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_System_AddNewUrl.sql
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...cs_System_AddNewUrl.sql'



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


/***************************************************
Adds another Url to an existing SiteSettings Record

Author: Scott Watermasysk
Date: 10/21/2004
****************************************************/

CREATE Proc [dbo].cs_System_AddNewUrl
(
	@ExistingUrl nvarchar(512),
	@NewUrl nvarchar(512)
)

as

if exists(Select SiteID FROM cs_Sites where SiteUrl = @NewUrl)
Return -1 -->> The site @NewUrl already exists

Declare @SiteID int
Declare @SettingsID int 
Declare @NewSiteID int

Select @SiteID = SiteID FROM cs_Sites where SiteUrl = @ExistingUrl

If @SiteID is null
Return -2 -->> The site at @ExistingUrl does not Exist

Select @SettingsID = SettingsID FROM cs_SiteMappings where SiteID = @SiteID
If @SettingsID is null
Return -3 -->> This Application is not yet mapped

Insert cs_Sites Values (@NewUrl)
Select @NewSiteID = @@Identity

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

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

GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create   procedure [dbo].cs_system_CleanForumsRead
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DELETE
		cs_SectionsRead
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

--exec cs_system_CreateAlias 'localhost/blahx','dev'


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

--restore database CommunityServer from disk='c:\CommunityServer.bak'

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

--exec cs_system_CreateCommunity 'localhost/cs55sdf2','devs55ssss', 'admin@example.com', 'admin', 'sTrongPassw0rd', 0, 1

create Proc [dbo].cs_system_CreateCommunity
(
	@SiteUrl nvarchar(512),
	@ApplicationName nvarchar(512),
	@AdminEmail nvarchar(256),
	@AdminUserName nvarchar(256),
	@AdminPassword nvarchar(256),
	@PasswordFormat int = 0,	-- 0 = clear text, 1 = encrypted
	@CreateSamples bit = 1
)

as

--We must have both these values to continue
if(@SiteUrl is null OR @ApplicationName is  null)
BEGIN
	Select -1
	RETURN
END

--@SiteUrl must be unique
if exists(Select SiteID FROM cs_Sites where Lower(SiteUrl) = Lower(@SiteUrl))
BEGIN
	Select -2
	RETURN
END

Declare @SettingsID int
DECLARE @SiteID int 
Declare @ApplicationID uniqueidentifier
Declare @AdminUserID uniqueidentifier
DECLARE @Version nvarchar(64)
DECLARE @IsApplicationCreated bit
DECLARE @GroupID int
DECLARE @AdminRoleID uniqueidentifier

Set @IsApplicationCreated = 0

Set @Version = null

--Insert Site Record. This maps a Url to an ID
Insert cs_Sites (SiteUrl) Values(@SiteUrl)
Select @SiteID = @@Identity

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

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

END
ELSE
BEGIN
	SET @IsApplicationCreated = 0
END

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

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

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




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


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

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

print 'Creating the default smilies...'
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':)', 'emoticons/emotion-1.gif', 'Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':D', 'emoticons/emotion-2.gif', 'Big Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':O', 'emoticons/emotion-3.gif', 'Surprise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':P', 'emoticons/emotion-4.gif', 'Stick out tongue', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (';)', 'emoticons/emotion-5.gif', 'Wink', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':(', 'emoticons/emotion-6.gif', 'Sad', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':S', 'emoticons/emotion-7.gif', 'Tongue Tied', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':|', 'emoticons/emotion-8.gif', 'Indifferent', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':''(', 'emoticons/emotion-9.gif', 'Crying', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':$', 'emoticons/emotion-10.gif', 'Embarrassed', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('H', 'emoticons/emotion-11.gif', 'Cool', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':@', 'emoticons/emotion-12.gif', 'Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('A', 'emoticons/emotion-13.gif', 'Angel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('6', 'emoticons/emotion-14.gif', 'Devil', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-|', 'emoticons/emotion-15.gif', 'Geeked', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':#', 'emoticons/emotion-16.gif', 'Zip it!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':-*', 'emoticons/emotion-17.gif', 'Whisper', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':^)', 'emoticons/emotion-18.gif', 'Huh?', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('<:o)', 'emoticons/emotion-19.gif', 'Party!!!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('|-)', 'emoticons/emotion-20.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Y', 'emoticons/emotion-21.gif', 'Yes', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('B', 'emoticons/emotion-22.gif', 'Beer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('{', 'emoticons/emotion-24.gif', 'Left Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8', 'emoticons/emotion-29.gif', 'Music', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*', 'emoticons/emotion-30.gif', 'Star', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('O', 'emoticons/emotion-31.gif', 'Time', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('sn', 'emoticons/emotion-32.gif', 'Snail', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('pi', 'emoticons/emotion-33.gif', 'Pizza', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('au', 'emoticons/emotion-34.gif', 'Automobile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('um', 'emoticons/emotion-35.gif', 'Umbrella', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('co', 'emoticons/emotion-36.gif', 'Computer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('st', 'emoticons/emotion-37.gif', 'Storm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('mo', 'emoticons/emotion-38.gif', 'Moon', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8o|', 'emoticons/emotion-39.gif', 'Super Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^o)', 'emoticons/emotion-40.gif', 'Hmm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('+o(', 'emoticons/emotion-41.gif', 'Ick!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*-)', 'emoticons/emotion-42.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-)', 'emoticons/emotion-43.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('C', 'emoticons/emotion-44.gif', 'Coffee', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('N', 'emoticons/emotion-45.gif', 'No', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('D', 'emoticons/emotion-46.gif', 'Drinks', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Z', 'emoticons/emotion-47.gif', 'Person', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('}', 'emoticons/emotion-48.gif', 'Right Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^', 'emoticons/emotion-49.gif', 'Cake', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('U', 'emoticons/emotion-50.gif', 'Broken Heart', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('G', 'emoticons/emotion-51.gif', 'Gift', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('W', 'emoticons/emotion-52.gif', 'Wilted Flower', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('~', 'emoticons/emotion-53.gif', 'Movie', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('&', 'emoticons/emotion-54.gif', 'Dog', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('I', 'emoticons/emotion-55.gif', 'Idea', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('S', 'emoticons/emotion-56.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('E', 'emoticons/emotion-57.gif', 'Email', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ap', 'emoticons/emotion-58.gif', 'Travel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ip', 'emoticons/emotion-59.gif', 'Paradise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('li', 'emoticons/emotion-60.gif', 'Lightning', 0, @SettingsID)

Declare @DeletedSectionID int
Declare @ReportingSectionID int

INSERT INTO cs_Groups 
	( [Name], [SortOrder], SettingsID, ApplicationType)
VALUES 
	( 'Administrators', 99999, @SettingsID, 0 )

Select @GroupID = @@Identity
Print 'Created Admin ForumGroup'

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

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



if(@IsApplicationCreated = 1)
Begin

	print 'Created default roles...'

	declare @EveryoneRoleID uniqueidentifier
	Set @EveryoneRoleID = newID()
	

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

	Declare @UserID uniqueidentifier
	Declare @cs_UserID int
	
	if(@AdminUserName is not null)
	Begin

		Set @UserID = newid()
		
		Print 'Create Admin User'
		INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
		      VALUES (@UserID, @ApplicationID, @AdminUserName, Lower(@AdminUserName), NULL, 0, getdate())
		--Do we need to make Salt configurable?
		INSERT INTO [aspnet_Membership] ([ApplicationId], [UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email], [LoweredEmail], [PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment], FailedPasswordAnswerAttemptWindowStart, FailedPasswordAnswerAttemptCount, FailedPasswordAttemptWindowStart, FailedPasswordAttemptCount, LastLockoutDate, IsLockedOut) 
					 VALUES (@ApplicationID, @UserID,  @AdminPassword, @PasswordFormat,   N'DVZTktxeMzDtXR7eik7Cdw==', NULL,       @AdminEmail,    NULL,            NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,                 '1753-01-01',                              0,                               '1753-01-01',                       0,                          '1753-01-01',      0)
		
		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
		VALUES(@UserID, 0,1, null, getdate(), '')


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

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

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

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

	--Create cs_UserProfile records for any cs_Users without Profiles

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

END

Declare @Perm_RoleID uniqueidentifier

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


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

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

	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- GuestBook Permission  >> Allow View, Reply  Deny Post
	-- SET SPECIFIC DELETED adn Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )
	
	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Editor'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000000F000000FF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 ) -- File Permission

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

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

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'GalleryAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x01001000000000BD, 0 ) -- Gallery Permission
	
		Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'FileAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x01001008000002FF, 0 ) -- File Permission

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

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

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

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


---Return New Data	

if @CreateSamples = 1
Begin
	exec cs_system_SampleGallery @SettingsID, @AdminUserName
	exec cs_system_SampleWeblog @SettingsID, @AdminUserName
	exec cs_system_SampleForum @SettingsID, @AdminUserName
	exec cs_system_SampleDownload @SettingsID, @AdminUserName
End

--Select * FROM cs_Sites
--DELETE FROM cs_Sites where ApplicationID > 50
Select * FROM aspnet_Applications where ApplicationId = @ApplicationID
Select * FROM aspnet_Users where ApplicationId = @ApplicationID
Select * FROM aspnet_Membership where UserId in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)
Select * FROM cs_UserProfile where SettingsID = @SettingsID
Select * FROM cs_Sites where SiteID = @SiteID
Select * FROM cs_SiteSettings where SettingsID = @SettingsID
Select * FROM cs_SiteMappings where SettingsID = @SettingsID and SiteID = @SiteID
Select * FROM cs_ProductPermissions where SettingsID = @SettingsID
Select * FROM cs_SectionPermissions where SettingsID = @SettingsID
Go

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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


CREATE procedure [dbo].cs_system_DeletePostAndAdoptChildren
(
	@PostID int,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT
)
AS
-- Deleted Post is really moved to "Deleted Posts" forum (ForumType = 50)

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------
print @parentid

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

-- This proc should only be called from non-thread starting posts
IF (@OldPostLevel <> 1)
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads
		(
			SectionID,
			PostDate,
			UserID,
			PostAuthor,
			ThreadDate,
			MostRecentPostAuthor,
			MostRecentPostAuthorID,
			MostRecentPostID,
			IsLocked,
			IsApproved,
			IsSticky,
			StickyDate,
			ThreadEmoticonID,
			SettingsID
		)
		VALUES
		(
			@DeletedSectionID,	-- the Deleted Posts forum
			@PostDate,
			@UserID,
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID,
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = @@IDENTITY
	END

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

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

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

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

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

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

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

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

		DECLARE	@level	int
		SET		@level = @OldPostLevel

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

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

	RETURN 1
END	

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

*/

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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


CREATE procedure [dbo].cs_system_DeletePostAndChildren
(
	@PostID int,
	@DeleteChildren bit = 1,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT,
	@NewPostLevel int = NULL
)
AS
-- Posts are not "deleted", but they are moved to SectionID=4.
-- Start deleting with @NewPostLevel being NULL

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

IF (@OldPostLevel = 1)
BEGIN		
	-- We may "move" the whole thread. So update and delete some records.
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID)

	UPDATE cs_Posts SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Threads related updates
	UPDATE cs_ThreadsRead SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	DELETE FROM cs_TrackedThreads WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	UPDATE cs_Threads SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Delete from the search index
	DELETE cs_SearchBarrel WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID
	
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
		
	RETURN 1
	------------------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads 	
		( 
			SectionID,
			PostDate, 
			UserID, 
			PostAuthor, 
			ThreadDate, 
			MostRecentPostAuthor, 
			MostRecentPostAuthorID, 	
			MostRecentPostID, 
			IsLocked, 
			IsApproved,
			IsSticky, 
			StickyDate, 
			ThreadEmoticonID,
			SettingsID 
		)
		VALUES
		( 
			@DeletedSectionID, 	-- the Deleted Posts forum
			@PostDate, 
			@UserID, 
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID, 
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID 
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = @@IDENTITY		
	END
	------------------------------------------------------------------------------------------
		
	-- Calculate Post Level, Parent ID & Sort Order values
	------------------------------------------------------------------------------------------
	IF (@NewPostLevel IS NULL)
	BEGIN
		-- We have an unknown post level, so we have to figure out its values
		IF (NOT EXISTS(SELECT PostID FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID))
		BEGIN
			-- Set this post as a tread starter post
			SET @NewPostLevel = 1					
			SET @ParentID = @PostID
			SET @SortOrder = 1
		END
		ELSE
		BEGIN				
			-- Bind this post to the thread starter post
			SET @NewPostLevel = 2
			SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
		END
		
		-- Set children's post level
		SET @PostLevel = (@NewPostLevel + 1)
	END
	ELSE
	BEGIN
		--SET @PostLevel = 2
		SET @PostLevel = (@NewPostLevel + 1)
		SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
	END
	------------------------------------------------------------------------------------------

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

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

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

	RETURN 1
END	

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

*/

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create procedure [dbo].cs_system_DuplicatePost
(
@UserID int,
@Body ntext,
@IntervalInMinutes int = 0,
@SettingsID int,
@IsDuplicate bit out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

	IF @IntervalInMinutes > 0
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body AND PostDate > DateAdd(minute, -@IntervalInMinutes, GetDate()) )
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0
        ELSE
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body)
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create procedure [dbo].cs_system_ModerationAction_AuditEntry
(
	@ModerationAction int,
	@ModeratorID int,
	@PostID int = null,
	@UserID int = null,
	@SectionID int = null,
	@SettingsID int,
	@Notes nvarchar(1024) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	INSERT INTO
		cs_ModerationAudit
		(
			ModerationAction,
			PostID,
			UserID,
			SectionID,
			ModeratorID,
			Notes,
			SettingsID
		)
	VALUES
		(
			@ModerationAction,
			@PostID,
			@UserID,
			@SectionID,
			@ModeratorID,
			@Notes,
			@SettingsID
		)

	UPDATE
		cs_ModerationAction
	SET
		TotalActions = TotalActions + 1
	WHERE
		ModerationAction = @ModerationAction and SettingsID = @SettingsID

		
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE      procedure [dbo].cs_system_ResetForumStatistics
(
	@SectionID int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @AutoDelete bit
DECLARE @AutoDeleteThreshold int
DECLARE @ThreadID int
DECLARE @PostID int

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

	DECLARE ForumCount_Cursor CURSOR FOR
		SELECT SectionID FROM cs_Sections

	OPEN ForumCount_Cursor
	FETCH NEXT FROM ForumCount_Cursor INTO @SectionID

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

	CLOSE ForumCount_Cursor
	DEALLOCATE ForumCount_Cursor
	
END
ELSE BEGIN

	DECLARE @SettingsID int

	Select @SettingsID = SettingsID FROM cs_Sections where SectionID = @SectionID
    
	-- Finally, perform any auto-delete
	SELECT 
		@AutoDelete = EnableAutoDelete, 
		@AutoDeleteThreshold = AutoDeleteThreshold 
	FROM 
		cs_Sections
	WHERE
		SectionID = @SectionID
	
	-- Do we need to cleanup the forum?
	IF @AutoDelete = 1
	BEGIN

		DECLARE @ThreadIDToDelete int

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

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

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

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

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].cs_system_ResetThreadStatistics
(
	@ThreadID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @PostID int
DECLARE @UserID int
DECLARE @PostDate datetime
DECLARE @PostAuthor varchar(64)
DECLARE @Subject varchar(256)
DECLARE @SettingsID int
DECLARE @StickyDate datetime
DECLARE @IsSticky bit

-- Select the most recent post in the thread.
SELECT TOP 1
	@PostID = PostID,
	@UserID = UserID,
	@PostDate = PostDate,
	@PostAuthor = PostAuthor,
	@SettingsID = SettingsID
FROM
	cs_Posts
WHERE
	ThreadID = @ThreadID
	AND IsApproved = 1
ORDER BY
	PostID DESC

-- Get sticky date for the thread we need top update
SELECT @StickyDate = StickyDate, @IsSticky = IsSticky FROM cs_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

IF @StickyDate < @PostDate
	-- Sticky is expired
	SET @StickyDate = @PostDate

IF @IsSticky = 0 AND @StickyDate > @PostDate
	-- A replying post in this thread has just been deleted
	SET @StickyDate = @PostDate

-- Update the thread.	
UPDATE 
	cs_Threads
SET
	TotalReplies = (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1 AND SettingsID = @SettingsID),
	MostRecentPostAuthorID = @UserID,
	MostRecentPostAuthor = @PostAuthor,	
	MostRecentPostID = @PostID,
	ThreadDate = @PostDate,
	StickyDate = @StickyDate
WHERE
	ThreadID = @ThreadID AND
  SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

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

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


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


declare @SectionID int


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


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


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


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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

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

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

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


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



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



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

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

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_system_SampleGallery
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_system_SampleGallery'


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

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

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


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


declare @SectionID int


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


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


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


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


declare @ptr varbinary(16)
select @ptr = textptr(Content) from cs_PostAttachments where PostID = @PicPostID
writetext cs_PostAttachments.Content @ptr 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_SampleWeblog
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_system_SampleWeblog'

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

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

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

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


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



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



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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].cs_system_UpdateForum
(
	@SectionID int,
	@ThreadID int,
	@PostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1, -- new param with a default value,
	@PostDisplayName nvarchar(64) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @UserID 		int
DECLARE @PostDate 		datetime
DECLARE @TotalThreads 		int
DECLARE @TotalPosts 		int
DECLARE @PostsToModerate	int
DECLARE @Subject		nvarchar(64)
DECLARE @User 		nvarchar(64)
DECLARE @PostConfiguration	int
DECLARE @IsApproved bit


-- Set default
SET @PostConfiguration = 0

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

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

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

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

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

END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



CREATE   procedure [dbo].cs_system_UpdateMostActiveUsers
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	SET NOCOUNT ON

	DELETE FROM cs_statistics_User WHERE SettingsID = @SettingsID
	
	INSERT INTO cs_statistics_User
	SELECT TOP 100
		U.cs_UserID,
		TotalPosts = ISNULL( (SELECT count(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SectionID = cs_Posts.SectionID and cs_Sections.SettingsID = @SettingsID AND UserID = U.cs_UserID AND PostDate > DateAdd(day, -1, GetDate())), 0),
		@SettingsID
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.IsIgnored = 0   AND
		U.cs_UserAccountStatus = 1 and U.SettingsID = @SettingsID
	ORDER BY
		TotalPosts DESC

	SET NOCOUNT OFF
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE PROCEDURE [dbo].[cs_system_UpdateSite]
(
	@UpdateUserPostRank bit = 1,
	@UpdateMostActiveUserList bit = 1,
	@SettingsID int,
	@UpdateWindow int = 3
)
AS

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

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')
SET @DateWindow = DATEADD(hh, -@UpdateWindow, GetDate())

if (@LastUpdate <  @DateWindow)
BEGIN


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

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



	SET NOCOUNT ON

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

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

	IF @UpdateMostActiveUserList = 1
		exec cs_system_UpdateMostActiveUsers @SettingsID

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

	-- Total Moderators, for this site only
	-- ***********************************************
	SET @TotalModerators = ISNULL(
					(
						SELECT 
							COUNT(*) 
						FROM 
							aspnet_UsersInRoles jUR
							JOIN aspnet_Roles jR ON jR.RoleID = jUR.RoleID
							JOIN aspnet_applications jA on jR.ApplicationId = jA.ApplicationId			
						WHERE 
							jR.LoweredRoleName = 'moderator' and LOWER(@ApplicationName) = jA.LoweredApplicationName
					), 0)

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

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

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


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

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

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


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

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


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


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


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

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

	-- Total Users in past 24 hours
	-- ***********************************************
	SET @NewUsersInPast24Hours = ISNULL(
						(SELECT COUNT(IsApproved) FROM aspnet_Membership WHERE ApplicationId = @ApplicationId and CreateDate > DATEADD(dd,-1,getdate())
					), 0)

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

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

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

	OPEN users_cursor

	FETCH NEXT FROM users_cursor 
	INTO @UserID

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

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

		FETCH NEXT FROM users_cursor
		INTO @UserID
	END

	CLOSE users_cursor
	DEALLOCATE users_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].cs_system_UpdateThread
(
	@ThreadID int,
	@ReplyPostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1 -- new param with a default value
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

SET NOCOUNT ON

DECLARE @ThreadDate datetime
DECLARE @StickyDate datetime
DECLARE @UserID int
DECLARE @PostAuthor nvarchar(64)
DECLARE @FirstPostID INT
DECLARE @PostConfiguration int

-- Set default
SET @PostConfiguration = 0

IF @ReplyPostID = 0
	SELECT TOP 1 
		@ReplyPostID = PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate DESC

-- Get details about the reply & PostConfiguration details
SELECT 
	@ThreadDate = PostDate, 
	@UserID = UserID, 
	@PostAuthor = PostAuthor,
	@PostConfiguration = PostConfiguration
FROM 
	cs_Posts 
WHERE 
	PostID = @ReplyPostID and SettingsID = @SettingsID

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

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

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

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

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

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

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


-- fix the PostLevel and SortOrder ordering, by date
-- this could be done better, as it's on a MassScale now.
UPDATE
	cs_Posts
SET
	PostLevel = 1,
	SortOrder = 1
WHERE
	ThreadID = @ThreadID
	AND PostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostID ASC)

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

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

SET NOCOUNT OFF

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create  procedure [dbo].cs_system_UpdateUserPostCount
(
	@SectionID 	int,
	@UserID		int,
	@SettingsID 	int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Does the forum track post statistics?
	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 0
		RETURN

	UPDATE cs_UserProfile SET TotalPosts = TotalPosts + 1 WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





create      procedure [dbo].cs_system_UpdateUserPostRank
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @Usercount int
DECLARE @LoopCounter int

	SET NOCOUNT ON

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

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

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


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

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

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


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


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

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

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

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


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

END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

	FETCH NEXT FROM sections_cursor 
	INTO @SectionID

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

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

		FETCH NEXT FROM sections_cursor
		INTO @SectionID
	END

	CLOSE sections_cursor
	DEALLOCATE sections_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_system_UserCanReadSection
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_system_UserCanReadSection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

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

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

RETURN @HasAccess

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

	-- Update cs_Users table
	UPDATE 
		cs_Users 
	SET 
		LastActivity = GetDate(),
		LastAction = @LastAction
	WHERE 
		UserID = @UserID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].[cs_Tags_Get] 
	@SectionQuerySQL ntext,
	@SettingsID int,
	@CategoryList nvarchar(4000) = null
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

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

if @CategoryList is null begin

	select [Name], count(*) as TotalCount
	from cs_Post_Categories C
	inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
	where C.SettingsID = @SettingsID
		and C.SectionID in (select SectionID from #Sections)
		and C.IsEnabled = 1
	group by [Name]
	order by [Name]

end else begin

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

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

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

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

	select [Name], count(*) as TotalCount
	from cs_Post_Categories C
	inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
	where C.SettingsID = @SettingsID
		and C.SectionID in (select SectionID from #Sections)
		and C.IsEnabled = 1
		and PiC.PostID in (
			select P2.PostID
			from #Tags X
			inner join cs_Post_Categories C2 on X.[Name] = C2.Name
			inner join cs_Posts_InCategories PiC2 on PiC2.CategoryID = C2.CategoryID
			inner join cs_Posts P2 on PiC2.PostID = P2.PostID
			where C2.SettingsID = @SettingsID
				and C2.SectionID in (select SectionID from #Sections)
				and C2.IsEnabled = 1
				and P2.SettingsID = @SettingsID
				and P2.IsApproved = 1
			group by P2.PostID
			having count(*) = @categoryCount
			)
	group by [Name]
	having [Name] not in (select [Name] from #Tags)
	order by [Name]

	DROP TABLE #Tags

	EXEC sp_xml_removedocument @idoc

end

DROP TABLE #Sections
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_Threads_GetThreadSet'

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_Threads_GetThreadSet
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlCount ntext,
	@sqlPopulate ntext,
	@UserID int,
	@SettingsID int,
	@ReturnRecordCount bit,
	@IncludeCategories bit = 0
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int
DECLARE @GroupID int

-- Set sticky posts unsticky by limiting the scope of the query: the ideea is any user will clean up its stickies when it gets the chance
IF (@SectionID IS NOT NULL AND @SectionID >= 0)
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE SectionID = @SectionID AND UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID
ELSE
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID

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

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


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

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

SELECT
	jT.*, U.*,
	HasRead = 0,
	jP.PostID,
	jP.Subject,
	jP.Body,
	jP.FormattedBody,
	UserName = jT.PostAuthor,
	jP.PropertyNames as PostPropertyNames, jp.PropertyValues as PostPropertyValues,
	jP.PostConfiguration
FROM 
	#PageIndex jPI
	JOIN cs_Threads jT ON jPI.ThreadID = jT.ThreadID
	JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.cs_UserID and U.SettingsID = @SettingsID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name], jP.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
		JOIN cs_Posts_InCategories PIC ON jP.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND jP.PostLevel = 1 AND jP.SettingsID = @SettingsID
End

-- Update that the user has read this forum
IF @UserID > 0
BEGIN
	IF @SectionID > 0
		EXEC cs_Section_MarkRead @UserID, @SectionID, @SettingsID, @GroupID
END

SET ROWCOUNT @RowsToReturn

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
	EXEC (@sqlCount)

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

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


Go
/***********************************************
* Sproc: cs_Threads_ThreadSet_Unanswered
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_Threads_ThreadSet_Unanswered'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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


CREATE PROCEDURE dbo.cs_Thread_Delete
(
	@SettingsID int,
	@SectionID int,
	@ThreadID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostID INT
DECLARE @PostSubject NVARCHAR(256)

SET @PostID = 0
SET @PostSubject = ''

-- Get thread starter's post ID and subject
SELECT
	@PostID = p.PostID,
	@PostSubject = p.Subject
FROM
	cs_Threads t 
	LEFT JOIN cs_Posts AS p 
	ON t.ThreadID = p.ThreadID AND p.PostLevel = 1
WHERE
	t.ThreadID = @ThreadID AND 
	t.SectionID = @SectionID AND
	t.SettingsID = @SettingsID

DELETE FROM cs_PostAttachments WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_PostEditNotes WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts_InCategories WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)
	
DELETE FROM cs_PostsArchive WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadRating WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID AND ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

-- Update Moderation Audit table
IF (@PostID IS NOT NULL AND @PostID > 0)
BEGIN
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: thread starter post has been permanently deleted on request. Thread ID: ' + CAST(@ThreadID AS NVARCHAR(30)) + '. Thread Name: ' + @PostSubject

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

-- Update forum's statistics?
IF (@ResetStatistics = 1)
BEGIN
	EXEC cs_system_ResetForumStatistics @SectionID

	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID
END

END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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



CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



CREATE procedure [dbo].cs_Thread_PrevNext
(
	@PostID int,
	@NavigationType int,
	@SettingsID int
)
AS

DECLARE @ThreadDate datetime
DECLARE	@SectionID int
DECLARE	@ThreadID int


-- Get thread info
SELECT
	@ThreadDate = T.StickyDate,
	@SectionID = T.SectionID
FROM
	cs_Threads T INNER JOIN cs_Posts P ON T.ThreadID = P.ThreadID
WHERE
	P.PostID = @PostID AND
	P.SettingsID = @SettingsID


-- Compute prev/next thread
IF @NavigationType = 1	-- previous thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate < @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky DESC,
		StickyDate DESC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the beginning, no previous, so find last thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky DESC,
			StickyDate DESC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END
ELSE IF @NavigationType = 0	-- next thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate > @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky ASC,
		StickyDate ASC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the end, no next, so find first thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky ASC,
			StickyDate ASC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END

SELECT ThreadID = @ThreadID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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


CREATE PROCEDURE [dbo].cs_Thread_Status_Update 
(
	@ThreadID int,
	@Status int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @Status IS NOT NULL
BEGIN

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END
ELSE
BEGIN

	IF EXISTS (SELECT * FROM cs_Posts WHERE ThreadID = @ThreadID AND (PostStatus & 64) = 64)
		SET @Status = 1	-- if at least one reply is marked as an answer, mark the thread as answered
	ELSE
		SET @Status = 2	-- otherwise, mark the thread as unanswered

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UpdateForumGroupSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UpdateForumGroupSortOrder]
GO
/***********************************************
* Sproc: cs_UrlRedirects_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...cs_UrlRedirects_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE proc [dbo].[cs_UrlRedirects_Get]
(
	@UrlID	int = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		UrlID, Url, Description, Impressions
	from
		cs_UrlRedirects
	where
		UrlID = @UrlID OR (@UrlID = 0)
	order by
		UrlID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE proc [dbo].[cs_UrlRedirect_CreateUpdateDelete]
(
	@UrlID			int out,
	@Url			nvarchar(4000),
	@Description	nvarchar(2000),
	@Action 		int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

--Create
IF @Action = 0
BEGIN
	INSERT INTO
		cs_UrlRedirects (Url, Description)
	VALUES
		(@Url, @Description)

	SET @UrlID = @@IDENTITY
END
--Update
ELSE IF @Action = 1
BEGIN
	UPDATE cs_UrlRedirects SET
		Description = @Description,
		Url = @Url
	WHERE
		UrlID = @UrlID
END
--Delete
ELSE IF @Action = 2
BEGIN
	DELETE FROM
		cs_UrlRedirects
	WHERE
		UrlID = @UrlID
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UrlRedirect_CreateUpdateDelete] to public
GO
/***********************************************
* Sproc: cs_Urls_Add
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...cs_Urls_Add'


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

Go

Create Proc [dbo].cs_Urls_Add
(
	@UrlID int,
	@Url nvarchar(512)
)

as 
SET Transaction Isolation Level Read UNCOMMITTED

if not exists (Select UrlID From cs_urls where UrlID = @UrlID)
Begin
	Insert cs_Urls (UrlID, Url) values (@UrlID, @Url)
End
go



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


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


create procedure [dbo].[cs_Urls_RedirectLookup]
    @UrlID        int
as
BEGIN
	SELECT 
		url
	FROM
		cs_UrlRedirects
	WHERE
		urlID = @UrlID


	UPDATE
		cs_UrlRedirects
	SET
		impressions = impressions + 1
	WHERE
		urlID = @UrlID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE     PROCEDURE [dbo].cs_UserActivityNightlyJob

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

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



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_UserActivityNightlyJob to public
go

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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




GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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



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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserFeed_DeleteFeed  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


create  procedure [dbo].cs_UserHasPostsAwaitingModeration
(
	@UserName nvarchar(50),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Can the user moderate all forums?
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE UserName=@UserName AND SectionID=0)

		-- return ALL posts awaiting moderation
		IF EXISTS(SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 and SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	ELSE
		-- return only those posts in the forum this user can moderate
		IF EXISTS (SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 AND P.SectionID IN (SELECT SectionID FROM Moderators (nolock) WHERE UserName=@UserName and SettingsID = @SettingsID)  and F.SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].cs_UserInvitations_Expire
	@DateInvited datetime
AS

delete from cs_UserInvitation
where DateInvited < @DateInvited
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

CREATE PROCEDURE [dbo].cs_UserInvitations_GetBeforeDate
	@DateInvited datetime
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where DateInvited < @DateInvited
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE PROCEDURE [dbo].cs_UserInvitations_GetByUser
	@UserID int
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where UserID = @UserID
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/***********************************************
* Sproc: cs_UserInvitation_Create
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_UserInvitation_Create'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_UserInvitation_Create
	@UserID int,
	@Email nvarchar(255),
	@DateInvited datetime,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@InvitationKey uniqueidentifier out
AS

set @InvitationKey = newid()

insert into cs_UserInvitation (InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues)
values (@InvitationKey, @UserID, @Email, @DateInvited, @PropertyNames, @PropertyValues)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_UserInvitation_Delete
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_UserInvitation_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].cs_UserInvitation_Delete
	@InvitationKey uniqueidentifier
AS

delete from cs_UserInvitation
where InvitationKey = @InvitationKey
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].cs_UserInvitation_Get
	@InvitationKey uniqueidentifier
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where InvitationKey = @InvitationKey

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

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

/***********************************************
* Sproc: cs_UserReadPost_MarkPostRead
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_UserReadPost_MarkPostRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserReadPost_MarkPostRead  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE proc [dbo].cs_users_BackPort
(
	@SettingsID int,
	@UserName nvarchar(256),
	@Password nvarchar(128) = null,
	@PasswordSalt nvarchar(128) = null,
	@PasswordFormat int = null
)
as
SET Transaction Isolation Level Read UNCOMMITTED
if(@Password is null)
Begin
	Select a.Password, a.PasswordSalt, a.PasswordFormat  FROM cs_vw_Users_FullUser c, aspnet_Membership a where a.UserId = c.UserId and SettingsID = @SettingsID and @UserName = UserName
End
Else
Begin
	Declare @UserID uniqueidentifier
	Select @UserID = UserId FROM cs_vw_Users_FullUser where UserName = @UserName and SettingsID = @SettingsID
	
	Update aspnet_Membership
	Set Password = @Password, PasswordSalt = @PasswordSalt, PasswordFormat = @PasswordFormat
	Where UserId = @UserID
		
End

go


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

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




--cs_users_count_Get 0, 10, 0, 0, null, 0, 1, 0, 0, 1000
CREATE          PROCEDURE [dbo].cs_users_count_Get
(
	@UsernameFilter nvarchar(128),
	@FilterIncludesEmailAddress bit = 0,
	@UserAccountStatus smallint = 1,
	@IncludeHiddenUsers bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @TotalUsers int

BEGIN

-- Do we need to return a record count?
-- *************************************
  IF ((@UsernameFilter IS NULL) OR (@UsernameFilter = ''))
    SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND (UserName LIKE @UsernameFilter OR Email LIKE @UsernameFilter))



END




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

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


/***********************************************
* Sproc: cs_users_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_users_Get'

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_users_Get
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@SearchText nvarchar(256),
	@ReturnModerationCounters bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

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

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

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

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

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

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



SET @TotalUsers = @@rowcount

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

END

-- Return the record count
SELECT @TotalUsers

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Users_GetUserIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Users_GetUserIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Users_GetUserIDByFilter
--	Returns a list of filtered UserIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Users_GetUserIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@UserSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of user set
		SET @UserSetSize = CONVERT(int, @FilterValue)

		-- limit number of users to work with (non-positive = ALL)
		IF @UserSetSize > 0
			SET ROWCOUNT @UserSetSize

		-- get posts to work with
		SELECT		UP.UserID
		FROM		cs_UserProfile UP
		WHERE		UP.SettingsID = @SettingsID
		ORDER BY	UP.PointsUpdated			-- start with "stalest" users

		-- limit has been used; reset to default
		IF @UserSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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

/***********************************************
* Sproc: cs_users_Online
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_users_Online'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

	-- Get users 
	SELECT
		U.*
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.cs_LastActivity  > DateAdd(minute, -@PastMinutes, GetDate()) AND
		U.SettingsID = @SettingsID
	ORDER BY U.UserName
	
	-- Get anonymous 
	SELECT
		UserID,
		LastActivity = LastLogin,
		LastAction
	FROM
		cs_AnonymousUsers where SettingsID = @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE [dbo].cs_users_UsersInRole_Get
(
	@PageIndex int,
	@PageSize int,
	@SortBy int = 0,
	@SortOrder int = 0,
	@RoleID uniqueidentifier,
	@UserAccountStatus smallint = 1,
	@ReturnRecordCount bit = 0,
	@SettingsID int
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

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

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

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

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

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

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

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

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

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

-- Get the user details
SELECT
	*,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID and SettingsID = @SettingsID)
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.IndexID
END

-- Return the record count if necessary

IF (@ReturnRecordCount = 1)
  SELECT @TotalUsers


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







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

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




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE  procedure [dbo].cs_User_Anonymous_Count
(
	@TimeWindow int,
	@SettingsID int,
	@AnonymousUserCount int out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @StatDate datetime

	-- Clean up the anonymous users table
	DELETE cs_AnonymousUsers WHERE LastLogin < DateAdd(minute, -@TimeWindow, GetDate())	 and  SettingsID = @SettingsID

	-- Get a count of anonymous users
	SET @AnonymousUserCount = (SELECT count(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID)

	-- Do we need to update our forum statistics?
	SET @StatDate = (SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID)
	IF (SELECT TotalAnonymousUsers FROM cs_statistics_Site WHERE DateCreated = @StatDate and SettingsID = @SettingsID) < @AnonymousUserCount 
		UPDATE
			cs_statistics_Site
		SET 
			TotalAnonymousUsers = @AnonymousUserCount
		WHERE
			DateCreated = @StatDate and SettingsID = @SettingsID

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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







CREATE     PROCEDURE [dbo].cs_User_Anonymous_Update
(
	@UserID char(36),
	@LastActivity datetime,
	@LastAction nvarchar(1024) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Does the user already exist?
	IF EXISTS (SELECT UserID FROM cs_AnonymousUsers WHERE UserID = @UserID and SettingsID = @SettingsID)

		UPDATE 
			cs_AnonymousUsers
		SET 
			LastLogin = @LastActivity,
			LastAction = @LastAction
		WHERE
			UserID = @UserID and SettingsID = @SettingsID

	ELSE

		INSERT INTO
			cs_AnonymousUsers
			(UserID, LastLogin, LastAction, SettingsID) 
		VALUES
			(@UserID, @LastActivity, @LastAction, @SettingsID)

END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



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

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

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

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE  procedure [dbo].cs_user_CreateUpdateDelete 
(
	@cs_UserID int out,
	@UserID uniqueidentifier = null,
	@UserName   nvarchar (64) = '',
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '',
	@ForumView   int = 0,
	@TimeZone   float = 0.0,
	@PostRank   binary(1) = 0x0,
	@PostSortOrder   int = 0,
	@IsAvatarApproved   smallint  = 0,
	@ForceLogin   bit   = 0,
	@ModerationLevel  smallint  = 0,
	@EnableThreadTracking  smallint  = 0,
	@EnableDisplayUnreadThreadsOnly smallint  = 0,
	@EnableAvatar    smallint  = 0,
	@EnableDisplayInMemberList  smallint  = 1,
	@EnablePrivateMessages  smallint  = 1,
	@EnableOnlineStatus smallint  = 1,
	@EnableEmail smallint  = 1,
	@EnableHtmlEmail   smallint  = 1,
	@FavoritesShared int = 0,
	@AllowSiteToContact bit = 0,
	@AllowSitePartnersToContact bit = 0,
	@SettingsID int,
	@Action    int,
	@UpdateAllSettingsID bit = 0
)
AS
/*
This sproc returns an int that indicates the CreateUserStatus enum value:
	UnknownFailure = 0
	Created = 1
	DuplicateUsername = 2
	DuplicateEmailAddress = 3
	InvalidFirstCharacter = 4
	DisallowedUsername = 5
	Updated = 6
	Deleted = 7
	InvalidQuestionAnswer = 8
	InvalidPassword = 9
*/

-- first, we need to check if the username is a dup

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

		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
		VALUES(@UserID, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '')

		Select @cs_UserID = @@Identity

		INSERT INTO cs_UserProfile ( [UserID], [TimeZone], [TotalPosts], 	[PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableEmail], [EnableHtmlEmail], [IsIgnored], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues], [FavoritesShared], [AllowSiteToContact], [AllowSitePartnersToContact])
		Select @cs_UserID, @TimeZone, 0, @PostSortOrder, @PostRank, @IsAvatarApproved, @ModerationLevel, @EnableThreadTracking,  @EnableDisplayUnreadThreadsOnly,  @EnableAvatar,   @EnableDisplayInMemberList, @EnablePrivateMessages,   @EnableOnlineStatus,  @EnableEmail, @EnableHtmlEmail, @IsIgnored,  @UserID, SettingsID, @PropertyNames, @PropertyValues, @FavoritesShared, @AllowSiteToContact, @AllowSitePartnersToContact
		FROM cs_SiteSettings where ApplicationName = @ApplicationName
		
		Select 1
		RETURN
	END
END
ELSE
BEGIN

	UPDATE
		cs_UserProfile
	SET
		TimeZone = @TimeZone,
		PostRank = @PostRank,
		PostSortOrder = @PostSortOrder,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		IsAvatarApproved = @IsAvatarApproved,
		ModerationLevel = @ModerationLevel,
		EnableThreadTracking = @EnableThreadTracking,
		EnableDisplayUnreadThreadsOnly = @EnableDisplayUnreadThreadsOnly,
		EnableAvatar = @EnableAvatar,
		EnableDisplayInMemberList = @EnableDisplayInMemberList,
		EnablePrivateMessages = @EnablePrivateMessages,
		EnableOnlineStatus = @EnableOnlineStatus,
		EnableEmail = @EnableEmail,
		EnableHtmlEmail = @EnableHtmlEmail,
		FavoritesShared = @FavoritesShared,
		AllowSiteToContact = @AllowSiteToContact,
		AllowSitePartnersToContact = @AllowSitePartnersToContact,
		IsIgnored = @IsIgnored
	WHERE
		UserID = @cs_UserID
		AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
	

	-- Update the user's anonymous settings passed in, as well.
	UPDATE aspnet_Users
	SET IsAnonymous = @IsAnonymous
	WHERE UserId = @UserID
  
	-- Some properties will be created/defaulted by SHS Create User.
	-- These values will be updated by Membership.UpdateUser as well. 
	-- Here we just update the properties which fall outside of MembershipUser
	-- First Update the cs_vw_forums_Users table

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

	SELECT 6
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE procedure [dbo].[cs_User_Delete]
(
	@UserID					int,
	@ReassignUserName		nvarchar(256)
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- locals
	DECLARE	@ApplicationGuid	uniqueidentifier
	DECLARE	@UserGuid			uniqueidentifier
	DECLARE	@ReassignUserID		int


	-- lookup application, user
	SELECT	@ApplicationGuid = ASP.ApplicationId, @UserGuid = ASP.UserId
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID


	-- lookup reassign user
	SELECT	@ReassignUserID = CS.UserID
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	LoweredUserName = LOWER(@ReassignUserName)
		AND	ApplicationId = @ApplicationGuid


	-- does the reassign user exist?
	IF (@ReassignUserID IS NULL)
	BEGIN
		SELECT 2 -- InvalidReassignUserName
		RETURN
	END


	-- reassign user appears valid
	BEGIN TRANSACTION


	-- be sure posts are set to be reindexed BEFORE they are reassigned
	EXECUTE cs_Posts_ReindexByUser @UserID
	IF (@@ERROR <> 0) GOTO Failure


	-- reassign content
	UPDATE	cs_InkData
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_ModerationAudit
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments_TEMP
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

	UPDATE	cs_Posts_Deleted_Archive
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostsArchive
	SET		UserName = CONVERT(nvarchar(64), @ReassignUserName)
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PrivateMessages
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

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

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

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

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


	-- delete content
	DELETE
	FROM	cs_FavoritePosts
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


	-- delete user
	DELETE
	FROM	cs_Moderators
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

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

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

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

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

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

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


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


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Delete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_user_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...cs_user_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE      PROCEDURE [dbo].cs_user_Get
(
	@UserID int,
	@Username nvarchar(64) = null,
	@IsOnline bit = 0,
	@LastAction nvarchar(1024) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @UserIDGUID as uniqueidentifier

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

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

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


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

	IF @IsOnline = 1
	BEGIN
		EXEC cs_system_UserIsOnline @UserID, @LastAction, @SettingsID
	END
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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






create procedure [dbo].cs_User_GetByEmail
(
	@Email		nvarchar(64),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	cs_UserID
FROM
	cs_vw_Users_FullUser
WHERE
	Email = @Email and SettingsID = @SettingsID





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROC [dbo].cs_User_GetOpmlFeedsFolders
	@UserId INT
AS

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_User_GetOpmlFeedsFolders  TO PUBLIC
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



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

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

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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE procedure [dbo].[cs_User_Rename]
(
	@UserID					int,
	@DesiredUserName		nvarchar(256),
	@IgnoreDisallowedNames	bit = 0
)
AS
	-- do we care about disallowed names?
	IF (@IgnoreDisallowedNames = 0)
		-- is username allowed?
		IF EXISTS (SELECT * FROM cs_DisallowedNames WHERE @DesiredUserName LIKE REPLACE(DisallowedName, '*', '%'))
		BEGIN
			SELECT 3 -- DisallowedUserName
			RETURN
		END


	-- is the desired username available?
	IF EXISTS (SELECT * FROM aspnet_Users WHERE LoweredUserName = LOWER(@DesiredUserName) AND ApplicationId = (SELECT ApplicationId FROM aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID WHERE CS.UserID = @UserID) AND UserId <> (SELECT CS2.MembershipID FROM cs_Users CS2 WHERE CS2.UserID = @UserID)) -- username is taken
	BEGIN
		SELECT 2 -- DuplicateUserName
		RETURN
	END


	-- username is available, begin update
	BEGIN TRANSACTION


	-- handle ASP.NET membership system
	UPDATE	aspnet_Users
	SET	UserName = @DesiredUserName, LoweredUserName = LOWER(@DesiredUserName)
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


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

	IF (@@ERROR <> 0) GOTO Failure


	-- be sure posts are reindexed
	EXECUTE cs_Posts_ReindexByUser @UserID

	IF (@@ERROR <> 0) GOTO Failure


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


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Rename] TO PUBLIC
GO
/***********************************************
* Sproc: cs_User_ToggleSettings
* File Date: 8/8/2006 9:28:12 AM
***********************************************/
Print 'Creating...cs_User_ToggleSettings'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE   procedure [dbo].[cs_User_ToggleSettings]
(
	@UserID int,
	@ModerationLevel int,
	@UserAccountStatus int,
	@ForceLogin bit = 0,
	@IsAvatarApproved bit,
	@ModeratorID int,
	@SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE	@CurrentUserAccountStatus	int
	SELECT	@CurrentUserAccountStatus = UserAccountStatus
	FROM	cs_Users
	WHERE	UserID = @UserID

	UPDATE 
		cs_Users
	SET
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		UserID = @UserID 

	DECLARE	@CurrentModerationLevel	int
	SELECT	@CurrentModerationLevel = ModerationLevel
	FROM	cs_UserProfile
	WHERE	UserID = @UserID
	AND		SettingsID = @SettingsID

	UPDATE
		cs_UserProfile
	SET
		ModerationLevel = @ModerationLevel,
		IsAvatarApproved = @IsAvatarApproved
	WHERE
		UserID = @UserID AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

	IF (@ModerationLevel != @CurrentModerationLevel)		-- moderation level has changed
	BEGIN
		IF (@ModerationLevel = 0)
			exec cs_system_ModerationAction_AuditEntry 11, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 10, @ModeratorID, null, @UserID, null, @SettingsID
	END

	IF (@UserAccountStatus != @CurrentUserAccountStatus)	-- user account status has changed
	BEGIN
		IF @UserAccountStatus = 1
			exec cs_system_ModerationAction_AuditEntry 13, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 12, @ModeratorID, null, @UserID, null, @SettingsID
	END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_Vote_Create
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_Vote_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


create procedure [dbo].cs_Vote_Create (
  @PostID int,
  @UserID int,
  @Vote nvarchar(2),
  @SettingsID int
)
AS
IF NOT EXISTS (
    SELECT
        PostID 
    FROM 
        cs_VoteSummary
    WHERE 
        PostID = @PostID AND Vote = @Vote and SettingsID = @SettingsID
)
BEGIN
        INSERT INTO 
            cs_VoteSummary
        VALUES
        (
            @PostID,
            @Vote,
            1,
	    @SettingsID
        )

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
END
ELSE
BEGIN
	IF EXISTS(SELECT UserID FROM cs_Votes WHERE PostID = @PostID AND UserID = @UserID)
		-- Already voted
		RETURN

        UPDATE 
          cs_VoteSummary
        SET 
          VoteCount  =  VoteCount + 1
        WHERE 
          PostID = @PostID AND
          Vote = @Vote and SettingsID = @SettingsID

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

CREATE   procedure [dbo].cs_Vote_GetSummary (
	@PostID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
  SELECT
	Vote,
	VoteCount
  FROM
	cs_VoteSummary
  WHERE
	PostID = @PostID

  SELECT
	UserID,
	Vote
  FROM
	cs_Votes
  WHERE
	PostID = @PostID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE   PROCEDURE [dbo].cs_weblog_DeleteStaleSpamComments
(
	@SettingsID int,
	@ExpirationDays int = 30
)
AS

SET Transaction Isolation Level Read UNCOMMITTED


DECLARE	@CommentsToDelete TABLE
		(PostID int)

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

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

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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/***********************************************
* Sproc: cs_weblog_Feedback_Get
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_weblog_Feedback_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Feedback_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Feedback_Get]
GO
/***********************************************
* Sproc: cs_weblog_PostsByMonth
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...cs_weblog_PostsByMonth'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE proc [dbo].cs_weblog_PostsByMonth
(
	@SectionID int,
	@Year int,
	@Month int
)
as

SET Transaction Isolation Level Read UNCOMMITTED


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




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE proc [dbo].cs_weblog_PostsByMonthList
(
	@SectionID int
)
as

SET Transaction Isolation Level Read UNCOMMITTED

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




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





CREATE PROCEDURE dbo.cs_weblog_PostSet
(
	@SectionID int,
	@PostID	int,
	@PostName nvarchar(512) = null,
	@PageIndex int,
	@PageSize int,
	@UserID int,
	@ReturnFullThread bit,
	@IncludeCategories bit,
	@TotalRecords int output
)
AS

BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int


-- Get the ThreadID
if(@PostName is null)
Begin
	SELECT
		@ThreadID = ThreadID
	FROM 
		cs_Posts
	WHERE 
		PostID = @PostID and SectionID = @SectionID
End
Else
Begin
	SELECT
		@ThreadID = P.ThreadID, @PostID = P.PostID
	FROM 
		cs_Posts P
	WHERE 
		P.SectionID = @SectionID and P.PostName = @PostName

End

--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, 
		P.SortOrder, P.Subject, P.PostDate, P.IsApproved, P.IsLocked, P.IsIndexed, P.TotalViews, 
		P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, 
		P.AggViews, P.PostPropertyNames, P.PostPropertyValues, P.PostConfiguration,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, T.TotalReplies as Replies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostName, P.UserTime,P.ApplicationPostType, P.Points as PostPoints,
		P.PostAuthor as Username,
		EditNotes = null,
		AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize,[FileName], p.Created, p.Height, p.Width,
		IsModerator = 0,
		HasRead = 0 -- not used,
		, P.PostStatus, P.SpamScore
	FROM 
		cs_vw_PostsWithAttachmentDetails P (nolock),
		cs_Threads T
	WHERE 
		P.PostID = @PostID AND
		T.ThreadID = P.ThreadID



--Do we want/need categories
	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End


--Are we going to honor paging?
if @ReturnFullThread = 0
Begin
	-- First set the rowcount
	DECLARE @RowsToReturn int
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	

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


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

	INSERT INTO #PageIndex (PostID)
	SELECT P.PostID 
	FROM cs_Posts P (nolock)
	WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel > 1 and P.ApplicationPostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY PostDate

	Set @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.UserTime,
		P.Points as PostPoints,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		#PageIndex.*,
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0,
		IsModerator = 0, 
		HasRead = 0 -- not used
		, P.PostStatus, P.SpamScore
	FROM 
		cs_Posts P (nolock),
		cs_Threads T,
		#PageIndex
	WHERE 
		P.PostID = #PageIndex.PostID AND
		T.ThreadID = P.ThreadID AND
		#PageIndex.IndexID > @PageLowerBound AND
		#PageIndex.IndexID < @PageUpperBound
	ORDER BY
		IndexID

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

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

	SELECT @TotalRecords = Count(P.PostID) FROM cs_Posts P (nolock) WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel <> 1 and P.PostType <> 16

END

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/***********************************************
* Sproc: cs_weblog_Posts_GetPostSet
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...cs_weblog_Posts_GetPostSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_Post_Create
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE   PROCEDURE [dbo].cs_weblog_Post_Create
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit = 0,
	@IsTracked bit = 0,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime,
	@UserTime datetime,
	@UserHostAddress nvarchar(32),
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@SpamScore int = 0,
	@PostStatus int = 0,
	@PostID int out
) 
AS
SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ThreadID int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @IsComment bit

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType)
	Begin
		Return 2
	End
End

if(@BlogPostType = 1 OR @BlogPostType = 2)
	SET @IsComment = 0
Else
	SET @IsComment = 1

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

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

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

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

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

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

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


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

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

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

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

	-- Get the new PostID
	SELECT 
		@PostID = @@IDENTITY


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

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = @@IDENTITY 


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1 
	BEGIN		
		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			--MostRecentPostAuthor = @PostAuthor, << We do not track comments
			--MostRecentPostAuthorID = @UserID, << We do not track comments
			--MostRecentPostID = @PostID, << We do not track Comments
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE  p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
			--IsLocked = @IsLocked,
			--StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			--ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID
	END
--	ELSE
/*
	BEGIN
		-- Moderated Posts: get the new PostID
		SELECT @PostID = @@IDENTITY 
	END
*/
/*
	-- Clean up ThreadsRead (this should work very well now)
	-- Not tracking in blogs
	DELETE
		cs_ThreadsRead
	WHERE
		ThreadID = @ThreadID 
		AND UserID <> @UserID
*/
END

--Increments posts totals ignoring settings id
IF @EnablePostStatistics = 1 AND @UserID > 0 AND @IsApproved = 1
BEGIN
	EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
END

IF(@BlogPostType = 1 OR @BlogPostType = 2)
BEGIN
	IF @IsTracked = 1
		BEGIN
		INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
		VALUES	( @ThreadID, @UserID, @SettingsID )
	END
	
	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
END

--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

	
COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_weblog_Post_Create] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Delete
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Delete]
GO



CREATE   PROCEDURE [dbo].cs_weblog_Post_Delete
(
	@SectionID int,
	@PostID int,
	@UserID int,
	@BlogPostType tinyint = 1,
	@SettingsID int
) 
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @ThreadID int
Select @ThreadID = ThreadID FROM cs_Posts where PostID = @PostID

if(@BlogPostType = 4 or @BlogPostType = 8)
Begin
	Delete FROM cs_Posts where PostID = @PostID
End
ELSE
Begin

	Delete FROM cs_Posts_InCategories where PostID = @PostID and SettingsID =  @SettingsID
	Delete FROM cs_PostAttachments where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_ThreadRating where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Referrals where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_TrackedThreads where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Posts where ThreadID = @ThreadID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_Threads where ThreadID = @ThreadID and SectionID = SectionID

End


-- exec cs_weblog_UpdateContentHistory @SectionID = @SectionID, @BlogPostTypeFilter = @BlogPostType
exec cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID

-- Update thread statistics
exec cs_system_ResetThreadStatistics @ThreadID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_weblog_Post_Delete] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Get]
GO




CREATE PROCEDURE dbo.cs_weblog_Post_Get --11, 36, 0, 1, 0
(

	@PostID	int,
	@IncludeCategories bit,
	@IsApprovedFilter bit,
	@SettingsID int
)
AS
BEGIN

DECLARE	@SectionID int
DECLARE @ThreadID int 
DECLARE @SortOrder int
DECLARE @IsApproved bit


SELECT 
	@SectionID = SectionID,
	@ThreadID = ThreadID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and  SettingsID = @SettingsID


SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues,
	P.PostConfiguration, P.UserTime, P.PostName,P.ApplicationPostType,
	P.Points as PostPoints,
	T.*, U.*,
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	HasRead = 0,
	EditNotes = null, -- (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = 0,  -- (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],p.Created, p.Height, p.Width,
	IsModerator = 0, -- (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID),
	Replies = T.TotalReplies, -- (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = 0,
	IsTracked = Convert(bit,0) -- Convert(bit, (Select Count(*) FROM cs_TrackedThreads where UserID = @UserID and ThreadID = P.ThreadID))
	, P.PostStatus, P.SpamScore
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND P.SettingsID = @SettingsID and T.SettingsID = @SettingsID AND
	U.SettingsID = @SettingsID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.cs_UserID AND
	P.IsApproved <> case @IsApprovedFilter when 1 then 0 else -1 END

	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_Post_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_Post_Update
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Update]
GO






CREATE  PROCEDURE [dbo].cs_weblog_Post_Update
(
	@PostID	int,
	@SectionID int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsApproved     bit = 0,
	@IsTracked      bit = 0,
	@EditedBy	int,
	@PostMedia int = 0, 
	@Excerpt nvarchar(500) = null,
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@UserTime datetime,
	@PostDate datetime,
	@PostStatus int = 0,
	@SpamScore int = 0
)
AS

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType and p.PostID <> @PostID)
	Begin
		Return 2
	End
End

	DECLARE @ThreadID int
	Declare @ParentID int
	--DECLARE @PostDate datetime

	Select @ThreadID = ThreadID, @ParentID = ParentID FROM cs_Posts where PostID = @PostID

	-- this sproc updates a post (called from the moderate/admin page)
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		IsApproved = @IsApproved,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostDate = @PostDate,
		PostName = @PostName,
		UserTime = @UserTime,
		PostConfiguration = @PostConfig,
		ApplicationPostType = @BlogPostType,
		PostMedia = @PostMedia,
		PostStatus = @PostStatus,
		SpamScore = @SpamScore
		
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID


	if(@PostID = @ParentID)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	


	-- Allow thread to update sticky properties.
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		-- Get the thread and postdate this applies to
		SELECT 
			@ThreadID = ThreadID,
			@PostDate = PostDate 
		FROM 
			cs_Posts 
		WHERE 
			PostID = @PostID and SettingsID = @SettingsID

		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @PostDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID		
		END
	END

	IF(@BlogPostType = 1 OR @BlogPostType = 2)
	BEGIN


		IF @IsTracked = 1
		BEGIN
			-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
			IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @EditedBy )
				INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
			VALUES	( @ThreadID, @EditedBy, @SettingsID)
		END
		Else
		Begin
			DELETE FROM cs_TrackedThreads where ThreadID = @ThreadID and UserID = @EditedBy and SettingsID = @SettingsID
		End


	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
	END


		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE P.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
		WHERE
			ThreadID = @ThreadID

	--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Post_Update] to public
go

/***********************************************
* Sproc: cs_weblog_Search
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_weblog_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search]
GO

/***********************************************
* Sproc: cs_weblog_Search_PostReindex
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
Print 'Creating...cs_weblog_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search_PostReindex]
GO




/***********************************************
* Sproc: cs_weblog_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:22 AM
***********************************************/
Print 'Creating...cs_weblog_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Threads_GetThreadSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_TrackedThreadsByUser
* File Date: 8/8/2006 9:28:13 AM
***********************************************/
Print 'Creating...cs_weblog_TrackedThreadsByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_TrackedThreadsByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_TrackedThreadsByUser]
GO



CREATE PROCEDURE dbo.cs_weblog_TrackedThreadsByUser
(
	@SectionID int,
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		T.*, U.*,P.PostName, P.UserTime, P.ApplicationPostType, P.PostConfiguration,
		P.Points as PostPoints,
		T.IsLocked,
		T.IsSticky,
		Username = P.PostAuthor,
		EditNotes = '',
		AttachmentFilename = null, -- ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		Replies = 0,-- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
		IsModerator = 0, --(SELECT count(UserID) from cs_Moderators where UserID = @UserID),
		HasRead = 0, -- not used
		P.PostStatus, P.SpamScore
FROM
		dbo.cs_TrackedThreads TT INNER JOIN
		dbo.cs_Threads T ON TT.ThreadID = T.ThreadID INNER JOIN
		dbo.cs_Posts P (nolock) ON T.ThreadID = P.ThreadID INNER JOIN
		dbo.cs_vw_Users_FullUser U ON TT.UserID = U.cs_UserID
WHERE
		(TT.SettingsID = @SettingsID) 
		AND (TT.UserID = @UserID) 
		AND (T.SectionID = @SectionID) 
		AND (P.PostLevel = 1) 
		AND (P.IsApproved = 1)


END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_weblog_TrackedThreadsByUser to public
go

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_TrackedThreadsByUser]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_UpdateContentHistory
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...cs_weblog_UpdateContentHistory'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateContentHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_UpdateContentHistory]
GO



/* TO ADD existing blog data
Insert cs_weblog_Weblogs (SectionID)
Select SectionID FROM cs_Sections where applicationtype = 1
*/

CREATE Proc [dbo].cs_weblog_UpdateContentHistory
(
	@SectionID int,
	@BlogPostTypeFilter tinyint = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
If @BlogPostTypeFilter = 1
BEGIN

	Declare @MostRecentPostID int
	Declare @MostRecentPostDate datetime
	Declare @MostRecentPostName nvarchar(256)
	Declare @MostRecentPostAuthorID int
	Declare @MostRecentPostAuthorName nvarchar(256)
	Declare @MostRecentPostSubject nvarchar(256)
	Declare @PostCount int

	--Get Post Info
	Select Top 1 
		@MostRecentPostID = P.PostID, 
		@MostRecentPostDate =  P.PostDate, 
		@MostRecentPostAuthorID = UserID, 
		@MostRecentPostAuthorName = PostAuthor, 
		@MostRecentPostName = PostName,
		@MostRecentPostSubject = Subject 
	FROM cs_Posts P
	where P.ApplicationPostType = 1 and P.SectionID = @SectionID and P.IsApproved = 1 Order by P.PostDate Desc

	Select @PostCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 1)

	update cs_weblog_Weblogs
	Set
		MostRecentPostID = isnull(@MostRecentPostID,0),
		MostRecentPostDate = isnull(@MostRecentPostDate,getdate()),
		MostRecentPostAuthorID = isnull(@MostRecentPostAuthorID,0),
		MostRecentPostAuthor = isnull(@MostRecentPostAuthorName,''),
		MostRecentPostName = @MostRecentPostName,
		MostRecentPostSubject = isnull(@MostRecentPostSubject,''),
		PostCount = @PostCount
	Where SectionID = @SectionID
END
Else If @BlogPostTypeFilter = 2
BEGIN

	Declare @MostRecentArticleID int
	Declare @MostRecentArticleDate datetime
	Declare @MostRecentArticleName nvarchar(256)
	Declare @MostRecentArticleAuthorID int
	Declare @MostRecentArticleAuthorName nvarchar(256)
	Declare @MostRecentArticleSubject nvarchar(256)
	Declare @ArticleCount int

--Get Article Info
	Select Top 1 
		@MostRecentArticleID = P.PostID, 
		@MostRecentArticleDate = P.PostDate, 
		@MostRecentArticleAuthorID = UserID, 
		@MostRecentArticleAuthorName = PostAuthor, 
		@MostRecentArticleName = PostName,
		@MostRecentArticleSubject = Subject
	FROM cs_Posts P
	where P.ApplicationPostType = 2 and P.SectionID = @SectionID and P.IsApproved = 1 Order by P.PostDate Desc

	Select @ArticleCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 2)


	update cs_weblog_Weblogs
	Set
		MostRecentArticleID = isnull(@MostRecentArticleID,0),
		MostRecentArticleDate = isnull(@MostRecentArticleDate,getdate()),
		MostRecentArticleAuthorID = isnull(@MostRecentArticleAuthorID,0),
		MostRecentArticleAuthor = isnull(@MostRecentArticleAuthorName,''),
		MostRecentArticleName = @MostRecentArticleName,
		MostRecentArticleSubject = isnull(@MostRecentArticleSubject,''),
		ArticleCount = @ArticleCount
	Where SectionID = @SectionID
End
ELSE If @BlogPostTypeFilter = 4
BEGIN
	Declare @CommentCount int
	Select @CommentCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 4)
	update cs_weblog_Weblogs
	Set
		CommentCount = @CommentCount
	Where SectionID = @SectionID
END
ELSE If @BlogPostTypeFilter = 8
BEGIN
	Declare @TrackBackCount int
	Select @TrackBackCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 8)
	update cs_weblog_Weblogs
	Set
		TrackbackCount = @TrackBackCount
	Where SectionID = @SectionID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_UpdateContentHistory] to public
go
/***********************************************
* Sproc: cs_weblog_UpdateWeblogRecentContent_Job
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...cs_weblog_UpdateWeblogRecentContent_Job'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateWeblogRecentContent_Job]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_UpdateWeblogRecentContent_Job]
GO



Create Proc [dbo].cs_weblog_UpdateWeblogRecentContent_Job
(
	@SettingsID int
) 

as

SET Transaction Isolation Level Read UNCOMMITTED

Set NOCount On

Update cs_weblog_weblogs
Set 
	MostRecentPostID = P.PostID, 
	MostRecentPostDate = P.UserTime, 
	MostRecentPostName = P.PostName, 
	MostRecentPostAuthorID = P.UserID, 
	MostRecentPostAuthor = P.PostAuthor, 
	MostRecentPostSubject = P.Subject
FROM
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where p.ApplicationPostType = 1 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID



--We may be able to can the articles part
Update cs_weblog_weblogs
Set 
	MostRecentArticleID = P.PostID , 
	MostRecentArticleDate = P.UserTime, 
	MostRecentArticleName = P.PostName, 
	MostRecentArticleAuthorID = P.UserID, 
	MostRecentArticleAuthor = P.PostAuthor, 
	MostRecentArticleSubject = P.Subject
FROM 
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where  p.ApplicationPostType = 2 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where 
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID

--Update Count Items
update cs_Weblog_Weblogs
Set
	PostCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 1 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	ArticleCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 2 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	CommentCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 4 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	TrackBackCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 8 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID)
where 
	cs_Weblog_Weblogs.SettingsID = @SettingsID


-- Update Weblog Section records. 
-- NOTE: Other applications update the Section table stats via cs_system_UpdateForum, called from cs_Post_CreateUpdate
UPDATE cs_Sections
SET
	TotalPosts = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1), 0),
	TotalThreads = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1 and p.PostLevel = 1), 0),
	-- For weblogs, only count feedback that is not approved (ignore posts/articles)
	PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = cs_Sections.SectionID AND p.IsApproved = 0 and p.PostLevel > 1), 0)
WHERE
	cs_Sections.SettingsID = @SettingsID
	and cs_Sections.ApplicationType = 1



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_UpdateWeblogRecentContent_Job] to public
go
/***********************************************
* Sproc: cs_weblog_Weblogs_Get
* File Date: 8/8/2006 9:28:14 AM
***********************************************/
Print 'Creating...cs_weblog_Weblogs_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Weblogs_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Weblogs_Get]
GO




CREATE        PROCEDURE [dbo].cs_weblog_Weblogs_Get
(
	@SettingsID	int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
-- Return all the forums

SELECT 
	F.[SectionID], F.[SettingsID], F.[IsActive], F.[ParentID], F.[GroupID], F.[Name], F.[NewsgroupName], F.[Description], F.[DateCreated], F.[Url], F.[IsModerated], F.[DaysToView], F.[SortOrder], F.[TotalPosts], F.[TotalThreads], F.[DisplayMask], F.[EnablePostStatistics], F.[EnablePostPoints], F.[EnableAutoDelete], F.[EnableAnonymousPosting], F.[AutoDeleteThreshold], F.[MostRecentThreadID], F.[MostRecentThreadReplies], F.[PostsToModerate], F.[ForumType], F.[IsSearchable], F.[ApplicationType], F.[ApplicationKey], 
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.[DefaultLanguage], W.*,
	null as	LastUserActivity
		
FROM
	cs_Sections F, cs_weblog_Weblogs W
WHERE
	F.SettingsID = @SettingsID AND
	 ApplicationType = 1 AND F.SectionID = W.SectionID


exec cs_Section_Permissions_Get @SettingsID, 0, 1
/*
SELECT
	P.*, F.ApplicationKey
FROM
	cs_SectionPermissions P,
	cs_Sections F,
	cs_UserProfile U,
	aspnet_UsersInRoles R
	
WHERE
	P.RoleID = R.RoleId AND
	U.MembershipID = R.UserId and
	(U.UserID = @UserID )--OR U.UserID = 0) 
	and F.ApplicationType = 1 and F.SectionID = P.SectionID
*/









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Weblogs_Get] to public
go
/***********************************************
* Sproc: files_Comments_GetComments
* File Date: 8/8/2006 9:28:18 AM
***********************************************/
Print 'Creating...files_Comments_GetComments'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_comments_getComments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_comments_getComments]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  PROCEDURE [dbo].[files_comments_getComments]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate ntext,
	@UserID int,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1



-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

--CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

SELECT 
	SortOrder = jPI.IndexID,
	jP.PostID, jP.ThreadID, jP.ParentID, jP.PostAuthor, jP.UserID, jP.SectionID, jP.PostLevel, jP.SortOrder, jP.Subject, jP.PostDate, jP.IsApproved,
	jP.IsLocked, jP.IsIndexed, jP.TotalViews, jP.Body, jP.FormattedBody, jP.IPAddress, jP.PostType, jP.PostMedia, jP.EmoticonID, jP.SettingsID, jP.AggViews,
	jP.PostPropertyNames, jP.PostPropertyValues,
	jP.PostConfiguration, jP.UserTime, jP.ApplicationPostType, jP.PostName, jP.PostStatus, jP.SpamScore,
	jP.Points as PostPoints, jP.RatingSum as PostRatingSum, jP.TotalRatings as PostTotalRatings,
	HasRead = 1,
	jT.*, jU.*,
	Username = jP.PostAuthor,
	ThreadStarterAuthor = jT.PostAuthor,
	ThreadStartDate = jT.PostDate,	
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = jP.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = jP.PostID), ''),
	Replies = 0, --not used(SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = 0 -- not used
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	JOIN cs_vw_Users_FullUser jU ON jU.cs_UserID = jP.UserID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	--AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID and jU.SettingsID = @SettingsID 
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

If @IncludePageIndex = 1
BEGIN
	SELECT IndexID, PostID from #PageIndex ORDER BY IndexID
END

DROP TABLE #PageIndex
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_Comments_GetComments] to public
go

/***********************************************
* Sproc: files_Downloads_Log
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...files_Downloads_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Downloads_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Downloads_Log]
GO

CREATE PROCEDURE [dbo].files_Downloads_Log
	@PostID int,
	@UserID int
AS

INSERT INTO files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Downloads_Log to public
go
/***********************************************
* Sproc: files_Entries_GetEntries
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...files_Entries_GetEntries'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entries_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entries_GetEntries]
GO

CREATE PROCEDURE dbo.files_Entries_GetEntries
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate nText,
	@UserID int,
	@IncludeCategories bit,
	@SettingsID int,
	@TotalRecords int output
)
AS


DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)


INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET ROWCOUNT @RowsToReturn

SELECT 
	jT.*,
	jP.PostID, jP.ThreadID, jP.ParentID, jP.PostAuthor, jP.UserID, jP.SectionID, jP.PostLevel, jP.SortOrder, jP.Subject, jP.PostDate, jP.IsApproved,
	jP.IsLocked, jP.IsIndexed, jP.TotalViews, jP.Body, jP.FormattedBody, jP.IPAddress, jP.PostType, jP.PostMedia, jP.EmoticonID, jP.SettingsID, jP.AggViews,
	jP.PostPropertyNames, jP.PostPropertyValues,
	jP.Points as PostPoints,
	jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.Height, jP.Width, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created,
	HasRead = 1,
	UserName = jT.PostAuthor,
	Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_Downloads fD (nolock) WHERE fD.PostID = jP.PostID)
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	AND jp.SettingsID = @SettingsID and jT.SettingsID = @SettingsID
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

Select @TotalRecords = Count(*) FROM #PageIndex

IF @IncludeCategories = 1
Begin

Select 
	Cats.[Name], jP.PostID
FROM 
	#PageIndex jPI
	JOIN cs_Posts jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jT.ThreadID = jP.ThreadID
	JOIN cs_Posts_InCategories PIC on jP.PostID = PIC.PostID
	JOIN cs_Post_Categories Cats on PIC.CategoryID = Cats.CategoryID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 and jT.SettingsID = @SettingsID and jP.SettingsID = @SettingsID


End

DROP TABLE #PageIndex
GO

grant execute on [dbo].[files_Entries_GetEntries] to public
go

/***********************************************
* Sproc: files_Entry_Get
* File Date: 8/8/2006 9:28:19 AM
***********************************************/
Print 'Creating...files_Entry_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entry_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entry_Get]
GO







CREATE        PROCEDURE [dbo].files_Entry_Get
/*

	Procedure for getting basic information on a single post.

*/
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int
) AS
DECLARE @NextThreadID int
DECLARE @PrevThreadID int
DECLARE @ThreadID int 
DECLARE @SectionID int
DECLARE @SortOrder int
DECLARE @IsApproved bit

SELECT 
	@ThreadID = ThreadID, 
	@SectionID = SectionID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

DECLARE @TrackingThread bit

IF @TrackViews = 1
BEGIN
	-- Update the counter for the number of times this post is viewed
	UPDATE cs_Posts SET TotalViews = (TotalViews + 1) WHERE PostID = @PostID and SettingsID = @SettingsID
	UPDATE cs_Threads SET TotalViews = (TotalViews + 1) WHERE ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- If @UserID is 0 the user is anonymous
IF @UserID > 0 AND @IsApproved = 1
BEGIN

	-- Mark the post as read
	-- *********************
	IF NOT EXISTS (SELECT ThreadID FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		INSERT INTO cs_ThreadsRead (UserID, ThreadID, SectionID, SettingsID) VALUES (@UserID, @ThreadID, @SectionID, @SettingsID)

END

-- get the anonymous user id for this site
if( @UserID = 0 ) 
BEGIN
	exec cs_GetAnonymousUserID @SettingsID, @UserID output
END


IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SELECT @TrackingThread = 1
ELSE
	SELECT @TrackingThread = 0

SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues,
	P.Points as PostPoints,
	P.PostAuthor as [Username],
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	T.RatingSum,
	T.TotalRatings,
	HasRead = 0,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],p.Created, P.Height, P.Width,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = P.UserID),
	Replies = (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_Downloads fD (nolock) WHERE fD.PostID = P.PostID),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T
WHERE 
	P.PostID = @PostID AND
	P.ThreadID = T.ThreadID AND
	P.SettingsID = @SettingsID



SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Entry_Get to public
go
/***********************************************
* Sproc: files_PostAttachment_Get
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...files_PostAttachment_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_PostAttachment_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_PostAttachment_Get]
GO







create procedure [dbo].files_PostAttachment_Get
(
	@PostID int,
	@UserID int=0,
	@LogDownload bit=0
)
AS

if @LogDownload = 1
begin
	INSERT files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())
end

SELECT
	*
FROM
	cs_PostAttachments
WHERE
	PostID = @PostID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_PostAttachment_Get] to public
go
/***********************************************
* Sproc: files_Post_GetSortOrder
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...files_Post_GetSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Post_GetSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Post_GetSortOrder]
GO

CREATE PROCEDURE [dbo].files_Post_GetSortOrder
	@PostID int,
	@sqlPopulate nvarchar(4000),
	@SettingsID int
AS

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ThreadID int
)

CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (ThreadID)
EXEC (@sqlPopulate)

SELECT IndexID
	FROM #PageIndex I
	LEFT JOIN cs_Posts P ON P.ThreadID = I.ThreadID
	WHERE P.PostID = @PostID
		AND P.SettingsID = @SettingsID

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Post_GetSortOrder to public
go
/***********************************************
* Sproc: files_Search_PostReindex
* File Date: 8/8/2006 9:28:21 AM
***********************************************/
Print 'Creating...files_Search_PostReindex'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Search_PostReindex]
GO



/***********************************************
* Sproc: files_users_WhoDownloadedFile
* File Date: 8/8/2006 9:28:20 AM
***********************************************/
Print 'Creating...files_users_WhoDownloadedFile'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_users_WhoDownloadedFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_users_WhoDownloadedFile]
GO

CREATE PROCEDURE [dbo].files_users_WhoDownloadedFile
(
	@PageIndex int,
	@PageSize int,
	@PostID int,
	@ReturnRecordCount bit = 0,
	@SettingsID int,
	@StartDate datetime,
	@EndDate datetime
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	LatestDownloadDate datetime,
	TotalDownloads int,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(distinct U.cs_UserId) FROM cs_vw_Users_FullUser U, files_Downloads D WHERE D.UserId = U.cs_UserId and D.PostID = @PostID and U.SettingsID = @SettingsID and D.DownloadDate between @StartDate and @EndDate)

-- Special case depending on what the user wants and how they want it ordered by
-- *************************************

INSERT INTO #PageIndexForUsers (UserID, LatestDownloadDate, TotalDownloads)
SELECT U.cs_UserID, Max(D.DownloadDate), count(*)
FROM cs_vw_Users_FullUser U, files_Downloads D 
WHERE D.UserId = U.cs_UserId 
	and D.PostID = @PostID 
	and U.SettingsID = @SettingsID 
	and D.DownloadDate between @StartDate and @EndDate
GROUP BY U.cs_UserID
ORDER BY Max(D.DownloadDate)

-- Get the user details
SELECT
	*, @PostID as PostID
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.IndexID
END

-- Return the record count if necessary

IF (@ReturnRecordCount = 1)
  SELECT @TotalUsers

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_users_WhoDownloadedFile  to public
go
/***********************************************
* Sproc: forums_Threads_GetThreadSet
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...forums_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[forums_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[forums_Threads_GetThreadSet]
GO

/***********************************************
* Sproc: HasReadPost
* File Date: 8/8/2006 9:28:11 AM
***********************************************/
Print 'Creating...HasReadPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[HasReadPost]') and OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
drop function [dbo].[HasReadPost]
GO

/***********************************************
* Sproc: spam_GetRecentPostCountFromIP
* File Date: 8/8/2006 9:28:17 AM
***********************************************/
Print 'Creating...spam_GetRecentPostCountFromIP'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spam_GetRecentPostCountFromIP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spam_GetRecentPostCountFromIP]
GO

CREATE PROCEDURE [dbo].[spam_GetRecentPostCountFromIP]
(
	@IPAddress	nvarchar(50),
	@Duration	int,
	@SettingsID	int
)
AS
	SELECT	COUNT(*)
	FROM	cs_Posts
	WHERE	SettingsID = @SettingsID AND
			IPAddress = @IPAddress AND
			PostDate > DATEADD(s, -@Duration, GETDATE())

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[spam_GetRecentPostCountFromIP] TO PUBLIC
GO
