SET QUOTED_IDENTIFIER ON
GO
SET TRANSACTION ISOLATION Level SERIALIZABLE
GO



PRINT 'Creating Table AEUser'
GO

CREATE TABLE dbo.AEUser
	(
 	UserId 			int 			NOT NULL IDENTITY (1, 1),
	Username 		nvarchar(450) 	NOT NULL,
	UsernameUpper 	nvarchar(450) 	NOT NULL,
	UserSID 		varchar(255) 	NULL 
	) ON [PRIMARY]
GO

CREATE UNIQUE NONCLUSTERED INDEX AEUser_UserName ON dbo.AEUser
	(
	UsernameUpper
	) ON [PRIMARY]
GO

ALTER TABLE dbo.AEUser ADD CONSTRAINT
	PK_AEUser PRIMARY KEY CLUSTERED 
	(
	UserId
	) ON [PRIMARY]
GO

insert into dbo.AEUser (Username, UsernameUpper, UserSID)
values( 'Everybody', 'EVERYBODY', NULL)
go


PRINT 'Creating Table BlobTable'
GO

CREATE TABLE dbo.BlobTable
	(
 	BlobId 			int 		NOT NULL IDENTITY (1, 1),
	BlobSecret 		varchar(32) NOT NULL,
	BlobFileExt 	nvarchar(256)	NOT NULL,
	BlobGUID 		char(38) 	NOT NULL,
	BlobExecFlag 	tinyint 	NOT NULL,
	BlobTimeCreated datetime 	NOT NULL,
	BlobSize 		int 		NOT NULL,
	BlobMetaFlag 	tinyint 	NOT NULL,
	BlobData 		image 		NULL
	) ON [PRIMARY]
	 TEXTIMAGE_ON [PRIMARY]
GO

CREATE UNIQUE NONCLUSTERED INDEX BlobTable_BlobGUID ON dbo.BlobTable
	(
	BlobGUID
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX BlobTable_BlobTimeCreated ON dbo.BlobTable
	(
	BlobTimeCreated
	) ON [PRIMARY]
GO
ALTER TABLE dbo.BlobTable ADD CONSTRAINT
	PK_BlobTable PRIMARY KEY CLUSTERED 
	(
	BlobId
	) ON [PRIMARY]
GO




PRINT 'Creating Table ChangeTable'
GO

CREATE TABLE dbo.ChangeTable
	(
	NodeGUID	char(38) NOT NULL,
	ParentGUID	char(38) null,
	Reason 		int	NOT NULL,
	LastChangeTime datetime NOT NULL,
	CommitTime 		datetime NOT NULL,
	LastDeployTime	datetime NULL,
	Type			int null,
	IsShortcut		tinyint null,
	Name			nvarchar(250) null,
	FollowGUID		varchar(38) null,
	TemplateGUID	varchar(38) null,
	PageDefinitionGUID	varchar(38) null
	)
Go

ALTER TABLE dbo.ChangeTable ADD CONSTRAINT
	PK_ChangeTable Primary Key Nonclustered
	(
	NodeGUID
	)
Go
CREATE clustered Index ChangeTable_CommitTime On dbo.ChangeTable
	(
	CommitTime
	)
Go



PRINT 'Creating Table ClientAccount'
GO

CREATE TABLE dbo.ClientAccount
	(
 	UserId 				int 			NOT NULL IDENTITY (1, 1),
	Username 			nvarchar(450) 	NOT NULL,
	UsernameUpper 		nvarchar(450) 	NOT NULL,
	AuthType			nvarchar(100)	NOT NULL,
	AuthTypeUpper		nvarchar(100)	NOT NULL
	) ON [PRIMARY]
GO

CREATE UNIQUE NONCLUSTERED INDEX ClientAccount_UserName ON dbo.ClientAccount
	(
	UsernameUpper,
	AuthTypeUpper
	) ON [PRIMARY]
GO
ALTER TABLE dbo.ClientAccount ADD CONSTRAINT
	PK_ClientAccount PRIMARY KEY CLUSTERED 
	(
	UserId
	) ON [PRIMARY]

GO



PRINT 'Creating Table LayoutProperty'
GO

CREATE TABLE dbo.LayoutProperty
	(
 	NodeId 			int 		NOT NULL,
	LayoutId 		int 		NOT NULL,
	Id 			int 		NOT NULL,
	PropName 		nvarchar(100) 	NOT NULL,
	IsControl 		tinyint 	NOT NULL,
	ControlId 		int 		NULL,
	
	IsBeingInserted 	tinyint 	NOT NULL,
	IsBeingDeleted 		tinyint 	NOT NULL,
	IsBeingUpdated		tinyint		NOT NULL,
	
	NewPropName 		nvarchar(100) 	NULL,
	NewIsControl 		tinyint 	NULL,
	NewControlId 		int 		NULL,
	
	PropValue 		ntext 		NULL,
	NewPropValue 		ntext 		NULL
	) ON [PRIMARY]
	 TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE dbo.LayoutProperty ADD CONSTRAINT
	PK_LayoutProperty PRIMARY KEY CLUSTERED 
	(
	NodeId,
	LayoutId,
	Id
	) ON [PRIMARY]
GO




PRINT 'Creating Table Utility'
GO

create table dbo.Utility
	(
	DeltaGMT int,
	LastRevisionPurge datetime null
	)
go

insert into Utility (LastRevisionPurge) values('1900-01-01 00:00:00')
go

PRINT 'Creating Table ServerReadLock'
GO

create table dbo.ServerReadLock
	(
	IsLocked tinyint not null PRIMARY KEY CLUSTERED
	)
go
insert into ServerReadLock values(0)
go

PRINT 'Creating Table ServerWriteLock'
GO

create table dbo.ServerWriteLock
	(
	IsLocked tinyint not null PRIMARY KEY CLUSTERED
	)
go
insert into ServerWriteLock values(0)
go

create table dbo.SiteDeployImportLock
	(
	IsLocked tinyint not null PRIMARY KEY CLUSTERED
	)
go
insert into SiteDeployImportLock values(0)
go



PRINT 'Creating Table NodeLayout'
GO

CREATE TABLE dbo.NodeLayout
	(
 	NodeId 				int 		NOT NULL,
	Id 				int 		NOT NULL,
	Name 				nvarchar(255) 	NOT NULL,
	LayoutTemplateGUID 		char(38) 	NULL,
	IsBeingInserted 		tinyint 	NOT NULL,
	IsBeingDeleted 			tinyint 	NOT NULL,
	IsBeingUpdated			tinyint		NOT NULL,
	
	NewName 			nvarchar(255) 	NULL,
	NewLayoutTemplateGUID 		char(38) 	NULL
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX NodeLayout_LayoutTemplateGUID ON dbo.NodeLayout
	(
	LayoutTemplateGUID
	) ON [PRIMARY]
GO
ALTER TABLE dbo.NodeLayout ADD CONSTRAINT
	PK_NodeLayout PRIMARY KEY CLUSTERED 
	(
	NodeId,
	Id
	) ON [PRIMARY]
GO




PRINT 'Creating Table NodeLock'
GO

CREATE TABLE dbo.NodeLock
	(
 	NodeId 					int 		NOT NULL,
 	
	NewIsHighPriority 		tinyint 	NOT NULL,
	NewSameRightsAsParent 	tinyint 	NOT NULL,
	NewReadyForApproval 	tinyint 	NOT NULL,
	NewSortOrdinal 			int 		NOT NULL,
	
	NewApprovalStatus		int			NOT NULL,
	NewApprovedByUserId	 	int 		NULL,
	NewOwnerId	 			int 		NOT NULL,
	NewEffectiveDate 		datetime 	NULL,
	NewExpiryDate 			datetime 	NULL,
	NewTemplateGUID 		char(38) 	NULL,

	NewName 				nvarchar(250) 	NULL,
	NewDirectoryService 	nvarchar(500)	NULL,
	NewDirectoryGUID	 	char(38) 		NULL,

	NewIsHiddenModePublished	bit 	NULL,
	NewIsRobotFollowable	bit 		NULL,
	NewIsRobotIndexable		bit 		NULL,
	NewDisplayName			nvarchar(250) NULL,
	
	NewPageDefinitionGUID	char(38)	NULL,

	NewApprovedByClientId 	int 		NULL,
	NewOwnerClientId		int 		NULL,

	NewTemplateAspPath		ntext		NULL,
	NewSchemaXML			ntext		NULL,

	NewOuterScriptFile		ntext		NULL,
	NewUseOuterScriptForPostings 	tinyint NULL,
	NewDefaultPostingName	  	nvarchar(250) NULL

	) ON [PRIMARY]
	
GO

ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	PK_NodeLock PRIMARY KEY CLUSTERED 
	(
	NodeId
	) ON [PRIMARY]
GO




PRINT 'Creating Table NodePlaceholderContent'
GO

CREATE TABLE dbo.NodePlaceholderContent
	(
 	NodeId 			int 		NOT NULL,
	PlaceholderId 		int 		NOT NULL,
	Id 				int 		NOT NULL,
	PropName 		nvarchar(100) 	NOT NULL,
	IsResource 		tinyint 	NOT NULL,
	ResourceId 		int 		NULL,
	IsBeingInserted 	tinyint 	NOT NULL,
	IsBeingDeleted 		tinyint 	NOT NULL,
	IsBeingUpdated		tinyint		NOT NULL,
	
	NewPropName 		nvarchar(100) 	NULL,
	NewIsResource		tinyint 	NULL,
	NewResourceId 		int 		NULL,
	
	PropValue 			ntext 		NULL,
	NewPropValue 		ntext 		NULL
	) ON [PRIMARY]
	 TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE dbo.NodePlaceholderContent ADD CONSTRAINT
	PK_NodeContent PRIMARY KEY CLUSTERED 
	(
	NodeId,
	PlaceholderId,
	Id
	) ON [PRIMARY]
GO




PRINT 'Creating Table NodePlaceholder'
GO

CREATE TABLE dbo.NodePlaceholder
	(
 	NodeId 			int 		NOT NULL,
	Id 				int 		NOT NULL,
	Name 			nvarchar(100) 	NOT NULL,
	ControlGUID 		char(38) 	NOT NULL,
	IsBeingInserted 	tinyint 	NOT NULL,
	IsBeingDeleted 		tinyint 	NOT NULL,
	IsBeingUpdated		tinyint		NOT NULL,
	
	NewName 		nvarchar(100) 	NULL,
	) ON [PRIMARY]
GO

ALTER TABLE dbo.NodePlaceholder ADD CONSTRAINT
	PK_NodePlaceholder PRIMARY KEY CLUSTERED 
	(
	NodeId,
	Id
	) ON [PRIMARY]
GO

ALTER TABLE dbo.NodePlaceholder ADD CONSTRAINT
	UQ_NodePlaceholder UNIQUE 
	(
	NodeId,
	Name,
	IsBeingDeleted
	) ON [PRIMARY]
GO




PRINT 'Creating Table NodeProperty'
GO

CREATE TABLE dbo.NodeProperty
	(
 	NodeId 				int 		NOT NULL,
	Id 				int 		NOT NULL,
	PropName 			nvarchar(50) 	NOT NULL,
	PropValue 			nvarchar(300)	NULL,
	PropType			int	NOT NULL,
	IsBeingInserted 		tinyint 	NOT NULL,
	IsBeingDeleted 			tinyint 	NOT NULL,
	IsBeingUpdated			tinyint		NOT NULL,
	
	NewPropValue 			nvarchar(300)	NULL,
	
	PropValueLong			ntext			NULL,
	NewPropValueLong		ntext			NULL
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX NodeProperty_NameValue ON dbo.NodeProperty
	(
	PropName,
	PropValue
	) ON [PRIMARY]

CREATE NONCLUSTERED INDEX NodeProperty_Value ON dbo.NodeProperty
	(
	PropValue
	) ON [PRIMARY]
GO

ALTER TABLE dbo.NodeProperty ADD CONSTRAINT
	PK_NodeProperty PRIMARY KEY CLUSTERED 
	(
	NodeId,
	Id
	) ON [PRIMARY]
GO





PRINT 'Creating Table NodeResource'
GO

CREATE TABLE dbo.NodeResource
	(
 	NodeId 				int		NOT NULL,
	Id 				int 		NOT NULL,
	Name				nvarchar(100) 	NOT NULL,
	IsLink 				tinyint 	NOT NULL,
	ResourceBlobId 			int 		NULL,
	NodeGUID			char(38) 	NULL,
	LinkAnchor 			nvarchar(255) 	NULL,
	IsBeingInserted 		tinyint 	NOT NULL,
	IsBeingDeleted 			tinyint 	NOT NULL,
	IsBeingUpdated			tinyint		NOT NULL,

	NewName 			nvarchar(100) 	NULL,
	NewIsLink 			tinyint 	NULL,
	NewResourceBlobId 		int 		NULL,
	NewNodeGUID 			char(38) 	NULL,
	NewLinkAnchor 			nvarchar(255) 	NULL,
	URL 				ntext 		NULL,
	NewURL 				ntext 		NULL
	) ON [PRIMARY]
	 TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE dbo.NodeResource ADD CONSTRAINT
	PK_NodeResource PRIMARY KEY CLUSTERED 
	(
	NodeId,
	Id
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX NodeResource_ResourceBlobId ON dbo.NodeResource
	(
	ResourceBlobId
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX NodeResource_NodeGUID ON dbo.NodeResource
	(
	NodeGUID
	) ON [PRIMARY]
GO




PRINT 'Creating Table NodeRole'
GO

CREATE TABLE dbo.NodeRole
	(
 	NodeId 			int 		NOT NULL,
	RoleGUID 		char(38) 	NOT NULL,
	
	IsBeingInserted 	tinyint 	NOT NULL,
	IsBeingDeleted 		tinyint 	NOT NULL,
	IsBeingUpdated		tinyint		NOT NULL
	) ON [PRIMARY]
GO

ALTER TABLE dbo.NodeRole ADD CONSTRAINT
	PK_NodeRole PRIMARY KEY CLUSTERED 
	(
	NodeId,
	RoleGUID
	) ON [PRIMARY]
GO




PRINT 'Creating Table Node'
GO

CREATE TABLE dbo.Node
	(
 	Id 						int 		NOT NULL IDENTITY (1, 1),
 	
	IsLocked 				tinyint 	NOT NULL,
	IsCheckedOut 			tinyint 	NOT NULL,
	IsCheckedOutVersion 	tinyint 	NOT NULL,
	HasCheckedInVersion 	tinyint 	NOT NULL,
	CheckedInVersionHasExisted tinyint 	NOT NULL,
	IsShortcut 				tinyint 	NOT NULL,
	IsBeingInserted 		tinyint 	NOT NULL,

	IsHighPriority 			tinyint 	NOT NULL,
	SameRightsAsParent 		tinyint 	NOT NULL,
	ReadyForApproval 		tinyint 	NOT NULL,

	ApprovalStatus 			int 		NOT NULL,

	Type 					int 		NOT NULL,
	SortOrdinal 			int 		NOT NULL,

	NodeGUID 				char(38) 	NOT NULL,
	ParentGUID 				char(38) 	NULL,
	FollowGUID 				char(38) 	NULL,
	DeletedWhen				datetime	NULL,
	DeletedByUserId			int			NULL,
	CreatedByUserId 		int 		NOT NULL,
	CreatedWhen 			datetime 	NOT NULL,
	ModifiedByUserId 		int 		NOT NULL,
	ModifiedWhen 			datetime 	NOT NULL,
	OwnerId	 				int 		NOT NULL,
	ApprovedByUserId 		int 		NULL,
	EffectiveDate 			datetime 	NULL,
	ExpiryDate 				datetime 	NULL,
	TemplateGUID 			char(38) 	NULL,

	ArchiveSourceGUID 		char(38) 	NULL,

	ApprovedWhen 			datetime 	NULL,
	ArchivedWhen 			datetime 	NULL,

	LockUserId 				int 		NULL,
	LockMachinename 		nvarchar(50) NULL,
	
	Name 					nvarchar(250) NULL,
	TemplateType 			nvarchar(150) NULL,
	DirectoryService 		nvarchar(500) NULL,
	DirectoryGUID 			char(38) 	  NULL,	
	
	IsHiddenModePublished	tinyint 	NULL,
	IsRobotFollowable		tinyint 	NULL,
	IsRobotIndexable		tinyint 	NULL,
	DisplayName				nvarchar(250) 	NULL,

	LastChangeTime 			datetime 	NOT NULL,

	PageDefinitionGUID 		char(38) 	NULL,
	DeletedByClientId		int			NULL,
	CreatedByClientId 		int 		NULL,
	ModifiedByClientId 		int 		NULL,
	ApprovedByClientId 		int 		NULL,
	OwnerClientId	 		int 		NULL,
	LockClientId 			int			NULL,

	CheckedOutByUserId 		int 		NULL,
	CheckedOutByMachine		nvarchar(50) NULL,

	TemplateAspPath			ntext		NULL,
	SchemaXML				ntext		NULL,
	UserRoleType			int			NULL,

	OuterScriptFile			ntext		NULL,
	UseOuterScriptForPostings 	tinyint NULL,
	DefaultPostingName	  	nvarchar(250) NULL
	) ON [PRIMARY]
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	PK_Node PRIMARY KEY NONCLUSTERED 
	(
	Id
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_LastChangeTime ON dbo.Node
	(
	LastChangeTime
	) ON [PRIMARY]
GO
CREATE UNIQUE CLUSTERED INDEX Node_NodeGUID ON dbo.Node
	(
	NodeGUID,
	IsCheckedOutVersion
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_ArchiveSourceGUID ON dbo.Node
	(
	ArchiveSourceGUID
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_CreatedByUserId ON dbo.Node
	(
	CreatedByUserId,
	Id
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX Node_FollowGUID ON dbo.Node
	(
	FollowGUID
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_ModifiedWhen ON dbo.Node
	(
	ModifiedWhen
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_Name ON dbo.Node
	(
	Name
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_OwnerId ON dbo.Node
	(
	OwnerId
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_ParentGUID ON dbo.Node
	(
	ParentGUID
	) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX Node_Type ON dbo.Node
	(
	Type
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX Node_TypeParentGUID ON dbo.Node
	(
	Type
	,ParentGUID
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX Node_PageDefinitionGUID ON dbo.Node
	(
	PageDefinitionGUID
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX Node_EffectiveDate ON dbo.Node
	(
	EffectiveDate
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX Node_ExpiryDate ON dbo.Node
	(
	ExpiryDate
	) ON [PRIMARY]
GO


PRINT 'Creating Table Patch'
GO

CREATE TABLE dbo.Patch (
	PatchId int NOT NULL ,
	PatchDescript nvarchar(255) NOT NULL ,
	UpdateTime datetime NOT NULL 
) ON [PRIMARY]
GO

 CREATE  UNIQUE  CLUSTERED  INDEX [Patch_PK] ON [dbo].[Patch]([PatchId]) WITH  FILLFACTOR = 90 ON [PRIMARY]
GO



PRINT 'Creating Table UserRoleMember'
GO

CREATE TABLE dbo.UserRoleMember
	(
 	NodeId int NOT NULL,
	UserId int NOT NULL,
	IsBeingInserted tinyint NOT NULL,
	IsBeingDeleted tinyint NOT NULL,
	IsBeingUpdated tinyint NOT NULL
	) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX URM_UserId ON dbo.UserRoleMember
	(
	UserId
	) ON [PRIMARY]
GO
ALTER TABLE dbo.UserRoleMember ADD CONSTRAINT
	PK_UserRoleMember PRIMARY KEY CLUSTERED 
	(
	NodeId,
	UserId
	) ON [PRIMARY]
GO



 
 
 alter table dbo.AEUser Add constraint UserNameUpper_Default 
DEFAULT '' for UsernameUpper
go

alter table dbo.Node add constraint Node_CreatedWhen_Default
DEFAULT '1900-01-01 00:00:00' for CreatedWhen
go

alter table dbo.Node add constraint Node_ModifiedWhen_Default
DEFAULT '1900-01-01 00:00:00' for ModifiedWhen
go

alter table dbo.Node add constraint Node_LastChangeTime_Default
DEFAULT '1900-01-01 00:00:00' for LastChangeTime
go

alter table dbo.NodeProperty add constraint NodePropery_PropType_Default
DEFAULT 0 for PropType
go

alter table dbo.ChangeTable add constraint ChangeTable_Reason_Default
DEFAULT 0 for Reason
go




PRINT 'Creating foreign keys on NodeProperty table'
GO

ALTER TABLE dbo.NodeProperty ADD CONSTRAINT
	FK_NodeProperty_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO

PRINT 'Creating foreign keys on NodeRole table'
GO

ALTER TABLE dbo.NodeRole ADD CONSTRAINT
	FK_NodeRole_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO


PRINT 'Creating foreign keys on UserRoleMember table'
GO

ALTER TABLE dbo.UserRoleMember ADD CONSTRAINT
	FK_UserRoleMember_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO
ALTER TABLE dbo.UserRoleMember ADD CONSTRAINT
	FK_UserRoleMember_AEUser FOREIGN KEY
	(
	UserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO




PRINT 'Creating foreign keys on Node table'
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_CreatedByUserId FOREIGN KEY
	(
	CreatedByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
go


ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_ModifiedByUserId FOREIGN KEY
	(
	ModifiedByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_ApprovedByUserId FOREIGN KEY
	(
	ApprovedByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_DeletedByUserId FOREIGN KEY
	(
	DeletedByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_OwnerId FOREIGN KEY
	(
	OwnerId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
go


ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_CreatedByClientId FOREIGN KEY
	(
	CreatedByClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
go


ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_ModifiedByClientId FOREIGN KEY
	(
	ModifiedByClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_ApprovedByClientId FOREIGN KEY
	(
	ApprovedByClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_DeletedByClientId FOREIGN KEY
	(
	DeletedByClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
GO

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_OwnerClientId FOREIGN KEY
	(
	OwnerClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
go

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_LockClientId FOREIGN KEY
	(
	LockClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
go

ALTER TABLE dbo.Node ADD CONSTRAINT
	FK_Node_CheckedOutByUserId FOREIGN KEY
	(
	CheckedOutByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
go
 
 

PRINT 'Creating foreign keys on NodeLayout table'
GO

 ALTER TABLE dbo.NodeLayout ADD CONSTRAINT
	FK_NodeLayout_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO

PRINT 'Creating foreign keys on LayoutProperty table'
GO

ALTER TABLE dbo.LayoutProperty ADD CONSTRAINT
	FK_LayoutProperty_NodeLayout FOREIGN KEY
	(
	NodeId,
	LayoutId
	) REFERENCES dbo.NodeLayout
	(
	NodeId,
	Id
	)
GO



PRINT 'Creating foreign keys on NodeLock table'
GO


 ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	FK_NodeLock_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO

ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	FK_NodeLock_NewApprovedByUserId FOREIGN KEY
	(
	NewApprovedByUserId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO

ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	FK_NodeLock_NewOwnerId FOREIGN KEY
	(
	NewOwnerId
	) REFERENCES dbo.AEUser
	(
	UserId
	)
GO

ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	FK_NodeLock_NewApprovedByClientId FOREIGN KEY
	(
	NewApprovedByClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)
GO

ALTER TABLE dbo.NodeLock ADD CONSTRAINT
	FK_NodeLock_NewOwnerClientId FOREIGN KEY
	(
	NewOwnerClientId
	) REFERENCES dbo.ClientAccount
	(
	UserId
	)

GO


PRINT 'Creating foreign keys on NodePlaceholder table'
GO

 ALTER TABLE dbo.NodePlaceholder ADD CONSTRAINT
	FK_NodePlaceholder_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO

PRINT 'Creating foreign keys on NodePlaceholderContent table'
GO

ALTER TABLE dbo.NodePlaceholderContent ADD CONSTRAINT
	FK_NodeContent_NodePlaceholder FOREIGN KEY
	(
	NodeId,
	PlaceholderId
	) REFERENCES dbo.NodePlaceholder
	(
	NodeId,
	Id
	)
GO



PRINT 'Creating foreign keys on NodeResource table'
GO

ALTER TABLE dbo.NodeResource ADD CONSTRAINT
	FK_NodeResource_Node FOREIGN KEY
	(
	NodeId
	) REFERENCES dbo.Node
	(
	Id
	)
GO

ALTER TABLE dbo.NodeResource ADD CONSTRAINT
	FK_NodeResource_BlobTable FOREIGN KEY
	(
	ResourceBlobId
	) REFERENCES dbo.BlobTable
	(
	BlobId
	)
GO

ALTER TABLE dbo.NodeResource ADD CONSTRAINT
	FK_NewNodeResource_BlobTable FOREIGN KEY
	(
	NewResourceBlobId
	) REFERENCES dbo.BlobTable
	(
	BlobId
	)
GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'TR' AND name = 'ChangeTrigger_Delete')
	BEGIN
		PRINT 'Dropping Trigger ChangeTrigger_Delete'
		DROP  Trigger ChangeTrigger_Delete
	END
GO


PRINT 'Creating Trigger ChangeTrigger_Delete'
GO

create Trigger ChangeTrigger_Delete
on dbo.Node
with encryption
FOR DELETE
as
 SET NOCOUNT ON
 
if (SELECT OBJECT_ID('tempdb..#Sandbox')) IS NOT NULL
BEGIN
	 /* update the corresponding entry into the ChangeTable*/	  
	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	
	exec GetGMTTime @dateCurrent, @dateGMT out
	
	DECLARE @DeletedNodeGUID char(38)
			,@DeletedParentGUID char(38)
			,@Type int
			,@IsShortcut tinyint
			,@Name nvarchar(250)
			,@FollowGUID varchar(38)
			,@ArchiveSourceGUID varchar(38)
			,@IsCheckedOutVersion tinyint
			,@DeletedWhen datetime
			,@TemplateGUID varchar(38)
			,@PageDefinitionGUID varchar(38)

	DECLARE DeletedItems CURSOR LOCAL READ_ONLY FOR 
		select 
			NodeGUID
			,ParentGUID
			,Type
			,IsShortcut
			,case 
				when IsShortcut = 0 then Name
				when IsShortcut = 1 then DisplayName
				else NULL
			end
			,FollowGUID
			,ArchiveSourceGUID
			,IsCheckedOutVersion
			,DeletedWhen
			,TemplateGUID
			,PageDefinitionGUID
		from deleted dl 
		where not exists 
		(select Id 
		from Node 
		where NodeGUID = dl.NodeGUID) 
	OPEN DeletedItems

	FETCH NEXT FROM DeletedItems INTO 
									@DeletedNodeGUID
									,@DeletedParentGUID
									,@Type
									,@IsShortcut
									,@Name
									,@FollowGUID
									,@ArchiveSourceGUID
									,@IsCheckedOutVersion
									,@DeletedWhen
									,@TemplateGUID
									,@PageDefinitionGUID
 	WHILE @@FETCH_STATUS = 0
	BEGIN
		if @IsShortcut = 1 and isNull(@Name, '') = ''
			and @ArchiveSourceGUID is null
		begin
			if exists(select NodeGUID from deleted where NodeGUID = @FollowGUID)
				/*the corresponding page for this posting is deleted as well
				 get its Name form deleted table,
				 prefer checked in version*/
				select @Name = Name from deleted where NodeGUID = @FollowGUID
				order by IsCheckedOutVersion desc
			else
				/*the corresponding page is not being deleted*/
				select @Name = Name from Node where NodeGUID = @FollowGUID 
				order by IsCheckedOutVersion desc
		end
		exec sp_executesql N'
			if exists( select NodeGUID from #Sandbox where NodeGUID = @DeletedNodeGUID)
			begin
				Update #Sandbox set 
					ParentGUID = @DeletedParentGUID
					,Reason = 2
					,LastChangeTime = @dateGMT
					,Type = @Type
					,IsShortcut = @IsShortcut
					,Name = case 
							when @IsShortcut = 0 and @DeletedWhen is null and @IsCheckedOutVersion = 1 then Name
							else @Name
							end
					,FollowGUID = @FollowGUID
					,TemplateGUID = @TemplateGUID
					,PageDefinitionGUID = @PageDefinitionGUID
				where #Sandbox.NodeGUID  = @DeletedNodeGUID
			end
			else
			begin
				INSERT INTO #Sandbox ( NodeGUID, ParentGUID, Reason, LastChangeTime,
										Type, IsShortcut, Name,
										FollowGUID, TemplateGUID, PageDefinitionGUID) 
				VALUES (@DeletedNodeGUID, @DeletedParentGUID, 2, @dateGMT,
						@Type, @IsShortcut, @Name,
						@FollowGUID, @TemplateGUID, @PageDefinitionGUID)
			end',
		N'@DeletedNodeGUID char(38), @DeletedParentGUID char(38), @dateGMT datetime,
			@Type int, @IsShortcut tinyint, @Name nvarchar(250),
			@IsCheckedOutVersion tinyint, @DeletedWhen datetime,
			@FollowGUID char(38), @TemplateGUID char(38), @PageDefinitionGUID char(38)',
		@DeletedNodeGUID, @DeletedParentGUID, @dateGMT, @Type, @IsShortcut, @Name,
		@IsCheckedOutVersion, @DeletedWhen,
		@FollowGUID, @TemplateGUID, @PageDefinitionGUID

		FETCH NEXT FROM DeletedItems INTO @DeletedNodeGUID
										,@DeletedParentGUID
										,@Type
										,@IsShortcut
										,@Name
										,@FollowGUID
										,@ArchiveSourceGUID
										,@IsCheckedOutVersion
										,@DeletedWhen
										,@TemplateGUID
										,@PageDefinitionGUID
	END

	close DeletedItems
	deallocate DeletedItems

end
else
begin
	print 'Warning: Database is being updated manually. This is not recommended.'
	print 'Execute UpdateChangeTable stored procedure after you finish your changes.'
end
GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'TR' AND name = 'ChangeTrigger_Insert')
	BEGIN
		PRINT 'Dropping Trigger ChangeTrigger_Insert'
		DROP  Trigger ChangeTrigger_Insert
	END
GO


PRINT 'Creating Trigger Trigger_Name'
GO

create Trigger ChangeTrigger_Insert
	on dbo.Node
	with encryption
	FOR INSERT
	as
	 SET NOCOUNT ON

	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out

	DECLARE @InsertedId int
			,@InsertedNodeGUID char(38)
			,@InsertedParentGUID char(38)
			,@Type int
			,@IsShortcut tinyint
			
	DECLARE InsertedItems CURSOR LOCAL READ_ONLY FOR 
	SELECT	Id
			,NodeGUID
			,ParentGUID 
			,Type
			,IsShortcut
	FROM inserted 
	OPEN InsertedItems

	FETCH NEXT FROM InsertedItems INTO 
									@InsertedId
									,@InsertedNodeGUID
									,@InsertedParentGUID
									,@Type
									,@IsShortcut
 	WHILE @@FETCH_STATUS = 0
	BEGIN

		UPDATE Node SET 
			CreatedWhen = CASE Node.CreatedWhen WHEN  '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.CreatedWhen END,
			ModifiedWhen = CASE Node.ModifiedWhen WHEN  '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.ModifiedWhen END,
			ApprovedWhen = CASE Node.ApprovedWhen WHEN '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.ApprovedWhen END,
			LastChangeTime = @dateGMT 
	 	FROM Node WHERE Node.Id =@InsertedId 

		if (SELECT OBJECT_ID('tempdb..#Sandbox')) IS NOT NULL
		BEGIN
			exec sp_executesql N'if exists( select NodeGUID from #Sandbox where NodeGUID = @InsertedNodeGUID)
			begin
				Update #Sandbox set ParentGUID = @InsertedParentGuid,
					Reason = 0,
					LastChangeTime = @dateGMT,
					Type = @Type,
					IsShortcut = @IsShortcut
				where #Sandbox.NodeGUID = @InsertedNodeGUID
			end
			else
			begin
				INSERT INTO #Sandbox ( NodeGUID, ParentGUID, Reason, Type, IsShortcut, LastChangeTime) 
					VALUES (@InsertedNodeGUID, @InsertedParentGuid, 0, @Type, @IsShortcut, @dateGMT) 
			end', N'@InsertedNodeGUID  char(38), @InsertedParentGuid char(38), @dateGMT datetime,
			@Type int, @IsShortcut tinyint', 
			@InsertedNodeGUID, @InsertedParentGuid, @dateGMT, @Type, @IsShortcut
		end
		else
		begin
			print 'Warning: Database is being updated manually. This is not recommended.'
			print 'Execute UpdateChangeTable stored procedure after you finish your changes.'
		end

		FETCH NEXT FROM InsertedItems INTO 
											@InsertedId
											,@InsertedNodeGUID
											,@InsertedParentGUID
											,@Type
											,@IsShortcut
	END

	close InsertedItems
	deallocate InsertedItems


GO




IF EXISTS (SELECT * FROM sysobjects WHERE type = 'TR' AND name = 'NodeLockTrigger_Update')
	BEGIN
		PRINT 'Dropping Trigger NodeLockTrigger_Update'
		DROP  Trigger NodeLockTrigger_Update
	END
GO

PRINT 'Creating Trigger NodeLockTrigger_Update'
GO

create trigger NodeLockTrigger_Update
on dbo.NodeLock
with encryption
FOR UPDATE
as
 SET NOCOUNT ON

/*Execute an update on Node table to trigger LastChangeTime update*/
 UPDATE Node SET IsLocked = IsLocked
 from inserted
 WHERE Node.Id = inserted.NodeId  

GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'TR' AND name = 'ChangeTrigger_Update')
	BEGIN
		PRINT 'Dropping Trigger ChangeTrigger_Update'
		DROP  Trigger ChangeTrigger_Update
	END
GO


PRINT 'Creating Trigger ChangeTrigger_Update'
GO

CREATE Trigger ChangeTrigger_Update
	on dbo.Node
	with encryption
	FOR UPDATE
	as
	 SET NOCOUNT ON

	if( (SELECT trigger_nestlevel()) > 1 and
		(SELECT trigger_nestlevel( object_ID('NodeLockTrigger_Update'))) = 0   )
		return

	 /*update LastChangeTime field in Node table*/
	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out

	DECLARE @InsertedId int
			,@InsertedNodeGUID char(38)
			,@InsertedParentGUID char(38)
			,@Type int
			,@IsShortcut tinyint
			,@IsCheckedOutVersion tinyint
			
	DECLARE InsertedItems CURSOR LOCAL READ_ONLY FOR 
	SELECT	Id
			,NodeGUID
			,ParentGUID 
			,Type
			,IsShortcut
			,IsCheckedOutVersion
	FROM inserted 
	OPEN InsertedItems

	FETCH NEXT FROM InsertedItems INTO	@InsertedId
										,@InsertedNodeGUID
										,@InsertedParentGUID
										,@Type
										,@IsShortcut
										,@IsCheckedOutVersion
 	WHILE @@FETCH_STATUS = 0
	BEGIN

		UPDATE Node SET 
			CreatedWhen = CASE Node.CreatedWhen WHEN  '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.CreatedWhen END,
			ModifiedWhen = CASE Node.ModifiedWhen WHEN  '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.ModifiedWhen END,			
			ApprovedWhen = CASE Node.ApprovedWhen WHEN '1900-01-01 00:00:00' THEN @dateGMT ELSE Node.ApprovedWhen END,
			LastChangeTime = @dateGMT 
	 	FROM Node WHERE Node.Id =@InsertedId 
	 	
	 	if @IsCheckedOutVersion = 1
	 		update Node set LastChangeTime = @dateGMT where NodeGUID = @InsertedNodeGUID and IsCheckedOutVersion = 0

		if (SELECT OBJECT_ID('tempdb..#Sandbox')) IS NOT NULL
		BEGIN
			exec sp_executesql N'if exists( select NodeGUID from #Sandbox where NodeGUID = @InsertedNodeGUID)
			begin
				Update #Sandbox set ParentGUID = @InsertedParentGuid,
						Reason = 1,
						LastChangeTime = @dateGMT,
						Type = @Type,
						IsShortcut = @IsShortcut
				where #Sandbox.NodeGUID = @InsertedNodeGUID
			end
			else
			begin
				INSERT INTO #Sandbox ( NodeGUID, ParentGUID, Reason, LastChangeTime, Type, IsShortcut) 
					VALUES (@InsertedNodeGUID, @InsertedParentGuid, 1, @dateGMT, @Type, @IsShortcut) 
			end', N'@InsertedNodeGUID  char(38), @InsertedParentGuid char(38), @dateGMT datetime,
			@Type int, @IsShortcut tinyint', 
			@InsertedNodeGUID, @InsertedParentGuid, @dateGMT, @Type, @IsShortcut
		end
		else
		begin
			print 'Warning: Database is being updated manually. This is not recommended.'
			print 'Execute UpdateChangeTable stored procedure after you finish your changes.'
		end

		FETCH NEXT FROM InsertedItems INTO	@InsertedId
											,@InsertedNodeGUID
											,@InsertedParentGUID
											,@Type
											,@IsShortcut
											,@IsCheckedOutVersion
											
	END
GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'ArchiveDeletedResource')
	BEGIN
		PRINT 'Dropping Procedure ArchiveDeletedResource'
		DROP  Procedure  dbo.ArchiveDeletedResource
	END

GO

PRINT 'Creating Procedure ArchiveDeletedResource'
GO

CREATE Procedure dbo.ArchiveDeletedResource
(
	@NodeGUID char(38),
	@ArchiveParentGUID char(38)
)
with encryption
As
	set nocount on

	declare @SourceNodeId int
	set @SourceNodeId = 0
	
	/*check if this guid exists in the database and it's a resource gallery item that's been deleted*/
	select @SourceNodeId = Id from Node where NodeGUID = @NodeGUID and ParentGUID = @ArchiveParentGUID and Type = 256
	and ArchiveSourceGUID is null

	if( @SourceNodeId is not null and @SourceNodeId > 0 )
	begin
		declare @newGUID char(38)
		set @newGUID = '{' + convert(varchar(38), NEWID()) + '}'	

		exec CreateArchiveFromCheckedIn @newGUID, @NodeGUID, @SourceNodeId, @ArchiveParentGUID

	end
GO


GRANT EXEC ON dbo.ArchiveDeletedResource TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CheckoutNode')
	BEGIN
		PRINT 'Dropping Procedure CheckoutNode'
		DROP  Procedure  dbo.CheckoutNode
	END

GO

PRINT 'Creating Procedure CheckoutNode'
GO

create procedure dbo.CheckoutNode
	(
	@NodeId int,
	@CheckoutDestructive int,
	@NodeType int,
	@EmptyTables int,
	@IsShortcut int,
	@UserId int,
	@UserMachineName nvarchar(50),
	@ClientAccountId int
	)
	with encryption

as
	set nocount on

	if @UserId = 0
	begin
		raiserror ('Invalid user Id.', 15, 1)
		return
	end

	if @CheckoutDestructive > 0
		begin
		UPDATE Node SET CheckedInVersionHasExisted=1, IsCheckedOut=1, 
		IsCheckedOutVersion=1, HasCheckedInVersion=0, 
		CheckedOutByUserId = @UserId, CheckedOutByMachine = @UserMachineName,
		ApprovalStatus = 0 WHERE Id = @NodeId
		end
	else
		begin

		declare @NewNodeID int
		
		insert into Node (IsLocked, IsCheckedOut, IsCheckedOutVersion, HasCheckedInVersion,
					CheckedInVersionHasExisted, IsShortcut, IsBeingInserted, 
					Type, CreatedByUserId, ModifiedByUserId, CreatedWhen, ModifiedWhen,
					LockUserId, LockMachinename, CheckedOutByUserId, CheckedOutByMachine,
					NodeGUID, ParentGUID, OwnerId,
					EffectiveDate, ExpiryDate, IsHighPriority, SameRightsAsParent,
					ReadyForApproval, ApprovalStatus, SortOrdinal, ApprovedByUserId,
					DeletedByUserId, DeletedWhen, Name, TemplateType, FollowGUID,DirectoryService, DirectoryGUID,
					TemplateGUID, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, DisplayName,
					PageDefinitionGUID, 
					CreatedByClientId, ModifiedByClientId, LockClientId, OwnerClientId, ApprovedByClientId, DeletedByClientId,
					TemplateAspPath, SchemaXML, OuterScriptFile, UseOuterScriptForPostings,DefaultPostingName)

		select 0, 1, 1, 1, 1, @IsShortcut, 0, Type, CreatedByUserId, @UserId, CreatedWhen,
			ModifiedWhen, NULL, NULL, @UserId, @UserMachineName, 
			NodeGUID, ParentGUID, OwnerId,
			EffectiveDate, ExpiryDate, IsHighPriority, SameRightsAsParent,
			ReadyForApproval, 0, SortOrdinal, NULL,
			DeletedByUserId, DeletedWhen, Name, TemplateType, FollowGUID,DirectoryService, DirectoryGUID,
			TemplateGUID, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, DisplayName,
			PageDefinitionGUID, 
			CreatedByClientId, @ClientAccountId, LockClientId, OwnerClientId, ApprovedByClientId, DeletedByClientId,
			TemplateAspPath, SchemaXML, OuterScriptFile, UseOuterScriptForPostings,DefaultPostingName
		from Node 
		where Id = @NodeId
	
		select @NewNodeID = @@IDENTITY
	
		UPDATE Node SET IsCheckedOut = 1, CheckedOutByUserId = @UserId, CheckedOutByMachine = @UserMachineName
		where Id = @NodeId
	
		exec CopyAssociatedData @NodeId, @NewNodeID, 0, @NodeType, @EmptyTables
		end
go


GRANT EXEC ON dbo.CheckoutNode TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CommitNode')
	BEGIN
		PRINT 'Dropping Procedure CommitNode'
		DROP  Procedure  dbo.CommitNode
	END

GO

PRINT 'Creating Procedure CommitNode'
GO

create Procedure dbo.CommitNode
	(
	@NodeId int,
	@NodeType int,
	@UserId int,
	@KeepLocked tinyint,
	@EmptyTables int,
	@ClientAccountId int
	)
	with encryption

As

	/*empty collection enum*/
	declare @NO_ROLE_ACL 		tinyint, 	--NodeRole
			@NO_GENERIC_PROPS 	tinyint,	--NodeProperty
			@NO_CONTROL_ITEMS	tinyint,	--GalleryControl
			@NO_LAYOUTS			tinyint,	--NodeLayout
			@NO_RESOURCES		tinyint,	--NodeResource
			@NO_CONTROLS		tinyint,	--NodePlaceholder
			@NO_TEMPLATE_PROPS	tinyint		--LayoutTemplatePropery

	set @NO_ROLE_ACL = 1
	set @NO_GENERIC_PROPS = 2
	set @NO_CONTROL_ITEMS = 4
	set @NO_LAYOUTS = 8
	set @NO_RESOURCES = 16
	set @NO_CONTROLS = 32
	set @NO_TEMPLATE_PROPS = 64

	/* these are the flags that will help us to determine if assoc data has been deleted, inserted or updated*/
	declare @RECORDS_INSERTED	tinyint,
			@RECORDS_UPDATED	tinyint,
			@RECORDS_DELETED	tinyint

	set @RECORDS_INSERTED = 1
	set @RECORDS_UPDATED = 2
	set @RECORDS_DELETED = 4

	declare @UserRoleMemberFlag tinyint,
			@UserRoleNodeFlag tinyint,
			@NodeResourceFlag tinyint,
			@NodeContentFlag tinyint,
			@NodePlaceholderFlag tinyint,
			@LayoutPropertyFlag tinyint,
			@NodeLayoutFlag tinyint,
			@NodeRoleFlag tinyint,
			@NodePropertyFlag tinyint,
			@SchemaElementFlag tinyint


	set @UserRoleMemberFlag = 0
	set @UserRoleNodeFlag = 0
	set @NodeResourceFlag = 0
	set @NodeContentFlag = 0
	set @NodePlaceholderFlag = 0
	set @LayoutPropertyFlag = 0
	set @NodeLayoutFlag = 0
	set @NodeRoleFlag = 0
	set @NodePropertyFlag = 0
	set @SchemaElementFlag = 0

	set nocount on
	
	/* 
	 * delete the entries to be deleted.
	 */

	/* User role */
	if @nodeType = 0x100000
	begin
		select @UserRoleMemberFlag =  max(IsBeingInserted) |
					case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
					case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
				 from UserRoleMember WHERE NodeId = @NodeId

		if( @UserRoleMemberFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
			DELETE FROM UserRoleMember WHERE NodeId = @NodeId and IsBeingDeleted = 1

	end
	

	/* If we are not a shortcut... */
	if @nodetype <> 0x80000020
	begin
		if ( @EmptyTables & @NO_RESOURCES ) = 0
		begin
			select @NodeResourceFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
					 from NodeResource WHERE NodeId = @NodeId
			
			if( @NodeResourceFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
				DELETE FROM NodeResource WHERE NodeId = @NodeId and IsBeingDeleted = 1
		end

		if ( @EmptyTables & @NO_CONTROLS ) = 0
		begin
			select @NodeContentFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
					 from NodePlaceholderContent WHERE NodeId = @NodeId
			
			if( @NodeContentFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
				DELETE FROM NodePlaceholderContent WHERE NodeId = @NodeId and IsBeingDeleted = 1

			select @NodePlaceholderFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
					 from NodePlaceholder WHERE NodeId = @NodeId
			
			if( @NodePlaceholderFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
				DELETE FROM NodePlaceholder WHERE NodeId = @NodeId and IsBeingDeleted = 1
		end

		if ( @EmptyTables & @NO_LAYOUTS ) = 0
		begin
			select @LayoutPropertyFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
					 from LayoutProperty WHERE NodeId = @NodeId
			
			if( @LayoutPropertyFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
				DELETE FROM LayoutProperty WHERE NodeId = @NodeId and IsBeingDeleted = 1

			select @NodeLayoutFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
					 from NodeLayout WHERE NodeId = @NodeId
			
			if( @NodeLayoutFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
				DELETE FROM NodeLayout WHERE NodeId = @NodeId and IsBeingDeleted = 1
		end
	end
	
	/* Every Type of Node is concerned with these settings: */
	if ( @EmptyTables & @NO_ROLE_ACL ) = 0
	begin
		select @NodeRoleFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
				 from NodeRole WHERE NodeId = @NodeId
		
		if( @NodeRoleFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
			DELETE FROM NodeRole WHERE NodeId = @NodeId and IsBeingDeleted = 1
	end

	if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0
	begin
		select @NodePropertyFlag =  max(IsBeingInserted) |
						case when max(IsBeingUpdated) > 0 then @RECORDS_UPDATED else 0 end |
						case when max(IsBeingDeleted) > 0 then @RECORDS_DELETED else 0 end  
				 from NodeProperty WHERE NodeId = @NodeId
		
		if( @NodePropertyFlag & @RECORDS_DELETED ) = @RECORDS_DELETED
			DELETE FROM NodeProperty WHERE NodeId = @NodeId and IsBeingDeleted = 1
	end


	/*
	 * update the data being updated.
	 */
	
	/* User role */
	if @nodeType = 0x100000
	begin
		if(  @UserRoleMemberFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update UserRoleMember set  IsBeingUpdated = 0 WHERE NodeId = @NodeId and IsBeingUpdated = 1
	end

	/* If we are not a shortcut... */
	if @nodetype <> 0x80000020
	begin
		if (@NodeLayoutFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update NodeLayout set  IsBeingUpdated = 0, Name = NewName, LayoutTemplateGUID = NewLayoutTemplateGUID  WHERE NodeId = @NodeId and  IsBeingUpdated = 1
		if (@LayoutPropertyFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update LayoutProperty set  IsBeingUpdated = 0,PropName = NewPropName, IsControl = NewIsControl, PropValue = NewPropValue, ControlId = NewControlId  WHERE NodeId = @NodeId and IsBeingUpdated = 1
		if (@NodePlaceholderFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update NodePlaceholder set  IsBeingUpdated = 0, Name = NewName  WHERE NodeId = @NodeId and  IsBeingUpdated = 1
		if (@NodeContentFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update NodePlaceholderContent set  IsBeingUpdated = 0, PropName = NewPropName, IsResource = NewIsResource, PropValue = NewPropValue, ResourceId = NewResourceId  WHERE NodeId = @NodeId and IsBeingUpdated = 1
		
		if (@NodeResourceFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
			update NodeResource set IsBeingUpdated = 0,Name = NewName, IsLink = NewIsLink, URL = NewURL, ResourceBlobId = NewResourceBlobId, NodeGUID = NewNodeGUID, LinkAnchor = NewLinkAnchor WHERE NodeId = @NodeId and IsBeingUpdated = 1
	end


	/* Every Type of Node is concerned with the following: */
	if (@NodePropertyFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
		update NodeProperty set IsBeingUpdated = 0,  PropValue = NewPropValue,
		PropValueLong = NewPropValueLong
		WHERE NodeId = @NodeId and IsBeingUpdated = 1
	
	if (@NodeRoleFlag & @RECORDS_UPDATED ) = @RECORDS_UPDATED
		update NodeRole set IsBeingUpdated = 0 WHERE NodeId = @NodeId and IsBeingUpdated = 1



	/*
	 * update the data being inserted. 
   	 */

	/* User role */
	if @nodeType = 0x100000
	begin
		if ( @UserRoleMemberFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED 
			update UserRoleMember set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
	end


	/* If we are not a shortcut... */
	if @nodetype <> 0x80000020
	begin
		if ( @NodeLayoutFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
			update NodeLayout  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
		if ( @LayoutPropertyFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
			update LayoutProperty  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
		if ( @NodePlaceholderFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
			update NodePlaceholder  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
		if ( @NodeContentFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
			update NodePlaceholderContent  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
		if ( @NodeResourceFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
			update NodeResource  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
	end

	/* All nodes are concerned with the following: */
	if ( @NodeRoleFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
		update NodeRole  set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1
	if ( @NodePropertyFlag & @RECORDS_INSERTED ) = @RECORDS_INSERTED
		update NodeProperty set IsBeingInserted = 0  WHERE NodeId = @NodeId and IsBeingInserted = 1



	/* 
	 * Update the Node table itself 
	 */
	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	
	exec GetGMTTime @dateCurrent, @dateGMT out

	if @KeepLocked = 1
	begin
		UPDATE Node SET ModifiedByUserId = @UserId, ModifiedByClientId = @ClientAccountId, IsBeingInserted = 0, 
		 	IsHighPriority = NewIsHighPriority, SameRightsAsParent = NewSameRightsAsParent, ReadyForApproval = NewReadyForApproval, 
			SortOrdinal = NewSortOrdinal, ApprovalStatus = NewApprovalStatus, 
			ApprovedByUserId  = NewApprovedByUserId, OwnerId = NewOwnerId, 
			ApprovedByClientId  = NewApprovedByClientId, OwnerClientId = NewOwnerClientId, 
			EffectiveDate = NewEffectiveDate, ExpiryDate = NewExpiryDate, TemplateGUID = NewTemplateGUID, 
			Name = NewName,  
			DirectoryService = NewDirectoryService, DirectoryGUID = NewDirectoryGUID,
			IsHiddenModePublished = NewIsHiddenModePublished, IsRobotFollowable = NewIsRobotFollowable,
			IsRobotIndexable = NewIsRobotIndexable, DisplayName = NewDisplayName,  
			TemplateAspPath = NewTemplateAspPath, SchemaXML = NewSchemaXML, OuterScriptFile=NewOuterScriptFile, UseOuterScriptForPostings=NewUseOuterScriptForPostings,DefaultPostingName=NewDefaultPostingName, PageDefinitionGUID = NewPageDefinitionGUID,
			ModifiedWhen = @dateGMT,
			ApprovedWhen = case when IsCheckedOutVersion = 0 and Type = 256 then @dateGMT
								when IsCheckedOutVersion = 0 and Type <> 256 then ApprovedWhen
								else NULL
							end
			FROM NodeLock WHERE Node.Id = @NodeId AND Node.Id = NodeLock.NodeId
	end

	if @KeepLocked = 0
	begin
		UPDATE Node SET ModifiedByUserId = @UserId, ModifiedByClientId = @ClientAccountId,
			IsLocked = 0, IsBeingInserted = 0,LockMachinename = NULL, LockUserId = NULL, LockClientId = NULL,
			IsHighPriority = NewIsHighPriority, SameRightsAsParent = NewSameRightsAsParent, 
			ReadyForApproval = NewReadyForApproval, SortOrdinal = NewSortOrdinal, 
			ApprovalStatus = NewApprovalStatus, ApprovedByUserId  = NewApprovedByUserId, 
			OwnerId = NewOwnerId, 
			ApprovedByClientId  = NewApprovedByClientId, OwnerClientId = NewOwnerClientId, 	
			EffectiveDate = NewEffectiveDate, ExpiryDate = NewExpiryDate, 
			TemplateGUID = NewTemplateGUID, 
			Name = NewName, DirectoryService = NewDirectoryService, DirectoryGUID = NewDirectoryGUID,
			IsHiddenModePublished = NewIsHiddenModePublished, IsRobotFollowable = NewIsRobotFollowable,
			IsRobotIndexable = NewIsRobotIndexable, DisplayName = NewDisplayName, 
			TemplateAspPath = NewTemplateAspPath, SchemaXML = NewSchemaXML, OuterScriptFile=NewOuterScriptFile, UseOuterScriptForPostings=NewUseOuterScriptForPostings,DefaultPostingName=NewDefaultPostingName, PageDefinitionGUID = NewPageDefinitionGUID,
			ModifiedWhen = @dateGMT, 
			ApprovedWhen = case when IsCheckedOutVersion = 0 and Type = 256 then @dateGMT
								when IsCheckedOutVersion = 0 and Type <> 256 then ApprovedWhen
								else NULL
							end
			 FROM NodeLock WHERE Id = @NodeId AND NodeLock.NodeId = Node.Id	

		DELETE FROM NodeLock WHERE NodeId = @NodeId
	end


GO


GRANT EXEC ON dbo.CommitNode TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CopyAssociatedData')
	BEGIN
		PRINT 'Dropping Procedure CopyAssociatedData'
		DROP  Procedure  dbo.CopyAssociatedData
	END

GO

PRINT 'Creating Procedure CopyAssociatedData'
GO
create  procedure dbo.CopyAssociatedData( @SourceId int, 
				      @DestID int, 
			          @CopyFromLock int, 
				      @NodeType int,
				      @EmptyTables int )
with encryption
AS

set nocount on

	/*empty collection enum*/
	declare @NO_ROLE_ACL 		tinyint, 	--NodeRole
			@NO_GENERIC_PROPS 	tinyint,	--NodeProperty
			@NO_CONTROL_ITEMS	tinyint,	--GalleryControl
			@NO_LAYOUTS			tinyint,	--NodeLayout
			@NO_RESOURCES		tinyint,	--NodeResource
			@NO_CONTROLS		tinyint,	--NodePlaceholder
			@NO_TEMPLATE_PROPS	tinyint		--LayoutTemplatePropery

	set @NO_ROLE_ACL = 1
	set @NO_GENERIC_PROPS = 2
	set @NO_CONTROL_ITEMS = 4
	set @NO_LAYOUTS = 8
	set @NO_RESOURCES = 16
	set @NO_CONTROLS = 32
	set @NO_TEMPLATE_PROPS = 64

IF @CopyFromLock = 1
BEGIN

	/* User role */
	if @nodeType = 0x100000
	begin
		INSERT INTO UserRoleMember (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, UserId)
			SELECT 0, 0, 0, @DestID, UserId FROM UserRoleMember WHERE NodeId = @SourceId AND IsBeingDeleted = 0

	end
	

	/* If we are not a shortcut... */
	if @nodetype <> 0x80000020
	begin
		if ( @Emptytables & @NO_RESOURCES ) = 0
		begin
			INSERT INTO NodeResource (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, IsLink, URL, ResourceBlobId, NodeGUID, LinkAnchor) 
				SELECT 0, 0, 0, @DestID, Id, NewName, NewIsLink, NewURL, NewResourceBlobId, NewNodeGUID, NewLinkAnchor FROM NodeResource WHERE NodeId = @SourceId AND IsBeingDeleted = 0 and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )
			INSERT INTO NodeResource (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, IsLink, URL, ResourceBlobId, NodeGUID, LinkAnchor) 
				SELECT 0, 0, 0, @DestID, Id, Name, IsLink, URL, ResourceBlobId, NodeGUID, LinkAnchor FROM NodeResource WHERE NodeId = @SourceId AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )
		end
		if ( @Emptytables & @NO_CONTROLS ) = 0
		begin
			INSERT INTO NodePlaceholder (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, NewName, ControlGUID) 
				SELECT 0, 0, 0, @DestID, Id, NewName, ControlGUID FROM NodePlaceholder WHERE NodeId = @SourceId AND IsBeingDeleted = 0 and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )
			INSERT INTO NodePlaceholder (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, ControlGUID) 
				SELECT 0, 0, 0, @DestID, Id, Name, ControlGUID FROM NodePlaceholder WHERE NodeId = @SourceId  AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )

			INSERT INTO NodePlaceholderContent (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, PlaceholderId, Id, PropName, IsResource, PropValue, ResourceId) 
				SELECT 0, 0, 0, @DestID, PlaceholderId, Id, NewPropName, NewIsResource, NewPropValue, NewResourceId FROM NodePlaceholderContent WHERE NodeId = @SourceId AND IsBeingDeleted = 0 and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )
			INSERT INTO NodePlaceholderContent (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, PlaceholderId, Id, PropName, IsResource, PropValue, ResourceId) 
				SELECT 0, 0, 0, @DestID, PlaceholderId, Id, PropName, IsResource, PropValue, ResourceId FROM NodePlaceholderContent WHERE NodeId = @SourceId  AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )
		end
		if ( @Emptytables & @NO_LAYOUTS ) = 0
		begin
			INSERT INTO NodeLayout (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, LayoutTemplateGUID) 
				SELECT 0, 0, 0, @DestID, Id, NewName, NewLayoutTemplateGUID FROM NodeLayout WHERE NodeId = @SourceId AND IsBeingDeleted = 0 and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )
			INSERT INTO NodeLayout (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, LayoutTemplateGUID) 
				SELECT 0, 0, 0, @DestID, Id, Name, LayoutTemplateGUID FROM NodeLayout WHERE NodeId = @SourceId  AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )

			INSERT INTO LayoutProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, LayoutId, Id, PropName, IsControl, PropValue, ControlId) 
				SELECT 0, 0, 0, @DestID, LayoutId, Id, NewPropName, NewIsControl, NewPropValue, NewControlId FROM LayoutProperty WHERE NodeId = @SourceId AND IsBeingDeleted = 0 and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )
			INSERT INTO LayoutProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, LayoutId, Id, PropName, IsControl, PropValue, ControlId) 
				SELECT 0, 0, 0, @DestID, LayoutId, Id, PropName, IsControl, PropValue, ControlId FROM LayoutProperty WHERE NodeId = @SourceId AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )
		end
	end

	/* All the rest */
	if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0
	begin
		INSERT INTO NodeProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, 
									PropName, PropValue, PropValueLong, PropType) 
			SELECT 0, 0, 0, @DestID, Id, PropName, NewPropValue, NewPropValueLong, PropType
			FROM NodeProperty WHERE NodeId = @SourceId AND IsBeingDeleted = 0  and ( IsBeingInserted = 1 or IsBeingUpdated = 1 )

		INSERT INTO NodeProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, PropName, 
								PropValue, PropValueLong, PropType) 
			SELECT 0, 0, 0, @DestID, Id, PropName, PropValue, PropValueLong, PropType
			FROM NodeProperty WHERE NodeId = @SourceId AND ( IsBeingInserted = 0 AND IsBeingUpdated = 0 )

	end
	if ( @EmptyTables & @NO_ROLE_ACL ) = 0
	begin
		INSERT INTO NodeRole (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, RoleGUID) 
			SELECT 0, 0, 0, @DestID, RoleGUID FROM NodeRole WHERE NodeId = @SourceId AND IsBeingDeleted = 0
	end
END
ELSE
BEGIN

	/* User role */
	if @nodeType = 0x100000
	begin
		INSERT INTO UserRoleMember (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, UserId)
			SELECT 0, 0, 0, @DestID, UserId FROM UserRoleMember WHERE NodeId = @SourceId AND IsBeingInserted = 0
	end
	
	/* If we are not a shortcut... */
	if @nodetype <> 0x80000020
	begin
		if ( @EmptyTables & @NO_RESOURCES ) = 0
			INSERT INTO NodeResource (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, IsLink, URL, ResourceBlobId, NodeGUID, LinkAnchor) 
				SELECT 0, 0, 0, @DestID, Id, Name, IsLink, URL, ResourceBlobId, NodeGUID, LinkAnchor FROM NodeResource WHERE NodeId = @SourceId AND IsBeingInserted = 0			

		if ( @EmptyTables & @NO_CONTROLS ) = 0
		begin
			INSERT INTO NodePlaceholder (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, ControlGUID) 
				SELECT 0, 0, 0, @DestID, Id, Name, ControlGUID FROM NodePlaceholder WHERE NodeId = @SourceId AND IsBeingInserted = 0

			INSERT INTO NodePlaceholderContent (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, PlaceholderId, Id, PropName, IsResource, PropValue, ResourceId) 
				SELECT 0, 0, 0, @DestID, PlaceholderId, Id, PropName, IsResource, PropValue, ResourceId FROM NodePlaceholderContent WHERE NodeId = @SourceId AND IsBeingInserted = 0
		end

		if ( @EmptyTables & @NO_LAYOUTS ) = 0
		begin
			INSERT INTO NodeLayout (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, Name, LayoutTemplateGUID) 
				SELECT 0, 0, 0, @DestID, Id, Name, LayoutTemplateGUID FROM NodeLayout WHERE NodeId = @SourceId AND IsBeingInserted = 0
			INSERT INTO LayoutProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, LayoutId, Id, PropName, IsControl, PropValue, ControlId) 
				SELECT 0, 0, 0, @DestID, LayoutId, Id, PropName, IsControl, PropValue, ControlId FROM LayoutProperty WHERE NodeId = @SourceId AND IsBeingInserted = 0
		end
	end


	if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0
		INSERT INTO NodeProperty (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, Id, PropName, 
								PropValue, PropValueLong, PropType) 
			SELECT 0, 0, 0, @DestID, Id, PropName, PropValue, PropValueLong, PropType
			FROM NodeProperty WHERE NodeId = @SourceId AND IsBeingInserted = 0
	if ( @EmptyTables & @NO_ROLE_ACL ) = 0
		INSERT INTO NodeRole (IsBeingInserted, IsBeingUpdated, IsBeingDeleted, NodeId, RoleGUID) 
			SELECT 0, 0, 0, @DestID, RoleGUID FROM NodeRole WHERE NodeId = @SourceId AND IsBeingInserted = 0
	
END

GO

GRANT EXEC ON dbo.CopyAssociatedData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CopyAssocDataToOtherVersion')
	BEGIN
		PRINT 'Dropping Procedure CopyAssocDataToOtherVersion'
		DROP  Procedure  dbo.CopyAssocDataToOtherVersion
	END

GO

PRINT 'Creating Procedure CopyAssocDataToOtherVersion'
GO

create PROCEDURE dbo.CopyAssocDataToOtherVersion
	( 
	@SourceId int 
	)
	with encryption
AS

set nocount on

DECLARE @DestID int, @NodeType int

select @DestID = node1.Id, @NodeType = node1.Type FROM Node node1, Node node2 where node1.NodeGUID = node2.NodeGUID and node1.Id <> node2.Id and node2.Id = @SourceId

Exec CopyAssociatedData @SourceId, @DestID, 0, @NodeType, 0


GO

GRANT EXEC ON dbo.CopyAssocDataToOtherVersion TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CreateArchive')
	BEGIN
		PRINT 'Dropping Procedure CreateArchive'
		DROP  Procedure  dbo.CreateArchive
	END

GO

PRINT 'Creating Procedure CreateArchive'
GO

Create Procedure dbo.CreateArchive
	(
		@NewGUID char(38),
		@SourceGUID char(38),
		@SourceNodeId int,
		@ArchiveParentGUID char(38)
	)
	with encryption

As
	set nocount on

	DECLARE @dateGMT datetime, @dateCurrent datetime
	
	select @dateCurrent = GETDATE()
	
	exec GetGMTTime @dateCurrent, @dateGMT out
	
		INSERT INTO Node (IsLocked, IsCheckedOut, IsCheckedOutVersion, HasCheckedInVersion, 
			CheckedInVersionHasExisted, IsShortcut, IsBeingInserted,IsHighPriority,SameRightsAsParent,
			ReadyForApproval, ApprovalStatus,Type,SortOrdinal,NodeGUID,	  ParentGUID, 
			TemplateType, FollowGUID,  DeletedWhen, DeletedByUserId, CreatedByUserId, CreatedWhen, ModifiedByUserId,
			ModifiedWhen,	OwnerId, ApprovedByUserId, EffectiveDate, ExpiryDate, TemplateGUID, 
			ArchiveSourceGUID, ApprovedWhen, ArchivedWhen, 
			LockUserId, LastChangeTime, LockMachinename, Name,   
			DirectoryService, DirectoryGUID, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, DisplayName,
			CreatedByClientId, ModifiedByClientId, LockClientId, OwnerClientId, ApprovedByClientId, DeletedByClientId,
			TemplateAspPath, SchemaXML, OuterScriptFile, UseOuterScriptForPostings,DefaultPostingName ) 
		SELECT  0, 0, 0, 1, 
			1, IsShortcut, 0, IsHighPriority,SameRightsAsParent,
			ReadyForApproval, ApprovalStatus,Type,SortOrdinal,@NewGUID, @ArchiveParentGUID,
			TemplateType, FollowGUID, NULL, NULL, CreatedByUserId, @dateGMT, ModifiedByUserId, 
			ModifiedWhen,	OwnerId, ApprovedByUserId, EffectiveDate, ExpiryDate, TemplateGUID, 
			@SourceGUID, ApprovedWhen, @dateGMT, 
			NULL, LastChangeTime, NULL, Name,  
			DirectoryService, DirectoryGUID,
			IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, DisplayName,
			CreatedByClientId, ModifiedByClientId, LockClientId, OwnerClientId, ApprovedByClientId, DeletedByClientId,
			TemplateAspPath, SchemaXML, OuterScriptFile, UseOuterScriptForPostings,DefaultPostingName
			FROM Node WHERE Id=@SourceNodeId
	
	Declare @NewNodeID int
	Declare @NodeType int
	
	select @NewNodeID = Id, @NodeType = Type  from Node where NodeGUID = @NewGUID
	
	Exec CopyAssociatedData @SourceNodeId, @NewNodeID, 0, @NodeType, 0
GO

GRANT EXEC ON dbo.CreateArchive TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CreateArchiveFromCheckedIn')
	BEGIN
		PRINT 'Dropping Procedure CreateArchiveFromCheckedIn'
		DROP  Procedure  dbo.CreateArchiveFromCheckedIn
	END

GO

PRINT 'Creating Procedure CreateArchiveFromCheckedIn'
GO

CREATE Procedure dbo.CreateArchiveFromCheckedIn
(
	@NewGUID char(38),
	@NodeGUID char(38),
	@SourceNodeId int,
	@ArchiveParentGUID char(38)
)
with encryption

As
	set nocount on

	DECLARE @dateGMT datetime, @dateCurrent datetime
	
	select @dateCurrent = GETDATE()
	
	exec GetGMTTime @dateCurrent, @dateGMT out
	
	update Node set NodeGUID = @NewGUID, 
			 ParentGUID	= @ArchiveParentGUID,
       		 IsCheckedOut = 0, 
			 CheckedOutByUserId = NULL, CheckedOutByMachine = NULL,
			 CreatedWhen = @dateGMT, 
			 ArchivedWhen = @dateGMT,
			 ArchiveSourceGUID = @NodeGUID
	where Id = @SourceNodeId
GO


GRANT EXEC ON dbo.CreateArchiveFromCheckedIn TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'DeleteNodeByGUID')
	BEGIN
		PRINT 'Dropping Procedure DeleteNodeByGUID'
		DROP  Procedure  dbo.DeleteNodeByGUID
	END

GO

PRINT 'Creating Procedure DeleteNodeByGUID'
GO

Create Procedure dbo.DeleteNodeByGUID
	(
		@NodeGUID varchar(38),
        @EmptyTables int 
	) 
	with encryption
As
	SET NOCOUNT ON 
 
 DECLARE @CurrentId as int

 DECLARE DeletedItems CURSOR LOCAL READ_ONLY 
    FOR SELECT Id FROM Node WHERE NodeGUID = @NodeGUID 

  OPEN DeletedItems
  FETCH NEXT FROM DeletedItems INTO @CurrentId
  WHILE @@FETCH_STATUS = 0
  BEGIN
		exec DeleteNodeById @CurrentId, @EmptyTables
		
		FETCH NEXT FROM DeletedItems INTO @CurrentId
  END  

  CLOSE DeletedItems
  DEALLOCATE DeletedItems

return
GO



GO

GRANT EXEC ON dbo.DeleteNodeByGUID TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'DeleteNodeById')
	BEGIN
		PRINT 'Dropping Procedure DeleteNodeById'
		DROP  Procedure  dbo.DeleteNodeById
	END

GO

PRINT 'Creating Procedure DeleteNodeById'
GO

create Procedure dbo.DeleteNodeById
	(
		@CurrentId int,
		@EmptyTables int
	)
	with encryption
As
 SET NOCOUNT ON

	/*empty collection enum*/
	declare @NO_ROLE_ACL 		tinyint, 	--NodeRole
			@NO_GENERIC_PROPS 	tinyint,	--NodeProperty
			@NO_CONTROL_ITEMS	tinyint,	--GalleryControl
			@NO_LAYOUTS			tinyint,	--NodeLayout
			@NO_RESOURCES		tinyint,	--NodeResource
			@NO_CONTROLS		tinyint,	--NodePlaceholder
			@NO_TEMPLATE_PROPS	tinyint,	--LayoutTemplatePropery
			@NO_ROLE_RIGHTS		tinyint		--UserRoleNode

	set @NO_ROLE_ACL = 1
	set @NO_GENERIC_PROPS = 2
	set @NO_CONTROL_ITEMS = 4
	set @NO_LAYOUTS = 8
	set @NO_RESOURCES = 16
	set @NO_CONTROLS = 32
	set @NO_TEMPLATE_PROPS = 64
	set @NO_ROLE_RIGHTS = 128
  
	if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0 
		DELETE FROM NodeProperty WHERE NodeId = @CurrentId

	if ( @EmptyTables & @NO_ROLE_ACL ) = 0 
		DELETE FROM NodeRole WHERE NodeId = @CurrentId

	if ( @EmptyTables & @NO_RESOURCES ) = 0 
		DELETE FROM NodeResource WHERE NodeId = @CurrentId

	if ( @EmptyTables & @NO_CONTROLS ) = 0 
	begin
		DELETE FROM NodePlaceholderContent WHERE NodeId = @CurrentId
		DELETE FROM NodePlaceholder WHERE NodeId = @CurrentId
	end

	if ( @EmptyTables & @NO_LAYOUTS ) = 0 
	begin
		DELETE FROM LayoutProperty WHERE NodeId = @CurrentId
		DELETE FROM NodeLayout WHERE NodeId = @CurrentId
	end

	if ( @EmptyTables & @NO_ROLE_RIGHTS ) = 0 
	begin
		DELETE FROM UserRoleMember WHERE NodeId = @CurrentId
	end


	DELETE FROM NodeLock WHERE NodeId = @CurrentId
	DELETE FROM Node WHERE Id = @CurrentId
return
GO

GRANT EXEC ON dbo.DeleteNodeById TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'DeleteRecursive')
	BEGIN
		PRINT 'Dropping Procedure DeleteRecursive'
		DROP  Procedure  dbo.DeleteRecursive
	END

GO

PRINT 'Creating Procedure DeleteRecursive'
GO

create procedure dbo.DeleteRecursive
	(
	@DeleteAction int,					--see below
	@SourceNodeGuid char(38),			--Item being deleted
	@NewParentGUID char(38),			--New parent for move
	@UserId	int,						--User who is deleting
	@UserMachineName nvarchar(50),		--Client machine doing delete
	@UserGroupIDs varchar(1000),		--Don't use, but it is ids of groups user is member of
	@ArchiveFolderGUID char(38),		--For resources only
	@ClientAccountId int				--Same as user id (auditing purposes)
	)
	with encryption
as
/*Enum values for @DeleteAction
	0 - Move to Recycle Bin
	1 - Move from Recycle Bin
	2 - Purge from the database
*/

/*Enum values for Node Status
	2 - USER_LOCK_FAILED
	4 - RIGHTS_FAILED
	8 - TEMPLATE_FAILED
	32- CONTENT_SCHEMA_FAILED
	64 -CHECKEDOUT_NODE_FAILED
*/
	declare @MOVE_TO_RECYCLE_BIN int, @MOVE_FROM_RECYCLE_BIN int, @PURGE int
	set @MOVE_TO_RECYCLE_BIN = 0
	set @MOVE_FROM_RECYCLE_BIN = 1
	set @PURGE = 2

	declare @ACL_FULL_CONTROL varchar(15), @ACL_DELETE_SIMPLE_NODE varchar(15), @ACL_DELETE_OWN_NODE varchar(15)
	set @ACL_FULL_CONTROL = '-2147483648'
	set @ACL_DELETE_SIMPLE_NODE = '16'
	set @ACL_DELETE_OWN_NODE = '67108864'

   declare @Level int, @currParentGUID char(38), @currID int, @Type int, @Name varchar(250), @IsShortcut tinyint
   declare @Failed tinyint
   declare @NodeType int, @IsPosting tinyint
   declare @SQL nvarchar(1000)
   declare @HasRights int
   declare @IsItem tinyint
   DECLARE @dateGMT datetime, @dateCurrent datetime
   declare @IsSourceNodeDeleted int
  
   set nocount on
   set @Failed = 0
   set @IsItem = 0
   set @Type = 0
   set @HasRights = 0
   set @NodeType = 0
   set @IsPosting = 0

   /*temporary table that stores nodes being deleted, 
	that is the specified Node plus all its children*/
    create table #nodes_to_delete
		(
		seq_no	int IDENTITY,
		NodeLevel int not null,
		Id int not null,
		NodeGUID char(38) collate database_default not null,
		Type int not null,
		IsShortcut tinyint not null,
		Name varchar(250) collate database_default null
		);

    CREATE Index nodes_to_delete_id On #nodes_to_delete
		(
		Id
		)
		
    CREATE Index nodes_to_delete_nodeguid On #nodes_to_delete
		(
		NodeGUID
		)
		
   /* temporary table that stores Node Status info*/
   create table #nodes_delete_info
		(
		NodeGUID char(38) collate database_default not null,
		NodeState int default 0,
		NodeLevel int NULL,
		LockingUser int,
		LockingMachine nvarchar(50) collate database_default,
		Name varchar(250) collate database_default null
		)

    CREATE Index nodes_delete_info_nodeguid On #nodes_delete_info
		(
		NodeGUID
		)

    /*another temporary table that serves as a stack when expanding tree hierarchy*/
   create table #node_stack
		(
		NodeLevel int not null,
		Id int not null,	
		NodeGUID char(38) collate database_default not null,
		Type int not null,
		IsShortcut tinyint,
		Name varchar(250) collate database_default null
		);    	

    CREATE Index node_stack_level On #node_stack
		(
		NodeLevel
		)

	/*find out whether we're deleting a single Node or a container*/
	set rowcount 1	
	select @NodeType = Type, @IsPosting = IsShortcut, @IsSourceNodeDeleted = DeletedByUserId 
	from Node 
	where NodeGUID = @SourceNodeGuid

	if @NodeType = 0 or @NodeType is null
	begin
		select @SQL = 'Node with GUID ' + @SourceNodeGuid + ' does not exist in the database.'
		raiserror (@SQL, 15, 1)
		goto Cleanup
	end
	else
		if @NodeType != 4 and @NodeType != 64 and @NodeType != 1024 and 	/*these are all container types*/
		@NodeType != 16384 and @NodeType != 524288 and @NodeType != 2097152 and @NodeType != 16777216
			set @IsItem = 1	

	set rowcount 0

   	/*retrieve all children of the specified Node*/
	if @IsItem > 0 	/*single Node case*/
   	begin
	    insert into #nodes_to_delete (NodeLevel, Id, NodeGUID, Type, IsShortcut, Name)
		select 0, Id, NodeGUID, Type, IsShortcut, Name 
		from Node 
		where NodeGUID = @SourceNodeGuid
	end

	else	/*container*/

	begin	
		select @Level = 1, @currParentGuid = NodeGUID, @currID = Id, @Type = Type, 
		@IsShortcut = IsShortcut, @Name = Name  
		from Node with (UPDLOCK)
		where NodeGUID = @SourceNodeGuid

		insert into #node_stack (NodeLevel, Id, NodeGUID, Type, IsShortcut, Name ) 
		values (@Level, @currID, @currParentGUID, @Type, @IsShortcut, @Name )

		while (@Level > 0 )	--Do if any levels remain
		   begin
			--see if there are any rows for the Level we're on
			if exists( select Id from #node_stack where NodeLevel = @Level )
			   begin
				--get first Node at current Level
				set rowcount 1
				select @currParentGUID = NodeGUID, @currID = Id, @Type = Type, 
				@IsShortcut = IsShortcut, @Name = Name
				from #node_stack where NodeLevel = @Level
				
				set rowcount 0
	
				--insert this Node into result table
				insert into #nodes_to_delete (NodeLevel, Id, NodeGUID, Type, IsShortcut, Name )
					values (@Level, @currID, @currParentGUID, @Type, @IsShortcut, @Name )
				
				--delete this Node from the stack
				delete from #node_stack 
				where NodeLevel = @Level and Id = @currID
	
				--get children of this Node
				insert into #node_stack (NodeLevel, Id, NodeGUID, Type, IsShortcut, Name )
					select @Level + 1, n1.Id, n1.NodeGUID, n1.Type, n1.IsShortcut, n1.Name 
					from Node n1 with (UPDLOCK)
					where ParentGUID = @currParentGUID 

				if @@ROWCOUNT > 0
				   set @Level = @Level + 1
			    end
			else
			   --there is no Level below this one, so pop up one
			   set @Level = @Level - 1
		  end	--while (@Level > 0 )
     end	--container

    /*OK, at this point we have descendants in the #nodes_to_delete table */    
	if @NodeType = 2097152 or (@NodeType = 16 and @IsPosting = 0)
	begin
		/*retrieve all shortcuts to the pages we're deleting*/
	    insert into #nodes_to_delete (NodeLevel, Id, NodeGUID, Type, IsShortcut, Name)
			select nd.NodeLevel, Posting.Id, Posting.NodeGUID, Posting.Type, Posting.IsShortcut, Page.Name 
			from #nodes_to_delete nd, Node Posting with (UPDLOCK), Node Page 
			where Posting.FollowGUID = nd.NodeGUID
			and Page.NodeGUID = Posting.FollowGUID
	end

    /*populate delete_info table*/
    insert into #nodes_delete_info (NodeGUID, NodeLevel, Name) 
		select distinct nd.NodeGUID, nd.NodeLevel, nd.Name  
		from #nodes_to_delete nd 
		order by nd.NodeLevel
	
	if @DeleteAction != @MOVE_FROM_RECYCLE_BIN /*if we're moving to recycle bin or purging*/
	begin
		if @NodeType = 16384 or @NodeType = 65536	/*template or template gallery*/
		begin
		    /*make sure there are no postings that depend on templates*/
		    update #nodes_delete_info set NodeState = NodeState | 8  /*TEMPLATE_FAILED*/
			from Node 
			where #nodes_delete_info.NodeGUID = Node.TemplateGUID
			and Node.ArchiveSourceGUID is null /*do not check archived versions*/
	
		    if @@ROWCOUNT > 0 
				set @Failed = 1
				
		    /*make sure there are no pages that depend on templates*/
		    update #nodes_delete_info set NodeState = NodeState | 8  /*TEMPLATE_FAILED*/
			from NodeLayout, Node 
			where #nodes_delete_info.NodeGUID = NodeLayout.LayoutTemplateGUID
			and NodeLayout.NodeId = Node.Id and Node.ArchiveSourceGUID is null /*do not check archived versions*/
	
		    if @@ROWCOUNT > 0 
				set @Failed = 1

		    /*find nodes that are checked out and check if the user is allowed to modify them*/
		    --update #nodes_delete_info 
			--set NodeState = NodeState | 64,  /*CHECKEDOUT_NODE_FAILED*/
			--LockingUser = n.CheckedOutByUserId, LockingMachine = n.CheckedOutByMachine
			--from #nodes_to_delete nd inner join  Node n on (nd.Id = n.Id)
			--where #nodes_delete_info.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1 and 
			--n.CheckedOutByUserId != @UserId
		
		    --if @@ROWCOUNT > 0 
			--	set @Failed = 1

		end
		else if @NodeType = 16777216 or @NodeType = 33554432	/*content schema or content schema gallery*/
		begin
		    /*make sure there are no templates that depend on content schemas*/
		    update #nodes_delete_info set NodeState = NodeState | 32  /*CONTENT_SCHEMA_FAILED*/
			from Node schemas inner join Node templates on schemas.NodeGUID = templates.PageDefinitionGUID
			where #nodes_delete_info.NodeGUID = schemas.NodeGUID
	
		    if @@ROWCOUNT > 0 
				set @Failed = 1

		    /*find nodes that are checked out and check if the user is allowed to modify them*/
		    --update #nodes_delete_info 
			--set NodeState = NodeState | 64,  /*CHECKEDOUT_NODE_FAILED*/
			--LockingUser = n.CheckedOutByUserId, LockingMachine = n.CheckedOutByMachine
			--from #nodes_to_delete nd inner join  Node n on (nd.Id = n.Id)
			--where #nodes_delete_info.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1 and 
			--n.CheckedOutByUserId != @UserId
		
		    --if @@ROWCOUNT > 0 
			--	set @Failed = 1

		end
		else	/*everything else*/
		begin
		    /*find nodes that are locked and check if the user is the one who locked them*/
		    update #nodes_delete_info 
			set NodeState = NodeState | 2,  /*USER_LOCK_FAILED*/
			LockingUser = n.LockUserId, LockingMachine = n.LockMachinename
			from #nodes_to_delete nd inner join  Node n on (nd.Id = n.Id)
			where #nodes_delete_info.NodeGUID = n.NodeGUID and n.IsLocked = 1 and 
			(n.LockUserId != @UserId or upper(n.LockMachinename) != upper(@UserMachineName))
		
		    if @@ROWCOUNT > 0 
				set @Failed = 1
		end 
	end

    /*check if user has rights to delete/undelete these nodes using the following logic:
	- currently we require a user to be an administrator in order delete/restore containers
    (this check is actually done in the server code, but we're double checking just in case)
	- if a user is purging or restoring an item (page, template, etc.) and he is not an administrator 
	then we check if he is the same user who originally deleted this item (that is moved to Recycle Bin)
	- things get really ugly when we're moving an item to Recycle Bin as at this time we have to perform 
	a horrible join to check user's rights to this item
	*/
	
	--exec CheckAdminRights @UserGroupIds, @HasRights out
	/*we used to check administrator's rights within the stored procedure, but this didn't account for local 
	administrators, so now we're passing this info in @UserGroupIDs */
	if @UserGroupIDs = '-1'
		set @HasRights = 1

	if @HasRights = 0 
	begin
		--we're dealing with a single Node here
		if @IsItem > 0
			begin
				declare @everybody int
				select @everybody = UserId 
				from AEUser 
				where UsernameUpper = 'EVERYBODY' 

				-- we're purging or restoring an item
				if @DeleteAction = @MOVE_FROM_RECYCLE_BIN or
					(@DeleteAction = @PURGE and @IsSourceNodeDeleted is not null 
					and @IsSourceNodeDeleted > 0) --the item is already in Recycle Bin
					begin
						set @SQL = 'update #nodes_delete_info set NodeState = NodeState | 4 ' +  /*RIGHTS_FAILED*/ 
						'where #nodes_delete_info.NodeGUID not in ' + 
						'(select n.NodeGUID from #nodes_to_delete nd inner join  Node n on (nd.Id = n.Id) ' + 
						'where n.DeletedByUserId = ' + convert(varchar(10), @UserId)  +
						' or n.OwnerId IN (' + @UserGroupIDs + ') or n.OwnerId = ' +
						convert(varchar(10),@everybody) + ')'

						exec sp_executesql @SQL
					
					    if @@ROWCOUNT > 0 
							set @Failed = 1
					end
				else	--moving an item into Recycle Bin or purging from WBC
					begin
						--now let's do that horrible join...
					    --set @SQL = 'update #nodes_delete_info set NodeState = NodeState | 4 ' +   /*RIGHTS_FAILED*/ 
						/*'where NodeGUID not in (select n1.NodeGUID ' +  
						'from #nodes_to_delete nd, Node n1, Node NodeParent, NodeRole as nr, Node as UserRole, ' + 
						'UserRoleNode as urn, UserRoleMember as urm ' +  
						'where nd.Id = n1.Id and n1.ParentGUID = NodeParent.NodeGUID and ' +  
						'NodeParent.Id = nr.NodeId and nr.RoleGUID = UserRole.NodeGUID and ' + 
						'UserRole.Id = urn.NodeId and urn.NodeType = ' + 
						'case when n1.Type = 16 and n1.IsShortcut > 0 then -2147483616 else n1.Type end and ' + 
						'urn.NodeId = urm.NodeId and ' + 
						'urm.UserId IN (' + @UserGroupIDs + ') ' + 
						' AND (urn.Rights = ' + @ACL_FULL_CONTROL + 
						' or floor(urn.Rights/' + @ACL_DELETE_SIMPLE_NODE + ')%2 > 0 or ' + 
						'(floor(urn.Rights/' + @ACL_DELETE_OWN_NODE + ')%2 > 0 and ' + 
						'( n1.OwnerId IN (' + @UserGroupIDs + ') or n1.OwnerId = ' + 
						convert(varchar(10),@everybody) + '))) )'

						exec sp_executesql @SQL
				    	
						if @@ROWCOUNT > 0 
						*/
							set @Failed = 1
					end
			end
		else	--containers and their children, need administrator's rights
			begin
			   update #nodes_delete_info set NodeState = NodeState | 4  /*RIGHTS_FAILED*/ 
			   set @Failed = 1
			end	
	end


   	if @Failed = 0 
	begin
		if @DeleteAction = @MOVE_TO_RECYCLE_BIN	/*moving into recycle bin*/
			begin
				set @dateCurrent = GETDATE()
				
				exec GetGMTTime @dateCurrent, @dateGMT out

				update Node set DeletedByUserId = @UserId, DeletedWhen = @dateGMT ,
					ApprovalStatus = 0, DeletedByClientId = @ClientAccountId
					from #nodes_to_delete 
					WHERE Node.Id = #nodes_to_delete.Id

				update NodeLock set NewApprovalStatus = 0
					from #nodes_to_delete 
					WHERE NodeLock.NodeId = #nodes_to_delete.Id
				
				update Node set IsCheckedOut = 1, IsCheckedOutVersion = 1, HasCheckedInVersion = 0
					from #nodes_to_delete 
					where Node.Id = #nodes_to_delete.Id and 
					Node.Type in (16, 65536, 33554432) and Node.IsCheckedOut = 0

				update Node set ParentGUID = @NewParentGUID 
				where NodeGUID = @SourceNodeGuid
			end
		else if @DeleteAction = @MOVE_FROM_RECYCLE_BIN	/*Moving from recycle bin*/
		begin
			update Node set DeletedByUserId = NULL, DeletedWhen = NULL, DeletedByClientId = NULL
				from #nodes_to_delete 
				WHERE Node.Id = #nodes_to_delete.Id

			update Node set ParentGUID = @NewParentGUID 
			where NodeGUID = @SourceNodeGuid
		end

		else 		/*@DeleteAction = 2 - purging*/
	 	begin
			/*now it's time to delete these nodes*/
			if @NodeType != 256 and @NodeType != 64		/*everything but resources and resource gallery*/
			begin
				DELETE NodeProperty FROM #nodes_to_delete WHERE NodeProperty.NodeId = #nodes_to_delete.Id 
				DELETE NodeRole from #nodes_to_delete WHERE NodeRole.NodeId = #nodes_to_delete.Id
				
				if @NodeType = 524288 or @NodeType = 1048576	/*user roles and galleries*/
				begin
					DELETE UserRoleMember from #nodes_to_delete WHERE UserRoleMember.NodeId = #nodes_to_delete.Id
				end

				else 
				begin
					if @IsPosting = 0								/*pages, templates*/
					begin
						DELETE NodeResource from #nodes_to_delete WHERE NodeResource.NodeId = #nodes_to_delete.Id
						DELETE NodePlaceholderContent from #nodes_to_delete WHERE NodePlaceholderContent.NodeId = #nodes_to_delete.Id
						DELETE NodePlaceholder from #nodes_to_delete WHERE NodePlaceholder.NodeId = #nodes_to_delete.Id
						DELETE LayoutProperty from #nodes_to_delete WHERE LayoutProperty.NodeId = #nodes_to_delete.Id
						DELETE NodeLayout from #nodes_to_delete WHERE NodeLayout.NodeId = #nodes_to_delete.Id
					end

					/* delete revisions */
					DELETE NodeProperty where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)
					DELETE NodeRole where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)
					DELETE NodeResource where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID) 
					DELETE NodePlaceholderContent where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)
					DELETE NodePlaceholder where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)
		
					DELETE LayoutProperty where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)
					DELETE NodeLayout where NodeId in (select Node.Id from Node, #nodes_to_delete 
													WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)

					DELETE NodeLock 
					where NodeId in (select Node.Id from Node, #nodes_to_delete 
					WHERE #nodes_to_delete.NodeGUID = Node.ArchiveSourceGUID)		
					
					DELETE Node 
					FROM #nodes_to_delete 
					WHERE ArchiveSourceGUID = #nodes_to_delete.NodeGUID
				end 

				DELETE NodeLock from #nodes_to_delete WHERE NodeLock.NodeId = #nodes_to_delete.Id

				DELETE Node from #nodes_to_delete WHERE Node.Id = #nodes_to_delete.Id
			end --if @NodeType != 256 and @NodeType != 64

			else /*resources and galleries*/
			begin
				--double check whether we have valid ArchiveFolder guid
				if @ArchiveFolderGUID is null
				begin
					Set @ArchiveFolderGUID = (select PropValue
							from Node,NodeProperty
							where Node.Id=NodeProperty.NodeId
							and Node.Type=1
							and PropName='_ArchiveFolder')
					If (@ArchiveFolderGUID Is Null)
						RAISERROR ('Archive Folder Not Found',16,1)

				end
				
				DELETE NodeProperty FROM #nodes_to_delete WHERE NodeProperty.NodeId = #nodes_to_delete.Id and #nodes_to_delete.Type != 256
				DELETE NodeRole from #nodes_to_delete WHERE NodeRole.NodeId = #nodes_to_delete.Id and #nodes_to_delete.Type != 256
				DELETE NodeLock from #nodes_to_delete WHERE NodeLock.NodeId = #nodes_to_delete.Id and #nodes_to_delete.Type != 256

				DELETE Node from #nodes_to_delete WHERE Node.Id = #nodes_to_delete.Id and #nodes_to_delete.Type != 256

				select @dateCurrent = GETDATE()
				exec GetGMTTime @dateCurrent, @dateGMT out
		
				--move resource galery items to Archive Folder
				update Node set ParentGUID = @ArchiveFolderGUID,
				ArchivedWhen = @dateGMT,
				IsLocked = 0	
				from #nodes_to_delete
				where #nodes_to_delete.Id = Node.Id and #nodes_to_delete.Type = 256

				--clear the lock on resource galery items 
				DELETE NodeLock 
				from #nodes_to_delete, Node 
				where #nodes_to_delete.Id = Node.Id and #nodes_to_delete.Type = 256 and NodeLock.NodeId = Node.Id

			end 
		
		end  /*@DeleteAction = 2 - purging*/
			
	    /*return Node Status into*/	
    	exec sp_executesql N'select ndi.NodeGUID, ndi.NodeState, nd.Type, nd.IsShortcut, nd.Name,
		ndi.LockingUser, ndi.LockingMachine, #Sandbox.LastChangeTime
		from (#nodes_delete_info ndi left join 
		(select distinct NodeGUID, Type, IsShortcut, Name from #nodes_to_delete) as nd 
		on ndi.NodeGUID = nd.NodeGUID) left join #Sandbox on ndi.NodeGUID = #Sandbox.NodeGUID'
	end
	else
	    /*return Node Status into*/	
    	exec sp_executesql N'select distinct ndi.NodeGUID, ndi.NodeState, n.Type, n.IsShortcut, ndi.Name,
		ndi.LockingUser, ndi.LockingMachine, max(n.LastChangeTime) as LastChangeTime
		from #nodes_delete_info ndi left join Node as n
		on ndi.NodeGUID = n.NodeGUID 
		where ndi.NodeState > 0
		group by ndi.NodeGUID, ndi.NodeState, n.Type, n.IsShortcut, ndi.Name,
		ndi.LockingUser, ndi.LockingMachine'


Cleanup:

   /*we're done, clean up temp tables*/
   drop table #nodes_to_delete
   drop table #nodes_delete_info
   drop table #node_stack


GO


GRANT EXEC ON dbo.DeleteRecursive TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetClientAccountID')
	BEGIN
		PRINT 'Dropping Procedure GetClientAccountID'
		DROP  Procedure  dbo.GetClientAccountID
	END

GO

PRINT 'Creating Procedure GetClientAccountID'
GO

create procedure dbo.GetClientAccountID
	(
	@Username		nvarchar(250), 
	@AuthType		nvarchar(100),
	@UserId 		int OUTPUT
	)
	with encryption
as
	set nocount on
	set @UserId = 0
	
	/*search for Username and authentication Type*/
	SELECT @UserId = UserId FROM ClientAccount WHERE UsernameUpper = UPPER(@Username) and AuthTypeUpper = upper(IsNull(@AuthType, ''))

	if isnull(@UserId, 0) = 0
	begin
		INSERT INTO ClientAccount (Username, UsernameUpper, AuthType, AuthTypeUpper) 
		VALUES (@Username, upper(@Username), IsNull(@AuthType, ''), upper(IsNull(@AuthType, '')))
		set @UserId = @@IDENTITY
	end


GO


GRANT EXEC ON dbo.GetClientAccountID TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetDescendants')
	BEGIN
		PRINT 'Dropping Procedure GetDescendants'
		DROP  Procedure  dbo.GetDescendants
	END

GO

PRINT 'Creating Procedure GetDescendants'
GO

create procedure dbo.GetDescendants
	(
	@ParentGUID char(38),
    @GetCheckedOutVersion int,
	@UserGroupIDs varchar(1000)
	)
	with encryption
as
   declare @Level int, @currParentGUID char(38), @currID int
   declare @SQL nvarchar(1000), @TempTableCreated int
   declare @IsAdministrator int

   select @IsAdministrator = 0
   select @TempTableCreated = 0

   set nocount on

   /*first check if the user is an administrator*/
   --exec CheckAdminRights @UserGroupIds, @IsAdministrator out
	if @UserGroupIDs = '-1'
		set @IsAdministrator = 1

 
   if @IsAdministrator = 0 
 	   begin
		create table #Node_temp
		(
		NodeGUID char(38) collate database_default not null,
		ParentGUID char(38) collate database_default,
		Id int not null,
		Type int not null
		)
		select @TempTableCreated = 1;

	    /*retrieve nodes that the user has rights to read into a temporary table*/
       	/*set @SQL = 'insert into #Node_temp (NodeGUID, ParentGUID, Id, Type) ' + 
		'select n1.NodeGUID, n1.ParentGUID, n1.Id, n1.Type '  + 
		'from Node as n1, NodeRole as nr, Node as UserRole, UserRoleNode as urn, UserRoleMember as urm ' +
		'where n1.Id = nr.NodeId and nr.RoleGUID = UserRole.NodeGUID and '+ 
		'UserRole.Id = urn.NodeId and urn.NodeType = n1.Type '+ 
		'and urn.NodeId = urm.NodeId AND urn.Rights%2 > 0 ' +
		' and urm.UserId IN (' + @UserGroupIDs + ') and ' +
		'(n1.IsCheckedOutVersion = convert(tinyint, @GetCheckedOutVersion) or '+
		'(n1.IsCheckedOutVersion != convert(tinyint, @GetCheckedOutVersion) and not exists (select Id from Node as n2 '+
		'where n2.IsCheckedOutVersion = convert(tinyint, @GetCheckedOutVersion) and n2.NodeGUID = n1.NodeGUID)))'
 
   		exec sp_executesql @SQL, N'@GetCheckedOutVersion int', @GetCheckedOutVersion
		*/
   		CREATE Index Node_temp_nodeguid On #Node_temp
		(
		NodeGUID
		)

	   end

    /*now create a temporary table that will store expanded hierarchy*/
    create table #node_result
		(
		seq_no	int IDENTITY,
		NodeLevel int not null,
		Id int not null
		);

    /*create another temporary table that will serve as a stack*/
   create table #node_stack
		(
		NodeLevel int not null,
		NodeGUID char(38) collate database_default not null,
		Id int not null
		);    	

   select @currID = 0
   if @IsAdministrator > 0 
	select @Level = 1, @currParentGuid = NodeGUID, @currID = Id from Node where NodeGUID = @ParentGUID
   else
	select @Level = 1, @currParentGuid = NodeGUID, @currID = Id from #Node_temp where NodeGUID = @ParentGUID

   if @@ROWCOUNT > 0 
      begin
	insert into #node_stack values (@Level, @currParentGUID, @currID)

	while (@Level > 0 )	--Do if any levels remain
	   begin
		--see if there are any rows for the Level we're on
		if exists( select * from #node_stack where NodeLevel = @Level )
		   begin
			--get first Node at current Level
			set rowcount 1
			select @currParentGUID = NodeGUID, @currID = Id from #node_stack where NodeLevel = @Level
			set rowcount 0

			--insert this Node into result table
			insert into #node_result (NodeLevel, Id) values (@Level, @currID)
			
			--delete this Node from the stack
			delete from #node_stack where NodeLevel = @Level and Id = @currID

			--get children of this Node
			if @IsAdministrator > 0 
			   begin
				insert into #node_stack select @Level + 1, n1.NodeGUID, n1.Id from Node n1
				where ParentGUID = @currParentGUID and 
				(n1.IsCheckedOutVersion = @GetCheckedOutVersion or 
		  		(n1.IsCheckedOutVersion != @GetCheckedOutVersion 
				and not exists (select Id from Node as n2 
				where n2.IsCheckedOutVersion = @GetCheckedOutVersion and n2.NodeGUID = n1.NodeGUID)))
				if @@ROWCOUNT > 0
				   select @Level = @Level + 1
			   end
			else
			   begin
				insert into #node_stack select @Level + 1, NodeGUID, Id from #Node_temp
				where ParentGUID = @currParentGUID
				if @@ROWCOUNT > 0
				   select @Level = @Level + 1
			   end
		     end
		else
		   --there is no Level below this one, so pop up one
		   select @Level = @Level - 1
	   end	
      end
    else
	begin
		select @SQL = 'Node with GUID ' + @ParentGUID + ' does not exist in the database.'
		raiserror (@SQL, 15, 1)
		goto Cleanup
	end

   --now just join Node table to the #node_result   
   select tmp.NodeLevel as [Level], n.NodeGUID, n.ParentGUID, n.Id, n.Type, 
	n.IsShortcut, n.Name from
	Node as n join #node_result as tmp on (n.Id = tmp.Id)
	order by tmp.seq_no

Cleanup:
   drop table #node_stack, #node_result

   if @TempTableCreated > 0
	drop table #Node_temp

go   


GRANT EXEC ON dbo.GetDescendants TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetGMTTime')
	BEGIN
		PRINT 'Dropping Procedure GetGMTTime'
		DROP  Procedure  dbo.GetGMTTime
	END

GO

PRINT 'Creating Procedure GetGMTTime'
GO

Create Procedure dbo.GetGMTTime (@dateCurrent datetime, @dateGMT datetime output)
				with encryption
As
Set nocount on
if substring(@@VERSION, PATINDEX('%_.__.___%', @@VERSION), 1) = '8'
Begin
	Select @dateGMT = getutcdate()
End
Else	
Begin
	Declare @DeltaGMT int
	Select @DeltaGMT = DeltaGMT from Utility
	Select @dateGMT = DATEADD(minute,@DeltaGMT,@dateCurrent)
End

GO

GRANT EXEC ON dbo.GetGMTTime TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetNextPublishingChangeTime')
	BEGIN
		PRINT 'Dropping Procedure GetNextPublishingChangeTime'
		DROP  Procedure  dbo.GetNextPublishingChangeTime
	END

GO

PRINT 'Creating Procedure GetNextPublishingChangeTime'
GO

create procedure dbo.GetNextPublishingChangeTime
	(
	@NextChangeTime datetime out
	)
with encryption
as
	declare @NextEffectiveDate datetime, @NextExpiryDate datetime

	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out

	select @NextEffectiveDate = min(EffectiveDate)
	from Node
	where EffectiveDate > @dateGMT and ApprovalStatus = 1

	select @NextExpiryDate = min(ExpiryDate)
	from Node
	where ExpiryDate > @dateGMT and ApprovalStatus = 1

	if @NextEffectiveDate <= @NextExpiryDate
		set @NextChangeTime = @NextEffectiveDate
	else if @NextExpiryDate < @NextEffectiveDate 
		set @NextChangeTime = @NextExpiryDate
	else	--one of these values is null
		set @NextChangeTime = isnull(COALESCE(@NextEffectiveDate, @NextExpiryDate ), '3000-01-01 00:00:00.000')

go


GRANT EXEC ON dbo.GetNextPublishingChangeTime TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetRevisionCause')
	BEGIN
		PRINT 'Dropping Procedure GetRevisionCause'
		DROP  Procedure  dbo.GetRevisionCause
	END

GO

PRINT 'Creating Procedure GetRevisionCause'
GO

create procedure dbo.GetRevisionCause
		(
		@PostingGUID char(38),
		@RevisionDate datetime
		)
	with encryption
as
/**
	@exception - Couldn't find the requested posting in the database
	@exception - RevisionDate is before the date when the posting was created
	@exception - Posting has never been published, so no revisions can exist
	@exception - RevisionDate is older than the last revision purge
 */
	declare @CheckedInVersionHasExisted tinyint
	declare @CreatedDate datetime, @LastPurgeDate datetime
	declare @FollowGUID char(38)
	declare @PageFirstApproveDate datetime
	declare @SQL varchar(255)

	set nocount on
	
	set @RevisionDate = dateadd(ss, 1, @RevisionDate)

	/*check if RevisionDate is older than the last revision purge*/
	select @LastPurgeDate = LastRevisionPurge from Utility

	if @LastPurgeDate is not null and @LastPurgeDate >= @RevisionDate 
	begin
		select @LastPurgeDate
		return 1	/*The specified date is older than the last revision purge date*/
	end

	/*do some checking on the posting*/
	select @CheckedInVersionHasExisted = posting.CheckedInVersionHasExisted, @CreatedDate = posting.CreatedWhen, 
	@FollowGUID = posting.FollowGUID
	from Node posting 
	where posting.NodeGUID = @PostingGUID
	
	if @@rowcount = 0
	begin
		select @@rowcount
		return 2 	/*this posting doesn't exist in our database */
	end
	
	if @CheckedInVersionHasExisted = 0 
	begin
		select @CheckedInVersionHasExisted
		return 3	/*Posting has never been published */
	end

	select @PageFirstApproveDate = min(ApprovedWhen) from Node
	where (NodeGUID = @FollowGUID and IsCheckedOutVersion = 0 and ArchiveSourceGUID is null)	--cuurent version 
	 or (ArchiveSourceGUID = @FollowGUID )

	if @CreatedDate > @RevisionDate or @PageFirstApproveDate > @RevisionDate
	begin
		select @CreatedDate
		return 4	/*RevisionDate is before the date when the posting was created */
	end
	

	select top 1 rev.NodeGUID, rev.ApprovedWhen as RevisionTime
	from (
		/*get the posting itself in case if nothing that it depends on has been archived yet*/
		select NodeGUID, CreatedWhen as ApprovedWhen, 10 as RevisionSortOrder from Node where NodeGUID = @PostingGUID	
		UNION ALL

		/*get revisions of the posting's page*/
		select @PostingGUID, PageRev.ApprovedWhen, 1 as RevisionSortOrder 
		from Node PageRev 
		where ( (PageRev.NodeGUID = @FollowGUID and PageRev.ArchiveSourceGUID is null )
			or (PageRev.ArchiveSourceGUID is not null and PageRev.ArchiveSourceGUID = @FollowGUID)) and 
		PageRev.ApprovedWhen <= @RevisionDate
		and PageRev.ApprovedWhen > @LastPurgeDate

		/*get revisions of the page resources*/
		UNION ALL
		select case ResourceRev.ArchiveSourceGUID when null then ResourceRev.NodeGUID
				else ResourceRev.ArchiveSourceGUID end as NodeGUID,
				ResourceRev.ApprovedWhen, 3 as RevisionSortOrder 
		from Node Page, NodeResource, Node ResourceRev
		where (Page.NodeGUID = @FollowGUID or Page.ArchiveSourceGUID = @FollowGUID) 
		and Page.Id = NodeResource.NodeId and 
		NodeResource.NodeGUID = ResourceRev.ArchiveSourceGUID 
			and (ResourceRev.ApprovedWhen < Page.ArchivedWhen or Page.ArchivedWhen is null)
			and ResourceRev.ApprovedWhen >= Page.ApprovedWhen
		and ResourceRev.ApprovedWhen <= @RevisionDate
		and ResourceRev.ApprovedWhen > @LastPurgeDate

		UNION ALL
		select case ResourceRev.ArchiveSourceGUID when null then ResourceRev.NodeGUID
				else ResourceRev.ArchiveSourceGUID end as NodeGUID,
				ResourceRev.ApprovedWhen, 3 as RevisionSortOrder 
		from Node Page, NodeResource, Node ResourceRev
		where (Page.NodeGUID = @FollowGUID or Page.ArchiveSourceGUID = @FollowGUID) 
		and Page.Id = NodeResource.NodeId and 
		NodeResource.NodeGUID = ResourceRev.NodeGUID 
			and (ResourceRev.ApprovedWhen < Page.ArchivedWhen or Page.ArchivedWhen is null)
			and ResourceRev.ApprovedWhen >= Page.ApprovedWhen
		and ResourceRev.ApprovedWhen <= @RevisionDate
		and ResourceRev.ApprovedWhen > @LastPurgeDate
		) rev
	order by rev.ApprovedWhen desc, rev.RevisionSortOrder ASC
	return 0
		
go

GRANT EXEC ON dbo.GetRevisionCause TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetRevisionHistory')
	BEGIN
		PRINT 'Dropping Procedure GetRevisionHistory'
		DROP  Procedure  dbo.GetRevisionHistory
	END

GO

PRINT 'Creating Procedure GetRevisionHistory'
GO

create  procedure dbo.GetRevisionHistory
		(
		@PostingGUID char(38),
		@IncludeDependency int
		)
with encryption
as
	/* These are the values for @IncludeDependency:
	PAGE			= 1,
	PAGE_RESOURCES	= 2
	*/

/**
	@exception - Posting doesn't exist in the database
 */
	set nocount on
	declare @LastPurgeDate datetime
			,@CheckedInVersionHasExisted tinyint

	/*do some checking on the posting*/
	select @CheckedInVersionHasExisted = posting.CheckedInVersionHasExisted
	from dbo.Node posting 
	where posting.NodeGUID = @PostingGUID
	
	if @@rowcount = 0
	begin
		select @@rowcount
		return 2 	/*this posting doesn't exist in our database */
	end

	if @CheckedInVersionHasExisted = 0 
	begin
		select @CheckedInVersionHasExisted 
		return 3	/*Posting has never been published */
	end


	create table #Revisions
		(
		NodeGUID char(38) collate database_default not null,	
		ArchiveSourceGUID char(38) collate database_default null,	
		CreatedWhen datetime null,
		ArchivedWhen datetime null,
		ApprovedWhen datetime null,		
		Type tinyint not null
		)

	create index Revisions_NodeGUID on #Revisions
		(
		NodeGUID
		)

	declare @PostingCreateDate datetime
	declare @PostingFollowGUID char(38)
	declare @PageFirstApproveDate datetime

	select @LastPurgeDate = LastRevisionPurge from Utility

	select	@PostingFollowGUID = FollowGUID, 
			@PostingCreateDate = CreatedWhen from Node 
	where NodeGUID = @PostingGUID

	select @PageFirstApproveDate = min(ApprovedWhen) from Node
	where (NodeGUID = @PostingFollowGUID and IsCheckedOutVersion = 0 and ArchiveSourceGUID is null)	--cuurent version 
	 or (ArchiveSourceGUID = @PostingFollowGUID )

	/*first get all revisions of the posting's page*/
	if (@IncludeDependency & 1 ) = 1 or (@IncludeDependency & 2 ) = 2
	begin
		/*get the checked in version of the page */
		insert into #Revisions (NodeGUID, ArchiveSourceGUID, CreatedWhen, ApprovedWhen, Type)
		select Pages.NodeGUID, @PostingGUID, Pages.CreatedWhen, Pages.ApprovedWhen, 1 
		from Node Pages 
		where Pages.NodeGUID = @PostingFollowGUID and
		Pages.IsCheckedOutVersion = 0  
		
		/*get page revisions*/
		insert into #Revisions (NodeGUID, ArchiveSourceGUID, ArchivedWhen, ApprovedWhen, Type)
		select Pages.NodeGUID, @PostingGUID, Pages.ArchivedWhen, Pages.ApprovedWhen, 1 
		from Node Pages 
		where Pages.ArchiveSourceGUID = @PostingFollowGUID 
	end

	/*now let's find resource revisions of the page*/
	if (@IncludeDependency & 2 ) = 2
	begin
		/*get current version of the resource*/
		insert into #Revisions (NodeGUID, ArchiveSourceGUID, CreatedWhen, ApprovedWhen, Type)
		select distinct Resources.NodeGUID, Resources.NodeGUID, Resources.CreatedWhen, Resources.ModifiedWhen, 2
		from Node Resources, Node Pages, NodeResource, #Revisions
		where #Revisions.NodeGUID = Pages.NodeGUID and #Revisions.Type = 1 and 
		Pages.IsCheckedOutVersion = 0 and Pages.Id = NodeResource.NodeId and 
		NodeResource.NodeGUID = Resources.NodeGUID
		and (Resources.ModifiedWhen < #Revisions.ArchivedWhen or #Revisions.ArchivedWhen is null)
		and Resources.ModifiedWhen >= #Revisions.ApprovedWhen

		/*get resource revisions*/
		insert into #Revisions (NodeGUID, ArchiveSourceGUID, ArchivedWhen, ApprovedWhen, Type)
		select distinct Resources.NodeGUID, Resources.ArchiveSourceGUID, Resources.ArchivedWhen, Resources.ModifiedWhen, 2
		from Node Resources, Node Pages, NodeResource, #Revisions
		where #Revisions.NodeGUID = Pages.NodeGUID and #Revisions.Type = 1 and 
		Pages.Id = NodeResource.NodeId and 
		NodeResource.NodeGUID = Resources.ArchiveSourceGUID
		and (Resources.ModifiedWhen < #Revisions.ArchivedWhen or #Revisions.ArchivedWhen is null)
		and Resources.ModifiedWhen >= #Revisions.ApprovedWhen

	end


	select distinct ArchiveSourceGUID as NodeGUID, ApprovedWhen as RevisionTime
	from #Revisions
	where (@IncludeDependency & Type) = Type 
	and ApprovedWhen >= @PostingCreateDate and ApprovedWhen >= @PageFirstApproveDate
	and ApprovedWhen > @LastPurgeDate
	order by RevisionTime Asc

	return 0
			

GO


GRANT EXEC ON dbo.GetRevisionHistory TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetTimeZoneSetting')
	BEGIN
		PRINT 'Dropping Procedure GetTimeZoneSetting'
		DROP  Procedure  dbo.GetTimeZoneSetting
	END

GO

PRINT 'Creating Procedure GetTimeZoneSetting'
GO
create  procedure dbo.GetTimeZoneSetting
with encryption
as
if substring(@@VERSION, PATINDEX('%_.__.___%', @@VERSION), 1) <> '8'
begin
	DECLARE @DeltaGMT int
	
	EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
	'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
	'ActiveTimeBias', @DeltaGMT OUT
	
	if exists (select * from Utility )
		update Utility set DeltaGMT = @DeltaGMT
	else
		insert into Utility (DeltaGMT) values (@DeltaGMT)
end

GO

GRANT EXEC ON dbo.GetTimeZoneSetting TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetUserID')
	BEGIN
		PRINT 'Dropping Procedure GetUserID'
		DROP  Procedure  dbo.GetUserID
	END

GO

PRINT 'Creating Procedure GetUserID'
GO

create PROCEDURE dbo.GetUserID
	(
	@Username		nvarchar(450), 
	@SID			varchar(255),
	@Alias			nvarchar(450),	
	@AddIfNotFound	tinyint,
	@UserId 		int OUTPUT
	)
	with encryption
as
	set nocount on
	set @UserId = 0
	
	declare @UpdateSID tinyint
	declare @ExistingSID varchar(255)
	set @UpdateSID = 0

	/*first search by Username*/
	SELECT @UserId = UserId, @ExistingSID = UserSID FROM AEUser WHERE UsernameUpper = UPPER(@Username)

	/*see if we can use SID to find the user*/
	if isnull(@UserId, 0) = 0  and  isnull(@SID, '') <> ''
		SELECT @UserId = UserId, @ExistingSID = UserSID FROM AEUser WHERE UserSID is not null and UserSID = @SID 

	/*see if we can use Alias*/
	if isnull(@UserId, 0) = 0 and isnull(@Alias, '') <> ''
		SELECT @UserId = UserId, @ExistingSID = UserSID FROM AEUser WHERE UsernameUpper = UPPER(@Alias)

	if isnull(@UserId, 0) = 0
	begin
		if @AddIfNotFound = 1
		begin
			INSERT INTO AEUser (Username, UsernameUpper, UserSID) VALUES (@Username, upper(@Username), nullif(@SID, ''))
			set @UserId = @@IDENTITY
		end
		else
			set @UserId = isnull(@UserId, 0)
	end
	else	--update SID if it's available
		if isnull(@ExistingSID, '') = '' and isnull(@SID, '') <> ''
			update AEUser set UserSID = @SID where UserId = @UserId	




GO

GRANT EXEC ON dbo.GetUserID TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'LockNode')
	BEGIN
		PRINT 'Dropping Procedure LockNode'
		DROP  Procedure  dbo.LockNode
	END

GO

PRINT 'Creating Procedure LockNode'
GO

create procedure dbo.LockNode
	(
	@NodeId int,
	@LockUserId int,
	@LockMachinename nvarchar(50),
	@ClientAccountId int
	) 
	with encryption
as

	set nocount on

	UPDATE Node SET IsLocked = 1, LockMachinename = @LockMachinename,
			LockUserId = @LockUserId, LockClientId = @ClientAccountId
	WHERE Id = @NodeId

	INSERT INTO NodeLock 
		(NodeId, NewIsHighPriority, NewSameRightsAsParent, 
		NewReadyForApproval, NewSortOrdinal, NewApprovalStatus, 
		NewApprovedByUserId, NewOwnerId, NewEffectiveDate, NewExpiryDate, 
		NewTemplateGUID, NewName, 
		NewDirectoryService, NewDirectoryGUID,
		NewIsHiddenModePublished, NewIsRobotFollowable, NewIsRobotIndexable, NewDisplayName,
		NewApprovedByClientId, NewOwnerClientId, NewPageDefinitionGUID, NewTemplateAspPath, NewSchemaXML, NewOuterScriptFile, NewUseOuterScriptForPostings,NewDefaultPostingName)
	select @NodeId, IsHighPriority, SameRightsAsParent, 
		ReadyForApproval, SortOrdinal, ApprovalStatus, 
		ApprovedByUserId, OwnerId, EffectiveDate, ExpiryDate, 
		TemplateGUID,  	Name, 
		DirectoryService, DirectoryGUID, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable,
		DisplayName, 
		ApprovedByClientId, OwnerClientId, PageDefinitionGUID, TemplateAspPath, SchemaXML,OuterScriptFile, UseOuterScriptForPostings,DefaultPostingName
	from Node
	where Id = @NodeId

go



GRANT EXEC ON dbo.LockNode TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'PropagateRights')
	BEGIN
		PRINT 'Dropping Procedure PropagateAddRights'
		DROP  Procedure  dbo.PropagateRights
	END

GO

PRINT 'Creating Procedure PropagateRights'
GO

/**
 *	This stored procedure assigns or removes the specified rights group from all sub-containers
 *	of the starting Node. 
 *
 *	@param	@Action						specifies whether to add or remove the rights group
 *										enum values: 1 - Add rights group
 *													 2 - Remove rights group
 *	@param	@startingNodeGuid			a container to start with
 *	@param  @rightsGroupGuid			rights group to be assigned to containers
 *	@param  @UserId						user performing the operation
 *	@param  @userMachineName			client machine performing the operation
 *
 *	@return								a list of nodes affected
*/
create Procedure dbo.PropagateRights
	(
	@Action tinyint
	,@startingNodeGuid varchar(38)
	,@rightsGroupGuid varchar(38)
	,@UserId int
	,@userMachineName nvarchar(50)
	)
with encryption
as
begin
	set nocount on
	
	declare @nodeType int
			,@Level int
			,@ParentGUID varchar(38)
			,@NodeGUID varchar(38)
			,@errorMsg nvarchar(1000)
			,@dateGMT datetime
			,@dateCurrent datetime

	declare @descendants table 
				(
				NodeGUID varchar(38) collate database_default not null primary key
				,NodeLevel int not null
				,NodeState int default 0
				)
	
	/*first validate input parameters*/
	select @nodeType = Type from Node where NodeGUID = @startingNodeGuid
	if @@rowcount > 0 
	begin
		/*make sure this is a container Node*/
		if @nodeType not in (4,64,1024,16384,262144,2097152,524288,16777216)
		begin
			set @errorMsg = 'The specified parent Node is not a container.'
			raiserror (@errorMsg, 15, 1)
			return
		end
	end
	else
	begin
		select @errorMsg = 'The specified parent Node does not exist in the database.'
		raiserror (@errorMsg, 15, 1)
		return
	end		
	
	if not exists (select 1 from Node where NodeGUID = @rightsGroupGuid)
	begin
		set @errorMsg = 'The specified rights group does not exist in the database.'
		raiserror (@errorMsg, 15, 1)
		return
	end
	
	/*now populate the descendants table with sub-containers of the starting Node*/
	set @Level = 1
	
	insert into @descendants (
							NodeLevel
							,NodeGUID
							) 
	select distinct @Level
					,NodeGUID
	from Node with (UPDLOCK)
	where ParentGUID = @startingNodeGuid
	and Type in (4,64,1024,16384,262144,2097152,524288,16777216)

	while (@@rowcount > 0 )	
	begin
		set @Level = @Level + 1	
		
		insert into @descendants (
							NodeLevel
							,NodeGUID
							) 
		select distinct @Level
						,n.NodeGUID
		from Node n with (UPDLOCK) inner join @descendants d
		on n.ParentGUID = d.NodeGUID and d.NodeLevel = @Level - 1
		where Type in (4,64,1024,16384,262144,2097152,524288,16777216)
	end	

	update @descendants
	set NodeState = case when n.IsLocked = 0 then 0 
					when n.IsLocked = 1 
						and n.LockUserId = @UserId 
						and upper(n.LockMachinename) = upper(@userMachineName) then 0
					else 2 /*USER_LOCK_FAILED*/
			end
	from Node n inner join @descendants d
	on n.NodeGUID = d.NodeGUID

	/*check whether there are any nodes that are locked by other users*/
	if exists (select * from @descendants where NodeState > 0)
		select 	d.NodeGUID
				,d.NodeState
				,n.Type
				,n.LockUserId
				,n.LockMachinename
				,n.Name 
				,n.LastChangeTime
		from @descendants d inner join Node n
		on d.NodeGUID = n.NodeGUID
		where NodeState > 0
	else
	begin
		if @Action = 1	/*assign the rights group*/
		begin
			/*assign the specified rights group to the selected nodes*/
			insert into NodeRole (NodeId, RoleGUID, IsBeingUpdated, IsBeingInserted, IsBeingDeleted)
			select n.Id, @rightsGroupGuid, 0, 0, 0
			from @descendants d inner join Node n
			on d.NodeGUID = n.NodeGUID
			where not exists
				(select 1 
				from NodeRole nr
				where nr.NodeId = n.Id 
				and nr.RoleGUID = @rightsGroupGuid
				)
		end
		else if @Action = 2	/*remove the rights group*/
		begin
			delete from NodeRole
			from @descendants d inner join Node n
			on d.NodeGUID = n.NodeGUID
			inner join NodeRole nr
			on nr.NodeId = n.Id and nr.RoleGUID = @rightsGroupGuid
		end
		
		/*update ModifiedWhen for affected nodes*/					
		select @dateCurrent = GETDATE()
		exec GetGMTTime @dateCurrent, @dateGMT out

		update dbo.Node
			set ModifiedWhen = @dateGMT
		where Node.NodeGUID in 
		(select NodeGUID from @descendants)
					
		/*now return the list of affected nodes*/
		select 	distinct d.NodeGUID
						,d.NodeState
						,n.Type
						,n.LockUserId
						,n.LockMachinename
						,n.Name 
						,n.LastChangeTime
		from @descendants d inner join Node n
		on d.NodeGUID = n.NodeGUID
	end

end
GO


GRANT EXEC ON dbo.PropagateRights TO PUBLIC
GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'PurgeRevisionsByDate')
	BEGIN
		PRINT 'Dropping Procedure PurgeRevisionsByDate'
		DROP  Procedure  dbo.PurgeRevisionsByDate
	END

GO

PRINT 'Creating Procedure PurgeRevisionsByDate'
GO

create procedure dbo.PurgeRevisionsByDate
		(
		@RevisionDate datetime
		)
	with encryption
as
/**
	@exception - @RevisionDate is older than the most resent Revision Purge
 */
	declare @LastPurgeDate datetime
	declare @SQL varchar(255)

	set nocount on

	/*check if RevisionDate is older than the last revision purge*/
	select @LastPurgeDate = LastRevisionPurge from Utility

	if @LastPurgeDate is not null and @LastPurgeDate >= @RevisionDate 
		return 1	/*RevisionDate is older than the last revision purge*/


	DECLARE @CurrentId as int
	
	DECLARE DeletedItems CURSOR LOCAL READ_ONLY 
	    FOR SELECT Id FROM Node WHERE ArchivedWhen <= @RevisionDate 
		and (Type <> 256 or (Type = 256 and NodeGUID not in (select NodeGUID from NodeResource where NodeGUID is not null) )) 
	
	OPEN DeletedItems
	FETCH NEXT FROM DeletedItems INTO @CurrentId
	
	WHILE @@FETCH_STATUS = 0
	  BEGIN
			exec DeleteNodeById @CurrentId, 0
			FETCH NEXT FROM DeletedItems INTO @CurrentId
	  END  

	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out
	
	if @RevisionDate > @dateGMT
		set @RevisionDate = @dateGMT

	if exists (select * from Utility )
		update Utility set LastRevisionPurge = @RevisionDate
	else
		insert into Utility (LastRevisionPurge) values(@RevisionDate)

	close DeletedItems
	deallocate DeletedItems

	return 0			
go


GRANT EXEC ON dbo.PurgeRevisionsByDate TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveGMTTime')
	BEGIN
		PRINT 'Dropping Procedure RetrieveGMTTime'
		DROP  Procedure  dbo.RetrieveGMTTime
	END

GO

PRINT 'Creating Procedure RetrieveGMTTime'
GO

if substring(@@VERSION, PATINDEX('%_.__.___%', @@VERSION), 1) = '8'
	exec sp_executesql N'CREATE PROCEDURE dbo.RetrieveGMTTime with encryption as set nocount on select getutcdate() as GMTTime'
else
	exec sp_executesql N'
	CREATE PROCEDURE RetrieveGMTTime
	AS
	set nocount on
	Declare @curdate datetime,
		@newdate datetime,
		@offset int
	select @curdate = GetDate()
	Select @offset = DeltaGMT from Utility
	select @newdate = DateAdd(minute,@offset,@curdate)
	select @newdate as GMTTime'
go

GRANT EXEC ON dbo.RetrieveGMTTime TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RollbackLock')
	BEGIN
		PRINT 'Dropping Procedure RollbackLock'
		DROP  Procedure  dbo.RollbackLock
	END

GO

PRINT 'Creating Procedure RollbackLock'
GO

create procedure dbo.RollbackLock
        ( 
        @NodeId int, 
        @NodeType int, 
        @EmptyTables int 
        ) 
	with encryption
as 

	/*empty collection enum*/
	declare @NO_ROLE_ACL 		tinyint, 	--NodeRole
			@NO_GENERIC_PROPS 	tinyint,	--NodeProperty
			@NO_CONTROL_ITEMS	tinyint,	--GalleryControl
			@NO_LAYOUTS			tinyint,	--NodeLayout
			@NO_RESOURCES		tinyint,	--NodeResource
			@NO_CONTROLS		tinyint,	--NodePlaceholder
			@NO_TEMPLATE_PROPS	tinyint		--LayoutTemplatePropery

	set @NO_ROLE_ACL = 1
	set @NO_GENERIC_PROPS = 2
	set @NO_CONTROL_ITEMS = 4
	set @NO_LAYOUTS = 8
	set @NO_RESOURCES = 16
	set @NO_CONTROLS = 32
	set @NO_TEMPLATE_PROPS = 64


    set nocount on 

    /* 
     * delete the entries that are being inserted. 
     */ 

    /* User role */ 
    if @nodeType = 0x100000 
    begin 
        DELETE FROM UserRoleMember WHERE NodeId = @NodeId and IsBeingInserted = 1 
    end 
        

    /* If we are not a shortcut... */ 
    if @nodetype <> 0x80000020 
    begin 
        if ( @EmptyTables & @NO_RESOURCES ) = 0 
                DELETE FROM NodeResource WHERE NodeId = @NodeId and IsBeingInserted = 1 
        if ( @EmptyTables & @NO_CONTROLS ) = 0 
		begin
            DELETE FROM NodePlaceholderContent WHERE NodeId = @NodeId and IsBeingInserted = 1 
            DELETE FROM NodePlaceholder WHERE NodeId = @NodeId and IsBeingInserted = 1 
		end
        if ( @EmptyTables & @NO_LAYOUTS ) = 0 
		begin
            DELETE FROM LayoutProperty WHERE NodeId = @NodeId and IsBeingInserted = 1 
            DELETE FROM NodeLayout WHERE NodeId = @NodeId and IsBeingInserted = 1 
		end
    end 
        
    /* Every Type of Node is concerned with these settings: */ 
    if ( @EmptyTables & @NO_ROLE_ACL ) = 0 
        DELETE FROM NodeRole WHERE NodeId = @NodeId and IsBeingInserted = 1 
    if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0 
        DELETE FROM NodeProperty WHERE NodeId = @NodeId and IsBeingInserted = 1 



    /* 
     * rollback the data being updated, and undelete objects being deleted. 
     */ 
    
    /* User role */ 
    if @nodeType = 0x100000 
    begin 
        update UserRoleMember set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0 
                WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 ) 
    end 


    /* If we are not a shortcut... */ 
    if @nodetype <> 0x80000020 
    begin 
        if ( @EmptyTables & @NO_LAYOUTS ) = 0 
		begin
            update NodeLayout set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                    NewName = NULL, NewLayoutTemplateGUID = NULL 
                    WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 ) 

            update LayoutProperty set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                            NewPropName = NULL, NewIsControl = NULL, 
                            NewPropValue = NULL, NewControlId = NULL 
                            WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 ) 
		end

        if ( @EmptyTables & @NO_CONTROLS ) = 0 
		begin
            update NodePlaceholder set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                    NewName = NULL  WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 ) 

            update NodePlaceholderContent set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                    NewPropName = NULL, NewIsResource = NULL, NewPropValue = NULL, 
                    NewResourceId = NULL  WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 )
		end
        if ( @EmptyTables & @NO_RESOURCES ) = 0 
            update NodeResource set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                    NewName = NULL, NewIsLink = NULL, NewURL = NULL, 
                    NewResourceBlobId = NULL, NewNodeGUID = NULL, NewLinkAnchor = NULL 
                    WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 0 ) 
    end 


    /* Every Type of Node is concerned with the following: */ 
    if ( @EmptyTables & @NO_GENERIC_PROPS ) = 0 
        update NodeProperty set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0, 
                NewPropValue = null, NewPropValueLong = null WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 )

    if ( @EmptyTables & @NO_ROLE_ACL ) = 0 
            update NodeRole set IsBeingDeleted = 0, IsBeingUpdated = 0, IsBeingInserted = 0 
            WHERE NodeId = @NodeId and ( IsBeingUpdated = 1 or IsBeingDeleted = 1 ) 



    DELETE FROM NodeLock WHERE NodeId = @NodeId 

    UPDATE Node SET IsLocked = 0, LockMachinename = NULL, LockUserId = NULL, LockClientId = NULL 
    WHERE Id = @NodeId 

GO 


GRANT EXEC ON dbo.RollbackLock TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SearchPostingCustomProperties')
	BEGIN
		PRINT 'Dropping Procedure SearchPostingCustomProperties'
		DROP  Procedure  dbo.SearchPostingCustomProperties
	END

GO

PRINT 'Creating Procedure SearchPostingCustomProperties'
GO

create procedure dbo.SearchPostingCustomProperties
	(
	@SearchMode int,
	@PropName nvarchar(50),
	@PropValue nvarchar(300),
	@IsCheckedOutVersion tinyint
	)
	with encryption
as
	set nocount on
/*
enum values for @SearchMode
	0 - Search property Name only
	1 - Search property Name and value	
*/
		if @SearchMode = 0 	/* search property Name only */
		begin
			-- TODO: -- replace with content schema sql when custom props are removed from templates
			/*select Postings.NodeGUID, Postings.ModifiedWhen, Postings.Name, Postings.OwnerId, Postings.ParentGUID, Postings.Type, 
					Postings.IsShortcut, Postings.SameRightsAsParent, Postings.IsCheckedOutVersion
			from Node Postings, NodeProperty, Node Templates, Node Schemas
			WHERE Postings.TemplateGUID = Templates.NodeGUID
			AND Templates.PageDefinitionGUID = Schemas.NodeGUID
			AND Schemas.Id = NodeProperty.NodeId
		   	AND Postings.IsBeingInserted = 0
	       	AND PropName = @PropName*/			
			select Postings.NodeGUID
				   ,Postings.ModifiedWhen
				   ,Postings.Name
				   ,Postings.OwnerId
				   ,Postings.ParentGUID
				   ,Postings.Type
				   ,Postings.IsShortcut
				   ,Postings.SameRightsAsParent
				   ,Postings.IsCheckedOutVersion
				from Node Postings
				where 
				Postings.Type = 16 
				and Postings.IsShortcut = 1 
				and Postings.IsBeingInserted = 0 
				and	exists
				(select 1 
				from Node template inner join NodeProperty np
				on template.IsCheckedOutVersion = 0 
				and template.Id = np.NodeId 
				and np.PropName = @PropName
				where template.NodeGUID = Postings.TemplateGUID
				)	       	
	       		
		end

		else	/*search property Name and value*/
		begin
			select Postings.NodeGUID, Postings.ModifiedWhen, Postings.Name, Postings.OwnerId, Postings.ParentGUID, Postings.Type, 
					Postings.IsShortcut, Postings.SameRightsAsParent, Postings.IsCheckedOutVersion
			from Node Postings, NodeProperty, Node Pages
			WHERE Postings.FollowGUID = Pages.NodeGUID 
			AND Postings.IsBeingInserted = 0 
			AND Pages.IsCheckedOutVersion = @IsCheckedOutVersion
			AND Pages.Id = NodeProperty.NodeId 
			AND NodeProperty.PropName = @PropName
		    AND ( ((@PropValue is null or len(@PropValue) = 0) and (NodeProperty.PropValue = '' or NodeProperty.PropValue Is NULL)) or
					(len(@PropValue) > 0 and NodeProperty.PropValue like @PropValue) )
			/*AND Postings.NodeGUID in
			(
			select Postings.NodeGUID
			from Node Postings, NodeProperty, Node Templates
			WHERE Postings.TemplateGUID = Templates.NodeGUID 
			AND Templates.Id = NodeProperty.NodeId
			AND Postings.IsBeingInserted = 0 
			AND PropName = @PropName
			)*/
				
			UNION
			/*now get postings that do not have overrides on the page*/

			-- TODO: -- replace with content schema sql when custom props are removed from templates
			/*select Postings.NodeGUID, Postings.ModifiedWhen, Postings.Name, Postings.OwnerId, Postings.ParentGUID, Postings.Type, 
					Postings.IsShortcut, Postings.SameRightsAsParent, Postings.IsCheckedOutVersion
			from Node Postings, NodeProperty, Node Templates, Node Schemas
			WHERE Postings.TemplateGUID = Templates.NodeGUID 
			AND Templates.PageDefinitionGUID = Schemas.NodeGUID
			AND Schemas.Id = NodeProperty.NodeId
			AND Postings.IsBeingInserted = 0 
			AND PropName = @PropName
		    AND ( ((@PropValue is null or len(@PropValue) = 0) and (PropValue = '' or PropValue Is NULL)) or
					(len(@PropValue) > 0 and PropValue like @PropValue) )
			AND Postings.NodeGUID not in
			(select Postings.NodeGUID
				from Node Postings, NodeProperty, Node Pages
				WHERE Postings.FollowGUID = Pages.NodeGUID 
				AND Pages.IsCheckedOutVersion = @IsCheckedOutVersion
				AND Pages.Id = NodeId 
				AND Postings.IsBeingInserted = 0 
				AND PropName = @PropName
			)*/
			/*now get postings that do not have overrides on the page*/
			select Postings.NodeGUID, Postings.ModifiedWhen, Postings.Name, Postings.OwnerId, Postings.ParentGUID, Postings.Type, 
					Postings.IsShortcut, Postings.SameRightsAsParent, Postings.IsCheckedOutVersion
			from Node Postings, NodeProperty, Node Templates
			WHERE Postings.TemplateGUID = Templates.NodeGUID 
			AND Templates.IsCheckedOutVersion = 0
			AND Templates.Id = NodeProperty.NodeId
			AND Postings.IsBeingInserted = 0 
			AND PropName = @PropName
		    AND ( ((@PropValue is null or len(@PropValue) = 0) and (PropValue = '' or PropValue Is NULL)) or
					(len(@PropValue) > 0 and PropValue like @PropValue) )
			AND Postings.NodeGUID not in
			(select Postings.NodeGUID
				from Node Postings, NodeProperty, Node Pages
				WHERE Postings.FollowGUID = Pages.NodeGUID 
				AND Pages.IsCheckedOutVersion = @IsCheckedOutVersion
				AND Pages.Id = NodeId 
				AND Postings.IsBeingInserted = 0 
				AND PropName = @PropName
			)


	end
go


GRANT EXEC ON dbo.SearchPostingCustomProperties TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SetExclusiveLock')
	BEGIN
		PRINT 'Dropping Procedure SetExclusiveLock'
		DROP  Procedure  dbo.SetExclusiveLock
	END

GO

PRINT 'Creating Procedure SetExclusiveLock'
GO

create procedure dbo.SetExclusiveLock 
	(
		@locktype tinyint
		,@locktimeout int = -1
	)
with encryption
as
/**
 *	This stored procedure puts an exclusive lock on ServerReadLock and/or ServerWriteLock
 *	tables depending on the @locktype value. This is done to prevent read or update operations
 *	from staring. If a read or update is already in progress setting exclusive lock fails
 *	and the procedure will throw  sql error 1222 "Lock request time-out period exceeded". 
 *
 *	@param	@locktype		specifies the Type of the lock to set
 *							0 - exclusive write
 *							1 - exclusive read/write
 *
 *	@see SetExclusiveLock
*/
begin
	set nocount on
	
	declare @sql nvarchar(4000)
			,@locktimeout_orig int
			,@retval int

	set @locktimeout_orig = @@LOCK_TIMEOUT
	
	set @sql = 	N'declare @IsLocked tinyint '
			
	+ N' SET LOCK_TIMEOUT ' + cast(@locktimeout as nvarchar(10))
	
	--always place an exclusive lock on ServerWriteLock table
	+ N'  update ServerWriteLock set IsLocked = IsLocked where IsLocked = 0'
	+ N' set @retval = @@error'
	
	+ N' if @retval = 0 and @locktype = 1'	--exclusive read/write
	+ N' begin'
		--place a shared lock on ServerWriteLock table
	+ N' 	update ServerReadLock set IsLocked = IsLocked where IsLocked = 0'
	+ N' end'
	
	+ N' SET LOCK_TIMEOUT ' + cast(@locktimeout_orig as nvarchar(10))

	exec sp_executesql @sql, N'@retval int output, @locktype tinyint', @retval output, @locktype
	
	return @retval
end	
GO

GRANT EXEC ON dbo.SetExclusiveLock TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SetIntentLock')
	BEGIN
		PRINT 'Dropping Procedure SetIntentLock'
		DROP  Procedure  dbo.SetIntentLock
	END

GO

PRINT 'Creating Procedure SetIntentLock'
GO

create procedure dbo.SetIntentLock 
	(
		@locktype tinyint
	)
with encryption
as
/**
 *	This stored procedure puts a shared lock on ServerReadLock and/or ServerWriteLock
 *	tables depending on the @locktype value. This is done to prevent bacth transactions
 *	like import or background processing from staring. If a bacth transaction is already
 *	in progress these tables are locked exclusively, and the procedure will fail with 
 *	sql error 1222 "Lock request time-out period exceeded". 
 *
 *	@param	@locktype		specifies the Type of the lock to set
 *							0 - intent to read
 *							1 - intent to write
 *
 *	@see SetExclusiveLock
*/
begin
	set nocount on

	declare @sql nvarchar(4000)
			,@locktimeout_orig int
			,@retval int

	set @locktimeout_orig = @@LOCK_TIMEOUT
	
	set @sql = 	N'declare @IsLocked tinyint '
			
	+ N' SET LOCK_TIMEOUT 0'
	
	--always place a shared lock on ServerReadLock table
	+ N' select @IsLocked=IsLocked from ServerReadLock with(HOLDLOCK) where IsLocked=0'
	+ N' set @retval = @@error'
	
	+ N' if @retval = 0 and @locktype = 1'	--intent to write
	+ N' begin'
		--place a shared lock on ServerWriteLock table
		+ N' select @IsLocked=IsLocked from ServerWriteLock with(HOLDLOCK) where IsLocked=0'
	+ N' end'
	
	+ N' SET LOCK_TIMEOUT ' + cast(@locktimeout_orig as nvarchar(10))

	exec sp_executesql @sql, N'@retval int output, @locktype tinyint', @retval output, @locktype
	
	return @retval
end	
GO

GRANT EXEC ON dbo.SetIntentLock TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'UpdateChangeTable')
	BEGIN
		PRINT 'Dropping Procedure UpdateChangeTable'
		DROP  Procedure  dbo.UpdateChangeTable
	END

GO

PRINT 'Creating Procedure UpdateChangeTable'
GO

create  procedure dbo.UpdateChangeTable
with encryption
as
begin
	declare @sql nvarchar(4000)

	set @sql = N'DECLARE @dateGMT datetime, @dateCurrent datetime, @MaxCommit datetime, @CommitTime datetime
	select @dateCurrent = GETDATE()

	exec GetGMTTime @dateCurrent, @dateGMT out

	if exists(select NodeGUID from .dbo.#Sandbox)
	begin
		select  @MaxCommit = MAX( CommitTime ) from [' + db_name() + '].dbo.ChangeTable WITH(UPDLOCK) 
		select  @CommitTime = case when @dateGMT <= @MaxCommit then DateAdd( ms, 3, @MaxCommit ) else @dateGMT END

		UPDATE  [' + db_name() + '].dbo.ChangeTable 
				SET Reason = nodes.Reason, 
				LastChangeTime = nodes.LastChangeTime,
				CommitTime = @CommitTime,
				ParentGUID = nodes.ParentGUID,
				Type = nodes.Type,
				IsShortcut = nodes.IsShortcut,
				Name = nodes.Name,
				FollowGUID = nodes.FollowGUID,
				TemplateGUID = nodes.TemplateGUID,
				PageDefinitionGUID = nodes.PageDefinitionGUID
			from .dbo.#Sandbox nodes
			where ChangeTable.NodeGUID = nodes.NodeGUID

		INSERT INTO  [' + db_name() + '].dbo.ChangeTable (NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime,
									Type, IsShortcut, Name,
									FollowGUID, TemplateGUID, PageDefinitionGUID) 
			select NodeGUID, ParentGUID, Reason, LastChangeTime, @CommitTime, 
					Type, IsShortcut, Name, FollowGUID, TemplateGUID, PageDefinitionGUID
			from .dbo.#Sandbox  
				where NodeGUID not in (select NodeGUID from  [' + db_name() + '].dbo.ChangeTable)
	end'

	exec sp_executesql @sql
end
GO

GRANT EXEC ON dbo.UpdateChangeTable TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_ConsistencyCheck')
	BEGIN
		PRINT 'Dropping Procedure bgp_ConsistencyCheck'
		DROP  Procedure  dbo.bgp_ConsistencyCheck
	END

GO

PRINT 'Creating Procedure bgp_ConsistencyCheck'
GO

CREATE Procedure dbo.bgp_ConsistencyCheck
with encryption
AS

/**
 *	This stored procedure runs a few checks on the database to verify
 *	data consistency. Used by the background processing.
 *
 *	@return	0 -		Success
 *			1 -		Failure
 */
begin
	set nocount on
	
	declare @checkFailed tinyint
	set @checkFailed = 0
	
	--localizable strings
	declare @localized_string_bgp_ConsistencyCheck_Staring as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_Staring = N'Data consistency check - started'

	declare @localized_string_bgp_ConsistencyCheck_Complete as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_Complete = N'Data consistency check - complete'
	
	declare @localized_string_bgp_ConsistencyCheck_Failed as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_Failed = N'Data consistency check - failed'
	
	declare @localized_string_bgp_ConsistencyCheck_PostingsWithNoPages as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_PostingsWithNoPages = N'Found Postings that do not have a corresponding Page:'

	declare @localized_string_bgp_ConsistencyCheck_PostingsWithNoTemplates as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_PostingsWithNoTemplates = N'Found Postings that do not have a corresponding Template:'

	declare @localized_string_bgp_ConsistencyCheck_NodesWithNoParent as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_NodesWithNoParent = N'Found Nodes that reference an invalid Parent Node:'

	declare @localized_string_bgp_ConsistencyCheck_NodesWithNoLockRecord as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_NodesWithNoLockRecord = N'Found locked Nodes that do not have a corresponding record in NodeLock table:'
	
	declare @localized_string_bgp_ConsistencyCheck_ArchivedNodesWithNoSource as nvarchar(512)
	set @localized_string_bgp_ConsistencyCheck_ArchivedNodesWithNoSource = N'Found archived Nodes that do not have a corresponding source Node:'
	

	print @localized_string_bgp_ConsistencyCheck_Staring
	
	--postings that have no corresponding pages
	if exists(	select 1 from dbo.Node 
				where Type = 16 and IsShortcut = 0
				and FollowGUID not in
				(select NodeGUID from dbo.Node
				where Type = 16
				)
			 )
	begin
		print @localized_string_bgp_ConsistencyCheck_PostingsWithNoPages
		
		select	NodeGUID
				,ParentGUID
				,FollowGUID as PageGUID
				,TemplateGUID
				,DisplayName
		from dbo.Node 
		where Type = 16 and IsShortcut = 0
		and FollowGUID not in
		(select NodeGUID from dbo.Node
		where Type = 16
		) 
		
		set @checkFailed = 1
	end			 
	
	--postings that have no corresponding templates
	if exists(	select 1 from dbo.Node 
				where Type = 16 and IsShortcut = 0
				and TemplateGUID not in
				(select NodeGUID from dbo.Node
				where Type = 65536
				)
			 )
	begin
		print @localized_string_bgp_ConsistencyCheck_PostingsWithNoTemplates
		
		select	NodeGUID
				,ParentGUID
				,FollowGUID as PageGUID
				,TemplateGUID
				,DisplayName
		from dbo.Node 
		where Type = 16 and IsShortcut = 0
		and TemplateGUID not in
		(select NodeGUID from dbo.Node
		where Type = 65536
		)
		
		set @checkFailed = 1
	end	
			 	
	--nodes that do not have parents
	if exists(	select 1 from dbo.Node 
				where ParentGUID is not null and ParentGUID not in
				(select NodeGUID from dbo.Node
				)
			 )
	begin
		print @localized_string_bgp_ConsistencyCheck_NodesWithNoParent
		
		select	Id
				,NodeGUID
				,Type
				,IsShortcut
				,ParentGUID
				,Name
		from dbo.Node 
		where ParentGUID is not null and ParentGUID not in
		(select NodeGUID from dbo.Node
		)
		
		set @checkFailed = 1
	end			 	
	
	--nodes that are locked with no corresponding record in NodeLock table
	if exists(	select 1 from dbo.Node n
				where IsLocked = 1 
				and not exists
				(select 1 from dbo.NodeLock nl
				where nl.NodeId = n.Id
				)
			 )
	begin
		print @localized_string_bgp_ConsistencyCheck_NodesWithNoLockRecord
		
		select	Id
				,NodeGUID
				,Type
				,IsShortcut
				,ParentGUID
				,Name
				,u.Username	as LockUsername
				,LockMachinename
		from dbo.Node n inner join dbo.AEUser u
		on n.LockUserId = u.UserId
		where IsLocked = 1 
		and not exists
		(select 1 from dbo.NodeLock nl
		where nl.NodeId = n.Id
		)
	
		set @checkFailed = 1
	end			 	
	
	--archived nodes that do not have source Node
	if exists(	select 1 from dbo.Node 
				where ArchiveSourceGUID is not null and ArchiveSourceGUID not in
				(select NodeGUID from dbo.Node
				)
			 )
	begin
		print @localized_string_bgp_ConsistencyCheck_ArchivedNodesWithNoSource
		
		select	Id
				,NodeGUID
				,ArchiveSourceGUID
				,Type
				,IsShortcut
				,ParentGUID
				,Name
		from dbo.Node 
		where ArchiveSourceGUID is not null and ArchiveSourceGUID not in
		(select NodeGUID from dbo.Node
		)

		
		set @checkFailed = 1
	end			 		
		
	if @checkFailed = 0
	begin
		print @localized_string_bgp_ConsistencyCheck_Complete
	end
	else	
		print @localized_string_bgp_ConsistencyCheck_Failed
	
	return(@checkFailed)

end
GO

GRANT EXEC ON dbo.bgp_ConsistencyCheck TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CreateBackgroundProcessingJob')
	BEGIN
		PRINT 'Dropping Procedure CreateBackgroundProcessingJob'
		DROP  Procedure  dbo.CreateBackgroundProcessingJob
	END

GO

PRINT 'Creating Procedure CreateBackgroundProcessingJob'
GO

CREATE Procedure dbo.CreateBackgroundProcessingJob
		(
		@databaseName sysname
		,@jobName sysname 
		)

AS

/**
 *	This stored procedure is used to create a job to perform the background
 *	processing. The DCA runs this stored procedure for every database when 
 *	the database is created or upgraded.
 *
 *	@param	@databaseName		Name of the database to create the job for
 *	@param	@jobName out		Name of the job created
 *
 *	@return	0 -		Success
 *			1 -		Failure
 *			100 -	The job already exists
 */

begin

	set nocount on
	
	declare @tranCount int
			,@jobId uniqueidentifier
			,@outputFileName nvarchar(250)
			,@jobStepCommand nvarchar(512)
	
	--localizable strings
	declare @localized_string_InvalidInputParameter as nvarchar(128)
	set @localized_string_InvalidInputParameter = N'Invalid input parameter'
	
	declare @localized_string_JobDescription as nvarchar(128)
	set @localized_string_JobDescription = N'Purge expired information from MCMS tables'
	
	declare @localized_string_JobStep_ExpiredPages as nvarchar(128)
	set @localized_string_JobStep_ExpiredPages = N'Process expired pages'
	
	declare @localized_string_JobStep_DanglingPages as nvarchar(128)
	set @localized_string_JobStep_DanglingPages = N'Purge content for deleted pages'
	
	declare @localized_string_JobStep_GalleryBasedResources as nvarchar(128)
	set @localized_string_JobStep_GalleryBasedResources = N'Update gallery based resources'

	declare @localized_string_JobStep_DanglingBLOBs as nvarchar(128)
	set @localized_string_JobStep_DanglingBLOBs = N'Purge data for deleted resources'

	declare @localized_string_JobAlreadyExists as nvarchar(128)
	set @localized_string_JobAlreadyExists = N'The job already exists'
	
	--validate input
	if isnull(@databaseName, '') = '' or isnull(@jobName, '') = ''
	begin
		raiserror(@localized_string_InvalidInputParameter, 15, 1)
		return (1)	
	end
	
	--the job Name is the database Name prepended with 'BGP-'
	--set @jobName = cast('BGP-' + @databaseName as sysname)

	--if the job already exists for this database we're done
	IF exists (select 1
				from msdb.dbo.sysjobs
				where Name = @jobName
                and originating_server = lower(CONVERT(NVARCHAR(30), SERVERPROPERTY('ServerName'))))
    begin
		raiserror(@localized_string_JobAlreadyExists, 15, 100)
		return (1)	
	end
		

	--check whether we need to create a category for BGP jobs
	IF not exists (select 1
					from msdb.dbo.syscategories
					where (category_class = 1 /*local*/)
					and (Name = 'MCMS Background Processing'))
	begin
		exec msdb.dbo.sp_add_category @class = 'JOB'
									,@Type = 'LOCAL'
									,@Name = 'MCMS Background Processing'
		if @@error <> 0 return (1)	--failure
	end

	
	--start a new transaction if the caller hasn't started one
	set @tranCount = @@trancount
	if @tranCount > 0 
		save tran CreateBGPJob_tran
	else
		begin tran CreateBGPJob_tran
		
	--create a new job
	exec msdb.dbo.sp_add_job @job_name = @jobName
							,@enabled = 1
							,@description = @localized_string_JobDescription
							,@category_name = 'MCMS Background Processing'
							,@job_id = @jobId output
	if @@error <> 0 goto errorhandler

	set @outputFileName = '[SQLDIR]\JOBS\BGP-' + @databaseName + '-[STRTDT]-[STRTTM].log'
	
	--process expired pages
	exec msdb.dbo.sp_add_jobstep @job_id = @jobId
								,@step_name = @localized_string_JobStep_ExpiredPages					
								,@subsystem = 'TSQL'
								,@command = 'exec bgp_ProcessExpiredNodes'
								,@on_success_action = 3
								,@on_fail_action = 3
								,@database_name = @databaseName
								,@output_file_name = @outputFileName
								,@flags = 2
	if @@error <> 0 goto errorhandler

	--gallery based resources
	exec msdb.dbo.sp_add_jobstep @job_id = @jobId
								,@step_name = @localized_string_JobStep_DanglingPages					
								,@subsystem = 'TSQL'
								,@command = 'exec bgp_DeleteDanglingPages'
								,@on_success_action = 3
								,@on_fail_action = 3
								,@database_name = @databaseName
								,@output_file_name = @outputFileName
								,@flags = 2
	if @@error <> 0 goto errorhandler

	--gallery based resources
	exec msdb.dbo.sp_add_jobstep @job_id = @jobId
								,@step_name = @localized_string_JobStep_GalleryBasedResources					
								,@subsystem = 'TSQL'
								,@command = 'exec bgp_UpdateGalleryBasedResources'
								,@on_success_action = 3
								,@on_fail_action = 3
								,@database_name = @databaseName
								,@output_file_name = @outputFileName
								,@flags = 2
	if @@error <> 0 goto errorhandler

	--dangling BLOBs
	exec msdb.dbo.sp_add_jobstep @job_id = @jobId
								,@step_name = @localized_string_JobStep_DanglingBLOBs					
								,@subsystem = 'TSQL'
								,@command = 'exec bgp_DeleteDanglingBLOBs'
								,@on_success_action = 1
								,@on_fail_action = 2
								,@database_name = @databaseName
								,@output_file_name = @outputFileName
								,@flags = 2
	if @@error <> 0 goto errorhandler

	--set the second job step as the start step because by default we don't
	--process expired postings
	exec msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 2 
	
	--set the schedule	
	exec msdb.dbo.sp_add_jobschedule @job_id = @jobId
									,@Name = 'MCMS Background Processing Default'
									,@enabled = 1
									,@freq_type = 4
									,@freq_interval = 1
									,@active_start_time = 10000
	if @@error <> 0 goto errorhandler

	--notify the SQL Server Agent	
	exec msdb.dbo.sp_add_jobserver @job_id = @jobId
									,@server_name = N'(local)'	
	
	if @@error <> 0 goto errorhandler
	
	--commit if we started our own transaction
	if @tranCount = 0
		commit tran	CreateBGPJob_tran
		
	return(0)
		
errorhandler:
	if @@trancount > 0
		rollback tran CreateBGPJob_tran
		
	return(1)

end
GO

GRANT EXEC ON dbo.CreateBackgroundProcessingJob TO PUBLIC
GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_DeleteDanglingBLOBs')
	BEGIN
		PRINT 'Dropping Procedure bgp_DeleteDanglingBLOBs'
		DROP  Procedure  dbo.bgp_DeleteDanglingBLOBs
	END

GO

PRINT 'Creating Procedure bgp_DeleteDanglingBLOBs'
GO

CREATE Procedure dbo.bgp_DeleteDanglingBLOBs
with encryption
AS

/**
 *	This stored procedure is used by the background processing to remove
 *	BlobTable entries that are no longer referenced by any resources.
 *
 *	@return	0 -		Success
 *			1 -		Failure
 */
begin
	set nocount on
	
	declare @tranCount int
			,@retval int	


	declare @danglingBLOB table 
				(
				BlobId int not null 
				,BlobGUID varchar(38) not null 
				)


	--localizable strings
	declare @localized_string_bgp_DeleteDanglingBLOBs_Staring as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingBLOBs_Staring = N'MCMS Background Processing - Purging data for deleted resources - started'

	declare @localized_string_bgp_DeleteDanglingBLOBs_Complete as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingBLOBs_Complete = N'MCMS Background Processing - Purging data for deleted resources - complete'
	
	declare @localized_string_bgp_DeleteDanglingBLOBs_Failed as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingBLOBs_Failed = N'MCMS Background Processing - Purging data for deleted resources - failed'
	

	--start a new transaction if the caller hasn't started one
	set @tranCount = @@trancount
	if @tranCount > 0 
		save tran bgp_DanglingBLOBs_tran
	else
		begin tran bgp_DanglingBLOBs_tran

	--first make sure that there is no Site Deployment import
	--operation currently in progress. We also put a lock on SiteDeployLock table
	--so that the import won't start until we finish
	exec @retval = bgp_LockForBackgroundProcessing	
	if @retval <> 0 goto errorhandler

	print @localized_string_bgp_DeleteDanglingBLOBs_Staring

	--find pages that need to be updated. If the page is checked out we only take
	--its checked out version
	insert into @danglingBLOB (	BlobId
								,BlobGUID
							   )
	select 	BlobId
			,BlobGUID
	from dbo.BlobTable
	where BlobId not in
	(select ResourceBlobId 
	from dbo.NodeResource 
	where ResourceBlobId is not null)

	if @@error <> 0 goto errorhandler

	if exists(select 1 from @danglingBLOB)
	begin
		--lock the server 
		exec @retval = bgp_LockForWrite
		if @retval <> 0 goto errorhandler

		--delete BLOBs
		delete from dbo.BlobTable 
		where BlobId not in
		(select ResourceBlobId 
		from dbo.NodeResource 
		where ResourceBlobId is not null)
		OPTION (MAXDOP 1)
		
		if @@error <> 0 goto errorhandler							
		
	end

	--commit if we started our own transaction
	if @tranCount = 0
		commit tran	bgp_DanglingBLOBs_tran

	--output info about the nodes we've just deleted
	select	BlobGUID
			,'Deleted' as Action
			,'No longer referenced' as Reason
			,getdate() as Date
	from @danglingBLOB
	
	print @localized_string_bgp_DeleteDanglingBLOBs_Complete
			
	return(0)
			

errorhandler:
	if @@trancount > 0
		rollback tran bgp_DanglingBLOBs_tran
		
	print @localized_string_bgp_DeleteDanglingBLOBs_Failed
	
	return(1)

end
GO

GRANT EXEC ON dbo.bgp_DeleteDanglingBLOBs TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_DeleteDanglingPages')
	BEGIN
		PRINT 'Dropping Procedure bgp_DeleteDanglingPages'
		DROP  Procedure  dbo.bgp_DeleteDanglingPages
	END

GO

PRINT 'Creating Procedure bgp_DeleteDanglingPages'
GO
CREATE Procedure dbo.bgp_DeleteDanglingPages
with encryption
AS

/**
 *	This stored procedure is used by the background processing to delete 
 *	expired postings. 
 *
 *	@return	0 -		Success
 *			1 -		Failure
 */
begin
	
	set nocount on
	
	declare @tranCount int
			,@retval int	
			,@dateCurrentGMT datetime
			,@dateCurrent datetime
			
			
	declare @danglingPages table 
				(
				 NodeId int not null primary key
				,NodeGUID varchar(38) collate database_default not null 
				,Type int not null
				,Name nvarchar(250) collate database_default null
				)
			
	--localizable strings
	declare @localized_string_bgp_DeleteDanglingPages_Staring as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingPages_Staring = N'MCMS Background Processing - Purging content for deleted pages - started'
	
	declare @localized_string_bgp_DeleteDanglingPages_Complete as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingPages_Complete = N'MCMS Background Processing - Purging content for deleted pages - complete'
	
	declare @localized_string_bgp_DeleteDanglingPages_Failed as nvarchar(512)
	set @localized_string_bgp_DeleteDanglingPages_Failed = N'MCMS Background Processing - Purging content for deleted pages - failed'
	

	--start a new transaction if the caller hasn't started one
	set @tranCount = @@trancount
	if @tranCount > 0 
		save tran bgp_DeleteDanglingPages_tran
	else
		begin tran bgp_DeleteDanglingPages_tran

	--first make sure that there is no Site Deployment import
	--operation currently in progress. We also put a lock on SiteDeployLock table
	--so that the import won't start until we finish
	exec @retval = bgp_LockForBackgroundProcessing	
	if @retval <> 0 goto errorhandler

	print @localized_string_bgp_DeleteDanglingPages_Staring
	
	set @dateCurrent = getdate()
	exec GetGMTTime @dateCurrent, @dateCurrentGMT out
	
	--find all expired postings. This doesn't include expired postings that are either checked out
	--or use pages that are checked out.
	insert into @danglingPages ( NodeId
								,NodeGUID
								,Type 
								,Name)
	select	page.Id
			,page.NodeGUID
			,page.Type
			,page.Name
	from dbo.Node page
	where page.Type = 16 and page.IsShortcut = 0 
	and not exists
	(select 1 from dbo.Node posting
	where posting.FollowGUID = page.NodeGUID
	)
	
	if @@error <> 0 goto errorhandler

	if exists(select 1 from @danglingPages)
	begin
		--lock the server as deleting expired postings might take long time
		exec @retval = bgp_LockForWrite
		if @retval <> 0 goto errorhandler

		--create #Sandbox table
		create table #Sandbox (	NodeGUID char(38) collate database_default NOT NULL primary key
								,ParentGUID char(38) collate database_default null
								,Reason int NOT NULL DEFAULT 0
								,LastChangeTime datetime NOT NULL
								,LastDeployTime	datetime NULL
								,Type	int null
								,IsShortcut tinyint null
								,Name nvarchar(250) collate database_default null
								,FollowGUID varchar(38) collate database_default null
								,TemplateGUID varchar(38) collate database_default null
								,PageDefinitionGUID varchar(38) collate database_default null
								)	
								
		if @@error <> 0 goto errorhandler							
		
		--delete expired nodes
		
		--this applies to pages and postings
		delete NodeProperty 
		where NodeProperty.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		delete NodeRole 
		where NodeRole.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		delete NodeLock 
		where NodeLock.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		--this applies to pages only
		delete NodeResource 
		where NodeResource.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							
		
		delete NodePlaceholderContent 
		where NodePlaceholderContent.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		delete NodePlaceholder 
		where NodePlaceholder.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		delete LayoutProperty 
		where LayoutProperty.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							

		delete NodeLayout 
		where NodeLayout.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							
		
		delete NodeLock 
		where NodeLock.NodeId in
		(select NodeId from @danglingPages)

		if @@error <> 0 goto errorhandler							
		
		--page revisions
		delete NodeProperty 
		where NodeProperty.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)

		if @@error <> 0 goto errorhandler							
		
		delete NodeRole 
		where NodeRole.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)

		if @@error <> 0 goto errorhandler							
				
		delete NodeResource 
		where NodeResource.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)		

		if @@error <> 0 goto errorhandler							
		
		delete NodePlaceholderContent 
		where NodePlaceholderContent.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)	
	
		if @@error <> 0 goto errorhandler							
	
		delete NodePlaceholder 
		where NodePlaceholder.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)	

		if @@error <> 0 goto errorhandler							

		delete LayoutProperty 
		where LayoutProperty.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)	

		if @@error <> 0 goto errorhandler							

		delete NodeLayout 
		where NodeLayout.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)	

		if @@error <> 0 goto errorhandler							

		delete NodeLock 
		where NodeLock.NodeId in
		(select a.Id 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)			

		if @@error <> 0 goto errorhandler							
		
		delete Node 
		where Node.NodeGUID in
		(select a.NodeGUID 
		from @danglingPages e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		)					
				
		if @@error <> 0 goto errorhandler							
				
		delete from dbo.Node
		where NodeGUID in
		(select NodeGUID from @danglingPages)
	
		if @@error <> 0 goto errorhandler							
		
		exec UpdateChangeTable									
	end
	
	--commit if we started our own transaction
	if @tranCount = 0
		commit tran	bgp_DeleteDanglingPages_tran

	--output info about the nodes we've just deleted
	select	NodeGUID
			,'Deleted' as Action
			,'No longer referenced' as Reason
			,Name
			,getdate() as Date
	from @danglingPages
	
	print @localized_string_bgp_DeleteDanglingPages_Complete
			
	return(0)
		
errorhandler:
	if @@trancount > 0
		rollback tran bgp_DeleteDanglingPages_tran
		
	print @localized_string_bgp_DeleteDanglingPages_Failed
	return(1)
	 

end

GO

GRANT EXEC ON dbo.bgp_DeleteDanglingPages TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_LockForBackgroundProcessing')
	BEGIN
		PRINT 'Dropping Procedure bgp_LockForBackgroundProcessing'
		DROP  Procedure  dbo.bgp_LockForBackgroundProcessing
	END

GO

PRINT 'Creating Procedure bgp_LockForBackgroundProcessing'
GO

CREATE Procedure dbo.bgp_LockForBackgroundProcessing
with encryption
AS
/**
 *	This stored procedure is used by the background processing to check 
 *	whether there is an update operation currently in progress and 
 *	to put an exclusive lock on ServerWriteLock table so that 
 *	the updated won't take place until background processing is finished
 *
 *	@return	0 -		Success
 *			<> 0 -	Failure
 */
 
 begin
	
	set nocount on
	
	declare @retval int
	
	declare @localized_string_LockForBGP_Failed as nvarchar(512)
	set @localized_string_LockForBGP_Failed = N'Failed to set lock. There is currently Site Deployment or other update operation in progress.'
	
	--lock out updates
	exec @retval = SetExclusiveLock 0, 30000
	
	if @retval = 1222
		raiserror(@localized_string_LockForBGP_Failed, 15, 1) 
		
	return @retval
	
 end
GO

GRANT EXEC ON dbo.bgp_LockForBackgroundProcessing TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_LockForWrite')
	BEGIN
		PRINT 'Dropping Procedure bgp_LockForWrite'
		DROP  Procedure  dbo.bgp_LockForWrite
	END

GO

PRINT 'Creating Procedure bgp_LockForWrite'
GO

CREATE Procedure dbo.bgp_LockForWrite
with encryption
AS
/**
 *	This stored procedure is used by the background processing to lock the server
 *	while it's updating the database
 *
 *	@return	0 -		Success
 *			<> 0 -	Failure
 */
 
 begin
	
	set nocount on
	
	declare @retval int
	
	declare @localized_string_LockForBGP_Failed as nvarchar(512)
	set @localized_string_LockForBGP_Failed = N'Failed to set lock. There is currently another long running transaction in progress.'
	
	--lock out reads and updates
	exec @retval = SetExclusiveLock 1, 30000
	
	if @retval = 1222
		raiserror(@localized_string_LockForBGP_Failed, 15, 1) 
				
	return @retval
	
 end
GO

GRANT EXEC ON dbo.bgp_LockForWrite TO PUBLIC

GO


/** \File ProcessExpiredNodes.sql
 *	This stored procedure is used by the background processing to delete 
 *	expired postings. 
 *
 *	@return	0 -		Success
 *			1 -		Failure
 */

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_ProcessExpiredNodes')
	BEGIN
		PRINT 'Dropping Procedure bgp_ProcessExpiredNodes'
		DROP  Procedure  dbo.bgp_ProcessExpiredNodes
	END

GO

PRINT 'Creating Procedure bgp_ProcessExpiredNodes'
GO
CREATE Procedure dbo.bgp_ProcessExpiredNodes
with encryption
AS


begin
	
	set nocount on
	
	declare @tranCount int
			,@retval int	
			,@dateCurrentGMT datetime
			,@dateCurrent datetime
			,@MaxCommit datetime
			,@CommitTime datetime			
			
	declare @expiredNodes table 
				(
				NodeId int not null 
				,NodeGUID varchar(38) collate database_default not null primary key
				,ParentGUID varchar(38) collate database_default not null
				,Type int not null
				,IsShortcut tinyint not null
				,FollowGUID varchar(38) collate database_default null
				,TemplateGUID varchar(38) collate database_default null
				,Name nvarchar(250) collate database_default null
				)
			
	--localizable strings
	declare @localized_string_bgp_ProcessExpiredNodes_Staring as nvarchar(512)
	set @localized_string_bgp_ProcessExpiredNodes_Staring = N'MCMS Background Processing - Processing expired pages - started'
	
	declare @localized_string_bgp_ProcessExpiredNodes_Complete as nvarchar(512)
	set @localized_string_bgp_ProcessExpiredNodes_Complete = N'MCMS Background Processing - Processing expired pages - complete'
	
	declare @localized_string_bgp_ProcessExpiredNodes_Failed as nvarchar(512)
	set @localized_string_bgp_ProcessExpiredNodes_Failed = N'MCMS Background Processing - Processing expired pages - failed'
	

	--start a new transaction if the caller hasn't started one
	set @tranCount = @@trancount
	if @tranCount > 0 
		save tran bgp_ProcessExpiredNodes_tran
	else
		begin tran bgp_ProcessExpiredNodes_tran

	--first make sure that there is no Site Deployment import
	--operation currently in progress. We also put a lock on SiteDeployLock table
	--so that the import won't start until we finish
	exec @retval = bgp_LockForBackgroundProcessing	
	if @retval <> 0 goto errorhandler

	print @localized_string_bgp_ProcessExpiredNodes_Staring
	
	/*disable delete trigger on the Node table
	 we'll update the change table directly afterwards
	*/
	alter table Node disable trigger ChangeTrigger_Delete
	
	set @dateCurrent = getdate()
	exec GetGMTTime @dateCurrent, @dateCurrentGMT out
	
	--find all expired postings. This doesn't include expired postings that are either checked out
	--or use pages that are checked out.
	insert into @expiredNodes (	NodeId
								,NodeGUID
								,ParentGUID
								,Type 
								,IsShortcut
								,FollowGUID
								,Name
								,TemplateGUID)
	select	posting.Id
			,posting.NodeGUID
			,posting.ParentGUID
			,posting.Type
			,posting.IsShortcut
			,posting.FollowGUID
			,page.Name
			,posting.TemplateGUID
	from dbo.Node posting inner join dbo.Node page
	on posting.FollowGUID = page.NodeGUID
	and posting.IsCheckedOut = 0 
	and page.IsCheckedOut = 0
	where posting.ExpiryDate < @dateCurrentGMT

	if @@error <> 0 goto errorhandler

	if exists(select 1 from @expiredNodes)
	begin
		--we do have some expired postings
		--get the pages that we should remove along with the postings
		insert into @expiredNodes (	NodeId
									,NodeGUID
									,ParentGUID
									,Type 
									,IsShortcut
									,FollowGUID
									,Name)
		select	page.Id
				,page.NodeGUID
				,page.ParentGUID
				,page.Type
				,page.IsShortcut
				,NULL
				,page.Name
		from dbo.Node page
		where page.NodeGUID in
			(select FollowGUID from @expiredNodes)
		and not exists
			(select 1 from 
			dbo.Node posting
			where posting.FollowGUID = page.NodeGUID
			and posting.NodeGUID not in
				(select NodeGUID from @expiredNodes)
			)
		
		if @@error <> 0 goto errorhandler							
		
		--lock the server as deleting expired postings might take long time
		exec @retval = bgp_LockForWrite
		if @retval <> 0 goto errorhandler

		--delete expired nodes
		
		--this applies to pages and postings
		delete NodeProperty 
		where NodeProperty.NodeId in
		(select NodeId from @expiredNodes)

		if @@error <> 0 goto errorhandler							

		delete NodeRole 
		where NodeRole.NodeId in
		(select NodeId from @expiredNodes)

		if @@error <> 0 goto errorhandler							

		delete NodeLock 
		where NodeLock.NodeId in
		(select NodeId from @expiredNodes)

		if @@error <> 0 goto errorhandler							

		--this applies to pages only
		delete NodeResource 
		where NodeResource.NodeId in
		(select NodeId from @expiredNodes where IsShortcut = 0)

		if @@error <> 0 goto errorhandler							
		
		delete NodePlaceholderContent 
		where NodePlaceholderContent.NodeId in
		(select NodeId from @expiredNodes where IsShortcut = 0)

		if @@error <> 0 goto errorhandler							

		delete NodePlaceholder 
		where NodePlaceholder.NodeId in
		(select NodeId from @expiredNodes where IsShortcut = 0)

		if @@error <> 0 goto errorhandler							

		delete LayoutProperty 
		where LayoutProperty.NodeId in
		(select NodeId from @expiredNodes where IsShortcut = 0)

		if @@error <> 0 goto errorhandler							

		delete NodeLayout 
		where NodeLayout.NodeId in
		(select NodeId from @expiredNodes where IsShortcut = 0)

		if @@error <> 0 goto errorhandler							
		
		delete NodeLock 
		where NodeLock.NodeId in
		(select NodeId from @expiredNodes)

		if @@error <> 0 goto errorhandler							
		
		--page revisions
		delete NodeProperty 
		where NodeProperty.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)

		if @@error <> 0 goto errorhandler							
		
		delete NodeRole 
		where NodeRole.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)

		if @@error <> 0 goto errorhandler							
				
		delete NodeResource 
		where NodeResource.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)		

		if @@error <> 0 goto errorhandler							
		
		delete NodePlaceholderContent 
		where NodePlaceholderContent.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)	
	
		if @@error <> 0 goto errorhandler							
	
		delete NodePlaceholder 
		where NodePlaceholder.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)	

		if @@error <> 0 goto errorhandler							

		delete LayoutProperty 
		where LayoutProperty.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)	

		if @@error <> 0 goto errorhandler							

		delete NodeLayout 
		where NodeLayout.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)	

		if @@error <> 0 goto errorhandler							

		delete NodeLock 
		where NodeLock.NodeId in
		(select a.Id 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)			

		if @@error <> 0 goto errorhandler							
		
		delete Node 
		where Node.NodeGUID in
		(select a.NodeGUID 
		from @expiredNodes e inner join dbo.Node a
		on e.NodeGUID = a.ArchiveSourceGUID
		and e.IsShortcut = 0
		)					
				
		if @@error <> 0 goto errorhandler							
				
		delete from dbo.Node
		where NodeGUID in
		(select NodeGUID from @expiredNodes)
	
		if @@error <> 0 goto errorhandler							
		
		select  @MaxCommit = MAX( CommitTime ) from ChangeTable WITH(UPDLOCK) 
		if @@error <> 0 goto errorhandler							
		
		select  @CommitTime = case when @dateCurrentGMT <= @MaxCommit then DateAdd( ms, 3, @MaxCommit ) else @dateCurrentGMT END
		if @@error <> 0 goto errorhandler							
		
		UPDATE dbo.ChangeTable 
				SET Reason = 2, 
				LastChangeTime = @CommitTime,
				CommitTime = @CommitTime,
				ParentGUID = del.ParentGUID,
				Type = del.Type,
				IsShortcut = del.IsShortcut,
				Name = del.Name,
				FollowGUID = del.FollowGUID,
				TemplateGUID = del.TemplateGUID
		from @expiredNodes del
		where ChangeTable.NodeGUID = del.NodeGUID

		if @@error <> 0 goto errorhandler							
			
	end
	
	alter table Node enable trigger ChangeTrigger_Delete
	
	--commit if we started our own transaction
	if @tranCount = 0
		commit tran	bgp_ProcessExpiredNodes_tran

	--output info about the nodes we've just deleted
	select	NodeGUID
			,case when IsShortcut = 0 then 'Page'
					else 'Posting'
			 end as Type
			,'Deleted' as Action
			,'Expired' as Reason
			,Name
			,getdate() as Date
	from @expiredNodes
	
	print @localized_string_bgp_ProcessExpiredNodes_Complete
			
	return(0)
		
errorhandler:

	alter table Node enable trigger ChangeTrigger_Delete
	
	if @@trancount > 0
		rollback tran bgp_ProcessExpiredNodes_tran
		
	print @localized_string_bgp_ProcessExpiredNodes_Failed
	return(1)
	 

end

GO

GRANT EXEC ON dbo.bgp_ProcessExpiredNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'bgp_UpdateGalleryBasedResources')
	BEGIN
		PRINT 'Dropping Procedure bgp_UpdateGalleryBasedResources'
		DROP  Procedure  dbo.bgp_UpdateGalleryBasedResources
	END

GO

PRINT 'Creating Procedure bgp_UpdateGalleryBasedResources'
GO

CREATE Procedure dbo.bgp_UpdateGalleryBasedResources
with encryption
AS

/**
 *	This stored procedure is used by the background processing to synchronize 
 *	gallery based resources. It checks resources that are linked to a resource 
 *	gallery item, and if they are different from the resource gallery item's 
 *	_Content property, they are updated to hold the new ResourceBlobId. 
 *	If the resource gallery item the resource points to doesn't exist anymore,
 *	the link is removed (i.e. clear the NodeGUID field)
 *
 *	@return	0 -		Success
 *			1 -		Failure
 */
begin
	set nocount on
	
	declare @tranCount int
			,@retval int	


	declare @updatedPages table 
				(
				NodeId int not null 
				,NodeGUID varchar(38) not null 
				,Type int not null
				,Name nvarchar(250) null
				,IsLocked tinyint not null
				,LockUserId int null
				,LockMachinename nvarchar(50) null
				,ResourceId int not null
				,ResourceGalleryGUID varchar(38) null
				,NewResourceBlobId int null
				)


	--localizable strings
	declare @localized_string_bgp_UpdateGalleryBasedResources_Staring as nvarchar(512)
	set @localized_string_bgp_UpdateGalleryBasedResources_Staring = N'MCMS Background Processing - Updating gallery based resources - started'

	declare @localized_string_bgp_UpdateGalleryBasedResources_Complete as nvarchar(512)
	set @localized_string_bgp_UpdateGalleryBasedResources_Complete = N'MCMS Background Processing - Updating gallery based resource - complete'
	
	declare @localized_string_bgp_UpdateGalleryBasedResources_Failed as nvarchar(512)
	set @localized_string_bgp_UpdateGalleryBasedResources_Failed = N'MCMS Background Processing - Updating gallery based resource - failed'
	
	--start a new transaction if the caller hasn't started one
	set @tranCount = @@trancount
	if @tranCount > 0 
		save tran bgp_UpdateResources_tran
	else
		begin tran bgp_UpdateResources_tran

	--first make sure that there is no Site Deployment import
	--operation currently in progress. We also put a lock on SiteDeployLock table
	--so that the import won't start until we finish
	exec @retval = bgp_LockForBackgroundProcessing	
	if @retval <> 0 goto errorhandler

	print @localized_string_bgp_UpdateGalleryBasedResources_Staring

	--find pages that need to be updated. If the page is checked out we only take
	--its checked out version
	insert into @updatedPages (	NodeId
								,NodeGUID
								,Type
								,Name
								,IsLocked
								,LockUserId
								,LockMachinename
								,ResourceId
								,ResourceGalleryGUID
								,NewResourceBlobId
							   )
	select 	page.Id
			,page.NodeGUID
			,page.Type
			,page.Name
			,page.IsLocked
			,page.LockUserId
			,page.LockMachinename			
			,resource.Id
			,rgi.NodeGUID
			,rgiResource.ResourceBlobId			   
	from dbo.Node page inner join dbo.NodeResource resource
		on page.Id = resource.NodeId
		and resource.IsLink = 0
		and resource.NodeGUID is not null	
		and (page.IsCheckedOut = 0 or page.HasCheckedInVersion = 0)
		and page.ArchiveSourceGUID is null
	left join dbo.Node rgi
		on resource.NodeGUID = rgi.NodeGUID
	left join dbo.NodeResource rgiResource
		on rgi.Id = rgiResource.NodeId
	where rgiResource.ResourceBlobId <> resource.ResourceBlobId
	and rgi.IsCheckedOut = 0	
	and rgi.ArchiveSourceGUID is null
	and rgiResource.Name = '_Content'

	if @@error <> 0 goto errorhandler

	if exists(select 1 from @updatedPages)
	begin
		--lock the server 
		exec @retval = bgp_LockForWrite
		if @retval <> 0 goto errorhandler

		--create #Sandbox table
		create table #Sandbox (	NodeGUID char(38) collate database_default NOT NULL primary key
								,ParentGUID char(38) collate database_default null
								,Reason int NOT NULL DEFAULT 0
								,LastChangeTime datetime NOT NULL
								,LastDeployTime	datetime NULL
								,Type	int null
								,IsShortcut tinyint null
								,Name nvarchar(250) collate database_default null
								,FollowGUID varchar(38) collate database_default null
								,TemplateGUID varchar(38) collate database_default null
								,PageDefinitionGUID varchar(38) collate database_default null
								)	
								
		if @@error <> 0 goto errorhandler							
		
		--update NodeResource records with the new ResourceBlobId values
		update dbo.NodeResource
		set ResourceBlobId = up.NewResourceBlobId,
			NodeGUID = up.ResourceGalleryGUID
		from dbo.NodeResource resource inner join @updatedPages up
			on resource.NodeId = up.NodeId
			and resource.Id = up.ResourceId
		where up.IsLocked = 0
	
		if @@error <> 0 goto errorhandler							
		
		--update Node table to fire off the trigger
		update dbo.Node 
			set LastChangeTime = LastChangeTime
		where Id in
			(select distinct NodeId 
			 from @updatedPages 
			 where IsLocked = 0
			 )
		
		exec UpdateChangeTable									

	end

	--commit if we started our own transaction
	if @tranCount = 0
		commit tran	bgp_UpdateResources_tran

	--output info about the nodes we've just deleted
	select	distinct NodeGUID
				,'Page' as Type
				,case when IsLocked = 0 then 'Updated' 
						else 'Failed'
				 end as Action
				,case when IsLocked = 0 then 'Resource Sync' 
						else 'Locked'
				 end as Reason
				,ResourceGalleryGUID
				,Name
				,u.Username as LockUsername
				,LockMachinename
				,getdate() as Date
	from @updatedPages up left join dbo.AEUser u
	on up.LockUserId = u.UserId
	
	print @localized_string_bgp_UpdateGalleryBasedResources_Complete
			
	return(0)
			

errorhandler:
	if @@trancount > 0
		rollback tran bgp_UpdateResources_tran
		
	print @localized_string_bgp_UpdateGalleryBasedResources_Failed
	
	return(1)

end
GO

GRANT EXEC ON dbo.bgp_UpdateGalleryBasedResources TO PUBLIC

GO


/* 
 * File: CalculateLocation.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_CalculateLocation'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_CalculateLocation
go
/* Purpose: CalculateLocation determines the path (e.g. /Resources/RG1/RG2/RGI)
 * of all nodes ##ExportedNode table.
 * PreCondition:
 * The only columns referenced are NodeGUID, ParentGUID, Name and Depth.
 * These columns must be properly populated with nodes and their names and parents
 * as well as the proper Depth setting.
 * This procedure uses this structure to determine the Location or path from the top down.
 * All nodes in the table will have a Location calculated.
 */
CREATE PROC dbo.sd_CalculateLocation ( @TableName nvarchar(100) )
with encryption
AS
set nocount on
Declare
	@max_depth int,
	@Depth int,
	@defaultname nchar(11),
	@SeedLocationSql nvarchar(4000),
	@UpdateLocationSql nvarchar(4000)


/*		
		Node Types
	1			- Server
	2			- ????????????????
	4			- Channel
	16			- Page or Posting
	32			- ????????????????
	64			- Resource Gallery
	256			- Resource Gallery Item
	1024		- Control Gallery
	4096		- Control Gallery Item
	16384		- Template Gallery
	65536		- Template
	131072		- ???????????????
	262144		- User Directory
	524288		- User Role
	1048576		- Administrator
	2097152		- Folder
	4194304		- ???????????????
	8388608		- ???????????????
	16777216	- Page Definition Gallery
	33554432	- Page Definition
*/

/*update Location for nodes that exist in Node table and haven't been deleted*/
Set @SeedLocationSql = N'update ' + @TableName
				  + N' set Location = cast (case when parents.ParentGUID is null then '''' else parents.Name end '
				  + N' + ''/'' as nvarchar(4000) ), '
				  + N' CurrentParentGuid = parents.ParentGUID'
				  + N' from Node parents'
				  + N' where ' + @TableName + '.CurrentParentGuid = parents.NodeGUID '
				  + N' and ' + @TableName + '.CurrentParentGuid is not null'
				  + N' and parents.IsCheckedOutVersion = 0'
				  + N' and IsDeleted = 0'

Set @UpdateLocationSql = N'update ' + @TableName
				  + N' set Location = cast (case when parents.ParentGUID is null then '''' else parents.Name end '
				  + N' + ''/'' + IsNull(cast(Location as nvarchar(4000)), '''') as nvarchar(4000) ), '
				  + N' CurrentParentGuid = parents.ParentGUID'
				  + N' from Node parents'
				  + N' where ' + @TableName + '.CurrentParentGuid = parents.NodeGUID '
				  + N' and ' + @TableName + '.CurrentParentGuid is not null'
				  + N' and parents.IsCheckedOutVersion = 0'
				  + N' and IsDeleted = 0'
				  
Exec sp_executesql @SeedLocationSql

while @@rowcount > 0
begin
	Exec sp_executesql @UpdateLocationSql			
end

/*update Location for nodes that have been deleted*/
Set @SeedLocationSql = N'update ' + @TableName
				  + N' set Location = cast (case when parents.ParentGUID is null then '''' else parents.Name end '
				  + N' + ''/'' as nvarchar(4000) ), '
				  + N' CurrentParentGuid = parents.ParentGUID'
				  + N' from ChangeTable parents'
				  + N' where ' + @TableName + '.CurrentParentGuid = parents.NodeGUID '
				  + N' and ' + @TableName + '.CurrentParentGuid is not null'
				  + N' and IsDeleted = 1'

Set @UpdateLocationSql = N'update ' + @TableName
				  + N' set Location = cast (case when parents.ParentGUID is null then '''' else parents.Name end '
				  + N' + ''/'' + IsNull(cast(Location as nvarchar(4000)), '''') as nvarchar(4000) ), '
				  + N' CurrentParentGuid = parents.ParentGUID'
				  + N' from ChangeTable parents'
				  + N' where ' + @TableName + '.CurrentParentGuid = parents.NodeGUID '
				  + N' and ' + @TableName + '.CurrentParentGuid is not null'
				  + N' and IsDeleted = 1'

Exec sp_executesql @SeedLocationSql

while @@rowcount > 0
begin
	Exec sp_executesql @UpdateLocationSql			
end

return (@@error)
GO

GRANT EXEC ON dbo.sd_CalculateLocation TO PUBLIC

GO


/* 
 * File: CreateExportTables.sql
 */
-- Drop this procedure (if it exists) before creating it.
if exists (select * from sysobjects
    where name = 'sd_CreateExportTables'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_CreateExportTables
go
/* Purpose: CreateExportTables is a stored procedure for creating the export 
 * temporary table definitions.
 */
CREATE PROC dbo.sd_CreateExportTables (@suffix nchar(38))
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100),@CreateExportTable nvarchar(1000),@DropExportTable nvarchar(50)
		,@ExcludeTable nvarchar(100),@CreateExcludeTable nvarchar(500),@DropExcludeTable nvarchar(50)
		,@FailTable nvarchar(100),@CreateFailTable nvarchar(500),@DropFailTable nvarchar(50)
		,@MissingLinkTable nvarchar(100),@CreateMissingTable nvarchar(500),@AlterMissingTable nvarchar(500)
		,@DropMissingTable nvarchar(50), @MissingLinkConstraint nvarchar(100)
		,@ConfigTable nvarchar(100),@CreateConfigTable nvarchar(500),@DropConfigTable nvarchar(50)
		,@TempTable nvarchar(100),@CreateTempTable nvarchar(1000),@DropTempTable nvarchar(50)
		
Set @ExportTable		= N'##ExportedNode' + IsNull(@Suffix,N'')
Set @ExcludeTable		= N'##ExcludedNode' + IsNull(@Suffix,N'')
Set @FailTable			= N'##FailedNode'	+ IsNull(@Suffix,N'')
Set @MissingLinkTable	= N'##MissingLink'	+ IsNull(@Suffix,N'')
Set @MissingLinkConstraint	= N'PK_MissingLink'	+ IsNull(@Suffix,N'')
Set @ConfigTable		= N'##Config'		+ IsNull(@Suffix,N'')
Set @TempTable			= N'##TempHier'		+ IsNull(@Suffix,N'')

--Sql definitions
Set @CreateExportTable = N'Create table ' + @ExportTable
						+N'(Ordinal					int identity PRIMARY KEY CLUSTERED'
						+N' ,NodeGUID				varchar(38) collate database_default NOT NULL '
						+N',ParentGUID				varchar(38) collate database_default '
						+N',CurrentParentGuid		varchar(38)collate database_default '
						+N',Depth					int Not Null Default 0'
						+N',Type					int not null default 0'
						+N',IsShortcut				tinyint not null default 0 '
						+N',IsRecursive				tinyint Not Null Default 0'
						+N',ExplicitlySelected		tinyint Not Null Default 0'
						+N',IsDependent				tinyint Not Null Default 0'
						+N',CreatedByUserId			int '
						+N',LastModified			datetime '
						+N',ApprovalStatus			int '
						+N',ApprovedVersionExists	tinyint '
						+N',HasBrokenLinks			tinyint '
						+N',Name					nvarchar(250) collate database_default '
						+N',Location				nvarchar(3000) collate database_default '
						+N',NodeId					int Not Null Default 0'
						+N',Reason					int '
						+N',IsDeleted				tinyint Not Null Default 0'
						+N',FollowGUID				varchar(38) collate database_default '
						+N',TemplateGUID			varchar(38) collate database_default'
						+N',PageDefinitionGUID		varchar(38) collate database_default'
						+N')'
Set @DropExportTable = N'Drop table ' + @ExportTable

Set @CreateExcludeTable = N'Create table ' + @ExcludeTable
						+N'(NodeGUID	varchar(38) collate database_default NOT NULL PRIMARY KEY CLUSTERED'
						+N',Depth		int NOT NULL DEFAULT 1 '
						+N',Type			int		Not Null Default 0'
						+N',IsShortcut		tinyint Not Null Default 0'
						+N',Name			nvarchar(250) collate database_default'
						+N',LastModified	datetime'
						+N',NodeId			int DEFAULT 0'
						+N',ExplicitlySelected		tinyint Not Null Default 0'
						+N',Location		nvarchar(3000) collate database_default'
						+N')'
Set @DropExcludeTable = N'Drop table ' + @ExcludeTable
						
Set @CreateFailTable = N'Create table ' + @FailTable
						+N'(NodeGUID		varchar(38) collate database_default NOT NULL PRIMARY KEY CLUSTERED'
						+N',Type			int		Not Null Default 0'
						+N',IsShortcut		tinyint Not Null Default 0'
						+N',ParentGUID		varchar(38) collate database_default '
						+N',CurrentParentGuid	varchar(38)collate database_default '
						+N',Name			nvarchar(250) collate database_default'
						+N',LastModified	datetime'
						+N',Reason			int'
						+N',IsDeleted		tinyint Not Null Default 0'
						+N',Location		nvarchar(3000) collate database_default'
						+N')'
Set @DropFailTable = N'Drop table ' + @FailTable

Set @CreateMissingTable = N'Create table ' + @MissingLinkTable
						+N'(NodeGUID		varchar(38) collate database_default NOT NULL '
						+N',SourceNodeGuid	varchar(38)	collate database_default NOT NULL'
						+N',Type			int			Not Null Default 0'
						+N',IsShortcut		tinyint		Not Null Default 0'
						+N',Name			nvarchar(250) collate database_default'
						+N',LastModified	datetime'
						+N',Reason			int'
						+N',Location		nvarchar(3000) collate database_default'
						+N')'

Set @AlterMissingTable = N'ALTER TABLE ' + @MissingLinkTable
					    +N' ADD CONSTRAINT ' + @MissingLinkConstraint + N' PRIMARY KEY CLUSTERED '
						+N' (NodeGUID, SourceNodeGuid)'

Set @DropMissingTable = N'Drop table ' + @MissingLinkTable

Set @CreateTempTable = N'Create table ' + @TempTable
						+N'(NodeGUID				varchar(38) collate database_default NOT NULL PRIMARY KEY CLUSTERED'
						+N',ParentGUID				varchar(38) collate database_default '
						+N',CurrentParentGuid		varchar(38) collate database_default'
						+N',Depth					int			Not Null Default -1'
						+N',Type					int			Not Null Default 0'
						+N',IsShortcut				tinyint		Not Null Default 0'
						+N',IsRecursive				tinyint		Not Null Default 0'
						+N',ExplicitlySelected		tinyint		Not Null Default 0'
						+N',IsDependent				tinyint		Not Null Default 0'
						+N',CreatedByUserId			int '
						+N',LastModified			datetime'
						+N',ApprovalStatus			int'
						+N',ApprovedVersionExists	tinyint'
						+N',HasBrokenLinks			tinyint'
						+N',Name					nvarchar(250) collate database_default'
						+N',Location				nvarchar(3000) collate database_default'
						+N',NodeId					int Not Null Default 0'
						+N',FollowGUID				varchar(38) collate database_default'
						+N',TemplateGUID			varchar(38) collate database_default'
						+N',PageDefinitionGUID		varchar(38) collate database_default'
						+N')'
						
Set @DropTempTable = N'Drop table ' + @TempTable
		
--Create ExcludeNode table
if exists (select 1 from tempdb..sysobjects
    where name = @ExcludeTable
    and type = 'U' and uid = user_id())
Begin
    exec sp_executesql @DropExcludeTable
End
exec sp_executesql @CreateExcludeTable


--Create FailNode table
if exists (select 1 from tempdb..sysobjects
    where name = @FailTable
    and type = 'U' and uid = user_id())
Begin
    exec sp_executesql @DropFailTable
End
exec sp_executesql @CreateFailTable

--Create the ExportNode table
if exists (select 1 from tempdb..sysobjects
    where name = @ExportTable
    and type = 'U' and uid = user_id())
Begin
    exec sp_executesql @DropExportTable
End
						
exec sp_executesql @CreateExportTable


--Create the Missing Links table
if exists (select 1 from tempdb..sysobjects
    where name = @MissingLinkTable
    and type = 'U' and uid = user_id())
Begin
    exec sp_executesql @DropMissingTable
End
exec sp_executesql @CreateMissingTable
exec sp_executesql @AlterMissingTable


--Create the Temp hierarchy table
if exists (select 1 from tempdb..sysobjects
    where name = @TempTable
    and type = 'U' and uid = user_id())
Begin
    exec sp_executesql @DropTempTable
End
exec sp_executesql @CreateTempTable

Exec IndexExportTables @Suffix

return 0
GO

GRANT EXEC ON dbo.sd_CreateExportTables TO PUBLIC

GO


/* 
 * File: CreatSubHier.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_CreateSubHier'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_CreateSubHier
go
/* Purpose: Populates a table with a subhierarchy.
 * PreCondition:
 *
 * PostCondition:
 *
 */
CREATE PROC dbo.sd_CreateSubHier(@ContainersOnly int = 0
							,@GrowthPlan nchar(6) = N'both'
							,@HierTable nvarchar(100)
							,@IncludeDeletes tinyint = 0
							,@IncludeCreatedBy tinyint = 0
							,@Suffix	nvarchar(100) = Null)
with encryption
AS
set nocount on

	
-- Miscellaneous data
Declare
	@NodeGUID nchar(38),
	@ParentGUID nchar(38),
	@Location nvarchar(3000),
	@path nvarchar(3000),
	@nodename nvarchar(250),
	@ExcludeTable nvarchar(100),
	@UpdateChildrenSql nvarchar(4000),
	@InsertChildrenSql nvarchar(4000),
	@SelectChildrenSql nvarchar(4000),
	@UnionSql nvarchar(4000),
	@IterateSql nvarchar(4000),
	@nodetype int,
	@Depth int,
	@newdepth int,
	@rows_affected int,
	@return_status int,
	@ContainerRestriction nvarchar(500),
	@GetCountSql nvarchar(100),
	@Count int,
	@DeleteReason nchar(1)

--Default return Status
Set @return_status = 0
--Reason code for deletes in the change table
Set @DeleteReason = N'2'

/*		
		Node Types
	1			- Server
	2			- ????????????????
	4			- Channel
	16			- Page or Posting
	32			- ????????????????
	64			- Resource Gallery
	256			- Resource Gallery Item
	1024		- Control Gallery
	4096		- Control Gallery Item
	16384		- Template Gallery
	65536		- Template
	131072		- ???????????????
	262144		- User Directory
	524288		- User Role
	1048576		- Administrator
	2097152		- Folder
	4194304		- ???????????????
	8388608		- ???????????????
	16777216	- Page Definition Gallery
	33554432	- Page Definition
*/
--Set the Name of the Exclude Table
Set @ExcludeTable = RTRIM(N'##ExcludedNode' + IsNull(@Suffix,N''))

--This restriction applies only to case when adding only containers to the hiertable			
Set @ContainerRestriction = N' And n.Type in (4,64,1024,16384,262144,2097152,524288,16777216)'
Set @GetCountSql = N'Select @count=Count(*) from ' + @HierTable

Set @InsertChildrenSql = N' Insert into '+ @HierTable
									+ N'(NodeGUID '
									+ N' ,ParentGUID'
									+ N' ,CurrentParentGuid'
									+ N' ,Type'
									+ N' ,Depth'
									+ N' ,IsShortcut'
									+ N' ,IsDependent'
									+ N' ,NodeId'
									+ N' ,CreatedByUserId'
									+ N' ,LastModified'
									+ N' ,ApprovalStatus'
									+ N' ,ApprovedVersionExists'
									+ N' ,Name '
									+ N' ,ExplicitlySelected'
									+ N' ,IsRecursive '
									+ N' ,FollowGUID'
									+ N' ,TemplateGUID'
									+ N' ,PageDefinitionGUID) '
						
Set @SelectChildrenSql = N' Select Distinct n.NodeGUID '
									+ N',n.ParentGUID '
									+ N',n.ParentGUID '
									+ N',n.Type '
									+ N',(@Depth + 1) AS Depth '
									+ N',n.IsShortcut '
									+ N',0 as IsDependent '
									+ N',n.Id '
									+ N',case when @includeCreatedBy = 1 then NULL '
									+ N'		else n.CreatedByUserId '
									+ N' end '
									+ N',n.ModifiedWhen'
									+ N',n.ApprovalStatus'
									+ N' ,n.HasCheckedInVersion'
									+ N' ,n.Name'
									+ N' ,0'
									+ N' ,case when n.Type In (4,64,1024,16384,262144,2097152,524288,16777216) then 1 ' 
									+ N'	  else 0 '	
									+ N'  end '
									+ N' ,n.FollowGUID '
									+ N' ,n.TemplateGUID '
									+ N' ,n.PageDefinitionGUID '
									
				+ N' FROM Node as n, ' + @HierTable + N' as et '
				+ N' WHERE et.NodeGUID = n.ParentGUID '
				+ N' AND et.Depth = @Depth  '
				+ N' AND Not Exists '
				+ N'       ( Select 1 From ' + @ExcludeTable + N' as ex where ex.NodeGUID = n.NodeGUID ) ' 
				+ N' AND Not Exists '
				+ N'       ( Select 1 From ' + @HierTable + N' as ett where ett.NodeGUID = n.NodeGUID) '
				+ N' AND n.IsCheckedOutVersion = 0  '

If @containersOnly <> 0 And Rtrim(Lower(@GrowthPlan)) <> N'update'
Begin
	Set @SelectChildrenSql = @SelectChildrenSql + @ContainerRestriction
End

--Are we unioning the ChangeTable? 
--We do this to deal with deleted sub-hierarchies
If @IncludeDeletes <> 0
Begin
Set @UnionSql = N' Union '
				+ N' Select Distinct n.NodeGUID '
									+ N',n.ParentGUID '
									+ N',n.ParentGUID '
									+ N',n.Type '
									+ N',(@Depth + 1) AS Depth '
									+ N',n.IsShortcut '
									+ N',0 as IsDependent '
									+ N',0'
									+ N',NULL'
									+ N',n.LastChangeTime'
									+ N',NULL'
									+ N' ,NULL'
									+ N' ,n.Name'
									+ N' ,0'
									+ N' ,case when n.Type In (4,64,1024,16384,262144,2097152,524288,16777216) then 1 ' 
									+ N'	  else 0 '	
									+ N'  end '
									+ N' ,n.FollowGUID '
									+ N' ,n.TemplateGUID '
									+ N' ,n.PageDefinitionGUID '
									
				+ N' FROM ChangeTable as n, ' + @HierTable + N' as et '
				+ N' WHERE et.NodeGUID = n.ParentGUID '
				+ N' AND et.Depth = @Depth  '
				+ N' And n.Reason = ' + @DeleteReason
				+ N' AND Not Exists '
				+ N'       ( Select 1 From ' + @ExcludeTable + N' as ex where ex.NodeGUID = n.NodeGUID ) ' 
				+ N' AND Not Exists '
				+ N'       ( Select 1 From ' + @HierTable + N' as ett where ett.NodeGUID = n.NodeGUID) '
				
	If @containersOnly <> 0 And Rtrim(Lower(@GrowthPlan)) <> N'update'
	Begin
		Set @UnionSql = @UnionSql + @ContainerRestriction
	End
				
	Set @SelectChildrenSql = @SelectChildrenSql + @UnionSql
End
				
Set @UpdateChildrenSql = N' Update '+ @HierTable + N' Set Depth = (@Depth + 1) '
						+N' Where Exists (Select 1 from ' + @HierTable + ' as p '
						+N'	Where p.NodeGUID = ' + @HierTable+N'.ParentGUID '
						+N'	And p.Depth = @Depth) '	
								

/*
* Fill in Children of the selected nodes
* We are starting at the top a hierarchy (Depth = 0) and moving down
* We could be updating existing rows or adding new ones from Node table.
*/
If Rtrim(Lower(@GrowthPlan)) = N'insert'
Begin
	Set @IterateSql = @InsertChildrenSql + @SelectChildrenSql
End
Else If Rtrim(Lower(@GrowthPlan)) = N'update'
Begin
	Set @IterateSql = @UpdateChildrenSql
End
Else --both
Begin
	Set @IterateSql = @UpdateChildrenSql + @InsertChildrenSql + @SelectChildrenSql
End



Exec sp_executesql @GetCountSql,N'@count int out',@rows_affected out
Set @Depth = 0
While @rows_affected > 0
Begin
	Exec sp_executesql @IterateSql,N'@Depth int, @includeCreatedBy tinyint',@Depth, @includeCreatedBy
	Set @rows_affected = @@ROWCOUNT
	if @@error <> 0
		return @@error
	Set @Depth = @Depth + 1
End

return @return_status

GO

GRANT EXEC ON dbo.sd_CreateSubHier TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'sd_DropExportTables')
	BEGIN
		PRINT 'Dropping Procedure sd_DropExportTables'
		DROP  Procedure  dbo.sd_DropExportTables
	END

GO

PRINT 'Creating Procedure sd_DropExportTables'
GO
CREATE Procedure dbo.sd_DropExportTables
	(
	@suffix nchar(38)
	)
with encryption
AS
begin

	Declare @ExportTable nvarchar(100),@DropExportTable nvarchar(50)
			,@ExcludeTable nvarchar(100),@DropExcludeTable nvarchar(50)
			,@FailTable nvarchar(100), @DropFailTable nvarchar(50)
			,@MissingLinkTable nvarchar(100),@DropMissingTable nvarchar(50)
			,@ConfigTable nvarchar(100),@DropConfigTable nvarchar(50)
			,@TempTable nvarchar(100),@DropTempTable nvarchar(50)


	Set @ExportTable		= N'##ExportedNode' + IsNull(@Suffix,N'')
	Set @ExcludeTable		= N'##ExcludedNode' + IsNull(@Suffix,N'')
	Set @FailTable			= N'##FailedNode'		+ IsNull(@Suffix,N'')
	Set @MissingLinkTable	= N'##MissingLink'	+ IsNull(@Suffix,N'')
	Set @ConfigTable		= N'##Config'		+ IsNull(@Suffix,N'')
	Set @TempTable			= N'##TempHier'		+ IsNull(@Suffix,N'')

	Set @DropExportTable = N'Drop table ' + @ExportTable
	Set @DropExcludeTable = N'Drop table ' + @ExcludeTable
	Set @DropMissingTable = N'Drop table ' + @MissingLinkTable
	Set @DropConfigTable = N'Drop table ' + @ConfigTable
	Set @DropTempTable = N'Drop table ' + @TempTable

	if exists (select 1 from tempdb..sysobjects
		where name = @ExcludeTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropExcludeTable
	End

	if exists (select 1 from tempdb..sysobjects
		where name = @FailTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropFailTable
	End

	if exists (select 1 from tempdb..sysobjects
		where name = @ExportTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropExportTable
	End

	if exists (select 1 from tempdb..sysobjects
		where name = @ConfigTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropConfigTable
	End

	if exists (select 1 from tempdb..sysobjects
		where name = @MissingLinkTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropMissingTable
	End

	if exists (select 1 from tempdb..sysobjects
		where name = @TempTable
		and type = 'U' and uid = user_id())
	Begin
		exec sp_executesql @DropTempTable
	End

	return 0

end
GO

GRANT EXEC ON dbo.sd_DropExportTables TO PUBLIC

GO


/* 
 * File: failednodes.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_FailedNodes'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_FailedNodes
go
/* Purpose: FailedNodes populates the FailedNode table.
 * These are nodes which were originally included, but by the
 * time the export was run, they could not be found.
 * Input:
 * The ExportedNode table must already its NodeGUID column populated
 * and all children populated so that an attempt has been
 * made to update the NodeId column.
 * Failed nodes are identified by having a null or zero NodeId column
 * These nodes are MOVED to the ##FailedNode table.
 *
 */
CREATE PROC dbo.sd_FailedNodes (@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

-- Miscellaneous data
Declare
	@ExportTable nvarchar(100),
	@FailTable nvarchar(100),
	@Depth int,
	@rows_affected int,
	@DynamicSql nvarchar(1000),
	@DeleteReason nchar(1),
	@return_status int
	
--Delete Reason code
Set @DeleteReason = N'2'

Set @FailTable		= RTRIM(N'##FailedNode' + IsNull(@Suffix,N''))
Set @ExportTable	= RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))


Set @DynamicSql = N' INSERT INTO ' + @FailTable + N'(NodeGUID,Type,IsShortcut,ParentGUID,CurrentParentGUID,LastModified,Name,Location) '
				+ N' SELECT NodeGUID,Type,IsShortcut,ParentGUID,ParentGUID,LastModified,Name,Location '
				+ N' FROM ' + @ExportTable
				+ N' WHERE IsNull(NodeId, 0) = 0 '
				+ N' And IsNull(Reason, 0) < ' + @DeleteReason
Exec sp_executesql @DynamicSql
if @@error <> 0 
	return @@error

--exclude postings that do not have an approved version of a page
Set @DynamicSql = N' INSERT INTO ' + @FailTable + N'(NodeGUID,Type,IsShortcut,ParentGUID,CurrentParentGUID,LastModified,Name,Location) '
				+ N' SELECT NodeGUID,Type,IsShortcut,ParentGUID,ParentGUID,LastModified,Name,Location '
				+ N' FROM ' + @ExportTable + N' en'
				+ N' WHERE IsNull(en.Reason, 0) < ' + @DeleteReason
				+ N' and en.Type = 16 and en.IsShortcut = 1 '
				+ N' And not exists '
				+ N' (select 1 from dbo.Node n'
				+ N' where n.NodeGUID = en.FollowGUID '
				+ N' and n.IsCheckedOutVersion = 0) '
				+ N' And not exists '
				+ N' (select 1 from ' + @FailTable + N' ft'
				+ N' where ft.NodeGUID = en.NodeGUID) '
				
Exec sp_executesql @DynamicSql
if @@error <> 0 
	return @@error

--exclude postings that do not have an approved version of a template
Set @DynamicSql = N' INSERT INTO ' + @FailTable + N'(NodeGUID,Type,IsShortcut,ParentGUID,CurrentParentGUID,LastModified,Name,Location) '
				+ N' SELECT NodeGUID,Type,IsShortcut,ParentGUID,ParentGUID,LastModified,Name,Location '
				+ N' FROM ' + @ExportTable + N' en'
				+ N' WHERE IsNull(en.Reason, 0) < ' + @DeleteReason
				+ N' and en.Type = 16 and en.IsShortcut = 1 '
				+ N' And not exists '
				+ N' (select 1 from dbo.Node n'
				+ N' where n.NodeGUID = en.TemplateGUID '
				+ N' and n.IsCheckedOutVersion = 0) '
				+ N' And not exists '
				+ N' (select 1 from ' + @FailTable + N' ft'
				+ N' where ft.NodeGUID = en.NodeGUID) '
				
Exec sp_executesql @DynamicSql
if @@error <> 0 
	return @@error
	
--exclude postings that do not have an approved version of a page definition
Set @DynamicSql = N' INSERT INTO ' + @FailTable + N'(NodeGUID,Type,IsShortcut,ParentGUID,CurrentParentGUID,LastModified,Name,Location) '
				+ N' SELECT NodeGUID,Type,IsShortcut,ParentGUID,ParentGUID,LastModified,Name,Location '
				+ N' FROM ' + @ExportTable + N' en'
				+ N' WHERE IsNull(en.Reason, 0) < ' + @DeleteReason
				+ N' and en.Type = 16 and en.IsShortcut = 1 '
				+ N' And not exists '
				+ N' (select 1 from dbo.Node template'
				+ N' inner join dbo.Node pagedef '
				+ N' on template.PageDefinitionGUID = pagedef.NodeGUID '
				+ N' where template.NodeGUID = en.TemplateGUID '
				+ N' and template.IsCheckedOutVersion = 0 '
				+ N' and pagedef.IsCheckedOutVersion = 0) '
				+ N' And not exists '
				+ N' (select 1 from ' + @FailTable + N' ft'
				+ N' where ft.NodeGUID = en.NodeGUID) '
				
Exec sp_executesql @DynamicSql
if @@error <> 0 
	return @@error
		
Set @DynamicSql = N' DELETE from ' + @ExportTable 
				+ N' WHERE NodeGUID in'
				+ N' (select NodeGUID from ' + @FailTable + N' )'
								
Exec sp_executesql @DynamicSql
if @@error <> 0 
	return @@error

Exec @return_status = dbo.sd_CalculateLocation @FailTable
if @return_status <> 0
	return @return_status

Set @DynamicSql = N' Update ' + @FailTable
						+ N' Set Name				= Coalesce(Node.Name,Node.DisplayName,page.Name)'
					+ N' From ' + @FailTable + N' en '
					+ N' inner join Node Node on en.NodeGUID = Node.NodeGUID and Node.IsCheckedOutVersion = 0'
					+ N' and en.Type = 16 and en.IsShortcut = 1'
					+ N' left join Node page'
					+ N' on Node.FollowGUID = page.NodeGUID'
Exec sp_executesql @DynamicSql

if @@error <> 0
	return (@@error)
	
return @@error

GO

GRANT EXEC ON dbo.sd_FailedNodes TO PUBLIC

GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'sd_FillBrokenLinks')
	BEGIN
		PRINT 'Dropping Procedure sd_FillBrokenLinks'
		DROP  Procedure  dbo.sd_FillBrokenLinks
	END

GO

PRINT 'Creating Procedure sd_FillBrokenLinks'
GO
CREATE Procedure dbo.sd_FillBrokenLinks
	(
		@suffix	nvarchar(100) = Null
	)
with encryption
AS
begin

	set nocount on
	
	declare
		@ExportTable nvarchar(100),
		@MissingLinkTable nvarchar(100),
		@sql nvarchar(1000)
		
	Set @ExportTable		= RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
	Set @MissingLinkTable	= RTRIM(N'##MissingLink'	+ IsNull(@Suffix,N''))
	
	set @sql = 
	N'update ' + @ExportTable
	+ N' set HasBrokenLinks = 1'
	+ N' where NodeId in'
	+ N' (select en.NodeId from ' + @ExportTable + ' en'
	+ N' inner join NodeResource nr'
	+ N' on en.NodeId = nr.NodeId'
	+ N' and nr.IsLink = 1'
	+ N' and nr.NodeGUID is not null'
	+ N' where not exists'
	+ N' (select NodeGUID from ' + @ExportTable + ' et'
	+ N' where et.NodeGUID = nr.NodeGUID))'
	
	exec sp_executesql @sql
	if @@error <> 0
		return (@@error)
		
	set @sql = 	
	N'insert into ' + @MissingLinkTable
	+ N' (NodeGUID, SourceNodeGuid, Type, IsShortcut, Name)'
	+ N' select t.NodeGUID, s.NodeGUID, t.Type, t.IsShortcut, IsNull(t.Name, p.Name)'	
	+ N' from ' + @ExportTable + ' s inner join Node n '
	+ N' on s.NodeId = n.Id'
	+ N' and s.HasBrokenLinks = 1'
	+ N' inner join NodeResource nr'
	+ N' on n.Id = nr.NodeId'
	+ N' and nr.IsLink = 1'
	+ N' and nr.NodeGUID is not null'
	+ N' and not exists('
	+ N' select NodeGUID from ' + @ExportTable + ' et'
	+ N' where et.NodeGUID = nr.NodeGUID)'
	+ N' inner join Node t'	
	+ N' on nr.NodeGUID = t.NodeGUID'
	+ N' and t.IsCheckedOutVersion = 0'
	+ N' left join Node p'
	+ N' on t.FollowGUID = p.NodeGUID'
	+ N' and p.IsCheckedOutVersion = 0'
	+ N' and t.Type = 16 and t.IsShortcut = 1'

	exec sp_executesql @sql
	if @@error <> 0
		return (@@error)
		
end

GO

GRANT EXEC ON dbo.sd_FillBrokenLinks TO PUBLIC

GO


/* 
 * File: FillExcludedNodes.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_FillExcludedNodes'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_FillExcludedNodes
go
/* Purpose: FillExcludedNodes is a stored procedure for populating a table of nodes
 * to be excluded from an export operation.
 * Input:
 * The ExcludedNode table must already its NodeGUID column populated with
 * guids of excluded nodes.
 *
 */
CREATE PROC dbo.sd_FillExcludedNodes (@Suffix nchar(38) = Null )
with encryption
AS
set nocount on

Declare @ExcludeTable nvarchar(100)
		,@DynamicSql nvarchar(1000)

Set @ExcludeTable = RTRIM(N'##ExcludedNode' + IsNull(@Suffix,N''))
-- Miscellaneous data
Declare
	@Depth int,
	@rows_affected int

Set @DynamicSql = N'Select @count=Count(*) from ' + @ExcludeTable
Exec sp_executesql @DynamicSql,N'@count int out',@rows_affected out
Set @DynamicSql = 
	N'Insert into ' + @ExcludeTable + N'(NodeGUID,Type,IsShortcut,Depth,Name,NodeId) '
		+ N' Select distinct Node.NodeGUID '
				+ N',Node.Type '
				+ N',Node.IsShortcut '
				+ N',@Depth+1 AS Depth '
				+ N',Node.Name '
				+ N',Node.Id '
			+ N' FROM Node,' + @ExcludeTable + N' ex'
			+ N' WHERE ex.NodeGUID = Node.ParentGUID '
			+ N' AND ex.Depth = @Depth  '
			+ N' AND Not Exists (Select 1 From ' + @ExcludeTable + N' exx where exx.NodeGUID = Node.NodeGUID) '
			+ N' AND Node.IsCheckedOutVersion = 0  '
			+ N' AND Node.ApprovalStatus <> 2 '
Set @Depth = 1
While @rows_affected > 0
Begin
	Exec sp_executesql @DynamicSql,N'@Depth int',@Depth
	Set @rows_affected = @@ROWCOUNT
	Set @Depth = @Depth + 1
End

Exec dbo.sd_CalculateLocation @ExcludeTable

return 0

GO

GRANT EXEC ON dbo.sd_FillExcludedNodes TO PUBLIC

GO




/* 
 * File: FillExportedNodes.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_FillExportedNodes'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_FillExportedNodes
go
/* Purpose: FillExportedNodes populates a tree structure of nodes to be included 
 *			in an export operation. This is the main routine for staging data in
 *			the export process. Note that only Node data, not associated data,
 *			are processed here.
 *
 * PreCondition: ExportTable must be present.
 *              Either seed Node guids are already in the ExportTable 
 *				temporary table, or incremental deployment has been chosen.
 *				For incremental deployment, the @incremental parameter must 
 *				contain either a valid date/time,
 *				or contain the value 'lastdeploy' (case insensitive).
 *				For partial deployment to be included with the incremental,
 *				the guid of a channel should also be supplied. This restricts
 *				the incremental deployment to the (sub)hierarchy for which
 *				the ChannelGuid is the root.
 * param @includeOwners		indicates if owners are to be included
 * param @containersOnly	indicates whether only containers are to be exported
 * param @includeRightsGroups	indicates how and if rights groups are to be exported
 *								0 - Unknown
 *								1 - Do not include Rights Groups
 *								2 - Include Rights Groups without members
 *								4 - Include Rights Groups with members
 *								9 - Indicates that we are going to backup Rights Groups and members only
 *									NO OTHER WORK IS PERFORMED.
 * param @incremental		triggers incremental deployment
 * param @ChannenGuid		Causes partial deployment when @incremental is specified
 * param @Suffix			Table suffix for supporting multiple export operations
 */
CREATE PROC dbo.sd_FillExportedNodes(@includeCreatedBy	tinyint = 1
								,@containersOnly		int = 0
								,@includeRightsGroups	tinyint = 0
								,@incremental			nvarchar(30) = Null
								,@channelGuid			nchar(38) = Null
								,@suffix				nvarchar(100) = Null
								)
with encryption
AS
set nocount on

	
-- Miscellaneous data
Declare
	@NodeGUID nchar(38),
	@ParentGUID nchar(38),
	@Location nvarchar(3000),
	@path nvarchar(3000),
	@nodename nvarchar(250),
	@nodetype int,
	@Depth int,
	@newdepth int,
	@IsRecursive tinyint,
	@IsDependent tinyint,
	@HasBrokenLinks tinyint,
	@prev_size int,
	@new_size int,
	@rows_affected int,
	@return_status int,
	@ExportTable nvarchar(100),
	@ExcludeTable nvarchar(100),
	@FailTable nvarchar(100),
	@MissingLinkTable nvarchar(100),
	@TempTable nvarchar(100),
	@ServerNode nvarchar(6),
	@ContainersOnlySql nvarchar(4000),
	@NonContainersOnlySql nvarchar(4000),
	@UpdateBaseInfoSql nvarchar(4000)

--Default return Status
Set @return_status = 0
--Set all table names
Set @ServerNode = N'Server'
Set @ExportTable		= RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
Set @ExcludeTable		= RTRIM(N'##ExcludedNode' + IsNull(@Suffix,N''))
Set @FailTable			= RTRIM(N'##FailedNode'	+ IsNull(@Suffix,N''))
Set @MissingLinkTable	= RTRIM(N'##MissingLink'	+ IsNull(@Suffix,N''))
Set @TempTable			= RTRIM(N'##TempHier'		+ IsNull(@Suffix,N''))
/*		
		Node Types
	1			- Server
	2			- ????????????????
	4			- Channel
	16			- Page or Posting
	32			- ????????????????
	64			- Resource Gallery
	256			- Resource Gallery Item
	1024		- Control Gallery
	4096		- Control Gallery Item
	16384		- Template Gallery
	65536		- Template
	131072		- ???????????????
	262144		- User Directory
	524288		- User Role
	1048576		- Administrator
	2097152		- Folder
	4194304		- ???????????????
	8388608		- ???????????????
	16777216	- Page Definition Gallery
	33554432	- Page Definition
*/
			
					
Set @UpdateBaseInfoSql = N' Update ' + @ExportTable
						+ N' Set  Name					= case when Node.IsShortcut = 1 then '
						+ N'										coalesce(Node.Name, Node.DisplayName, Page.Name)'  	
						+ N'									else Node.Name'
						+ N'							  end '
						+ N' 	,ParentGUID				= Node.ParentGUID '
						+ N' 	,CurrentParentGuid		= Node.ParentGUID '
						+ N' 	,Type					= Node.Type '
						+ N' 	,IsShortcut				= Node.IsShortcut '
						+ N' 	,LastModified			= Node.ModifiedWhen '
						+ N' 	,ApprovalStatus			= Node.ApprovalStatus '
						+ N' 	,ApprovedVersionExists	= Node.HasCheckedInVersion '
						+ N' 	,NodeId					= Node.Id '
						+ N' 	,Depth					= 0 '
						+ N' 	,ExplicitlySelected		= 1 '
						+ N' 	,IsRecursive			= case when Node.Type In (4,64,1024,16384,262144,2097152,524288,16777216) then 1 ' 
						+ N'							  else 0 '	
						+ N'							  end '
						+ N' 	,FollowGUID				= Node.FollowGUID '
						+ N' 	,TemplateGUID			= Node.TemplateGUID '
						+ N' 	,PageDefinitionGUID		= Node.PageDefinitionGUID '
						+ N' 	,CreatedByUserId		= case when @includeCreatedBy = 1 then NULL '
						+ N'									else Node.CreatedByUserId'
						+ N'							  end '
						+ N' From ' + @ExportTable + N' en Inner Join Node on en.NodeGUID = Node.NodeGUID '
						+ N' and Node.IsCheckedOutVersion = 0'
						+ N' Left Join Node Page on Node.FollowGUID = Page.NodeGUID '
						+ N' and page.IsCheckedOutVersion = 0'

--++++++++++++++++++++++++++++++NOW START++++++++++++++++++++++++++++++++++++++++

/************************Rights Group/User Backup********************************
 * If doing RightsGroup and User backup, we do the Rights Group work here 
 * and then bail.
 */
If @includeRightsGroups = 9
Begin
	Exec @return_status = dbo.sd_GetRightsGroups @includeRightsGroups, @includeCreatedBy, @suffix
	if @return_status <> 0
		return @return_status
	
	Exec @return_status = dbo.sd_CalculateLocation @ExportTable

	return @return_status
End

/*************************Incremental Search******************************
 * If doing incremental deployment, then we seed the export table here
 */
If @incremental Is Not Null
Begin
	Set @containersOnly = 0
	Exec @return_status = dbo.sd_IncrementalSearch @incremental, @channelGuid, @includeCreatedBy, @suffix
	If @return_status <> 0
		return @return_status
end		
else
begin
	/***************************Update BaseInfo of Seeded Nodes*************************************
	* Update ExportedNode columns, at this point we only expect the guids,Name,...
	* to be there.
	*/
	Exec sp_executesql @UpdateBaseInfoSql, N'@includeCreatedBy tinyint', @includeCreatedBy
	if @@error <> 0
		return (@@error)
end

/**************************Update Depths/Descendents*****************************
* Get Children and/or update the depths of seeded nodes
*/
If @incremental Is Null
Begin
	--For the non-incremental case, we want to insert descendents and update the depths
	--Exec @return_status = sd_CreateSubHier @containersOnly,N'both',@ExportTable,0,@Suffix
	Exec @return_status = dbo.sd_CreateSubHier @containersOnly, N'insert', @ExportTable, 0, @includeCreatedBy, @Suffix
	If @return_status <> 0
		return @return_status
End

	
/**************************Failed Nodes***************************************
 * Failed nodes are nodes that have been seeded, but for some Reason are no
 * longer in the database.
 */
--Now check for failed nodes
Exec @return_status = dbo.sd_FailedNodes @Suffix
If @return_status <> 0
	return @return_status

/*****************************Dependency Nodes************************************
 * Get dependency nodes. Note that the order is important.
 * The order is determined by increasing independence.
 * e.g. pages depend on templates and resources; templates depend on page definitions
 * Postings depend on everything. Channels depend on Cover Pages and nav. templates.
 */
If @containersOnly = 0
Begin	
	--Load CoverPages
	Exec @return_status = dbo.sd_GetCoverPages @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
	
	--Load dependent pages
	Exec @return_status = dbo.sd_GetPages @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
	
	--Load dependent templates
	Exec @return_status = dbo.sd_GetTemplates @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
	
	--Load dependent Page Definitions
	Exec @return_status = dbo.sd_GetPageDefinitions @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
	
	--Load dependent resources
	Exec @return_status = dbo.sd_GetResources @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
	
End
Else
Begin
	--Load CoverPages
	Exec @return_status = dbo.sd_GetCoverPages @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
End

/*********************Rights Groups*****************************
 * If not a backup but Rights Groups are included
 */
--Get rights groups if specified
If @includeRightsGroups in (2,4)
Begin
	Exec @return_status = dbo.sd_GetRightsGroups @includeRightsGroups, @includeCreatedBy, @Suffix
	if @return_status <> 0
		return @return_status
End

/************************Update Base Info of Descendents********************************
 * We copy all necessary information when populating ExportedNode table, 
   but still need to fix null posting names
 */
Declare @UpdateBaseInfo nvarchar(1000)
Set @UpdateBaseInfo = N' Update ' + @ExportTable
						+ N' Set Name				= Coalesce(Node.Name,Node.DisplayName,page.Name)'
					+ N' From ' + @ExportTable + N' en '
					+ N' inner join Node Node on en.NodeGUID = Node.NodeGUID and Node.IsCheckedOutVersion = 0'
					+ N' and en.Type = 16 and en.IsShortcut = 1'
					+ N' left join Node page'
					+ N' on en.FollowGUID = page.NodeGUID'
					+ N' and page.IsCheckedOutVersion = 0'
Exec sp_executesql @UpdateBaseInfo

if @@error <> 0
	return (@@error)

/******************************Dependent Ancestry****************************
 * Now we must add dependent Node ancestory
 * However, this time we don't know the starting Depth 
 * because we are going from the bottom up for an indeterminate length.
*/
Declare @AddDependentAncestry nvarchar(2000)

Set @AddDependentAncestry = N' Insert Into ' + @ExportTable 
							+ N'(NodeGUID '
							+ N',ParentGUID '
							+ N',Depth '
							+ N',Type '
							+ N',IsShortcut '
							+ N',IsRecursive '
							+ N',IsDependent '
							+ N',ExplicitlySelected '
							+ N',CreatedByUserId'
							+ N',LastModified '
							+ N',ApprovalStatus '
							+ N',ApprovedVersionExists '
							+ N',Name '
							+ N',CurrentParentGuid '
							+ N',NodeId '
							+ N' ,FollowGUID'
							+ N' ,TemplateGUID'
							+ N' ,PageDefinitionGUID) '
							
					+ N' Select distinct Node.NodeGUID '
							+ N',Node.ParentGUID  '
							+ N',0 AS Depth '
							+ N',Node.Type '
							+ N',Node.IsShortcut '
							+ N',0 AS IsRecursive '
							+ N',1 AS IsDependent '
							+ N',0 As ExplicitlySelected '
							+ N',case when @includeCreatedBy = 1 then NULL '
							+ N'		else Node.CreatedByUserId '
							+ N' end '
							+ N',Node.ModifiedWhen '
							+ N',Node.ApprovalStatus '
							+ N',Node.HasCheckedInVersion '
							+ N',Node.Name '
							+ N',Node.ParentGUID  '
							+ N',Node.Id '
							+ N',Node.FollowGUID '
							+ N',Node.TemplateGUID '
							+ N',Node.PageDefinitionGUID '
						+ N' from Node where' 
						+ N' Node.IsCheckedOutVersion = 0 And Node.Type <> 1'
						+ N' and NodeGUID in' 
						+ N' (SELECT ParentGUID FROM '+ @ExportTable + N' en'
						+ N' where en.IsDependent = 1)'
						+ N' AND Not Exists' 
						+ N' ( SELECT 1 FROM ' + @ExportTable + N' enn' 
						+ N' Where enn.NodeGUID = Node.NodeGUID )'							
							
--Now add ancestry until there is no more to add
Set @rows_affected = 1
While @rows_affected <> 0
Begin		
	Exec sp_executesql @AddDependentAncestry, N'@includeCreatedBy tinyint', @includeCreatedBy
	Set @rows_affected = @@ROWCOUNT
	if @@error <> 0
		return @@error
End



/*************************Calculate Locations*******************************
 * Calculate the locations for all nodes
 */
Exec @return_status = dbo.sd_CalculateLocation @ExportTable
if @return_status <> 0
	return @return_status
	

/************************************************************************
 * Find nodes that have broken links and fill MissingLink table
 */
Exec @return_status = dbo.sd_FillBrokenLinks @Suffix


return @return_status


GO

GRANT EXEC ON dbo.sd_FillExportedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GenerateExportStatistics')
	BEGIN
		PRINT 'Dropping Procedure GenerateExportStatistics'
		DROP  Procedure  dbo.GenerateExportStatistics
	END

GO

PRINT 'Creating Procedure GenerateExportStatistics'
GO

create procedure dbo.GenerateExportStatistics
			(
			@Suffix nchar(38) = Null
			)
with encryption
as
begin
	set nocount on

	Declare @ExportTable nvarchar(100)
			,@DynamicSql nvarchar(4000)

	Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

	declare @channels int
			,@postings int
			,@folders int
			,@pages int
			,@resource_galleries int
			,@resources int
			,@template_galleries int
			,@templates int
			,@pagedef_galleries int
			,@pagedefs int
			,@rights_groups int

	

	set @DynamicSql = 
		N'select @channels = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 4'
	Exec sp_executesql @DynamicSql, N'@channels int output', @channels output
	
	
	set @DynamicSql = 
		N'select @postings = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 16 and IsShortcut = 1'
	Exec sp_executesql @DynamicSql, N'@postings int output', @postings output
	
	set @DynamicSql = 
		N'select @folders = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 2097152'
	Exec sp_executesql @DynamicSql, N'@folders int output', @folders output

	set @DynamicSql = 
		N'select @pages = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 16 and IsShortcut = 0'
	Exec sp_executesql @DynamicSql, N'@pages int output', @pages output

	set @DynamicSql = 
		N'select @resource_galleries = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 64'
	Exec sp_executesql @DynamicSql, N'@resource_galleries int output', @resource_galleries output

	set @DynamicSql = 
		N'select @resources = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 256'
	Exec sp_executesql @DynamicSql, N'@resources int output', @resources output

	set @DynamicSql = 
		N'select @template_galleries = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 16384'
	Exec sp_executesql @DynamicSql, N'@template_galleries int output', @template_galleries output

	set @DynamicSql = 
		N'select @templates = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 65536'
	Exec sp_executesql @DynamicSql, N'@templates int output', @templates output

	set @DynamicSql = 
		N'select @pagedef_galleries = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 16777216'
	Exec sp_executesql @DynamicSql, N'@pagedef_galleries int output', @pagedef_galleries output

	set @DynamicSql = 
		N'select @pagedefs = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 33554432'
	Exec sp_executesql @DynamicSql, N'@pagedefs int output', @pagedefs output

	set @DynamicSql = 
		N'select @rights_groups = count(*)'
		+ N' from ' + @ExportTable
		+ N' where Type = 1048576'
	Exec sp_executesql @DynamicSql, N'@rights_groups int output', @rights_groups output

	
	select @channels
			, @postings
			, @folders
			, @pages
			, @resource_galleries
			, @resources
			, @template_galleries
			, @templates
			, @pagedef_galleries
			, @pagedefs
			,@rights_groups
end


GO

GRANT EXEC ON dbo.GenerateExportStatistics TO PUBLIC

GO


/* 
 * File: GetPages.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetCoverPages'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetCoverPages
go
/* Purpose: GetCoverPages gets all cover pages for channels being exported.
 *
 */
CREATE PROC dbo.sd_GetCoverPages (@includeCreatedBy tinyint
								  ,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100)
		,@DynamicSql nvarchar(4000)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

--Load cover pages for channels being exported
Set @DynamicSql = N'Insert Into ' + @ExportTable + N'(NodeGUID'
					+ N' ,ParentGUID'
					+ N' ,CurrentParentGuid'
					+ N' ,Type'
					+ N' ,Depth'
					+ N' ,IsShortcut'
					+ N' ,IsDependent'
					+ N' ,NodeId'
					+ N' ,CreatedByUserId'
					+ N' ,LastModified'
					+ N' ,ApprovalStatus'
					+ N' ,ApprovedVersionExists'
					+ N' ,ExplicitlySelected'
					+ N' ,IsRecursive '
					+ N' ,FollowGUID'
					+ N' ,TemplateGUID'
					+ N' ,PageDefinitionGUID) '
					
	+ N' SELECT DISTINCT Posting.NodeGUID '
					+ N',Posting.ParentGUID '
					+ N',Posting.ParentGUID '
					+ N',Posting.Type '
					+ N',0 as Depth '
					+ N',Posting.IsShortcut '
					+ N',1 as IsDependent '
					+ N',Posting.Id '
					+ N',case when @includeCreatedBy = 1 then NULL '
					+ N'		else Posting.CreatedByUserId '
					+ N' end '					
					+ N',Posting.ModifiedWhen'
					+ N',Posting.ApprovalStatus'
					+ N' ,Posting.HasCheckedInVersion'
					+ N' ,0'
					+ N' ,0'
					+ N' ,Posting.FollowGUID '
					+ N' ,Posting.TemplateGUID '
					+ N' ,Posting.PageDefinitionGUID '
					
    + N' FROM ' + @ExportTable + N' en inner join Node Channel '
    + N' on en.NodeGUID = Channel.NodeGUID '
    + N' and en.Type = 4 '
    + N' and Channel.Type = 4 '
    + N' inner join NodeProperty np '
    + N' on channel.Id = np.Id '
    + N' and np.PropName = ''_CoverPageURL'' '
    + N' inner join Node posting '
    + N' on LTrim(np.PropValue) = posting.NodeGUID '
    + N' and posting.Type = 16 '
    + N' and posting.IsCheckedOutVersion = 0 '
    + N' AND Not Exists '
    + N' ( SELECT 1 FROM ' + @ExportTable + N' enn '
    + N' Where enn.NodeGUID = Posting.NodeGUID )'

Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy

return(@@error)

GO

GRANT EXEC ON dbo.sd_GetCoverPages TO PUBLIC

GO


/* 
 * File: GetPages.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetPageDefinitions'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetPageDefinitions 
go
/* Purpose: GetPages is a stored procedure which returns a hierarchy
 * as follows:
 * Input:
 *
 */
CREATE PROC dbo.sd_GetPageDefinitions(@includeCreatedBy tinyint
									  ,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100)
		,@DynamicSql nvarchar(4000)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

--Load dependent page definitions
Set @DynamicSql = N'Insert into ' + @ExportTable + N'(NodeGUID'
					+ N' ,ParentGUID'
					+ N' ,CurrentParentGuid'
					+ N' ,Type'
					+ N' ,Depth'
					+ N' ,IsShortcut'
					+ N' ,IsDependent'
					+ N' ,NodeId'
					+ N' ,CreatedByUserId'
					+ N' ,LastModified'
					+ N' ,ApprovalStatus'
					+ N' ,ApprovedVersionExists'
					+ N' ,Name '
					+ N' ,ExplicitlySelected'
					+ N' ,IsRecursive '
					+ N' ,FollowGUID'
					+ N' ,TemplateGUID'
					+ N' ,PageDefinitionGUID) '

	+ N' SELECT DISTINCT PageDefinitionNode.NodeGUID '
					+ N',PageDefinitionNode.ParentGUID '
					+ N',PageDefinitionNode.ParentGUID '
					+ N',PageDefinitionNode.Type '
					+ N',0 as Depth '
					+ N',PageDefinitionNode.IsShortcut '
					+ N',1 as IsDependent '
					+ N',PageDefinitionNode.Id '
					+ N',case when @includeCreatedBy = 1 then NULL '
					+ N'		else PageDefinitionNode.CreatedByUserId '
					+ N' end '
					+ N',PageDefinitionNode.ModifiedWhen'
					+ N',PageDefinitionNode.ApprovalStatus'
					+ N' ,PageDefinitionNode.HasCheckedInVersion'
					+ N' ,PageDefinitionNode.Name'
					+ N' ,0'
					+ N' ,0'
					+ N' ,PageDefinitionNode.FollowGUID'
					+ N' ,PageDefinitionNode.TemplateGUID'
					+ N' ,PageDefinitionNode.PageDefinitionGUID '
					
		+ N' FROM Node PageDefinitionNode inner join ' + @ExportTable + N' en '
        + N' on en.PageDefinitionGUID = PageDefinitionNode.NodeGUID '
		+ N' AND PageDefinitionNode.IsCheckedOutVersion = 0 '
        + N' Where Not Exists ( SELECT 1 FROM ' + @ExportTable + N' enn where enn.NodeGUID = PageDefinitionNode.NodeGUID)  '
		
Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy
if @@error <> 0
	return @@Error


Set @DynamicSql = N'Insert into ' + @ExportTable 
				+ N'(NodeGUID,ParentGUID,CurrentParentGuid, Type,Depth,IsShortcut,IsDependent,'
				+ N' NodeId, ExplicitlySelected, IsRecursive, Name, Reason, IsDeleted'
				+ N' ,FollowGUID'
				+ N' ,TemplateGUID'
				+ N' ,PageDefinitionGUID) '
		+ N' SELECT PageDefinitionNode.NodeGUID '
		+ N' ,PageDefinitionNode.ParentGUID '
		+ N' ,PageDefinitionNode.ParentGUID '
		+ N' ,PageDefinitionNode.Type '
		+ N' ,0 AS Depth '
		+ N' ,PageDefinitionNode.IsShortcut '
		+ N' ,1 AS IsDependent '
		+ N' ,0, 0, 0 '
		+ N' ,PageDefinitionNode.Name'
		+ N' ,PageDefinitionNode.Reason '
		+ N' ,1 '
		+ N' ,PageDefinitionNode.FollowGUID'
		+ N' ,PageDefinitionNode.TemplateGUID'
		+ N' ,PageDefinitionNode.PageDefinitionGUID '
		
		+ N' from ChangeTable PageDefinitionNode '
		+ N' where PageDefinitionNode.NodeGUID in '
		+ N' ( select Template.PageDefinitionGUID '
		+ N' from ' + @ExportTable + N' en inner join ChangeTable posting'
		+ N' on en.NodeGUID = posting.NodeGUID '
		+ N' and posting.Reason = 2 '
		+ N' inner join ChangeTable Template'
		+ N' on Template.NodeGUID = Posting.TemplateGUID'
		+ N' and Template.Reason = 2 )'
		+ N' and PageDefinitionNode.Reason = 2 '
		+ N' and not exists '
		+ N' (SELECT 1 from ' + @ExportTable + N' enn Where enn.NodeGUID = PageDefinitionNode.NodeGUID)'
		
Exec sp_executesql @DynamicSql

return(@@error)

GO

GRANT EXEC ON dbo.sd_GetPageDefinitions TO PUBLIC

GO


/* 
 * File: GetPages.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetPages'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetPages
go
/* Purpose: GetPages is a stored procedure which returns a hierarchy
 * as follows:
 * Input:
 *
 */
CREATE PROC dbo.sd_GetPages (@includeCreatedBy tinyint
							,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100)
		,@DynamicSql nvarchar(4000)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

--Load dependent pages
Set @DynamicSql = N'Insert into ' + @ExportTable + N'(NodeGUID'
					+ N' ,ParentGUID'
					+ N' ,CurrentParentGuid'
					+ N' ,Type'
					+ N' ,Depth'
					+ N' ,IsShortcut'
					+ N' ,IsDependent'
					+ N' ,NodeId'
					+ N' ,CreatedByUserId'
					+ N' ,LastModified'
					+ N' ,ApprovalStatus'
					+ N' ,ApprovedVersionExists'
					+ N' ,ExplicitlySelected'
					+ N' ,IsRecursive '
					+ N' ,Name '
					+ N' ,Reason '
					+ N' ,FollowGUID'
					+ N' ,TemplateGUID'
					+ N' ,PageDefinitionGUID) '
					
		+ N' SELECT PageNode.NodeGUID '
					+ N',PageNode.ParentGUID '
					+ N',PageNode.ParentGUID '
					+ N',PageNode.Type '
					+ N',0 as Depth '
					+ N',PageNode.IsShortcut '
					+ N',1 as IsDependent '
					+ N',PageNode.Id '
					+ N',case when @includeCreatedBy = 1 then NULL '
					+ N'		else PageNode.CreatedByUserId '
					+ N' end '
					+ N',PageNode.ModifiedWhen'
					+ N',PageNode.ApprovalStatus'
					+ N' ,PageNode.HasCheckedInVersion'
					+ N' ,0'
					+ N' ,0'
					+ N' ,PageNode.Name'
					+ N' ,NULL'	
					+ N' ,PageNode.FollowGUID'
					+ N' ,PageNode.TemplateGUID'
					+ N' ,PageNode.PageDefinitionGUID '
						
			+ N' from Node PageNode'
			+ N' where PageNode.IsCheckedOutVersion = 0'
			+ N' and PageNode.Type = 16'
			+ N' and PageNode.IsShortcut = 0'
			+ N' and exists'
			+ N' (select 1 from ' + @ExportTable + N' en'
			+ N' where en.FollowGUID = PageNode.NodeGUID)'
			+ N' and not exists'
			+ N' (SELECT 1 from ' + @ExportTable + N' enn Where enn.NodeGUID = PageNode.NodeGUID)'

Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy 
if @@error <> 0
	return @@Error
	
Set @DynamicSql = N'Insert into ' + @ExportTable 
				+ N'(NodeGUID,ParentGUID,CurrentParentGuid, Type,Depth,IsShortcut,IsDependent '
				+ N' ,NodeId, ExplicitlySelected, IsRecursive, Name, Reason, IsDeleted
					, FollowGUID, TemplateGUID, PageDefinitionGUID) '
		+ N' SELECT Page.NodeGUID '
		+ N' ,Page.ParentGUID '
		+ N' ,Page.ParentGUID '
		+ N' ,Page.Type '
		+ N' ,0 AS Depth '
		+ N' ,Page.IsShortcut '
		+ N' ,1 AS IsDependent '
		+ N' ,0, 0, 0 '
		+ N' ,Page.Name'
		+ N' ,Page.Reason '
		+ N' ,1'
		+ N' ,Page.FollowGUID'
		+ N' ,Page.TemplateGUID'
		+ N' ,Page.PageDefinitionGUID '
		
		+ N' from ChangeTable Page '
		+ N' where Page.NodeGUID in '
		+ N' ( select posting.FollowGUID '
		+ N' from ' + @ExportTable + N' en inner join ChangeTable posting'
		+ N' on en.NodeGUID = posting.NodeGUID '
		+ N' and posting.Reason = 2 ) '
		+ N' and Page.Reason = 2 '
		+ N' and not exists '
		+ N' (SELECT 1 from ' + @ExportTable + N' enn Where enn.NodeGUID = Page.NodeGUID)'
		
				
Exec sp_executesql @DynamicSql

return(@@error)

GO

GRANT EXEC ON dbo.sd_GetPages TO PUBLIC

GO


/* 
 * File: GetResources.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetResources'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetResources
go
/* Purpose: GetResource is a stored procedure which updates ##ExortedNode 
 * with resources as dependent objects.
 * Input:
 *	@ArchiveFolder		Guid of ArchiveFolder ... only needed if want to override
 */
CREATE PROC dbo.sd_GetResources(@includeCreatedBy tinyint
							    ,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

Declare @ArchiveFolder nvarchar(250)
		,@ExportTable nvarchar(100)
		,@DynamicSql nvarchar(4000)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

--Get the ArhiveFolder guid
Set @ArchiveFolder = (select PropValue
						from Node,NodeProperty
						where Node.Id=NodeProperty.NodeId
						and Node.Type=1
						and PropName='_ArchiveFolder')


--Raise error if could not find ArchiveFolder guid
If (@ArchiveFolder Is Null)
Begin
	RAISERROR ('Archive Folder Not Found',16,1)
End

Set @DynamicSql = 
		N'Insert into ' + @ExportTable + N'(NodeGUID'
					+ N' ,ParentGUID'
					+ N' ,CurrentParentGuid'
					+ N' ,Type'
					+ N' ,Depth'
					+ N' ,IsShortcut'
					+ N' ,IsDependent'
					+ N' ,NodeId'
					+ N' ,CreatedByUserId'
					+ N' ,LastModified'
					+ N' ,ApprovalStatus'
					+ N' ,ApprovedVersionExists'
					+ N' ,Name '
					+ N' ,ExplicitlySelected'
					+ N' ,IsRecursive) '
		
		+ N' SELECT DISTINCT  ResourceNode.NodeGUID '
					+ N',ResourceNode.ParentGUID '
					+ N',ResourceNode.ParentGUID '
					+ N',ResourceNode.Type '
					+ N',0 as Depth '
					+ N',ResourceNode.IsShortcut '
					+ N',1 as IsDependent '
					+ N',ResourceNode.Id '
					+ N',case when @includeCreatedBy = 1 then NULL '
					+ N'		else ResourceNode.CreatedByUserId '
					+ N' end '
					+ N',ResourceNode.ModifiedWhen'
					+ N',ResourceNode.ApprovalStatus'
					+ N' ,ResourceNode.HasCheckedInVersion'
					+ N' ,ResourceNode.Name'
					+ N' ,0'
					+ N' ,0'
		+ N' FROM Node ResourceNode, Node Page,' + @ExportTable + N' en, NodeResource  '
		+ N' Where Page.NodeGUID = en.NodeGUID  '
        + N' AND Page.IsCheckedOutVersion = 0 '
		+ N' AND NodeResource.NodeId = Page.Id  '
        + N' AND NodeResource.IsLink = 0  '
		+ N' And ResourceNode.NodeGUID = NodeResource.NodeGUID '
        + N' AND ResourceNode.IsCheckedOutVersion = 0  '
        + N' AND ResourceNode.ParentGUID <> @ArchiveFolder '
        + N' AND en.Type = 16  '
        + N' AND Not Exists ( SELECT 1 from ' + @ExportTable + N' enn where enn.NodeGUID = ResourceNode.NodeGUID )  '
        
Exec sp_executesql @DynamicSql,N'@ArchiveFolder nvarchar(250), @includeCreatedBy tinyint',
								@ArchiveFolder, @includeCreatedBy 
						
return (@@error)

GO

GRANT EXEC ON dbo.sd_GetResources TO PUBLIC

GO

/* 
 * File: GetRightsGroups.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetRightsGroups'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetRightsGroups
go
/* Purpose: GetRightsGroups populates the ExportedNode table with rights groups data.
 * PreCondition:
 *		ExportTable must exist.
 * PostCondition:
 * Depending on the mode parameter:
 *		If @mode is 0 or 1, then no rights groups are included in export
 *		If @mode is 2 or 4, then all rights groups excluding administrators 
 *			are put in the ExportTable.
 *		If @mode is 9, then all rights groups are inserted into the ExportTable.
 */
CREATE PROC dbo.sd_GetRightsGroups (@mode int 
								,@includeCreatedBy tinyint
								,@Suffix nchar(38) = Null )
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100)
		,@DynamicSql nvarchar(2000)
		,@NoAdmin nvarchar(500)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))

If @mode in (2,4)
Begin

	Set @DynamicSql = 
				N'Insert into ' + @ExportTable + N'(NodeGUID'
						+ N' ,ParentGUID'
						+ N' ,CurrentParentGuid'
						+ N' ,Type'
						+ N' ,Depth'
						+ N' ,IsShortcut'
						+ N' ,IsDependent'
						+ N' ,NodeId'
						+ N' ,CreatedByUserId'
						+ N' ,LastModified'
						+ N' ,ApprovalStatus'
						+ N' ,ApprovedVersionExists'
						+ N' ,Name '
						+ N' ,ExplicitlySelected'
						+ N' ,IsRecursive) '
				
				+ N' Select distinct  RightsGroup.NodeGUID '
						+ N',RightsGroup.ParentGUID '
						+ N',RightsGroup.ParentGUID '
						+ N',RightsGroup.Type '
						+ N',0 as Depth '
						+ N',RightsGroup.IsShortcut '
						+ N',1 as IsDependent '
						+ N',RightsGroup.Id '
						+ N',case when @includeCreatedBy = 1 then NULL '
						+ N'		else RightsGroup.CreatedByUserId '
						+ N' end '
						+ N',RightsGroup.ModifiedWhen'
						+ N',RightsGroup.ApprovalStatus'
						+ N' ,RightsGroup.HasCheckedInVersion'
						+ N' ,RightsGroup.Name'
						+ N' ,0'
						+ N' ,0'
				+ N' From Node RightsGroup, Node Node, NodeRole, ' + @ExportTable + N' en '
				+ N' Where en.NodeGUID = Node.NodeGUID  '
				+ N' And Node.Id = NodeRole.NodeId  '
				+ N' And NodeRole.RoleGUID = RightsGroup.NodeGUID  '
				+ N' And RightsGroup.ParentGUID Is Not Null '
				+ N' And Not Exists ( Select 1 From ' + @ExportTable + N' enn where enn.NodeGUID = RightsGroup.NodeGUID) '
				+ N' And RightsGroup.Name <> '+CHAR(39)+N'Administrator'+CHAR(39) --If not a backup, then no admins are included

	Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy 
	return(@@error)
End
--Otherwise it is a backup so admins are included
Else if @mode = 9
Begin
	Set @DynamicSql =
				N'Insert into ' + @ExportTable + N'(NodeGUID'
						+ N' ,ParentGUID'
						+ N' ,CurrentParentGuid'
						+ N' ,Type'
						+ N' ,Depth'
						+ N' ,IsShortcut'
						+ N' ,IsDependent'
						+ N' ,NodeId'
						+ N' ,CreatedByUserId'
						+ N' ,LastModified'
						+ N' ,ApprovalStatus'
						+ N' ,ApprovedVersionExists'
						+ N' ,Name '
						+ N' ,ExplicitlySelected'
						+ N' ,IsRecursive) '
						
				+ N' Select RightsGroup.NodeGUID '
						+ N',RightsGroup.ParentGUID '
						+ N',RightsGroup.ParentGUID '
						+ N',RightsGroup.Type '
						+ N',0 as Depth '
						+ N',RightsGroup.IsShortcut '
						+ N',0 as IsDependent '
						+ N',RightsGroup.Id '
						+ N',case when @includeCreatedBy = 1 then NULL '
						+ N'		else RightsGroup.CreatedByUserId '
						+ N' end '
						+ N',RightsGroup.ModifiedWhen'
						+ N',RightsGroup.ApprovalStatus'
						+ N' ,RightsGroup.HasCheckedInVersion'
						+ N' ,RightsGroup.Name'
						+ N' ,0'
						+ N' ,0'
				+ N' From Node RightsGroup'
				+ N' Where RightsGroup.Type = 1048576 '
	
	Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy 
	return (@@error)
End

GO

GRANT EXEC ON dbo.sd_GetRightsGroups TO PUBLIC

GO


/* 
 * File: GetTemplates.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_GetTemplates'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_GetTemplates
go
/* Purpose: GetTemplates populates the ##ExportedNode table with
 * templates as dependent objects.
 * Input:
 *
 */
CREATE PROC dbo.sd_GetTemplates (@includeCreatedBy tinyint
							    ,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on

Declare @ExportTable nvarchar(100)
		,@DynamicSql nvarchar(4000)

Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
Set @DynamicSql =
		N'Insert into ' + @ExportTable + N'(NodeGUID'
					+ N' ,ParentGUID'
					+ N' ,CurrentParentGuid'
					+ N' ,Type'
					+ N' ,Depth'
					+ N' ,IsShortcut'
					+ N' ,IsDependent'
					+ N' ,NodeId'
					+ N' ,CreatedByUserId'
					+ N' ,LastModified'
					+ N' ,ApprovalStatus'
					+ N' ,ApprovedVersionExists'
					+ N' ,Name '
					+ N' ,ExplicitlySelected'
					+ N' ,IsRecursive '
					+ N' ,FollowGUID'
					+ N' ,TemplateGUID'
					+ N' ,PageDefinitionGUID) '

		+ N' Select distinct Template.NodeGUID '
					+ N',Template.ParentGUID '
					+ N',Template.ParentGUID '
					+ N',Template.Type '
					+ N',0 as Depth '
					+ N',Template.IsShortcut '
					+ N',1 as IsDependent '
					+ N',Template.Id '
					+ N',case when @includeCreatedBy = 1 then NULL '
					+ N'		else Template.CreatedByUserId '
					+ N' end '
					+ N',Template.ModifiedWhen'
					+ N',Template.ApprovalStatus'
					+ N' ,Template.HasCheckedInVersion'
					+ N' ,Template.Name'
					+ N' ,0'
					+ N' ,0'
					+ N' ,Template.FollowGUID'
					+ N' ,Template.TemplateGUID'
					+ N' ,Template.PageDefinitionGUID '
				
		+ N' From ' + @ExportTable + ' en '
		+ N' inner join Node Template'
		+ N' on en.TemplateGUID = template.NodeGUID and template.IsCheckedOutVersion = 0'
		+ N' where Not Exists'
		+ N' ( Select 1 From ' + @ExportTable + ' enn '
		+ N' Where enn.NodeGUID = Template.NodeGUID )'
	
 Exec sp_executesql @DynamicSql, N'@includeCreatedBy tinyint', @includeCreatedBy 
 if @@error <> 0
	return @@Error


Set @DynamicSql = N'Insert into ' + @ExportTable 
				+ N'(NodeGUID,ParentGUID,CurrentParentGuid, Type,Depth,IsShortcut,IsDependent,'
				+ N' NodeId, ExplicitlySelected, IsRecursive, Name, Reason, IsDeleted '
				+ N' ,FollowGUID'
				+ N' ,TemplateGUID'
				+ N' ,PageDefinitionGUID) '
				
		+ N' SELECT Template.NodeGUID '
		+ N' ,Template.ParentGUID '
		+ N' ,Template.ParentGUID '
		+ N' ,Template.Type '
		+ N' ,0 AS Depth '
		+ N' ,Template.IsShortcut '
		+ N' ,1 AS IsDependent '
		+ N' ,0, 0, 0 '
		+ N' ,Template.Name'
		+ N' ,Template.Reason '
		+ N' ,1 '
		+ N' ,Template.FollowGUID'
		+ N' ,Template.TemplateGUID'
		+ N' ,Template.PageDefinitionGUID '
		
		+ N' from ChangeTable Template '
		+ N' where Template.NodeGUID in '
		+ N' ( select posting.TemplateGUID '
		+ N' from ' + @ExportTable + N' en inner join ChangeTable posting'
		+ N' on en.NodeGUID = posting.NodeGUID '
		+ N' and posting.Reason = 2 ) '
		+ N' and Template.Reason = 2 '
		+ N' and not exists '
		+ N' (SELECT 1 from ' + @ExportTable + N' enn Where enn.NodeGUID = Template.NodeGUID)'

						
Exec sp_executesql @DynamicSql 
 return (@@error)

GO

GRANT EXEC ON dbo.sd_GetTemplates TO PUBLIC

GO


/* 
 * File: IncrementalSearch.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_IncrementalSearch'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_IncrementalSearch
go
/* Purpose: This procudure supports both incremental and partial export for deployment.
 *		IncrementalSearch searches for channels and postings
 * 		that have changed since the given point it time or since the last deployment.
 * 		In addition, this search can be further restricted by the hierarchy whose root is the supplied channel guid.
 *		This is called a partial deployment.
 * PreCondition: This should be the first procedure run when doing an incremental deployment.
 *					Any existing staged export data in the temporary tables may cause unexpected results.
 * param1	@Type			the Type of incremental search: since when, since last deploy
 * Param2	@ChannelGuid	the guid of a channel defining the (sub)hierarchy within with 
 *							to restrict the search for changed objects.
 * param3	@Suffix			the guid suffix for this table.
 *
 * PostCondition: The ExportedNode temporary table is populated with the objects to be exported.
 *				It is now possible to complete the export operations.
 *
 */
 Create Proc dbo.sd_IncrementalSearch ( @Type nvarchar(30)
									,@ChannelGuid nchar(38)
									,@includeCreatedBy tinyint
									,@Suffix nvarchar(100)
									)
with encryption
AS

Set nocount on

Declare @ChannelInsert nvarchar(500)
	,@ChannelDelete nvarchar(500)
	,@ExportTable nvarchar(100)
	,@SearchForChanges nvarchar(4000)
	,@SearchForDeletes nvarchar(4000)
	,@sinceWhen datetime
	,@SubChannel nchar(38)
	,@message nvarchar(100)
	,@RootChannel nchar(38)
	,@LoadChangedNodes nvarchar(4000)
	,@InsertFields nvarchar(1000)
	,@SearchForChannelChanges nvarchar(4000)
	,@SearchForPostingChanges nvarchar(4000)
	,@SearchForResourceChanges nvarchar(4000)
	,@SearchForPageChanges nvarchar(4000)
	,@SearchForTemplateChanges nvarchar(4000)
	,@SearchForPageDefChanges nvarchar(4000)
	,@SearchSinceWhen nvarchar(1000)
	,@ChannelSearchSinceWhen nvarchar(1000)
	,@NoDuplicatesClause nvarchar(1000)
	,@Restriction nvarchar(1000)
	,@TempTable nvarchar(100)
	,@DeletedNodesOnly tinyint
	,@DeleteReason nchar(1)
	,@returncode int
	
set @returncode	= 0

--Delete Reason code in ChangeTable
Set @DeleteReason = N'2'
	
--Is this a 'since when' deal?
Set @sinceWhen = Null
If Patindex(N'%lastdeploy%',Lower(@Type)) = 0
Begin
	Set @sinceWhen = Convert(datetime,@Type)
	If @sinceWhen = Null
	Begin
		select @message = 'Incremental Search: Invalid search date/time:' + @Type
		raiserror (@message, 15, 1)
		return -1
	End
End

/*
 If the channel guid supplied is the root channel
 then we know that all changed data falls within its hierarchy
 Therefore our job is greatly simplified and faster.
 @SubChannel will be null if it is not a channel guid or if it is the root channel.
*/
if @ChannelGuid is not null
begin
	Select @SubChannel = s.NodeGUID
			From Node s Inner Join Node p
				On s.ParentGUID = p.NodeGUID
				And s.Type = 4
			Where s.NodeGUID = @ChannelGuid
			And p.Type = 1
end
		
--Let's see if this channel was deleted	
--In which case we only want deleted nodes because the selected
--ParentChannel was deleted.
Set @DeletedNodesOnly = 0
if @SubChannel Is Null
Begin
	Select @SubChannel = NodeGUID
		From ChangeTable
		Where Type = 4
		And NodeGUID = @ChannelGuid
	If @SubChannel Is Not Null
		Set @DeletedNodesOnly = 1
End

--Set the Name of the Export Table
Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
Set @TempTable = RTRIM(N'##TempHier' + IsNull(@Suffix,N''))



--If @sinceWhen is not null, then the query must be time-based.					
If @sinceWhen Is Not Null
begin
	set @SearchSinceWhen = N' and (ct.CommitTime > @sinceWhen) '
	set @ChannelSearchSinceWhen = N' and (Node.ModifiedWhen > @sinceWhen) '
end
else
begin
	set @SearchSinceWhen = N' and (ct.CommitTime > isnull(LastDeployTime, 0))'
	set @ChannelSearchSinceWhen = N' and (Node.ModifiedWhen > isnull(LastDeployTime, 0))'
end

--This clause prevents duplicate entries in the Export table.
Set @NoDuplicatesClause = N' where not exists'
						+ N' (select NodeGUID from ' + @ExportTable + N' et where et.NodeGUID = Node.NodeGUID)'
						
 Set @InsertFields		= N'Insert into ' + @ExportTable + N'(NodeGUID'
						+ N' ,ParentGUID'
						+ N' ,CurrentParentGuid'
						+ N' ,Type'
						+ N' ,IsShortcut'
						+ N' ,LastModified'
						+ N' ,ApprovalStatus'
						+ N' ,ApprovedVersionExists'
						+ N' ,NodeId'
						+ N' ,CreatedByUserId'
						+ N' ,Depth'
						+ N' ,Name'
						+ N' ,ExplicitlySelected'
						+ N' ,IsRecursive'
						+ N' ,FollowGUID'
						+ N' ,TemplateGUID'
						+ N' ,PageDefinitionGUID'
						+ N' ,Reason'
						+ N' )'
						+ N' Select Node.NodeGUID'
						+ N' ,Node.ParentGUID' 
						+ N' ,Node.ParentGUID' 
						+ N' ,Node.Type'
						+ N' ,Node.IsShortcut'
						+ N' ,Node.ModifiedWhen'
						+ N' ,Node.ApprovalStatus'
						+ N' ,Node.HasCheckedInVersion'
						+ N' ,Node.Id'
						+ N',case when @includeCreatedBy = 1 then NULL '
						+ N'		else Node.CreatedByUserId '
						+ N' end '
						+ N' ,0'
						+ N' ,Node.Name'
						+ N' ,1'
						+ N' ,case when Node.Type In (4,64,1024,16384,262144,2097152,524288,16777216) then 1 ' 
						+ N'							  else 0 '	
						+ N'							  end '
						+ N' ,Node.FollowGUID '
						+ N' ,Node.TemplateGUID'
						+ N' ,Node.PageDefinitionGUID'
						
--when searching for channels to deploy use ModifiedWhen field in Node table
--This is due to the fact that when modifying channel's properties
--Site Manager locks the Node even though a user might cancel the modification later
--this results in ChangeTable being updated and this channel being deployed.
Set @SearchForChannelChanges = 	@InsertFields		
						+ N' ,IsNull(ct.Reason,1)'
						+ N' From ChangeTable ct Inner Join Node as Node '
						+ N' On ct.NodeGUID = Node.NodeGUID '
						+ N' Where Node.Type = 4 '
						+ @ChannelSearchSinceWhen
		
Set @SearchForPostingChanges = @InsertFields
						+ N' ,IsNull(ct.Reason,1)'
						+ N' From ChangeTable as ct Inner Join Node as Node'  
						+ N' On ct.NodeGUID = Node.NodeGUID'  
						+ N' And Node.IsCheckedOutVersion = 0' 
						+ N' And Node.Type = 16'
						+ N' And Node.IsShortcut = 1' 
						+ N' And Node.ArchiveSourceGUID is null' 
						+ @SearchSinceWhen

Set @SearchForResourceChanges = @InsertFields
						+ N' , 1 '  
						+ N' From Node as Node inner join Node As Page'
						+ N' on Node.FollowGUID = Page.NodeGUID'
						+ N' And Node.IsCheckedOutVersion = 0' 
						+ N' and page.ArchiveSourceGUID is null'
						+ N' and Page.IsCheckedOutVersion = 0'
						+ N' inner join NodeResource resource '
						+ N' on page.Id = resource.NodeId'
						+ N' inner join Node as rgi '
						+ N' on rgi.NodeGUID = resource.NodeGUID '
						+ N' and resource.IsLink = 0 '
						+ N' and rgi.IsCheckedOutVersion = 0'
						+ N' inner join ChangeTable ct'
						+ N' on rgi.NodeGUID = ct.NodeGUID '
						+ @NoDuplicatesClause
						+ @SearchSinceWhen
								
Set @SearchForPageChanges = @InsertFields
						+ N' , 1'   
						+ N' From Node as Node inner join Node As Page'
						+ N' on Node.FollowGUID = Page.NodeGUID'
						+ N' And Node.IsCheckedOutVersion = 0' 
						+ N' and Node.ArchiveSourceGUID is null'
						+ N' and Page.IsCheckedOutVersion = 0'
						+ N' inner join ChangeTable ct'
						+ N' on page.NodeGUID = ct.NodeGUID'
						+ @NoDuplicatesClause
						+ @SearchSinceWhen
							
Set @SearchForTemplateChanges = @InsertFields
						+ N' , 1'   
						+ N' From Node as Node inner join Node As Template'
						+ N' on Node.TemplateGUID = Template.NodeGUID'
						+ N' And Node.IsCheckedOutVersion = 0' 
						+ N' and Node.ArchiveSourceGUID is null'
						+ N' and Template.IsCheckedOutVersion = 0'
						+ N' inner join ChangeTable ct'
						+ N' on Template.NodeGUID = ct.NodeGUID'
						+ @NoDuplicatesClause		
						+ @SearchSinceWhen							

Set @SearchForPageDefChanges = @InsertFields
						+ N' , 1'   
						+ N' From Node as Node inner join Node As Template'
						+ N' on Node.TemplateGUID = Template.NodeGUID'
						+ N' And Node.IsCheckedOutVersion = 0' 
						+ N' and Node.ArchiveSourceGUID is null'
						+ N' and Template.IsCheckedOutVersion = 0'
						+ N' inner join Node as PageDef'
						+ N' on Template.PageDefinitionGUID = PageDef.NodeGUID'
						+ N' and PageDef.IsCheckedOutVersion = 0'
						+ N' inner join ChangeTable ct'
						+ N' on PageDef.NodeGUID = ct.NodeGUID'
						+ @NoDuplicatesClause	
						+ @SearchSinceWhen

Set @SearchForDeletes = N'Insert into ' + @ExportTable 
						+ N'(NodeGUID,ParentGUID,CurrentParentGuid,Type, IsShortcut, Name,Reason, IsDeleted)'
						+ N'Select ct.NodeGUID,ct.ParentGUID,ct.ParentGUID,ct.Type, ct.IsShortcut, ct.Name,ct.Reason, 1'
						+ N' From ChangeTable As ct '
						+ N' Where ((ct.Type = 4) Or (ct.Type=16 And ct.IsShortcut = 1)) '
						+ N' And ct.Reason = ' + @DeleteReason
						+ @SearchSinceWhen

--If we are restricting the query to a sub-channel ...
If @SubChannel Is Not Null
Begin
	--Set the Name of the config table which must be used in the query
	Set @TempTable = RTRIM(N'##TempHier' + IsNull(@Suffix,N''))
	
	Set @Restriction = N' And Exists (Select 1 From ' + @TempTable + N' as h '
						+ N'			Where h.NodeGUID in(Node.NodeGUID,Node.ParentGUID)) '
						
	--Now Restrict the queries
	Set @SearchForChannelChanges = @SearchForChannelChanges + @Restriction
	Set @SearchForPostingChanges = @SearchForPostingChanges + @Restriction
	Set @SearchForResourceChanges = @SearchForResourceChanges + @Restriction
	Set @SearchForPageChanges = @SearchForPageChanges + @Restriction
	Set @SearchForTemplateChanges = @SearchForTemplateChanges + @Restriction
	Set @SearchForPageDefChanges = @SearchForPageDefChanges + @Restriction
	
	Set @SearchForDeletes = @SearchForDeletes + N' And Exists (Select 1 From ' + @TempTable + N' as h '
											  + N' Where h.NodeGUID in(ct.NodeGUID,ct.ParentGUID)) '
	
	--Insert the subhierarchy parent guid into Temporary Table
	-- Used only to provide hierarchy info to restrict the searching
	-- Use Node table if selected ParentChannel was not deleted
	If @DeletedNodesOnly = 0
	Begin
		Set @ChannelInsert = N'Insert into ' + @TempTable + N'(NodeGUID,ParentGUID,Type,Depth,IsShortcut)'
						+N' Select Distinct NodeGUID, ParentGUID,Type,0 as Depth,IsShortcut'
						+N' From Node where NodeGUID = @SubChannel And Type =4'
	End
	Else
	--Use ChangeTable if selected Parent Channel was already deleted
	Begin
		Set @ChannelInsert = N'Insert into ' + @TempTable + N'(NodeGUID,ParentGUID,Type,Depth,IsShortcut)'
						+N' Select Distinct NodeGUID,ParentGUID,Type,0 as Depth,IsShortcut'
						+N' From ChangeTable where NodeGUID = @SubChannel And Type =4'
	End
	
	--Create sub-hierarchy with Channel guid as root for partial deployment
	Exec sp_executesql @ChannelInsert,N'@SubChannel nchar(38)',@SubChannel
	If @@error <> 0
		return(@@error)
	
	--We turn on the switch to use the ChangeTable deletes
	Exec @returncode = dbo.sd_CreateSubHier 1, 'insert', @TempTable, 1, @includeCreatedBy, @Suffix
	If @returncode <> 0
		return(@returncode)
	
End

Exec sp_executesql @SearchForChannelChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy

If @@error <> 0
	return(@@error)
	
Exec sp_executesql @SearchForPostingChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy
If @@error <> 0
	return(@@error)
	
Exec sp_executesql @SearchForResourceChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy
If @@error <> 0
	return(@@error)
					
Exec sp_executesql @SearchForPageChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy
If @@error <> 0
	return(@@error)
		
Exec sp_executesql @SearchForTemplateChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy
If @@error <> 0
	return(@@error)
		
Exec sp_executesql @SearchForPageDefChanges,N'@sinceWhen datetime, @includeCreatedBy tinyint',
											@sinceWhen, @includeCreatedBy
If @@error <> 0
	return(@@error)
		
Exec sp_executesql @SearchForDeletes,N'@sinceWhen datetime',@sinceWhen
return(@@error)

	
GO

GRANT EXEC ON dbo.sd_IncrementalSearch TO PUBLIC

GO


IF EXISTS (SELECT name 
	   FROM   sysobjects 
	   WHERE  name = N'IndexExportTables' 
	   AND 	  type = 'P')
    DROP PROCEDURE dbo.IndexExportTables
GO

PRINT 'Creating Procedure IndexExportTables'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *	It creates indexes on import temporary tables after the tables
 *	are populated with data from the object package
*/
create  procedure dbo.IndexExportTables (@Suffix nchar(38) = Null)
with encryption
as
begin

Declare @ExportTable nvarchar(100)
		,@ExcludeTable nvarchar(100)
		,@FailTable nvarchar(100)
		,@MissingLinkTable nvarchar(100)
		,@TempTable nvarchar(100)
		,@ConfigTable nvarchar(100)
		,@DynamicSql nvarchar(1000)

Set @ExportTable		= RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
Set @ExcludeTable		= RTRIM(N'##ExcludedNode' + IsNull(@Suffix,N''))
Set @FailTable			= RTRIM(N'##FailedNode'	+ IsNull(@Suffix,N''))
Set @MissingLinkTable	= RTRIM(N'##MissingLink'	+ IsNull(@Suffix,N''))
Set @ConfigTable		= RTRIM(N'##Config'		+ IsNull(@Suffix,N''))
Set @TempTable			= RTRIM(N'##TempHier'		+ IsNull(@Suffix,N''))

--Index on ExportedNode's ParentGUID
Set @DynamicSql =
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_ParentGUID ON '+@ExportTable
		+ N'(ParentGUID)' 
exec sp_executesql @DynamicSql

--Index on ExportedNode's Type
Set @DynamicSql =
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_Type ON '+@ExportTable
		+ N'(Type)'
exec sp_executesql @DynamicSql

Set @DynamicSql =
		N'CREATE  UNIQUE NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_NodeGUID ON '+@ExportTable
		+ N'(NodeGUID)'
exec sp_executesql @DynamicSql


--Index on ExportedNode's NodeId
Set @DynamicSql = 
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_NodeId ON '+@ExportTable
		+ N'(NodeId)'
exec sp_executesql @DynamicSql 

/*Set @DynamicSql =
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_FollowGuid ON '+@ExportTable
		+ N'(FollowGUID)'
exec sp_executesql @DynamicSql

Set @DynamicSql =
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_TemplateGuid ON '+@ExportTable
		+ N'(TemplateGUID)'
exec sp_executesql @DynamicSql

Set @DynamicSql =
		N'CREATE  NONCLUSTERED INDEX ' 
		+ @ExportTable + N'Node_PageDefinitionGuid ON '+@ExportTable
		+ N'(PageDefinitionGUID)'
exec sp_executesql @DynamicSql
*/
end
go

GRANT EXEC ON dbo.IndexExportTables TO PUBLIC
GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveDeployObjectAssocData')
	BEGIN
		PRINT 'Dropping Procedure RetrieveDeployObjectAssocData'
		DROP  Procedure  dbo.RetrieveDeployObjectAssocData
	END

GO

PRINT 'Creating Procedure RetrieveDeployObjectAssocData'
GO
CREATE Procedure dbo.RetrieveDeployObjectAssocData
	(
		@batchStart int
		,@batchEnd int
		,@hierarchytype nvarchar(50)
		,@includeRightsGroups tinyint
		,@Suffix nchar(38)
	)
with encryption
AS
begin
	set nocount on

	declare
		@ExportTable nvarchar(100)
		,@TreeTable	nvarchar(100)
		,@sql nvarchar(4000)
		,@NodeTypeFilter nvarchar(100)
		
	Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
	Set @TreeTable = RTRIM(N'##' + @hierarchytype + N'tree' + IsNull(@Suffix,N''))
			
	set @NodeTypeFilter = Case @hierarchytype
			when N'Channels' then				N' (en.Type = 4 or (en.Type = 16 and en.IsShortcut = 1))'
			when N'Resources' then				N' en.Type in (64, 256)'
			when N'Templates' then				N' en.Type in (16384, 65536)'
			when N'RightsGroups' then			N' en.Type = 1048576'
			when N'Folders' then				N' (en.Type = 2097152 or (en.Type = 16 and en.IsShortcut = 0))'
			when N'PageDefinitions' then		N' en.Type in (16777216, 33554432)'
			else								N' (en.Type = 4 or (en.Type = 16 and en.IsShortcut = 1))'
		end

	/* generic properties */
	set @sql = N'select en.Ordinal
				,ad.Id
				,ad.PropName
				,ad.PropValue
				,ad.PropType
				,ad.PropValueLong
		from ' + @ExportTable + ' en '
		+ N' inner join NodeProperty ad on en.NodeId = ad.NodeId '
		+ N' and ' + @NodeTypeFilter
		+ N' where en.Ordinal between @batchStart and @batchEnd'	
	
	exec sp_executesql @sql, N'@batchStart int, @batchEnd int', @batchStart, @batchEnd
	if @@error <> 0 
		return @@error
	
	/* ACL */
	set @sql = N'select en.Ordinal
			,RoleGUID
		from ' + @ExportTable + ' en '
		+ N' inner join NodeRole ad on en.NodeId = ad.NodeId '	
		+ N' and ' + @NodeTypeFilter
		+ N' where en.Ordinal between @batchStart and @batchEnd'	
		
	exec sp_executesql @sql, N'@batchStart int, @batchEnd int', @batchStart, @batchEnd
	if @@error <> 0 
		return @@error
	
	/* rights group */
	if @includeRightsGroups = 4 and @hierarchytype = 'RightsGroups'
	begin
		set @sql = N'select en.Ordinal'
				+ N' 	,users.Username'
				+ N' from ' + @ExportTable + ' en '
				+ N' inner join UserRoleMember ad on en.NodeId = ad.NodeId '	
				+ N' and ' + @NodeTypeFilter
				+ N' inner join AEUser users on ad.UserId = users.UserId '	
				+ N' where en.Ordinal between @batchStart and @batchEnd'	
		
		exec sp_executesql @sql, N'@batchStart int, @batchEnd int', @batchStart, @batchEnd
		if @@error <> 0 
			return @@error
	end

	

	/*resources*/
	if @hierarchytype = 'Resources' or @hierarchytype = 'Folders'
	begin
		set @sql = N'select en.Ordinal'
			+ N' 		,ad.Id'
			+ N' 		,ad.Name'
			+ N' 		,ad.IsLink'
			+ N' 		,ad.NodeGUID'
			+ N' 		,ad.ResourceBlobId'
			+ N' 		,ad.LinkAnchor'
			+ N' 		,URL'
			+ N' from ' + @ExportTable + ' en '
			+ N' inner join NodeResource ad on en.NodeId = ad.NodeId '	
			+ N' and ' + @NodeTypeFilter
			+ N' where en.Ordinal between @batchStart and @batchEnd'	

			+ N' select en.Ordinal'
			+ N' 		,blob.BlobId'
			+ N' 		,blob.BlobSecret'
			+ N' 		,blob.BlobFileExt'
			+ N' 		,blob.BlobGUID'
			+ N' 		,blob.BlobTimeCreated'
			+ N' 		,blob.BlobSize'
			+ N' 		,blob.BlobData'
			+ N' from ' + @ExportTable + ' en '
			+ N' inner join NodeResource nr on en.NodeId = nr.NodeId '	
			+ N' and ' + @NodeTypeFilter
			+ N' inner join BlobTable blob '
			+ N' on blob.BlobId = nr.ResourceBlobId'	
			+ N' where en.Ordinal between @batchStart and @batchEnd'	
		
		exec sp_executesql @sql, N'@batchStart int, @batchEnd int', @batchStart, @batchEnd
		if @@error <> 0 
			return @@error
	end
			
	/* placeholders */
	if @hierarchytype = 'Folders'
	begin
		set @sql = N'select en.Ordinal'
			+ N' 			,ad.Id'
			+ N' 			,ad.Name'
			+ N' from ' + @ExportTable + ' en '
			+ N' inner join NodePlaceholder ad on en.NodeId = ad.NodeId '	
			+ N' and ' + @NodeTypeFilter
			+ N' where en.Ordinal between @batchStart and @batchEnd'	
		
			+ N' select en.Ordinal'
			+ N' 		,ad.PlaceholderId'
			+ N' 		,ad.Id'
			+ N' 		,ad.PropName'
			+ N' 		,ad.IsResource'
			+ N' 		,ad.ResourceId'
			+ N' 		,ad.PropValue'
			+ N' from ' + @ExportTable + ' en '
			+ N' inner join NodePlaceholderContent ad on en.NodeId = ad.NodeId '	
			+ N' and ' + @NodeTypeFilter
			+ N' where en.Ordinal between @batchStart and @batchEnd'	
	
		exec sp_executesql @sql, N'@batchStart int, @batchEnd int', @batchStart, @batchEnd
		if @@error <> 0 
			return @@error	
	end
	
end



GO

GRANT EXEC ON dbo.RetrieveDeployObjectAssocData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveExportBrokenLinks')
	BEGIN
		PRINT 'Dropping Procedure RetrieveExportBrokenLinks'
		DROP  Procedure  dbo.RetrieveExportBrokenLinks
	END

GO

PRINT 'Creating Procedure RetrieveExportBrokenLinkss'
GO

create procedure dbo.RetrieveExportBrokenLinks
	(
		@suffix nchar(38)
	)
with encryption
as
begin
	declare @ExportTable nvarchar(100)
			,@MissingLinkTable nvarchar(100)
			,@select nvarchar(4000)
	
	Set @ExportTable =		N'##ExportedNode' + IsNull(@Suffix,N'')
	Set @MissingLinkTable = N'##MissingLink' + IsNull(@Suffix,N'')

	set @select = 
	N'select 
		p.NodeGUID
		,p.Type
		,p.IsShortcut
		,coalesce(np.DisplayName, page.Name, '''')
		,p.Location
	from '							--TODO: remove IsNull when posting names are populated
	+ @ExportTable + ' page inner join [' + db_name() + '].dbo.Node np '
	+ N' on page.NodeGUID = np.FollowGUID '
	+ N' inner join ' + @ExportTable + ' p'
	+ N' on np.NodeGUID = p.NodeGUID'
	+ ' where IsNull(page.HasBrokenLinks, 0) > 0 '

	exec sp_executesql @select

	set @select = 
	N' select 
		p.NodeGUID
		,ml.NodeGUID
		,ml.Type
		,ml.IsShortcut
		,ml.Name
		from ' + @MissingLinkTable + ' ml'
	+ N' inner join ' + @ExportTable + ' page'
	+ N' on ml.SourceNodeGuid = page.NodeGUID'
	+ N' and IsNull(page.HasBrokenLinks, 0) > 0 '
	+ N' inner join [' + db_name() + '].dbo.Node np '	
	+ N' on page.NodeGUID = np.FollowGUID '
	+ N' inner join ' + @ExportTable + ' p'
	+ N' on np.NodeGUID = p.NodeGUID'

	exec sp_executesql @select

end 
go

GO

GRANT EXEC ON dbo.RetrieveExportBrokenLinks TO PUBLIC

GO
 

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveExportedObjects')
	BEGIN
		PRINT 'Dropping Procedure RetrieveExportedObjects'
		DROP  Procedure  dbo.RetrieveExportedObjects
	END

GO

PRINT 'Creating Procedure RetrieveExportedObjects'
GO

create procedure dbo.RetrieveExportedObjects
	(
	@suffix nchar(38),
	@includeRightsGroups tinyint
	)
with encryption
as
begin
/* enum for includeRightsGroups
	Include_Rights_Groups_Unknown		= 0,
	Include_Rights_Groups_None			= 1,
	Include_Rights_Groups_Without_Users	= 2,
	Include_Rights_Groups_With_Users	= 4	
*/

	Declare @exportTable nvarchar(100), @excludeTable nvarchar(100)
	declare @selectExportedObjects nvarchar(4000), @selectExcludedObjects nvarchar(4000),
			@selectUsers nvarchar(4000), @select nvarchar(4000)
	
	Set @exportTable = N'##ExportedNode' + IsNull(@suffix, N'')
	Set @excludeTable = N'##ExcludedNode' + IsNull(@suffix, N'')
	
	set @select = 		
	N' select 
		NodeGUID
		,IsNull(Type, 0)
		,IsNull(IsShortcut, 0)
		,IsNull(ParentGUID, '''')
		,IsNull(Name, ''Unavailable'')
		,IsNull(Location, '''')
		,IsNull(LastModified, 0)
		,ExplicitlySelected
		,Included
		,IsDeleted
	  from ('  
	
	/*retrieve included objects*/
	set @selectExportedObjects = 
	N' select ' + 
		' NodeGUID ' +
		',Type	' + 
		',IsShortcut ' + 
		',ParentGUID ' + 
		',Name ' + 		
		',Location' + 
		',IsNull(LastModified, 0) as LastModified ' + 					--TODO: remove LastModified is populated for postings
		',ExplicitlySelected ' + 					
		',Cast(1 as tinyint) as Included ' + 
		',IsDeleted ' + 
		',Depth ' + 
	'from ' + @exportTable + 
	' where Type > 1 ' 

	set @select = @select + @selectExportedObjects
	
	if @includeRightsGroups = 4 
	begin
		/*include rights group members in the result set*/
		set @selectUsers =  
		N' select ' + 
			''''' as NodeGUID ' + 
			',12 as Type' + 
			',Cast(0 as tinyint) as IsShortcut' + 
			',groups.NodeGUID as ParentGUID ' + 
			',users.Username as Name' + 
			',groups.Location' + 
			',Cast(0 as datetime) as ModifiedWhen' + 
			',Cast(0 as tinyint) as ExplicitlySelected' + 
			',Cast(1 as tinyint) as Included' + 
			',Cast(0 as tinyint) as IsDeleted' + 
			',groups.Depth ' + 
		' from ' + @exportTable + 
		' as groups inner join [' + db_name() + '].dbo.UserRoleMember as member on ' + 
		' groups.NodeId = member.NodeId ' + 
		' and groups.Type = 1048576 ' +
		' inner join [' + db_name() + '].dbo.AEUser as users on ' + 
		' member.UserId = users.UserId '
		
		set @select = @select + 'union all ' + @selectUsers
		
	end
	
	set @select = @select + ' ) as u order by Depth asc '

	exec sp_executesql @select
	
	return (@@error)
end
go


GRANT EXEC ON dbo.RetrieveExportedObjects TO PUBLIC

GO


 IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveExportFailedObjects')
	BEGIN
		PRINT 'Dropping Procedure RetrieveExportFailedObjects'
		DROP  Procedure  dbo.RetrieveExportFailedObjects
	END

GO

PRINT 'Creating Procedure RetrieveExportFailedObjects'
GO

create procedure dbo.RetrieveExportFailedObjects
	(
	@suffix nchar(38)
	)
with encryption
as
begin

	declare @FailTable nvarchar(100), @select nvarchar(500)
	
	Set @FailTable = N'##FailedNode' + IsNull(@Suffix,N'')
	
	set @select = 
	N'select 
		NodeGUID
		,Type
		,IsShortcut
		,Name
		,Location
	from ' + @FailTable 

	exec sp_executesql @select

end
go


GRANT EXEC ON dbo.RetrieveExportFailedObjects TO PUBLIC

GO


/* 
 * File: RetrieveExportUsers.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_RetrieveExportUsers'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_RetrieveExportUsers
go
/*
 * Purpose: Retrieve users for inclusion in the export package.
 * PreCondition:
 *  Export options are known.
 * PostCondition:
 *  0 or 1 result set is returned containing Username and sid.
 * param	@includeUsers 	indication for retrieving createdby users
 * param 	@includeRightsGroups:
 * 			0 - unknown
 *			1 - Do not include rights groups
 *			2 - Include rights groups only
 *			4 - Include rights groups and members
 *			9 - Performing a user backup.
 */
Create Proc dbo.sd_RetrieveExportUsers(@includeUsers tinyint = 1
										,@includeRightsGroups tinyint = 1
										,@Suffix nchar(38) = Null)
with encryption
As
set nocount on

Declare @sql nvarchar(3000)
		,@ExportTable nvarchar(100)

Set @ExportTable = N'##ExportedNode' + IsNull(@Suffix,N'')

if @includeUsers = 2 And @includeRightsGroups in (4,9)
begin
	Set @sql =	N'Select u.Username,u.UserSID '
				+ N' from dbo.AEUser as u '
				+ N' where u.UserId in '
				+ N' ( select distinct CreatedByUserId'
				+ N' from ' + @ExportTable + ')'
				+ N' Union '
				+ N' Select u.Username,u.UserSID '
				+ N' from dbo.AEUser as u '
				+ N' where u.UserId in '
				+ N' (select distinct mem.UserId '
				+ N' from UserRoleMember as mem inner join ' + @ExportTable + ' as rg'
				+ N' on rg.NodeId = mem.NodeId '
				+ N' and rg.Type = 1048576) '
				
	exec sp_executesql @sql				
end
else if @includeUsers = 1 And @includeRightsGroups in (4,9)
begin
	Set @sql =	N'Select u.Username,u.UserSID '
				+ N' from ' + @ExportTable + ' as rg inner join UserRoleMember as mem '
				+ N' on rg.NodeId = mem.NodeId '
				+ N' and rg.Type = 1048576 '
				+ N' Inner Join AEUser as u on u.UserId = mem.UserId '
				
	exec sp_executesql @sql
end
else if @includeUsers = 2 and @includeRightsGroups not in (4,9)
begin
	Set @sql =	N'Select distinct u.Username,u.UserSID '
				+ N' from dbo.AEUser as u inner join ' + @ExportTable + ' as en '
				+ N' on u.UserId = en.CreatedByUserId '
				
	exec sp_executesql @sql
end

GO

GRANT EXEC ON dbo.sd_RetrieveExportUsers TO PUBLIC

GO

/* 
 * File: GenerateHierarchy.sql
 */
-- Drop this procedure (if it exists) 
-- before creating it.
if exists (select * from sysobjects
    where name = 'sd_ShowHierarchy'
    and type = 'P' and uid = user_id())
    drop proc dbo.sd_ShowHierarchy
go
/* Purpose: ShowHierarchy dumps the given hierarchy table
 * param2	@TreeTable		the Name of the table in which the tree is created.
 *
 */
CREATE PROC dbo.sd_ShowHierarchy(@hierarchytype nvarchar(100)
								,@Suffix nchar(38) = Null)
with encryption
AS
set nocount on
Declare @showsql nvarchar(3000)
		,@ExportTable nvarchar(100)
		,@NodeTypeFilter nvarchar(100)
		
		
Set @ExportTable = N'##ExportedNode' + IsNull(@Suffix,N'')

set @NodeTypeFilter = Case @hierarchytype
	    when N'Channels' then				N' (en.Type = 4 or (en.Type = 16 and en.IsShortcut = 1))'
	    when N'Resources' then				N' en.Type in (64, 256)'
	    when N'Templates' then				N' en.Type in (16384, 65536)'
	    when N'RightsGroups' then			N' en.Type = 1048576'
	    when N'Folders' then				N' (en.Type = 2097152 or (en.Type = 16 and en.IsShortcut = 0))'
	    when N'PageDefinitions' then		N' en.Type in (16777216, 33554432)'
	    else								N' (en.Type = 4 or (en.Type = 16 and en.IsShortcut = 1))'
	end


--Note: The Right Join with Node allows reporting of deleted nodes!
Set @showsql = N'Select en.Ordinal '
				+ N',0 as Depth '
				+ N',en.Type '
				+ N',en.IsShortcut '
				+ N',en.NodeGUID '
				+ N',0 as childcount '
				+ N',en.Location '
				+ N',en.Name '
				+ N',en.ParentGUID '
				+ N',n.ModifiedWhen '
				+ N',n.SameRightsAsParent '
				+ N',n.IsHighPriority '
				+ N',n.ApprovalStatus '
				+ N',n.ReadyForApproval '
				+ N','''' Username '
				+ N',n.SchemaXML '
				+ N',uc.Username '
				+ N',n.CreatedWhen '
				+ N',n.EffectiveDate '
				+ N',n.ExpiryDate '
				+ N',n.SortOrdinal '
				+ N',n.DisplayName '
				+ N',coalesce(n.TemplateGUID,ct.TemplateGUID) TemplateGUID '
				+ N',coalesce(n.FollowGUID,ct.FollowGUID) FollowGUID '
				+ N',n.IsHiddenModePublished '
				+ N',n.IsRobotFollowable '
				+ N',n.IsRobotIndexable '
				+ N',coalesce(n.PageDefinitionGUID,ct.PageDefinitionGUID) PageDefinitionGUID '
				+ N',n.TemplateAspPath '
				+ N',n.TemplateType '
				+ N',n.UserRoleType '
				+ N',n.OuterScriptFile '
				+ N',n.UseOuterScriptForPostings '
				+ N',n.DefaultPostingName '
				+ N',n.Id '
				+ N',en.Reason '
				+ N',en.IsDependent '
			+ N' from Node as n Right Join ' + @ExportTable
			+ N' en with (NOLOCK) on en.NodeId=n.Id'
			+ N' Left Join AEUser as uc on en.CreatedByUserId = uc.UserId '
			+ N' Left Join ChangeTable as ct on en.NodeGUID = ct.NodeGUID '
			+ N'       And ct.Reason = 2 '
			+ N' where ' + @NodeTypeFilter 
			+ N' order by en.Ordinal'


exec sp_executesql @showsql

return 0

GO

GRANT EXEC ON dbo.sd_ShowHierarchy TO PUBLIC

GO

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' 
			AND name = 'sd_UpdateLastDeployTime')
	BEGIN
		PRINT 'Dropping Procedure sd_UpdateLastDeployTime'
		DROP  Procedure  dbo.sd_UpdateLastDeployTime
	END

GO

PRINT 'Creating Procedure sd_UpdateLastDeployTime'
GO
CREATE Procedure dbo.sd_UpdateLastDeployTime (@Suffix nchar(38) = null)
with encryption
AS

/******************************************************************************
**		File: UpdateLastDeployTime.sql
**		Name: sd_UpdateLastDeployTime
**		Desc: Updates the last deployment time of all objects just exported.
**
**              
**		Return values: None
** 
**		Called by:  SiteDeployExport.cpp
**              
**		Parameters:
**		Input							Output
**     ----------							-----------
**
**		Auth: robinsm
**		Date: March 29, 2001
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------		--------				-------------------------------------------
**    
*******************************************************************************/
set nocount on

Declare @sql nvarchar(1000)
		,@ExportTable nvarchar(100)
		,@dateGMT datetime
		,@dateCurrent datetime
		
--Set the Name of the Export Table
Set @ExportTable = RTRIM(N'##ExportedNode' + IsNull(@Suffix,N''))
--Get the UTC time (GMT)
select @dateCurrent = GETDATE()
exec GetGMTTime @dateCurrent, @dateGMT out
--Update the ChangeTable
Set @sql = N' Update dbo.ChangeTable '
			+ N' Set LastDeployTime = @now '
			+ N' From ' + @ExportTable + N' en Inner Join ChangeTable '
			+ N'   on en.NodeGUID = ChangeTable.NodeGUID '
			
execute sp_executesql @sql,N'@now datetime',@dateGMT

return (@@error)

GO

GRANT EXEC ON dbo.sd_UpdateLastDeployTime TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'ArchiveImportedNodes')
	BEGIN
		PRINT 'Dropping Procedure ArchiveImportedNodes'
		DROP  Procedure  dbo.ArchiveImportedNodes
	END

GO

PRINT 'Creating Procedure ArchiveImportedNodes'
GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to archive nodes that are being replaced before the merge. 
 *	The nodes being archived are pages, templates, resources and page
 *	definitions. The new Node guid for archived nodes is generated
 *	when staging temporary tables.
 *
 *	@see MergeImportData
*/
create procedure dbo.ArchiveImportedNodes
with encryption
as
begin

	set nocount on

	declare @ArchiveFolderGUID char(38)
	select @ArchiveFolderGUID = PropValue 
	from NodeProperty 
	where PropName = '_ArchiveFolder'

	declare @dateCurrent datetime, @DateGMT datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out

	update Node 
	set		NodeGUID = tmp.ArchiveNodeGUID
			,ParentGUID	= @ArchiveFolderGUID
       		,IsCheckedOut = 0
			,CheckedOutByUserId = NULL
			,CheckedOutByMachine = NULL
			,CreatedWhen = @dateGMT 
			,ArchivedWhen = @dateGMT
			,ArchiveSourceGUID = tmp.NodeGUID
	from Node inner join ##impNode tmp
	on Node.Id = tmp.SourceId
	and Node.IsCheckedOutVersion = 0 
	and Node.ArchiveSourceGUID is null
	and tmp.SourceId > 0 
	and tmp.ArchiveNodeGUID is not null

	return (@@error)
end

GO

GRANT EXEC ON dbo.ArchiveImportedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CalculateBrokenLinks')
	BEGIN
		PRINT 'Dropping Procedure CalculateBrokenLinks'
		DROP  Procedure  dbo.CalculateBrokenLinks
	END

GO

PRINT 'Creating Procedure CalculateBrokenLinks'
GO

/**
 *	This stored procedure is used for Site Deployment import operation to
 *	gather information about broken links for reporting. 
 *	A Node has a broken link if one of its NodeResource records references
 *	a Node guid that is missing from the Node table. No other kinds of 
 *	relationship between nodes are considered within this procedure.
 *
 *	@see CollectImportReportingData
*/
create procedure dbo.CalculateBrokenLinks
with encryption
as
begin
	set nocount on

	insert into ##impBrokenLinkTargets 
		(
		LinkSourceGUID
		,LinkTargetGUID
		)
	select 
		tmp.NodeGUID
		,links.NodeGUID
	from 
	##impNode tmp inner join ##impNodeResource links
	on tmp.Id = links.NodeId 
	and links.IsLink = 1 
	and links.NodeGUID is not null
	where not exists
	(
		select NodeGUID 
		from ##impNode 
		where NodeGUID = links.NodeGUID
	union
		select NodeGUID 
		from Node 
		where NodeGUID = links.NodeGUID 
		and IsCheckedOutVersion = 0 
	)


	insert into ##impBrokenLinks
		(
		NodeGUID
		,Type
		,IsShortcut
		,Name
		,Location
		)
	select 
		tmp.NodeGUID
		,tmp.Type
		,tmp.IsShortcut 
		,coalesce(tmp.Name, tmp.DisplayName, pages.Name, tmppages.Name, '')
		,tmp.Location
	from ##impNode tmp inner join ##impBrokenLinkTargets links
	on tmp.NodeGUID = links.LinkSourceGUID
	left join Node pages
	on tmp.IsShortcut = 1 
	and tmp.FollowGUID = pages.NodeGUID 
	and pages.IsCheckedOutVersion = 0
	left join ##impNode tmppages
	on tmp.IsShortcut = 1 
	and tmp.FollowGUID = tmppages.NodeGUID 

end

GO

GRANT EXEC ON dbo.CalculateBrokenLinks TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CalculateLocationForDeletedNodes')
	BEGIN
		PRINT 'Dropping Procedure CalculateLocationForDeletedNodes'
		DROP  Procedure  dbo.CalculateLocationForDeletedNodes
	END

GO

PRINT 'Creating Procedure CalculateLocationForDeletedNodes'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It calculates a path for nodes that are to be deleted during merge
 *	operation. This information is only needed for reporting and is not
 *	collected if reporting is turned off. 
 *	The procedure opens up a cursor selecting all nodes from ##impNodesToDelete
 *	table that have Location missing (Location is also calculated when
 *	##impNodesToDelete table is being populated), and then for each selected
 *	Node ir traverses the tree up to the root Node.
 *
 *	@see PrepareNodesForDelete
 *	@see GetLocation
*/
create procedure dbo.CalculateLocationForDeletedNodes
with encryption
as
begin
	set nocount on

	declare @rowcount int

	declare @NodeLocation table 
				(
				NodeGUID char(38) collate database_default not null primary key,
				CurrentParentGuid char(38) collate database_default null,
				Name nvarchar(250) collate database_default null,
				Location ntext
				)


	insert into @NodeLocation (NodeGUID, CurrentParentGuid, Name)
	select distinct del.NodeGUID, del.ParentGUID, del.Name 
	from ##impNodesToDelete del 
	where del.CannotDelete = 0
	and del.Location is null 
	
	while @@rowcount > 0
	begin
		update @NodeLocation 
		set Location = cast (case when parents.ParentGUID is null then '' else parents.Name end 
						+ '/' + IsNull(cast(Location as nvarchar(4000)), nl.Name) as nvarchar(4000) ),
		CurrentParentGuid = parents.ParentGUID
		from @NodeLocation nl inner join Node parents
		on nl.CurrentParentGuid = parents.NodeGUID 
		and nl.CurrentParentGuid is not null
	end	
	
	update ##impNodesToDelete
	set Location = IsNull(cast(nl.Location as nvarchar(4000)), '')  
	from (select NodeGUID, Location from @NodeLocation) nl
	where ##impNodesToDelete.NodeGUID = nl.NodeGUID

	return (@@error)



/*	declare @NodeGUID char(38)
	declare @Location nvarchar(4000)

	DECLARE DeletedNodes CURSOR LOCAL READ_ONLY 
	    FOR SELECT distinct NodeGUID FROM ##impNodesToDelete
			where CannotDelete = 0
			and Location is null 

	OPEN DeletedNodes
	FETCH NEXT FROM DeletedNodes INTO @NodeGUID
	
	WHILE @@FETCH_STATUS = 0
	  BEGIN
			set @Location = null
			exec GetLocation @NodeGUID, @Location output
			update ##impNodesToDelete set Location = @Location + '/'
			where NodeGUID = @NodeGUID
		
			if @@error <> 0 return(1)

			FETCH NEXT FROM DeletedNodes INTO @NodeGUID
	  END  

	close DeletedNodes
	deallocate DeletedNodes
*/	

end

GO

GRANT EXEC ON dbo.CalculateLocationForDeletedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CalculateLocationForImportedNodes')
	BEGIN
		PRINT 'Dropping Procedure CalculateLocationForImportedNodes'
		DROP  Procedure  dbo.CalculateLocationForImportedNodes
	END

GO

PRINT 'Creating Procedure CalculateLocationForImportedNodes'
GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to calculate original Location for nodes that are beng replaced.
 *
 *	@param	@containerSyncOption		specifies whether to synchronize
 *										container hierarchy with the source
 *
 *	@see CollectImportReportingData
*/
create procedure dbo.CalculateLocationForImportedNodes
	(
	@containerSyncOption tinyint
	)
with encryption
as
begin

	set nocount on

	declare @rowcount int

	create table #impNodeLocation
	(
		NodeGUID char(38) collate database_default not null primary key,
		CurrentParentGuid char(38) collate database_default null,
		Name nvarchar(250) collate database_default null,
		Location ntext
	)

	create nonclustered index impNodeLocation_CurrentParentGUID ON #impNodeLocation
		(
		CurrentParentGuid
		)
		
	if @@error <> 0 return(1)

	if @containerSyncOption > 1	--hierarchy syncronization
	begin
		/*calculate before import Location*/
		insert into #impNodeLocation (NodeGUID, CurrentParentGuid, Name)
		select distinct n.NodeGUID, n.ParentGUID, n.Name 
		from Node n inner join ##impNode tmp on
		n.NodeGUID = tmp.ParentGUIDBeforeImport
		and (n.IsCheckedOutVersion = 0 or n.Type = 16 and n.IsShortcut = 1)
		and n.ArchiveSourceGUID is null

		while @@rowcount > 0
		begin
			update #impNodeLocation
			set Location = cast (case when parents.ParentGUID is null then '' else parents.Name end 
						  + '/' + IsNull(cast(Location as nvarchar(4000)), #impNodeLocation.Name) as nvarchar(4000) ),
			CurrentParentGuid = parents.ParentGUID
			from Node parents
			where #impNodeLocation.CurrentParentGuid = parents.NodeGUID 
			and #impNodeLocation.CurrentParentGuid is not null
			and parents.IsCheckedOutVersion = 0

		end
		
		update ##impNode
		set LocationBeforeImport = IsNull(cast(nl.Location as nvarchar(4000)), '') + '/' 
		from ##impNode tmp inner join #impNodeLocation nl
		on tmp.ParentGUIDBeforeImport = nl.NodeGUID

		if @@error <> 0 return(1)

		truncate table #impNodeLocation

		if @@error <> 0 return(1)

	end

	/*calculate after import Location*/
	insert into #impNodeLocation (NodeGUID, CurrentParentGuid, Name)
	select parent.NodeGUID, parent.ParentGUID, parent.Name
	from ##impNode parent 
	where exists( select 1 from ##impNode tmp where tmp.ParentGUID = parent.NodeGUID)

	insert into #impNodeLocation (NodeGUID, CurrentParentGuid, Name)
	select parent.NodeGUID, parent.ParentGUID, parent.Name
	from Node parent 
	where exists( select 1 from ##impNode tmp where tmp.ParentGUID = parent.NodeGUID)
	and not exists (select 1 from ##impNode where NodeGUID = parent.NodeGUID)
	
	while @@rowcount > 0
	begin
		update #impNodeLocation
		set Location = cast (case when u.ParentGUID is null then '' else u.Name end 
					+ '/' + IsNull( cast(Location as nvarchar(4000)), #impNodeLocation.Name) as nvarchar(4000) ),
		CurrentParentGuid = u.ParentGUID
		from 
		( 
			select parent.NodeGUID, parent.ParentGUID, parent.Name
			from ##impNode parent 
			where exists( select 1 from #impNodeLocation tmp where tmp.CurrentParentGuid = parent.NodeGUID)
		) as u
		where #impNodeLocation.CurrentParentGuid = u.NodeGUID

		update #impNodeLocation
		set Location = cast (case when u.ParentGUID is null then '' else u.Name end 
					+ '/' + IsNull( cast(Location as nvarchar(4000)), #impNodeLocation.Name) as nvarchar(4000) ),
		CurrentParentGuid = u.ParentGUID
		from
		( 
			select parent.NodeGUID, parent.ParentGUID, parent.Name
			from Node parent 
			where exists( select 1 from #impNodeLocation tmp where tmp.CurrentParentGuid = parent.NodeGUID)
			and not exists (select 1 from ##impNode where NodeGUID = parent.NodeGUID)
		) as u
		where #impNodeLocation.CurrentParentGuid = u.NodeGUID

	end

	update ##impNode
	set LocationBeforeImport = case when @containerSyncOption = 1 and SourceId > 0 then IsNull(cast(nl.Location as nvarchar(4000)), '') + '/'
			else LocationBeforeImport end,
	LocationAfterImport = IsNull(cast(nl.Location as nvarchar(4000)), '') + '/'
	from ##impNode tmp inner join #impNodeLocation nl
	on tmp.ParentGUID = nl.NodeGUID
	
	return (@@error)
end

GO

GRANT EXEC ON dbo.CalculateLocationForImportedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CollectImportReportingData')
	BEGIN
		PRINT 'Dropping Procedure CollectImportReportingData'
		DROP  Procedure  dbo.CollectImportReportingData
	END

GO

PRINT 'Creating Procedure CollectImportReportingData'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It gathers data needed for reporting purposes. Mostly this includes 
 *	original data for nodes that are being replaced, ie. original parent guid,
 *	Location before import, etc. It also checks if there are nodes that will have
 *	broken links after the import. 
 *
 *	@param	@containerSyncOption		specifies whether to synchronize
 *										container hierarchy with the source
 *
 *	@see CalculateLocationForImportedNodes
 *	@see CalculateBrokenLinks
*/
create procedure dbo.CollectImportReportingData
	(
	@containerSyncOption tinyint
	)
with encryption
as
begin
	set nocount on

	declare @retcode int
	set @retcode = 0

	/*get before import data for existing nodes*/
	update ##impNode
	set NameBeforeImport = case when n.IsShortcut = 0 then n.Name else pages.Name end,
	ModifiedWhenBeforeImport = n.ModifiedWhen,
	ParentGUIDBeforeImport = n.ParentGUID
	from 
	(##impNode tmp inner join Node n
	on tmp.NodeGUID = n.NodeGUID 
	and (
		tmp.IsCheckedOutVersion = n.IsCheckedOutVersion or
		n.Type = 16 and n.IsShortcut = 1
		)
	and n.ArchiveSourceGUID is null
	) 
	left join Node pages 
	on n.FollowGUID = pages.NodeGUID 
	and n.IsShortcut = 1 
	and n.ArchiveSourceGUID is null
	and pages.ArchiveSourceGUID is null

	if @@error <> 0 return(1)

	exec @retcode = CalculateLocationForImportedNodes @containerSyncOption
	if @@error <> 0 return (1)
	
	/*find broken links*/
	exec @retcode = CalculateBrokenLinks
	return (@retcode)	


end


GO

GRANT EXEC ON dbo.CollectImportReportingData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CreateDefaultContainer')
	BEGIN
		DROP  Procedure  dbo.CreateDefaultContainer
	END

GO

PRINT 'Creating Procedure CreateDefaultContainer'
GO


/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It creates a new container to store objects that do not have parent
 *	containers on the target system. The container is created under the 
 *	root container of the specified Type and is only accessible by 
 *	administrator. The Name of the container is 
 *	"CMS Default SiteDeploy Destination"
 *
 *	@param @containerType				Type of a container being created
 *	@param @containerGuid				guid of a container being created
 *	@param @UserId						Id for the user running import 
 *
 *	@see MoveNodesToDefaultContainer
 */
CREATE Procedure dbo.CreateDefaultContainer
	(
	@containerType int,
	@containerGuid char(38)
	)
with encryption
AS

begin
	set nocount on

	declare @ParentGUID char(38)
	DECLARE @dateGMT datetime, @dateCurrent datetime
	select @dateCurrent = GETDATE()
	
	exec GetGMTTime @dateCurrent, @dateGMT out

	if @containerType = 4
		set @ParentGUID = '{E4D19123-9DD3-11D1-B44E-006097071264}'	--root channel
	else if @containerType = 2097252	
		set @ParentGUID = '{E4D19124-9DD3-11D1-B44E-006097071264}'	--root folder
	else if @containerType = 16384
		set @ParentGUID = '{E4D1912B-9DD3-11D1-B44E-006097071264}' --root template gallery
	else if @containerType = 64
		set @ParentGUID = '{E4D1912A-9DD3-11D1-B44E-006097071264}' --root resource gallery

	insert into ##impNode (Id, IsLocked, IsCheckedOut, IsCheckedOutVersion, HasCheckedInVersion,
					CheckedInVersionHasExisted, IsShortcut, 
					IsHighPriority, SameRightsAsParent, ReadyForApproval,
					ApprovalStatus, Type, SortOrdinal, 
					NodeGUID, ParentGUID,  
					CreatedWhen, ModifiedWhen, IsDependent, 
					Name, Location)
	values ( -@containerType, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, @containerType, 0, @containerGuid, @ParentGUID,
			@dateGMT, @dateGMT, 0, 
			'CMS Default SiteDeploy Destination',
			case when @containerType = 4 then '/Channels/'
				 when @containerType = 2097252 then '/Folders/'
				 when @containerType = 16384 then '/Templates/'
				 when @containerType = 64 then '/Resources/'
			end)
	return(@@error)
end

GO

GRANT EXEC ON dbo.CreateDefaultContainer TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'CreateImportTables')
	BEGIN
		DROP  Procedure  dbo.CreateImportTables
	END

GO

PRINT 'Creating Procedure CreateImportTables'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *	It creates import temporary tables to store data from the object package
*/
create procedure dbo.CreateImportTables
with encryption
as
begin

	CREATE TABLE ##impAEUser
		(
		Username 		nvarchar(450) 	collate database_default	NOT NULL,
		UsernameUpper	nvarchar(450)	collate database_default	NOT NULL,
		UserSID 		varchar(255) 	collate database_default	NULL 
		)


	create table ##impBlobData
	(
 		BlobId 			int 										NOT NULL PRIMARY KEY,
		BlobSecret 		varchar(32) 	collate database_default	NOT NULL,
		BlobFileExt 	nvarchar(8) 	collate database_default	NOT NULL,
		BlobGUID 		char(38) 		collate database_default	NOT NULL,
		BlobExecFlag 	tinyint 									NOT NULL,
		BlobTimeCreated datetime 									NOT NULL,
		BlobSize 		int 										NOT NULL,
		BlobMetaFlag 	tinyint 									NOT NULL,
		BlobData 		image 										NULL
	)



	CREATE TABLE ##impNode
			(
		 	Id 						int 		NOT NULL PRIMARY KEY NONCLUSTERED,
		 	
			IsDependent				tinyint		Not Null,

			IsLocked 				tinyint 	NOT NULL default 0,
			IsCheckedOut 			tinyint 	NOT NULL,
			IsCheckedOutVersion 	tinyint 	NOT NULL,
			HasCheckedInVersion 	tinyint 	NOT NULL,
			CheckedInVersionHasExisted tinyint 	NULL,
			IsShortcut 				tinyint 	NOT NULL,
		
			IsHighPriority 			tinyint 	NOT NULL default 0,
			SameRightsAsParent 		tinyint 	NOT NULL,
			ReadyForApproval 		tinyint 	NOT NULL,
		
			ApprovalStatus 			int 		NOT NULL,
		
			Type 					int 		NOT NULL,
			SortOrdinal 			int 		NOT NULL,
		
			NodeGUID 				char(38) 	collate database_default	NOT NULL,
			ParentGUID 				char(38) 	collate database_default	NULL,
			FollowGUID 				char(38) 	collate database_default	NULL,
			DeletedWhen				datetime	NULL,

			CreatedByUser			nvarchar(450) collate database_default	NULL,
			CreatedWhen 			datetime 	NOT NULL,

			ModifiedWhen 			datetime 	NOT NULL,
			ApprovedWhen 			datetime 	NULL,

			Owner					nvarchar(450) collate database_default	NULL,

			EffectiveDate 			datetime 	NULL,
			ExpiryDate 				datetime 	NULL,
			TemplateGUID 			char(38) 	collate database_default	NULL,
		
			Name 					nvarchar(250) 	collate database_default	NULL,
			TemplateType 			nvarchar(150) 	collate database_default	NULL,
			
			IsHiddenModePublished	tinyint 	NULL,
			IsRobotFollowable		tinyint 	NULL,
			IsRobotIndexable		tinyint 	NULL,
			DisplayName				nvarchar(250) 	collate database_default	NULL,
		
			PageDefinitionGUID 		char(38) 	collate database_default	NULL,

			UserRoleType			int			NULL,

			OuterScriptFile			ntext		collate database_default	NULL,
			UseOuterScriptForPostings 	tinyint NULL,
			DefaultPostingName	  	nvarchar(250) collate database_default	 NULL,

			TemplateAspPath			ntext		collate database_default	NULL,
			SchemaXML				ntext		collate database_default	NULL,
			Location				ntext		collate database_default	null,
			SourceId				int			NOT NULL default 0,
			Action					int			NOT NULL default 1,
			ArchiveNodeGUID			char(38)	collate database_default	NULL,
			DeleteOnCommit			tinyint		NULL default 0,
			LockUserId 				int 			NULL,
			LockMachinename 		nvarchar(50) 	collate database_default	NULL,
			NameBeforeImport		nvarchar(250) 	collate database_default	NULL,
			ModifiedWhenBeforeImport	datetime 		NULL,
			ParentGUIDBeforeImport	char(38)		collate database_default	NULL,
			LocationBeforeImport	ntext			collate database_default	NULL,
			LocationAfterImport		ntext			collate database_default	NULL
			) 


	CREATE TABLE ##impUserRoleMember
		(
	 	NodeId 			int											NOT NULL,
		Username 		nvarchar(450) 	collate database_default	NOT NULL
		)


	CREATE TABLE ##impNodeRole
		(
	 	NodeId 			int 									NOT NULL,
		RoleGUID 		char(38) 	collate database_default	NOT NULL
		) 

	CREATE TABLE ##impNodeProperty
		(
	 	NodeId 				int 										NOT NULL,
		Id 					int 										NOT NULL,
		PropName 			nvarchar(50) 	collate database_default	NOT NULL,
		PropValue 			nvarchar(300)	collate database_default	NULL,
		PropType			int											NULL default 0,
		PropValueLong		ntext			collate database_default	NULL,
	)

	CREATE TABLE ##impNodeResource
		(
	 	NodeId 				int											NOT NULL,
		Id 					int 										NOT NULL,
		Name				nvarchar(100) 	collate database_default	NOT NULL,
		IsLink 				tinyint 									NOT NULL,
		NodeGUID			char(38) 		collate database_default	NULL,
		ResourceBlobId 		int 										NULL,
		LinkAnchor 			nvarchar(255) 	collate database_default	NULL,
		URL 				ntext 			collate database_default	NULL
		)



	CREATE TABLE ##impNodePlaceholder
		(
	 	NodeId 			int 										NOT NULL,
		Id 				int 										NOT NULL,
		Name 			nvarchar(100) 	collate database_default	NOT NULL,
		ControlGUID 	char(38) 		collate database_default	NULL
		)

	CREATE TABLE ##impNodePlaceholderContent
		(
	 	NodeId 			int 									NOT NULL,
		PlaceholderId	int 									NOT NULL,
		Id 				int 									NOT NULL,
		PropName 		nvarchar(100) collate database_default	NOT NULL,
		IsResource 		tinyint 								NOT NULL,
		ResourceId 		int 									NULL,
		PropValue 		ntext 		collate database_default	NULL
		)

	create table ##impNodesToDelete
		(
		NodeGUID	char(38)	collate database_default	not null,
		ParentGUID	char(38)	collate database_default	not null,
		TopParentGUID	char(38) collate database_default	null,
		Type		int										not null,
		IsShortcut	int										not null,
		Level		int										not null default 0,
		Reason		tinyint									not null,
		Status 		int										not null default 0,
		CannotDelete tinyint								not null default 0,
		Name		nvarchar(250)	collate database_default null,
		FollowGUID	varchar(38)		collate database_default	null,
		TemplateGUID varchar(38)	collate database_default	null,
		PageDefinitionGUID varchar(38) collate database_default	null,
		Location	ntext			collate database_default	null
		)

	create table ##impBrokenLinks
		(
		NodeGUID	char(38)	collate database_default	not null,
		Type		int										not null,
		IsShortcut	int										not null,
		Name		nvarchar(250) collate database_default	null,
		Location	ntext		collate database_default	null
		)

	create table ##impBrokenLinkTargets
		(
		LinkSourceGUID 	char(38)	collate database_default	not null,
		LinkTargetGUID	char(38)	collate database_default	not null,
		Type			int										null,
		IsShortcut		int										null,
		Name			nvarchar(250) collate database_default	null
		)
	
	create table ##impBrokenLinkPackageInfo
		(
		LinkTargetGUID	char(38)	collate database_default	not null,
		Type			int										not null,
		IsShortcut		int										not null,
		Name			nvarchar(250) collate database_default	not null
		)
end




GO

GRANT EXEC ON dbo.CreateImportTables TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'DropImportTables')
	BEGIN
		PRINT 'Dropping Procedure DropImportTables'
		DROP  Procedure  dbo.DropImportTables
	END

GO

PRINT 'Creating Procedure DropImportTables'
GO
CREATE Procedure dbo.DropImportTables
with encryption
AS
begin

	drop table ##impAEUser

	drop table ##impBlobData

	drop table ##impNode

	drop table ##impUserRoleMember

	drop table ##impNodeRole

	drop table ##impNodeProperty

	drop table ##impNodeResource
	
	drop table ##impNodePlaceholder

	drop table ##impNodePlaceholderContent

	drop table ##impNodeLayout

	drop table ##impLayoutProperty

	drop table ##impNodesToDelete

	drop table ##impBrokenLinks

	drop table ##impBrokenLinkTargets
	
	drop table ##impBrokenLinkPackageInfo

end
GO

GRANT EXEC ON dbo.DropImportTables TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GenerateImportStatistics')
	BEGIN
		PRINT 'Dropping Procedure GenerateImportStatistics'
		DROP  Procedure  dbo.GenerateImportStatistics
	END

GO

PRINT 'Creating Procedure GenerateImportStatistics'
GO

create procedure dbo.GenerateImportStatistics
with encryption
as
begin
	set nocount on

	declare @channels int
			,@postings int
			,@folders int
			,@pages int
			,@resource_galleries int
			,@resources int
			,@template_galleries int
			,@templates int
			,@pagedef_galleries int
			,@pagedefs int
			,@rights_groups int

	

	select @channels = count(*)
	from ##impNode
	where Type = 4
	
	select @postings = count(*)
	from ##impNode
	where Type = 16 and IsShortcut = 1
	
	select @folders = count(*)
	from ##impNode
	where Type = 2097152

	select @pages = count(*)
	from ##impNode
	where Type = 16 and IsShortcut = 0
	
	select @resource_galleries = count(*)
	from ##impNode
	where Type = 64

	select @resources = count(*)
	from ##impNode
	where Type = 256
	
	select @template_galleries = count(*)
	from ##impNode
	where Type = 16384

	select @templates = count(*)
	from ##impNode
	where Type = 65536

	select @pagedef_galleries = count(*)
	from ##impNode
	where Type = 16777216

	select @pagedefs = count(*)
	from ##impNode
	where Type = 33554432

	select @rights_groups = count(*)
	from ##impNode
	where Type = 1048576
	
	select @channels
			, @postings
			, @folders
			, @pages
			, @resource_galleries
			, @resources
			, @template_galleries
			, @templates
			, @pagedef_galleries
			, @pagedefs
			,@rights_groups
end


GO

GRANT EXEC ON dbo.GenerateImportStatistics TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetLocation')
	BEGIN
		PRINT 'Dropping Procedure GetLocation'
		DROP  Procedure  dbo.GetLocation
	END

GO

PRINT 'Creating Procedure GetLocation'
GO

create procedure dbo.GetLocation
	(
	@NodeGUID char(38),
	@Location nvarchar(4000) output
	) 
with encryption
as
begin
	set nocount on

	declare @Name nvarchar(250)
	declare @ParentGUID char(38)
	

	select @Name = Name, @ParentGUID = ParentGUID from Node where NodeGUID = @NodeGUID

	if @Location is null
		select @Location = '' 		--don't take the object Name
	else if @ParentGUID is not NULL	--don't take the server Name
		and @Name is not null		--not a shortcut
		select @Location = convert(nvarchar(4000), @Name + case when @Location = '' then @Location
																else '/' + @Location
																end)


	if @ParentGUID is not NULL
		exec GetLocation @ParentGUID, @Location output
	else
		set @Location = '/' + @Location
end


GO

GRANT EXEC ON dbo.GetLocation TO PUBLIC

GO



IF EXISTS (SELECT name 
	   FROM   sysobjects 
	   WHERE  name = N'IndexImportTables' 
	   AND 	  type = 'P')
    DROP PROCEDURE dbo.IndexImportTables
GO

PRINT 'Creating Procedure IndexImportTables'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *	It creates indexes on import temporary tables after the tables
 *	are populated with data from the object package
*/
create  procedure dbo.IndexImportTables
with encryption
as
begin

	CREATE UNIQUE CLUSTERED INDEX impAEUser_UserName ON ##impAEUser
		(
		UsernameUpper
		)

	CREATE UNIQUE NONCLUSTERED INDEX impBlobTable_BlobGUID ON ##impBlobData
		(
		BlobGUID
		) 

	CREATE UNIQUE NONCLUSTERED INDEX impNode_NodeGUID ON ##impNode
		(
		NodeGUID,
		IsCheckedOutVersion
		)
	CREATE NONCLUSTERED INDEX impNode_Type ON ##impNode
		(
		Type,
		IsShortcut
		)
			
	CREATE NONCLUSTERED INDEX impNode_FollowGuid ON ##impNode
		(
		FollowGUID
		)

	CREATE NONCLUSTERED INDEX impNode_SourceId ON ##impNode
		(
		SourceId
		)
		
	/*CREATE NONCLUSTERED INDEX impNode_CreatedByUser ON ##impNode
		(
		CreatedByUser
		)		
	*/
	CREATE INDEX impUserRoleMember_UserName ON ##impUserRoleMember
		(
		Username
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodeResource ON ##impNodeResource
		(
		NodeId,
		Id
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodeProperty ON ##impNodeProperty
		(
		NodeId,
		Id
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodePlaceholder ON ##impNodePlaceholder
		(
		NodeId,
		Id
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodePlaceholderContent ON ##impNodePlaceholderContent
		(
		NodeId,
		PlaceholderId,
		Id
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodeRole ON ##impNodeRole
		(
		NodeId,
		RoleGUID
		)
		
	CREATE UNIQUE NONCLUSTERED INDEX PK_impUserRoleMember ON ##impUserRoleMember
		(
		NodeId,
		Username
		)

	CREATE UNIQUE NONCLUSTERED INDEX PK_impNodesToDelete ON ##impNodesToDelete
		(
		NodeGUID,
		Level
		)		
		
	CREATE NONCLUSTERED INDEX impNodesToDelete_CannotDelete ON ##impNodesToDelete
		(
		CannotDelete
		)		
				
	CREATE UNIQUE NONCLUSTERED INDEX PK_impBrokenLinkTargets ON ##impBrokenLinkTargets
		(
		LinkSourceGUID,
		LinkTargetGUID
		)			

end
go

GRANT EXEC ON dbo.IndexImportTables TO PUBLIC
GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeBlobData')
	BEGIN
		PRINT 'Dropping Procedure MergeBlobData'
		DROP  Procedure  dbo.MergeBlobData
	END

GO

PRINT 'Creating Procedure MergeBlobData'
GO

create procedure dbo.MergeBlobData
with encryption
as
begin
	
	set nocount on

	/*update existing blobs*/
	update BlobTable
	set BlobSecret = tmp.BlobSecret
		,BlobFileExt =tmp.BlobFileExt
		,BlobExecFlag = tmp.BlobExecFlag 
		,BlobTimeCreated = tmp.BlobTimeCreated
		,BlobSize = tmp.BlobSize 
		,BlobMetaFlag = tmp.BlobMetaFlag
		,BlobData = tmp.BlobData
	from ##impBlobData tmp inner join BlobTable 
	on tmp.BlobGUID = BlobTable.BlobGUID

	if @@error <> 0 return(1)

	/*create new blobs*/
	insert into BlobTable
	(BlobGUID, BlobSecret, BlobFileExt, BlobExecFlag, BlobTimeCreated,BlobSize,BlobMetaFlag,BlobData)
	select BlobGUID, BlobSecret, BlobFileExt, BlobExecFlag, BlobTimeCreated,BlobSize,BlobMetaFlag,BlobData
	from ##impBlobData tmp
	where not exists 
	(select BlobGUID from BlobTable where BlobGUID = tmp.BlobGUID)

	return (@@error)
end
GO

GRANT EXEC ON dbo.MergeBlobData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeImportData')
	BEGIN
		PRINT 'Dropping Procedure MergeImportData'
		DROP  Procedure  dbo.MergeImportData
	END

GO

PRINT 'Creating Procedure MergeImportData'
GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to merge data from the import temporary tables into the main
 *	CMS tables.
 *
 *	@param	@includeRightsGroups		specifies how to import rights
 *										groups and membership
 *	@param @createdByUserSpecifier		whether to set CreatedBy to current 
 *										user or use package info
 *	@param @keepCreatedByUserOnReplace	whether to preserve CreatedBy for 
 *										existing nodes
 *	@param @rightsOnAdd					how to set rights on newly created nodes
 *	@param @rightsOnReplace				how to set rights on existing nodes
 *	@param @UserId						Id of the user running the import operation
 *
 *	@see CollectImportReportingData
*/
create procedure dbo.MergeImportData
	(
	@includeRightsGroups tinyint,
	@createdByUserSpecifier tinyint,
	@keepCreatedByUserOnReplace tinyint,
	@rightsOnAdd tinyint,
	@rightsOnReplace tinyint,
	@UserId int
	)
with encryption
as
begin
	set nocount on

	declare @retcode int
	set @retcode = 0

/* enum values for @includeRightsGroups
	ImportNone = 1,
	ImportWithoutMembers = 2,
	ImportWithMembersUsePackage = 3,
	ImportWithMembersUnionPackageAndExisting = 4
*/
/* enum values for @createdByUserSpecifier
	UsePackage = 1,
	CurrentUser = 2
*/


	/*first off, import users*/
	if exists (select Username from ##impAEUser)
	begin
		insert into AEUser (Username, UsernameUpper, UserSID)
		select Username, UsernameUpper, UserSID
		from ##impAEUser tmp
		where not exists
		(select UsernameUpper from AEUser where UsernameUpper = tmp.UsernameUpper)

		if @@error <> 0 return(1)

	end

	/*import blobs*/
	exec @retcode = MergeBlobData
	if @retcode <> 0 return (@retcode)

	/*first off, disable all triggers on the Node table as
	we don't want the overhead of executing a trigger code for
	every record we're updating or inserting,
	we'll update the change table directly afterwards*/
	alter table Node disable trigger all

	/*if the nodes being replaced are locked or checked out on the target,
	  kill lock and remove checked out version
	*/
	exec @retcode = UndoCheckoutForImportedNodes
	if @@error <> 0 
	begin
		set @retcode = @@error
		goto cleanup
	end	
	
	/*archive nodes that are being replaced*/
	exec @retcode = ArchiveImportedNodes
	if @@error <> 0 
	begin
		set @retcode = @@error
		goto cleanup
	end	
		
	/*now merge nodes into Node table*/
	exec @retcode = MergeNodes 0, @createdByUserSpecifier, @keepCreatedByUserOnReplace, @UserId
	if @@error <> 0 
	begin
		set @retcode = @@error
		goto cleanup
	end	
	
	/*import Node associated data*/
	exec @retcode = MergeNodeAssociatedData 0, @includeRightsGroups, @rightsOnAdd, @rightsOnReplace
	if @@error <> 0 
	begin
		set @retcode = @@error
		goto cleanup
	end	
	
	/*remove nodes that should be deleted either because of destructive
	  synchronization or because they were deleted on the source and 
	  incrementally deployed*/
	exec @retcode = PurgeDeletedNodes
	if @@error <> 0 
	begin
		set @retcode = @@error
		goto cleanup
	end	
	
cleanup:
	alter table Node enable trigger all

	return(@retcode)	
end


GO

GRANT EXEC ON dbo.MergeImportData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeLayouts')
	BEGIN
		PRINT 'Dropping Procedure MergeLayouts'
		DROP  Procedure  dbo.MergeLayouts
	END

GO

PRINT 'Creating Procedure MergeLayouts'
GO

create procedure dbo.MergeLayouts
with encryption
as
begin

	delete from LayoutProperty 
	where NodeId in
	(select SourceId from ##impNode)
	if @@error <> 0 return(1)

	delete from NodeLayout 
	where NodeId in
	(select SourceId from ##impNode)
	if @@error <> 0 return(1)

	insert into NodeLayout
	(NodeId, Id, Name, LayoutTemplateGUID, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
	select n.SourceId, na.Id, na.Name, LayoutTemplateGUID, 0, 0, 0
	from ##impNodeLayout na inner join ##impNode n
	on na.NodeId = n.Id
	if @@error <> 0 return(1)

	insert into LayoutProperty
	(NodeId, LayoutId, Id, PropName, IsControl, ControlId, 
	IsBeingInserted, IsBeingDeleted, IsBeingUpdated, PropValue)
	select n.SourceId, LayoutId, na.Id, PropName, IsControl, ControlId, 
	0, 0, 0, PropValue
	from ##impLayoutProperty na inner join ##impNode n
	on na.NodeId = n.Id
	if @@error <> 0 return(1)
end

GO

GRANT EXEC ON dbo.MergeLayouts TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeNodeACL')
	BEGIN
		PRINT 'Dropping Procedure MergeNodeACL'
		DROP  Procedure  dbo.MergeNodeACL
	END

GO

PRINT 'Creating Procedure MergeNodeACL'
GO

create procedure dbo.MergeNodeACL 
	(
	@rightsOnAdd tinyint,
	@rightsOnReplace tinyint
	)
with encryption
as
begin
	set nocount on


/* enum values for @rightsOnAdd and @rightsOnReplace
	ImportNone = 1,
	InheritFromParent = 2,
	UsePackageRights = 3,
	KeepExistingRights = 4,
	UnionPackageAndExistingRights = 5
*/

	if not (@rightsOnReplace = 4 or @rightsOnReplace = 5 )
	begin
		/*remove rights on replaced nodes*/
		delete from NodeRole 
		where NodeId in
		(select SourceId from ##impNode)
		if @@error <> 0 return(1)		
	end

	if @rightsOnAdd = 3 or @rightsOnReplace = 3	/*use package rights*/
	begin
		insert into NodeRole
		(NodeId, RoleGUID, IsBeingInserted, IsBeingUpdated, IsBeingDeleted)
		select n.SourceId, nr.RoleGUID, 0, 0, 0
		from ##impNode n inner join ##impNodeRole nr
		on n.Id = nr.NodeId 
		and n.Action = case when @rightsOnAdd = 3 and @rightsOnReplace = 3 then n.Action
							when @rightsOnAdd = 3 and @rightsOnReplace <> 3 then 1			 /*new nodes*/
							when @rightsOnAdd <> 3 and @rightsOnReplace = 3 then 2			/*replaced nodes*/
						end
		and n.SameRightsAsParent = 0
		where nr.RoleGUID in (select NodeGUID from Node where Type = 1048576)	/*make sure the rights group exists on the target*/
		if @@error <> 0 return(1)		
	end

	
	if @rightsOnReplace = 5	/*union package and existing rights*/
	begin
		insert into NodeRole
		(NodeId, RoleGUID, IsBeingInserted, IsBeingUpdated, IsBeingDeleted)
		select n.SourceId, nr.RoleGUID, 0, 0, 0
		from ##impNode n inner join ##impNodeRole nr
		on n.Id = nr.NodeId and n.Action = 2
		where nr.RoleGUID in (select NodeGUID from Node where Type = 1048576)	/*make sure the rights group exists on the target*/
		and not exists
		(select RoleGUID from NodeRole 		/*only add new rights*/
		where NodeId = n.SourceId
		and RoleGUID = nr.RoleGUID)
		if @@error <> 0 return(1)		
	end


	if @rightsOnAdd = 2 or @rightsOnReplace = 2
	begin
		/*set rights to inherit from their parent*/	
		insert into NodeRole
		(NodeId, RoleGUID, IsBeingInserted, IsBeingUpdated, IsBeingDeleted)
		select n.SourceId, nr.RoleGUID, 0, 0, 0
		from ##impNode n inner join Node parent
		on n.ParentGUID = parent.NodeGUID 
		and n.Action = case when @rightsOnAdd = 2 and @rightsOnReplace = 2 then n.Action
							when @rightsOnAdd = 2 and @rightsOnReplace <> 2 then 1 		 /*new nodes*/
							when @rightsOnAdd <> 2 and @rightsOnReplace = 2 then 2 		 /*replaced nodes*/
						end
		and n.SameRightsAsParent = 0
		inner join NodeRole nr on parent.Id = nr.NodeId

		while @@rowcount > 0 
		begin
			insert into NodeRole
			(NodeId, RoleGUID, IsBeingInserted, IsBeingUpdated, IsBeingDeleted)
			select n.SourceId, nr.RoleGUID, 0, 0, 0
			from ##impNode n inner join Node parent
			on n.ParentGUID = parent.NodeGUID 
			and n.Action = case when @rightsOnAdd = 2 and @rightsOnReplace = 2 then n.Action
								when @rightsOnAdd = 2 and @rightsOnReplace <> 2 then 1 		 /*new nodes*/
								when @rightsOnAdd <> 2 and @rightsOnReplace = 2 then 2 		 /*replaced nodes*/
							end
			and n.SameRightsAsParent = 0
			inner join NodeRole nr on parent.Id = nr.NodeId			
			where not exists
			(select RoleGUID from NodeRole 		/*only add new rights*/
			where NodeId = n.SourceId
			and RoleGUID = nr.RoleGUID)
		end
		
	end
end

GO

GRANT EXEC ON dbo.MergeNodeACL TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeNodeAssociatedData')
	BEGIN
		PRINT 'Dropping Procedure MergeNodeAssociatedData'
		DROP  Procedure  dbo.MergeNodeAssociatedData
	END

GO

PRINT 'Creating Procedure MergeNodeAssociatedData'
GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to merge Node associated data from the import temporary tables into
 *	the main CMS tables
 *
 *	@param @usersAndRightsGroupsOnly	specifies only rights groups are
 *										being imported
 *	@param	@includeRightsGroups		specifies how to import rights
 *										groups and membership
 *	@param @rightsOnAdd					how to set rights on newly created nodes
 *	@param @rightsOnReplace				how to set rights on existing nodes
 *
 *	@see MergeImportData
*/
create procedure dbo.MergeNodeAssociatedData 
	(
	@usersAndRightsGroupsOnly tinyint,
	@includeRightsGroups tinyint,
	@rightsOnAdd tinyint,
	@rightsOnReplace tinyint
	)
with encryption
as
begin
	set nocount on

	declare @retcode int
	set @retcode = 0


/* enum values for @rightsOnAdd and @rightsOnReplace
	ImportNone = 1,
	InheritFromParent = 2,
	UsePackageRights = 3,
	KeepExistingRights = 4,
	UnionPackageAndExistingRights = 5
*/

	/*import user role  members*/
	exec @retcode = MergeUserRoleMembers @includeRightsGroups
	if @retcode <> 0 return (@retcode)

	/*generic properties*/
	delete from NodeProperty 
	where NodeId in
	(select SourceId from ##impNode)
	if @@error <> 0 return(1)

	insert into NodeProperty
	(NodeId, Id, PropName, PropValue, PropType, PropValueLong, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
	select n.SourceId, na.Id, na.PropName, na.PropValue, na.PropType, na.PropValueLong, 0, 0, 0
	from ##impNodeProperty na inner join ##impNode n
	on na.NodeId = n.Id
	if @@error <> 0 return(1)

	if @usersAndRightsGroupsOnly = 0
	begin
		/*import Node ACL*/
		exec @retcode = MergeNodeACL @rightsOnAdd, @rightsOnReplace
		if @retcode <> 0 return (@retcode)
	
		/*resources*/
		delete from NodeResource 
		where NodeId in
		(select SourceId from ##impNode)
		if @@error <> 0 return(1)
	
		insert into NodeResource
		(NodeId, Id, Name, IsLink, ResourceBlobId, NodeGUID, LinkAnchor, URL, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
		select n.SourceId, na.Id, na.Name, na.IsLink, blob.BlobId, na.NodeGUID, na.LinkAnchor, na.URL, 0, 0, 0
		from (##impNodeResource na inner join ##impNode n
		on na.NodeId = n.Id)
		left join ##impBlobData tmpblob
		on na.ResourceBlobId = tmpblob.BlobId
		left join BlobTable blob
		on tmpblob.BlobGUID = blob.BlobGUID
	
		if @@error <> 0 return(1)

		/*import placeholders*/
		exec @retcode = MergePlaceholders
		if @retcode <> 0 return (@retcode)
	
	end
end

GO

GRANT EXEC ON dbo.MergeNodeAssociatedData TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeNodes')
	BEGIN
		DROP  Procedure  dbo.MergeNodes
	END

GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to merge data from the ##impNode temporary tables into the Node table
 *
 *	@param @usersAndRightsGroupsOnly	specifies only rights groups are
 *										being imported
 *	@param @createdByUserSpecifier		whether to set CreatedBy to current 
 *										user or use package info
 *	@param @keepCreatedByUserOnReplace	whether to preserve CreatedBy for 
 *										existing nodes
 *	@param @UserId						Id of the user running the import operation
 *
 *	@see MergeImportData
*/
create procedure dbo.MergeNodes
	(
	@usersAndRightsGroupsOnly tinyint,
	@createdByUserSpecifier tinyint,
	@keepCreatedByUserOnReplace tinyint,
	@UserId int
	)
with encryption
as
begin
/* enum values for @createdByUserSpecifier
	CurrentUser = 1
	UsePackage = 2
*/
	set nocount on
	declare @errorcode int
	set @errorcode = 0
	
	declare @sql nvarchar(4000)
	
	declare @dateCurrent datetime, @DateGMT datetime
	select @dateCurrent = GETDATE()
	exec GetGMTTime @dateCurrent, @dateGMT out
	
	if @@error <> 0 return (@@error)
	
	declare @OwnerId int
	select @OwnerId = UserId from AEUser where UsernameUpper = 'EVERYBODY'

	if @@error <> 0 return (@@error)

	
	/*update existing nodes first*/
	set @sql =  N'update [' + db_name() + N'].dbo.Node
	set IsLocked=0
		,IsCheckedOut=0
		,IsCheckedOutVersion=0
		,HasCheckedInVersion=1
		,CheckedInVersionHasExisted=1
		,IsShortcut=tmp.IsShortcut
		,IsBeingInserted=0
		,IsHighPriority=tmp.IsHighPriority
		,SameRightsAsParent=tmp.SameRightsAsParent
		,ReadyForApproval=tmp.ReadyForApproval
		,ApprovalStatus=tmp.ApprovalStatus
		,SortOrdinal=tmp.SortOrdinal
		,ParentGUID=tmp.ParentGUID
		,FollowGUID=tmp.FollowGUID
		,DeletedWhen= case when tmp.DeletedWhen is not null then @dateGMT else tmp.DeletedWhen end
		,DeletedByUserId= case when tmp.DeletedWhen is not null then @UserId else null end
		,CreatedByUserId = case when @keepCreatedByUserOnReplace = 1 then n.CreatedByUserId
				 	  		    when @createdByUserSpecifier = 1 then @UserId
				 	  		    when tmp.CreatedByUser is null then @UserId
					     	    else isnull((select UserId from AEUser where UsernameUpper = tmp.CreatedByUser), @UserId)  end
		,ModifiedByUserId= @UserId
		,ModifiedWhen=@dateGMT
		,ApprovedByUserId = @UserId
		,EffectiveDate=tmp.EffectiveDate
		,ExpiryDate=tmp.ExpiryDate
		,TemplateGUID=tmp.TemplateGUID
		,ApprovedWhen=@dateGMT
		,LockUserId=NULL
		,LockMachinename=NULL
		,Name=case when tmp.IsShortcut = 0 then tmp.Name
				else NULL
			  end
		,TemplateType=tmp.TemplateType
		,IsHiddenModePublished=tmp.IsHiddenModePublished
		,IsRobotFollowable=tmp.IsRobotFollowable
		,IsRobotIndexable=tmp.IsRobotIndexable
		,DisplayName=tmp.DisplayName
		,PageDefinitionGUID=tmp.PageDefinitionGUID
		,DeletedByClientId=NULL
		,CreatedByClientId=NULL
		,ModifiedByClientId=NULL
		,ApprovedByClientId=NULL
		,OwnerClientId=NULL
		,LockClientId=NULL
		,CheckedOutByUserId=NULL
		,CheckedOutByMachine=NULL
		,UserRoleType = tmp.UserRoleType
		,OuterScriptFile = tmp.OuterScriptFile
		,UseOuterScriptForPostings = tmp.UseOuterScriptForPostings
		,DefaultPostingName = tmp.DefaultPostingName
		,TemplateAspPath=tmp.TemplateAspPath
		,SchemaXML=tmp.SchemaXML
		,LastChangeTime = @dateGMT
	from .dbo.##impNode tmp inner join [' + db_name() + N'].dbo.Node n
	on tmp.SourceId = n.Id and tmp.SourceId > 0 and n.ArchiveSourceGUID is null'
	
	exec sp_executesql @sql,
	N'@dateGMT datetime, @createdByUserSpecifier tinyint, @keepCreatedByUserOnReplace tinyint,
	@UserId int', 
	@dateGMT, @createdByUserSpecifier, @keepCreatedByUserOnReplace, @UserId

	if @@error <> 0 return (@@error)
	
	/*now insert the new nodes*/
	set @sql =  N'insert into [' + db_name() + N'].dbo.Node
		(IsLocked, IsCheckedOut, IsCheckedOutVersion, HasCheckedInVersion, CheckedInVersionHasExisted, 
		IsShortcut, IsBeingInserted, IsHighPriority, SameRightsAsParent, ReadyForApproval, ApprovalStatus, 
		Type, SortOrdinal, NodeGUID, ParentGUID, FollowGUID, 
		DeletedWhen, DeletedByUserId, 
		CreatedByUserId, 
		CreatedWhen, ModifiedByUserId, ModifiedWhen, OwnerId, ApprovedByUserId, 
		EffectiveDate, ExpiryDate, TemplateGUID,  
		ApprovedWhen, Name, TemplateType,  
		IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, DisplayName, 
		PageDefinitionGUID, TemplateAspPath, SchemaXML,
		UserRoleType, OuterScriptFile, UseOuterScriptForPostings, DefaultPostingName,
		LastChangeTime)	
	select 0,0, 0, 1, 1,
		tmp.IsShortcut, 0, tmp.IsHighPriority, tmp.SameRightsAsParent, tmp.ReadyForApproval, tmp.ApprovalStatus,
		tmp.Type, tmp.SortOrdinal, tmp.NodeGUID, tmp.ParentGUID, tmp.FollowGUID,
		tmp.DeletedWhen, case when tmp.DeletedWhen is not null then @UserId else null end, 
		case when @createdByUserSpecifier = 1 then @UserId
  		     when tmp.CreatedByUser is null then @UserId
			 else isnull((select UserId from AEUser where UsernameUpper = tmp.CreatedByUser), @UserId)
			end,
		case when @usersAndRightsGroupsOnly = 1 then @dateGMT else tmp.CreatedWhen end,
		@UserId, @dateGMT, @OwnerId, @UserId,
		tmp.EffectiveDate, tmp.ExpiryDate, tmp.TemplateGUID, 
		@dateGMT, case when tmp.IsShortcut = 0 then tmp.Name else NULL end, 
		tmp.TemplateType,
		tmp.IsHiddenModePublished, tmp.IsRobotFollowable, tmp.IsRobotIndexable, tmp.DisplayName,
		tmp.PageDefinitionGUID, tmp.TemplateAspPath, tmp.SchemaXML,
		tmp.UserRoleType, tmp.OuterScriptFile, tmp.UseOuterScriptForPostings, tmp.DefaultPostingName,
		@dateGMT
	from .dbo.##impNode tmp 
	where not exists
	(select NodeGUID from Node where NodeGUID = tmp.NodeGUID and ArchiveSourceGUID is null)'
	
	exec sp_executesql @sql,
	N'@dateGMT datetime, @createdByUserSpecifier tinyint, @keepCreatedByUserOnReplace tinyint,
	@UserId int, @usersAndRightsGroupsOnly tinyint, @OwnerId int', 
	@dateGMT, @createdByUserSpecifier, @keepCreatedByUserOnReplace, @UserId, 
	@usersAndRightsGroupsOnly, @OwnerId

	if @@error <> 0 return (@@error)
	
	/*now update ##impNode table with the generated IDs for new nodes
	  this will prevent having multiple lookups when merging associated data
	*/
	set @sql = N'update .dbo.##impNode 
	set SourceId = n.Id
	from [' + db_name() + '].dbo.Node n inner join .dbo.##impNode tmp 
	on n.NodeGUID = tmp.NodeGUID'
	
	exec sp_executesql @sql
	
	return(@@error)
end
GO

GRANT EXEC ON dbo.MergeNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergePlaceholders')
	BEGIN
		PRINT 'Dropping Procedure MergePlaceholders'
		DROP  Procedure  dbo.MergePlaceholders
	END

GO

PRINT 'Creating Procedure MergePlaceholders'
GO

create procedure dbo.MergePlaceholders
with encryption
as
begin
	set nocount on

	/*placeholders*/
	delete from NodePlaceholderContent 
	where NodeId in
	(select SourceId from ##impNode
	)
	if @@error <> 0 return(1)

	delete from NodePlaceholder 
	where NodeId in
	(select SourceId from ##impNode
	)
	if @@error <> 0 return(1)

	insert into NodePlaceholder
	(NodeId, Id, Name, ControlGUID, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
	select n.SourceId, na.Id, na.Name, '{A767B720-71C5-11D1-88BE-006097B58A00}', 0, 0, 0
	from ##impNodePlaceholder na inner join ##impNode n
	on na.NodeId = n.Id
	if @@error <> 0 return(1)

	insert into NodePlaceholderContent
	(NodeId, PlaceholderId, Id, PropName, IsResource, ResourceId, 
	IsBeingInserted, IsBeingDeleted, IsBeingUpdated, PropValue)
	select n.SourceId, na.PlaceholderId, na.Id, na.PropName, na.IsResource, na.ResourceId, 0, 0, 0, PropValue
	from ##impNodePlaceholderContent na inner join ##impNode n
	on na.NodeId = n.Id 
	if @@error <> 0 return(1)

end

GO

GRANT EXEC ON dbo.MergePlaceholders TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeUserRoleMembers')
	BEGIN
		PRINT 'Dropping Procedure MergeUserRoleMembers'
		DROP  Procedure  dbo.MergeUserRoleMembers
	END

GO

PRINT 'Creating Procedure MergeUserRoleMembers'
GO

create procedure dbo.MergeUserRoleMembers
	(
	@includeRightsGroups tinyint
	)	
with encryption
as
begin
	set nocount on
/* enum values for @includeRightsGroups
	ImportNone = 1,
	ImportWithoutMembers = 2,
	ImportWithMembersUsePackage = 3,
	ImportWithMembersUnionPackageAndExisting = 4
*/

	if @includeRightsGroups = 3 
	begin
		/*delete existing role members if we should
		overwrite membership with members from the package*/
		delete from UserRoleMember 
		where NodeId in
		(select SourceId from ##impNode
		where Type = 1048576)
		if @@error <> 0 return(1)

		/*add members from the package*/
		insert into UserRoleMember
		(NodeId, UserId, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
		select n.SourceId, u.UserId, 0, 0, 0
		from ##impUserRoleMember na inner join ##impNode n
		on na.NodeId = n.Id and n.Type = 1048576
		inner join AEUser u on na.Username = u.UsernameUpper
		if @@error <> 0 return(1)
	end

	if @includeRightsGroups = 4
	begin
		insert into UserRoleMember
		(NodeId, UserId, IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
		select n.SourceId, u.UserId, 0, 0, 0
		from ##impUserRoleMember na inner join ##impNode n
		on na.NodeId = n.Id and n.Type = 1048576
		inner join AEUser u on na.Username = u.UsernameUpper
		where u.UserId not in
		(select urm.UserId from UserRoleMember urm
		where urm.NodeId = n.SourceId)

		if @@error <> 0 return(1)
	end

end


GO

GRANT EXEC ON dbo.MergeUserRoleMembers TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'MergeUsersAndRightsGroups')
	BEGIN
		PRINT 'Dropping Procedure MergeUsersAndRightsGroups'
		DROP  Procedure  dbo.MergeUsersAndRightsGroups
	END

GO

PRINT 'Creating Procedure MergeUsersAndRightsGroups'
GO

create procedure dbo.MergeUsersAndRightsGroups
	(
	@includeRightsGroups tinyint
	,@removeExistingMembers tinyint
	,@UserId int
	)
with encryption
as
begin
	set nocount on

	declare @retcode int
	set @retcode = 0

/* enum values for @includeRightsGroups
	ImportNone = 1,
	ImportWithoutMembers = 2,
	ImportWithMembersUsePackage = 3,
	ImportWithMembersUnionPackageAndExisting = 4
*/

	/*first off, import users*/
	insert into AEUser (Username, UsernameUpper, UserSID)
	select Username, UsernameUpper, UserSID
	from ##impAEUser tmp
	where not exists
	(select UsernameUpper from AEUser where UsernameUpper = tmp.UsernameUpper)


	if @@error <> 0 return(1)

	if @removeExistingMembers = 1
	begin
		--remove membership from the existing rights groups
		
		DECLARE @dateGMT datetime, @dateCurrent datetime, @MaxCommit datetime, @CommitTime datetime
		select @dateCurrent = GETDATE()

		exec GetGMTTime @dateCurrent, @dateGMT out

		select  @MaxCommit = MAX( CommitTime ) from ChangeTable WITH(UPDLOCK) 
		select  @CommitTime = case when @dateGMT <= @MaxCommit then DateAdd( ms, 3, @MaxCommit ) else @dateGMT END
		
		update dbo.Node set LastChangeTime = @dateGMT
							,ModifiedWhen = @CommitTime
		where Id in
		(select NodeId from dbo.UserRoleMember
		where not (
			NodeId in
				(select Id from dbo.Node
				where Name = 'Administrator'
				)
			and UserId = @UserId
			)
		)
		
		UPDATE ChangeTable 
			SET Reason = 1, 
			LastChangeTime = nodes.LastChangeTime,
			CommitTime = @CommitTime,
			ParentGUID = nodes.ParentGUID,
			Type = nodes.Type,
			IsShortcut = nodes.IsShortcut,
			Name = nodes.Name
			from dbo.Node nodes 		
			where ChangeTable.NodeGUID = nodes.NodeGUID and
			nodes.Id in
			(select NodeId from dbo.UserRoleMember
			where not (
				NodeId in
					(select Id from dbo.Node
					where Name = 'Administrator'
					)
				and UserId = @UserId
				)
			)
		
		delete from dbo.UserRoleMember
		where not (
		NodeId in
			(select Id from dbo.Node
			where Name = 'Administrator'
			)
		and UserId = @UserId
		)
		
	end
	
	/*now merge nodes into Node table*/
	exec @retcode = MergeNodes 1, 1/*new nodes created by current user*/, 1/*keep existing created by*/, @UserId
	if @retcode <> 0 return (@retcode)

	/*import Node associated data*/
	exec @retcode = MergeNodeAssociatedData 1, @includeRightsGroups, 1/*no rights on add*/, 4/*keep existing on replace*/
	if @retcode <> 0 return (@retcode)

	return (@retcode)

end

GO

GRANT EXEC ON dbo.MergeUsersAndRightsGroups TO PUBLIC

GO



IF EXISTS (SELECT name 
	   FROM   sysobjects 
	   WHERE  name = N'MoveNodesToDefaultContainer' 
	   AND 	  type = 'P')
    DROP PROCEDURE dbo.MoveNodesToDefaultContainer
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It assigns objects that do not have parents on the target system
 *  to default containers. If a default container is not specified
 *	it creates a new container under the root folder.
 *
 *	@param @defaultResourceGallery		guid of default resource gallery
 *	@param @defaultTemplateGallery		guid of default template gallery
 *	@param @defaultFolder				guid of default folder
 *	@param @defaultChannel				guid of default channel
 *	@param @UserId						Id for the user running import 
 *
 *	@see PrepareImportDataForMerge
 *	@see CreateDefaultContainer
 */
create  procedure dbo.MoveNodesToDefaultContainer
	(
	@defaultResourceGallery char(38),
	@defaultTemplateGallery char(38),
	@defaultFolder char(38),
	@defaultChannel char(38),
	@UserId int
	)
with encryption
as
begin
	set nocount on

	declare @retcode int
	set @retcode = 0

	declare @createResourceGallery tinyint
	declare @createTemplateGallery tinyint
	declare @createFolder tinyint
	declare @createChannel tinyint

	set @createResourceGallery = 0
	set @createTemplateGallery = 0
	set @createFolder = 0
	set @createChannel = 0

	/*if default container is not specified, so we should create one*/

	if isnull(@defaultResourceGallery, '') = ''
	begin
		set @defaultResourceGallery = '{' + convert(varchar(38), NEWID()) + '}'
		set @createResourceGallery = 1
	end

	if isnull(@defaultTemplateGallery, '') = ''
	begin
		set @defaultTemplateGallery = '{' + convert(varchar(38), NEWID()) + '}'
		set @createTemplateGallery = 1
	end

	if isnull(@defaultFolder, '') = ''
	begin
		set @defaultFolder = '{' + convert(varchar(38), NEWID()) + '}'
		set @createFolder = 1
	end

	if isnull(@defaultChannel, '') = ''
	begin
		set @defaultChannel = '{' + convert(varchar(38), NEWID()) + '}'
		set @createChannel = 1
	end

	/*assign nodes that do not have a parent to the specified default container*/
	update ##impNode
	set ParentGUID = case
		when Type = 64 or Type = 256 then @defaultResourceGallery
		when Type = 16384 or Type = 65536 then @defaultTemplateGallery
		when Type = 2097252 or (Type = 16 and IsShortcut = 0) then @defaultFolder
		when Type = 4 or (Type = 16 and IsShortcut = 1) then @defaultChannel
		else ParentGUID
		end
	where ParentGUID is not null 	
	and not exists 
	( select NodeGUID from Node n 
	  where n.NodeGUID = ##impNode.ParentGUID
		and n.IsCheckedOutVersion = 0 and n.ArchiveSourceGUID is null
	)
	and ParentGUID not in
	( select NodeGUID from ##impNode where SourceId = 0
	)

	if @@error <> 0 return(1)

	/*now create default containers if needed*/
	if @createResourceGallery = 1 and 
		exists(select Id from ##impNode where ParentGUID = @defaultResourceGallery)
	begin
			exec @retcode = CreateDefaultContainer 64, @defaultResourceGallery
			if @retcode <> 0 return (@retcode)
	end

	if @createTemplateGallery = 1 and 
		exists(select Id from ##impNode where ParentGUID = @defaultTemplateGallery)
	begin
			exec @retcode = CreateDefaultContainer 16384, @defaultTemplateGallery
			if @retcode <> 0 return (@retcode)
	end

	if @createFolder = 1 and 
		exists(select Id from ##impNode where ParentGUID = @defaultFolder)
	begin
			exec @retcode = CreateDefaultContainer 2097252, @defaultFolder
			if @retcode <> 0 return (@retcode)
	end

	if @createChannel = 1 and 
		exists(select Id from ##impNode where ParentGUID = @defaultChannel)
	begin
			exec @retcode = CreateDefaultContainer 4, @defaultChannel
			if @retcode <> 0 return (@retcode)
	end

	return(@retcode)
end
GO

GRANT EXEC ON dbo.MoveNodesToDefaultContainer TO PUBLIC
GO




IF EXISTS (SELECT name 
	   FROM   sysobjects 
	   WHERE  name = N'PrepareImportDataForMerge' 
	   AND 	  type = 'P')
    DROP PROCEDURE dbo.PrepareImportDataForMerge
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It massages the import data so that we can efficiently merge it.
 *	Most of the work is related to container synchronization:
 *   - assigning objects that do not have parents on the target
 *     to default containers,
 *	 - creating default containers not provided in the import
 *	   options
 *	 - finding objects that should be removed from the target
 *	   if destructive synchronization is requested
 *	- verifying that the objects can be deleted
 *
 *	@param	@containerSyncOption		specifies whether to synchronize
 *										container hierarchy with the source
 *	@param @usersAndRightsGroupsOnly 	set to 1 when importing users and 
 *										rights groups only. This applies to 
 *										full deployment when rights group
 *										membership is exported from the 
 *										target system before replacing the
 *										database with the source database.
 *	@param @defaultResourceGallery		guid of default resource gallery
 *	@param @defaultTemplateGallery		guid of default template gallery
 *	@param @defaultFolder				guid of default folder
 *	@param @defaultChannel				guid of default channel
 *	@param @UserId						Id for the user running import 
 *	@param @getReportData				indicates whether the report is
 *										generated after the import. The report
 *										needs some additional data that we
 *										otherwise do not collect
 *
 *	@see MoveNodesToDefaultContainer
 *	@see PrepareNodesForDelete
*/
create  procedure dbo.PrepareImportDataForMerge
	(
	@containerSyncOption tinyint,
	@usersAndRightsGroupsOnly tinyint,
	@defaultResourceGallery char(38),
	@defaultTemplateGallery char(38),
	@defaultFolder char(38),
	@defaultChannel char(38),
	@UserId int,
	@getReportData tinyint
	 )
with encryption
as
begin

	set nocount on

	declare @retcode int
	set @retcode = 0

/*enum ImportContainerSyncOption
	NoSync = 1,
	SyncNonDestructive = 2,
	SyncDestructive = 3
*/
	declare @ArchiveFolderGUID varchar(38)
	select @ArchiveFolderGUID = PropValue from NodeProperty where PropName = '_ArchiveFolder'

	/*find objects that already exists in the target and 
	get their Id, lock and checkout Status. 
	if we are not synchronizing container hierarchy
	we should get the parent from the target for the existing nodes unless it's an archived resource gallery item.
	When we delete RGI we always place them in ArchiveFolder; import should move them back to the parent
	specified in the package
	This should cover all nodes but checked out postings*/

	update ##impNode
		set SourceId = n.Id,
		Action = case when n.Type = 256 and n.ParentGUID = @ArchiveFolderGUID then 1 else 2 end,
		IsCheckedOut = n.IsCheckedOut,
		ParentGUID = case when @containerSyncOption = 1 and (n.Type <> 256 or n.ParentGUID <> @ArchiveFolderGUID )then n.ParentGUID 
						  when n.Type = 256 and n.ParentGUID = @ArchiveFolderGUID then tmp.ParentGUID
						  else tmp.ParentGUID 
					 end
	from ##impNode tmp inner join Node n
	on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 0 and n.ArchiveSourceGUID is null

	/*update postings now*/
	update ##impNode
		set SourceId = n.Id,
		Action = 2,
		IsCheckedOut = n.IsCheckedOut,
		ParentGUID = case when @containerSyncOption = 1 then n.ParentGUID else tmp.ParentGUID end
	from ##impNode tmp inner join Node n
	on tmp.NodeGUID = n.NodeGUID and n.Type = 16 and n.IsShortcut = 1


	if @@error <> 0 return (1)

	/*if we should generate a report find nodes that are locked,
	  we'll include lock Status in the report*/
	if @getReportData = 1
	begin
		update ##impNode
			set IsLocked = n.IsLocked,
			LockUserId = n.LockUserId,
			LockMachinename = n.LockMachinename
		from ##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and 
		n.IsLocked = 1

		if @@error <> 0 return(1)
	end

	/*if we're importing just rights groups we don't have to worry about
	  missing parent or deleted nodes*/
	if @usersAndRightsGroupsOnly = 0
	begin
		/*find objects that do not have parent on the target
		and assign them to default containers*/
		/*create default containers that are not provided in the import options */
		exec @retcode = MoveNodesToDefaultContainer @defaultResourceGallery,
										 @defaultTemplateGallery,
										 @defaultFolder,
										 @defaultChannel,
										 @UserId
	
		if @retcode <> 0 return (@retcode)

		/*compile a list of objects that should be removed from the target
		if destructive synchronization is requested or
		if deleted objects are deployed incrementally */
		exec PrepareNodesForDelete @containerSyncOption, @getReportData
	end

end
GO

GRANT EXEC ON dbo.PrepareImportDataForMerge TO PUBLIC
GO



IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'PrepareNodesForDelete')
	BEGIN
		PRINT 'Dropping Procedure PrepareNodesForDelete'
		DROP  Procedure  dbo.PrepareNodesForDelete
	END

GO

PRINT 'Creating Procedure PrepareNodesForDelete'
GO

/**
 *	This stored procedure is used for Site Deployment import operation.
 *  It finds objects that should be removed from the target if 
 *	destructive synchronization is requested and verifies that the 
 *	objects can be deleted
 *
 *	@param	@containerSyncOption		specifies whether to synchronize
 *										container hierarchy with the source
 *	@param @getReportData				indicates whether the report is
 *										generated after the import. The report
 *										needs some additional data that we
 *										otherwise do not collect
 *
 *	@see PrepareImportDataForMerge
 *	@see CalculateLocationForDeletedNodes
*/
create procedure dbo.PrepareNodesForDelete
	(
	@containerSyncOption tinyint,
	@getReportData tinyint
	)
with encryption
as 
begin
	set nocount on
	declare @Level int

	declare @retcode int
	set @retcode = 0
/*Enum values for Status
	2 - TemplateFailed
	4 - PageDefinitionFailed

*/
/*Enum values for Reason
	1 - IcrementalDeployment	populated when staging data to temp tables
	2 - DestructiveSync

*/
	/*if there are nodes that were deleted on the source system
	  make sure they exist on the target*/
	  if exists (select top 1 NodeGUID from ##impNodesToDelete)
	  begin
		update ##impNodesToDelete 
		set CannotDelete = 1
		where not exists
		(select NodeGUID from Node n
		where n.NodeGUID = ##impNodesToDelete.NodeGUID)
	  end 

	/*get immediate children that should be removed as a result of destructive sync.
	  ##impNodesToDelete table is already populated with nodes that were deleted
	  in the source database, but since incremental deployment doesn't perform
	  destructive synchronization we don't check for overlap
	*/
	if @containerSyncOption = 3	
	begin
		insert into ##impNodesToDelete (NodeGUID
										,ParentGUID
										,TopParentGUID
										,Type
										,IsShortcut
										,Level
										,Reason
										,Name
										,FollowGUID
										,TemplateGUID
										,PageDefinitionGUID)
		select	d.NodeGUID
				,d.ParentGUID
				,d.TopParentGUID
				,d.Type
				,d.IsShortcut
				,0
				,2
				,d.Name
				,d.FollowGUID
				,d.TemplateGUID
				,d.PageDefinitionGUID
		from 
		( select n.NodeGUID
				,n.ParentGUID
				,n.NodeGUID as TopParentGUID
				,n.Type
				,n.IsShortcut
				,n.Name
				,n.FollowGUID
				,n.TemplateGUID
				,n.PageDefinitionGUID
		  from Node n inner join ##impNode tmp
		  on n.ParentGUID = tmp.NodeGUID and tmp.SourceId > 0 and tmp.IsDependent = 0
		  and n.IsCheckedOutVersion = 0 and n.ArchiveSourceGUID is null
		) as d												/*get immediate children of the containers being replaced*/
		where not exists  
		( 
			select NodeGUID from ##impNode 
			where NodeGUID = d.NodeGUID
		)	/*that are not being deployed*/
		if @@error <> 0 return(1)

	end

	/*if we need to generate a report then we should populate the Location info
	 for deleted nodes*/
	if @getReportData = 1
	begin
		exec @retcode = CalculateLocationForDeletedNodes
		if @retcode <> 0 return(@retcode)
	end


	/*get all descendants of the nodes being deleted */
	if exists (select top 1 NodeGUID from ##impNodesToDelete where CannotDelete = 0) 
	begin
		set @Level = 0
		while 1=1
		begin
			insert into ##impNodesToDelete(	NodeGUID
											,ParentGUID
											,TopParentGUID
											,Type
											,IsShortcut
											,Level
											,Reason
											,Name
											,FollowGUID
											,TemplateGUID
											,PageDefinitionGUID
											,Location)
			select	n.NodeGUID
					,n.ParentGUID
					,del.TopParentGUID
					,n.Type
					,n.IsShortcut
					,@Level + 1
					,del.Reason
					,n.Name
					,n.FollowGUID
					,n.TemplateGUID
					,n.PageDefinitionGUID 
			--populating Location at the same time
					,case	when @getReportData = 1 then 
								convert(nvarchar(4000), cast(del.Location as nvarchar(4000)) + '/' + del.Name)	
							else null
					end
			from Node n inner join ##impNodesToDelete del
			on n.ParentGUID = del.NodeGUID and del.Level = @Level and n.IsCheckedOutVersion = 0
			and n.ArchiveSourceGUID is null
			where not exists 
			(
				select NodeGUID from ##impNode 
				where SourceId > 0
				and NodeGUID = n.NodeGUID
			)
			and not exists  
			( 
				select NodeGUID from ##impNodesToDelete 
				where NodeGUID = n.NodeGUID
			)	

			if @@rowcount = 0 
				break

			set @Level = @Level + 1
		end
	end	

	/*find postings that depend on the templates being deleted*/
	update ##impNodesToDelete 
	set Status = Status | 2,		/*TemplateFailed*/
	CannotDelete = 1
	from ##impNodesToDelete del inner join Node n
		on del.NodeGUID = n.TemplateGUID and del.Type = 65536 
		and n.ArchiveSourceGUID is null
	where not exists 
	(
		select NodeGUID from ##impNodesToDelete 
		where NodeGUID = n.NodeGUID
		and Type = 16 and IsShortcut = 1
	)	/*make sure we're not deleting these postings already*/

	if @@error <> 0 return(1)

	/*find templates that depend on the page definitions being deleted*/
	update ##impNodesToDelete 
	set Status = Status | 4,		/*PageDefinitionFailed*/
	CannotDelete = 1
	from ##impNodesToDelete del inner join Node schemas 
		on del.NodeGUID = schemas.NodeGUID and del.Type = 33554432 and schemas.IsCheckedOutVersion = 0
		inner join Node templates on schemas.NodeGUID = templates.PageDefinitionGUID and 
		templates.ArchiveSourceGUID is null
	where not exists 
	(
		select NodeGUID from ##impNodesToDelete 
		where NodeGUID = templates.NodeGUID
		and Type = 65536
	)	/*make sure we're not deleting these templates already*/

	if @@error <> 0 return(1)

	/*if we're removing postings we should remove their pages also if there are no other postings based on them*/
	insert into ##impNodesToDelete(NodeGUID, ParentGUID, TopParentGUID, Type, IsShortcut, 
									Level, Reason, Name)
	select distinct page.NodeGUID, page.ParentGUID, page.ParentGUID, page.Type, page.IsShortcut, 
	0, 2, page.Name
	from ##impNodesToDelete posting inner join Node page on 
	page.NodeGUID = posting.FollowGUID 
	and page.ArchiveSourceGUID is null
	and (page.IsCheckedOutVersion = 0 or (page.CheckedInVersionHasExisted = 0 and page.IsCheckedOutVersion = 1))
	and posting.Type = 16 and posting.IsShortcut = 1 
	and posting.CannotDelete = 0
	and not exists 
	(
		select 1 from ##impNodesToDelete 
		where NodeGUID = page.NodeGUID
		and Type = 16 and IsShortcut = 0 
		and ArchiveSourceGUID is null
	)
	and not exists 
	(
		select 1 from Node postings 
		where FollowGUID = page.NodeGUID
		and Type = 16 and IsShortcut = 1 
		and ArchiveSourceGUID is null
		and not exists 
		(
			select 1 from ##impNodesToDelete 
			where NodeGUID = postings.NodeGUID
			and Type = 16 and IsShortcut = 1 
			and ArchiveSourceGUID is null
		)		
	)
	
	if @@error <> 0 return(1)

	/*make sure we have names and Location for all postings if we're generating a report*/
	if @getReportData = 1
	begin
		/*this will populate missing Location info for postings we're taking along with the pages*/
		exec @retcode = CalculateLocationForDeletedNodes

		if @retcode <> 0 return(@retcode)

		/*get posting names from their pages*/
		update ##impNodesToDelete set Name = page.Name
		from Node page, Node posting
		where ##impNodesToDelete.Name is null and 
		##impNodesToDelete.NodeGUID = posting.NodeGUID and 
		posting.FollowGUID = page.NodeGUID and
		page.IsCheckedOutVersion = 0

		if @@error <> 0 return(1)
	
	end

	/*if we have a Node that failed the check then we can't delete its parent containers 
	all the way up to the immediate child of the container being synchronized destructively */
	update ##impNodesToDelete set CannotDelete = 1 
	where  TopParentGUID in
	(select TopParentGUID from ##impNodesToDelete failednodes where failednodes.Status > 0)

	return(@@error)

end

GO

GRANT EXEC ON dbo.PrepareNodesForDelete TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'PurgeDeletedNodeArchives')
	BEGIN
		PRINT 'Dropping Procedure PurgeDeletedNodeArchives'
		DROP  Procedure  dbo.PurgeDeletedNodeArchives
	END

GO

PRINT 'Creating Procedure PurgeDeletedNodeArchives'
GO


create procedure dbo.PurgeDeletedNodeArchives
with encryption
as
begin
	
	delete from NodeProperty 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)
	if @@error <> 0 return(1)

	delete from NodeRole 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)
	if @@error <> 0 return(1)

	delete from NodeResource 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)

	if @@error <> 0 return(1)

	delete from NodePlaceholderContent 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	and n.Type = 16 and n.IsShortcut = 0
	)

	if @@error <> 0 return(1)

	delete from NodePlaceholder 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	and n.Type = 16 and n.IsShortcut = 0
	)

	if @@error <> 0 return(1)

	delete from LayoutProperty 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)

	if @@error <> 0 return(1)

	delete from NodeLayout 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)

	if @@error <> 0 return(1)

	delete from NodeLock 
	where NodeId in
	(select n.Id from 
	Node n inner join ##impNodesToDelete tmp
	on n.ArchiveSourceGUID = tmp.NodeGUID and tmp.CannotDelete = 0
	)

	if @@error <> 0 return(1)

	delete Node 
	from ##impNodesToDelete
	where ArchiveSourceGUID = ##impNodesToDelete.NodeGUID

	return (@@error)
end


GO

GRANT EXEC ON dbo.PurgeDeletedNodeArchives TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'PurgeDeletedNodes')
	BEGIN
		PRINT 'Dropping Procedure PurgeDeletedNodes'
		DROP  Procedure  dbo.PurgeDeletedNodes
	END

GO

PRINT 'Creating Procedure PurgeDeletedNodes'
GO


create procedure dbo.PurgeDeletedNodes
with encryption
as
begin
	
	declare @retval int
	
	/*check if there nodes tp purge*/	
	if exists(select NodeGUID from ##impNodesToDelete where CannotDelete = 0)
	begin
		exec @retval = PurgeDeletedNodeArchives
		if @retval <> 0 return(1)

		delete from NodeProperty 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)
		if @@error <> 0 return(1)

		delete from NodeRole 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)
		if @@error <> 0 return(1)

		delete from NodeResource 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)

		if @@error <> 0 return(1)

		delete from NodePlaceholderContent 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		and n.Type = 16 and n.IsShortcut = 0
		)

		if @@error <> 0 return(1)

		delete from NodePlaceholder 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		and n.Type = 16 and n.IsShortcut = 0
		)

		if @@error <> 0 return(1)

		delete from LayoutProperty 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)

		if @@error <> 0 return(1)

		delete from NodeLayout 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)

		if @@error <> 0 return(1)

		delete from UserRoleMember 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		and n.Type = 1048576
		)

		if @@error <> 0 return(1)

		delete from NodeLock 
		where NodeId in
		(select n.Id from 
		Node n inner join ##impNodesToDelete tmp
		on n.NodeGUID = tmp.NodeGUID and tmp.CannotDelete = 0
		)

		if @@error <> 0 return(1)

		delete from Node 
		where NodeGUID in
		(select NodeGUID from 
		##impNodesToDelete 
		where CannotDelete = 0
		)

		if @@error <> 0 return(1)

	end

	return (@@error)
end


GO

GRANT EXEC ON dbo.PurgeDeletedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveDeletedObjects')
	BEGIN
		PRINT 'Dropping Procedure RetrieveDeletedObjects'
		DROP  Procedure  dbo.RetrieveDeletedObjects
	END

GO

PRINT 'Creating Procedure RetrieveDeletedObjects'
GO

create procedure dbo.RetrieveDeletedObjects
with encryption
as
begin

	select NodeGUID, ParentGUID, TopParentGUID, Type, 
	IsShortcut, Reason, Name, Location
	from ##impNodesToDelete
	where CannotDelete = 0
	order by TopParentGUID, Level


end
go


GRANT EXEC ON dbo.RetrieveDeletedObjects TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveImportBrokenLinks')
	BEGIN
		PRINT 'Dropping Procedure RetrieveImportBrokenLinks'
		DROP  Procedure  dbo.RetrieveImportBrokenLinks
	END

GO

PRINT 'Creating Procedure RetrieveImportBrokenLinks'
GO

create procedure dbo.RetrieveImportBrokenLinks

with encryption
as
begin

	select 
		NodeGUID
		,Type
		,cast(IsShortcut as tinyint)
		,Name
		,Location
	from ##impBrokenLinks

	select 
		tmp.LinkSourceGUID
		,tmp.LinkTargetGUID
		,p.Type
		,cast(p.IsShortcut as tinyint)
		,p.Name
	from ##impBrokenLinkTargets tmp left join ##impBrokenLinkPackageInfo p
	on tmp.LinkTargetGUID = p.LinkTargetGUID

end
go

GO

GRANT EXEC ON dbo.RetrieveImportBrokenLinks TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RetrieveImportedObjects')
	BEGIN
		PRINT 'Dropping Procedure RetrieveImportedObjects'
		DROP  Procedure  dbo.RetrieveImportedObjects
	END

GO

PRINT 'Creating Procedure RetrieveImportedObjects'
GO

create procedure dbo.RetrieveImportedObjects
	(
	@isPreview tinyint,
	@includeRightsGroups tinyint
	)
with encryption
as
begin
/* enum for includeRightsGroups
	ImportNone = 1,
	ImportWithoutMembers = 2,
	ImportWithMembersUsePackage = 3,
	ImportWithMembersUnionPackageAndExisting = 4

*/
	if @isPreview = 1
	begin
		DECLARE @dateGMT datetime, @dateCurrent datetime
		select @dateCurrent = GETDATE()
		
		exec GetGMTTime @dateCurrent, @dateGMT out
	
		select 
		/*source data*/
		tmp.NodeGUID
		,tmp.Type
		,tmp.IsShortcut
		,tmp.ParentGUID
		,tmp.Action
		,COALESCE(tmp.Name, tmp.DisplayName, page.Name, '')
		,tmp.Location
		,tmp.ModifiedWhen
		/*after import data*/
		,tmp.LocationAfterImport
		,@dateGMT as ModifiedWhenAfterImport
		/*before import data*/
		,tmp.NameBeforeImport
		,tmp.ModifiedWhenBeforeImport
		,tmp.ParentGUIDBeforeImport
		,tmp.LocationBeforeImport
		,tmp.IsLocked
		,u.Username as LockUser
		,tmp.LockMachinename
		from ##impNode tmp left join Node page
		on tmp.FollowGUID = page.NodeGUID 
		and page.IsCheckedOutVersion = 0 
		and tmp.IsShortcut = 1
		left join AEUser u 
		on tmp.LockUserId = u.UserId

		--now get the users for the rights groups
		if @includeRightsGroups = 3 
		begin
			select tmp.NodeGUID, members.Username
			from ##impNode tmp inner join ##impUserRoleMember members
				on tmp.Id = members.NodeId and tmp.Type = 1048576
		end
		else if @includeRightsGroups = 4
		begin
			select tmp.NodeGUID, upper(members.Username)
			from ##impNode tmp inner join ##impUserRoleMember members
				on tmp.Id = members.NodeId and tmp.Type = 1048576
			union
			select tmp.NodeGUID, users.UsernameUpper
			from ##impNode tmp inner join Node n 
				on tmp.NodeGUID = n.NodeGUID and tmp.Type = 1048576
			inner join UserRoleMember members on n.Id = members.NodeId
			inner join AEUser users on members.UserId = users.UserId
		end
	end
	else
	begin
		select 
		/*source data*/
		tmp.NodeGUID
		,tmp.Type
		,tmp.IsShortcut
		,tmp.ParentGUID
		,Action
		,COALESCE(tmp.Name, tmp.DisplayName, page.Name, '')
		,tmp.Location
		,tmp.ModifiedWhen
		/*after import data*/
		,tmp.LocationAfterImport
		,n.ModifiedWhen as ModifiedWhenAfterImport
		/*before import data*/
		,tmp.NameBeforeImport
		,tmp.ModifiedWhenBeforeImport
		,tmp.ParentGUIDBeforeImport
		,tmp.LocationBeforeImport
		,tmp.IsLocked
		,u.Username as LockUser
		,tmp.LockMachinename
		from (##impNode tmp inner join Node n on
		tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 0
		)
		left join Node page
		on tmp.FollowGUID = page.NodeGUID 
		and page.IsCheckedOutVersion = 0 
		and tmp.IsShortcut = 1		
		left join AEUser u on tmp.LockUserId = u.UserId

		--now get the users for the rights groups
		if @includeRightsGroups = 3 or @includeRightsGroups = 4
		begin
			select tmp.NodeGUID, users.Username
			from ##impNode tmp inner join Node n 
				on tmp.NodeGUID = n.NodeGUID and tmp.Type = 1048576
			inner join UserRoleMember members on n.Id = members.NodeId
			inner join AEUser users on members.UserId = users.UserId
		end
	end

end
go


GRANT EXEC ON dbo.RetrieveImportedObjects TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SetImportLock')
	BEGIN
		PRINT 'Dropping Procedure SetImportLock'
		DROP  Procedure  dbo.SetImportLock
	END

GO

PRINT 'Creating Procedure SetImportLock'
GO

create procedure dbo.SetImportLock 
	(
		@locktimeout int = -1
	)
with encryption
as
/**
 *	This stored procedure puts an exclusive lock on ServerReadLock and/or ServerWriteLock
 *	tables depending on the @locktype value. This is done to prevent read or update operations
 *	from staring. If a read or update is already in progress setting exclusive lock fails
 *	and the procedure will throw  sql error 1222 "Lock request time-out period exceeded". 
 *
 *	@param	@locktype		specifies the Type of the lock to set
 *							0 - exclusive write
 *							1 - exclusive read/write
 *
 *	@see SetImportLock
*/
begin
	set nocount on
	
	declare @sql nvarchar(4000)
			,@locktimeout_orig int
			,@retval int

	set @locktimeout_orig = @@LOCK_TIMEOUT
	
	set @sql = 	N'declare @IsLocked tinyint '
			
	+ N' SET LOCK_TIMEOUT ' + cast(@locktimeout as nvarchar(10))
	
	+ N'  update SiteDeployImportLock set IsLocked = IsLocked where IsLocked = 0'
	+ N' set @retval = @@error'
	
	+ N' SET LOCK_TIMEOUT ' + cast(@locktimeout_orig as nvarchar(10))

	exec sp_executesql @sql, N'@retval int output', @retval output
	
	return @retval
end	
GO

GRANT EXEC ON dbo.SetImportLock TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'UndoCheckoutForImportedNodes')
	BEGIN
		PRINT 'Dropping Procedure UndoCheckoutForImportedNodes'
		DROP  Procedure  dbo.UndoCheckoutForImportedNodes
	END

GO

PRINT 'Creating Procedure UndoCheckoutForImportedNodes'
GO

/**
 *	This stored procedure is used for Site Deployment import operation
 *  to rollback checkout versions for nodes that are being replaced during
 *	import. It deletes the checkout version of a Node and resets IsCheckedOut
 *	flag on a checked in version (if there is one)
 *
 *	@see MergeImportData
*/
create procedure dbo.UndoCheckoutForImportedNodes
with encryption
as
begin
	
	/*check if there nodes that are currently checked out on the target*/	
	if exists(select Id from ##impNode where SourceId > 0 and IsCheckedOut = 1 )
	begin
		delete from NodeProperty 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodeRole 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodeResource 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodePlaceholderContent 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodePlaceholder 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)
		
/*TODO: remove statements that delete from NodeLayout and LayoutProperty
once the migration is completed*/
		delete from LayoutProperty 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodeLayout 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from UserRoleMember 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from NodeLock 
		where NodeId in
		(select n.Id from 
		##impNode tmp inner join Node n
		on tmp.NodeGUID = n.NodeGUID and n.IsCheckedOutVersion = 1
		and tmp.IsCheckedOut = 1
		)
		if @@error <> 0 return(1)

		delete from Node 
		where NodeGUID in
		(select NodeGUID from 
		##impNode tmp where SourceId > 0 
		and IsCheckedOut = 1
		)
		and IsCheckedOutVersion = 1

		if @@error <> 0 return(1)

	end

	/*ok, at this point all nodes that we're replacing are checked in,
	  make sure there are no locked nodes (containers might be locked without
	  being checked out*/
	if exists(select n.Id from ##impNode tmp inner join Node n
			 on tmp.SourceId = n.Id and n.IsLocked = 1)
	begin
		/*don't bother resetting locked values, we'll take care of them on update,
		just delete from NodeLock */
		delete from NodeLock 
		where NodeId in
		(select SourceId from ##impNode
		where SourceId > 0)
	end
	
	return (@@error)
end

GO

GRANT EXEC ON dbo.UndoCheckoutForImportedNodes TO PUBLIC

GO


IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'UpdateChangeTableWithImportedNodes')
	BEGIN
		PRINT 'Dropping Procedure UpdateChangeTableWithImportedNodes'
		DROP  Procedure  dbo.UpdateChangeTableWithImportedNodes
	END

GO

PRINT 'Creating Procedure UpdateChangeTableWithImportedNodes'
GO

create  procedure dbo.UpdateChangeTableWithImportedNodes
with encryption
as
begin

	set nocount on
	
	DECLARE @dateGMT datetime, @dateCurrent datetime, @MaxCommit datetime, @CommitTime datetime
	select @dateCurrent = GETDATE()

	exec GetGMTTime @dateCurrent, @dateGMT out

	select  @MaxCommit = MAX( CommitTime ) from ChangeTable WITH(UPDLOCK) 
	select  @CommitTime = case when @dateGMT <= @MaxCommit then DateAdd( ms, 3, @MaxCommit ) else @dateGMT END

	--replaced nodes and nodes that were originally deleted from the target system
	--but now are being added back by the import
	UPDATE ChangeTable 
			SET Reason = case when tmp.Action = 2 then 1
							  else 0
						 end, 
			LastChangeTime = nodes.LastChangeTime,
			CommitTime = @CommitTime,
			ParentGUID = nodes.ParentGUID,
			Type = nodes.Type,
			IsShortcut = nodes.IsShortcut,
			Name = nodes.Name
			from Node nodes inner join ##impNode tmp
			on nodes.NodeGUID = tmp.NodeGUID and nodes.IsCheckedOutVersion = 0
			--and tmp.Action = 2 or tmp.Action = 1
			where ChangeTable.NodeGUID = nodes.NodeGUID

	--newly added nodes
	INSERT INTO ChangeTable (NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime,
							Type, IsShortcut, Name) 
	select nodes.NodeGUID, nodes.ParentGUID, 0, nodes.LastChangeTime, @CommitTime, 
			nodes.Type, nodes.IsShortcut, nodes.Name
	from Node nodes inner join ##impNode tmp
		on nodes.NodeGUID = tmp.NodeGUID and nodes.IsCheckedOutVersion = 0
		--and tmp.Action = 1
	where not exists 
	(
		select NodeGUID from ChangeTable
		where NodeGUID = nodes.NodeGUID
	)

	--deleted nodes
	UPDATE ChangeTable 
			SET Reason = 2, 
			LastChangeTime = @CommitTime,
			CommitTime = @CommitTime,
			ParentGUID = del.ParentGUID,
			Type = del.Type,
			IsShortcut = del.IsShortcut,
			Name = del.Name,
			FollowGUID = del.FollowGUID,
			TemplateGUID = del.TemplateGUID,
			PageDefinitionGUID = del.PageDefinitionGUID
			from ##impNodesToDelete del
			where ChangeTable.NodeGUID = del.NodeGUID
			and del.CannotDelete = 0

end
GO

GRANT EXEC ON dbo.UpdateChangeTableWithImportedNodes TO PUBLIC

GO


exec sp_createstats @fullscan = 'fullscan'
GO
exec GetTimeZoneSetting
GO



DECLARE @dateGMT datetime, @dateCurrent datetime

select @dateCurrent = GETDATE()

exec GetGMTTime @dateCurrent, @dateGMT out

/* Server */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 0
	   ,1, 1, '{9673B503-9C31-11D1-B449-006097071264}', NULL, 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Server'
	   ,NULL, NULL, NULL, NULL, NULL) 
	   
/* User Roles */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 0
	   ,524288, 1, '{6A33E801-9D05-11D1-B44A-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'User Roles'
	   ,NULL, NULL, NULL, NULL, NULL)	   
	   
	   
/* Administrators */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{58313A41-9DD0-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Administrators'
	   ,NULL, NULL, NULL, NULL, NULL)	   	   
	   
	   
/* Administrator */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,1048576, 1, '{9673B504-9C31-11D1-B449-006097071264}', '{58313A41-9DD0-11D1-B44E-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Administrator'
	   ,NULL, NULL, NULL, NULL, 1)	
	   
/* Subscribers */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D1912D-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Subscribers'
	   ,NULL, NULL, NULL, NULL, NULL)	
	   
/* Authors */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D1912F-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Authors'
	   ,NULL, NULL, NULL, NULL, NULL)	
	   
/* Editors */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D19131-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Editors'
	   ,NULL, NULL, NULL, NULL, NULL)	
	   
/* Moderators */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D19132-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Moderators'
	   ,NULL, NULL, NULL, NULL, NULL)	  	     	   
	      		   
/* Resource Managers */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D19133-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Resource Managers'
	   ,NULL, NULL, NULL, NULL, NULL)	 
	   
/* Template Designers */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{E4D19134-9DD3-11D1-B44E-006097071264}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Template Designers'
	   ,NULL, NULL, NULL, NULL, NULL)	
	   
/* Channel Managers */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 1, 0, 0
	   ,524288, 1, '{58313A41-9EE0-11D1-B44E-006097071364}', '{6A33E801-9D05-11D1-B44A-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Channel Managers'
	   ,NULL, NULL, NULL, NULL, NULL)		  	   
/* Channels */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,4, 0, '{E4D19123-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Channels'
	   ,NULL, NULL, 1, 1, NULL) 
	   
/* Folders */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,2097152, 0, '{E4D19124-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Folders'
	   ,NULL, NULL, NULL, NULL, NULL) 		   	   
	   
/* Resources */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,64, 0, '{E4D1912A-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Resources'
	   ,NULL, NULL, NULL, NULL, NULL) 	
	   
/* Templates */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,16384, 0, '{E4D1912B-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Templates'
	   ,NULL, NULL, NULL, NULL, NULL) 	
	   
/* Schemas */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,16777216, 0, '{128FE591-191C-46A5-B122-AAD6E49BE3C4}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, NULL, @dateGMT, '3000-01-01 00:00:00.000', NULL, 'Schemas'
	   ,NULL, NULL, NULL, NULL, NULL) 	
	   	   
	   
/* Archive Folder */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,2097152, 30, '{6962A730-AE9C-11D3-8097-00C04F4F5BEA}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Archive Folder'
	   ,NULL, NULL, NULL, NULL, NULL) 		   	   	   		   
	   
	   
/* Deleted Items - Channels */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,4, 0, '{E4D1911E-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Deleted Items'
	   ,1, NULL, 1, 1, NULL) 
	   
insert into dbo.ChangeTable (
		NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime, Type, IsShortcut, Name
		)
values ('{E4D1911E-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, @dateGMT, 4, 0, 'Deleted Items')

	   
/* Deleted Items */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,2097152, 0, '{E4D1911F-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Deleted Items'
	   ,1, NULL, NULL, NULL, NULL) 	   
	   
insert into dbo.ChangeTable (
		NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime, Type, IsShortcut, Name
		)
values ('{E4D1911F-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, @dateGMT, 2097152, 0, 'Deleted Items')
	   
	   
/* Deleted Items */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,64, 0, '{E4D19121-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Deleted Items'
	   ,1, NULL, NULL, NULL, NULL) 	 
	   
insert into dbo.ChangeTable (
		NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime, Type, IsShortcut, Name
		)
values ('{E4D19121-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, @dateGMT, 64, 0, 'Deleted Items')
	   
/* Deleted Items */
INSERT INTO dbo.Node(
		IsLocked,IsCheckedOut,IsCheckedOutVersion,HasCheckedInVersion,CheckedInVersionHasExisted
		,IsShortcut,IsBeingInserted,IsHighPriority,SameRightsAsParent,ReadyForApproval,ApprovalStatus
		,Type,SortOrdinal,NodeGUID,ParentGUID,CreatedByUserId,CreatedWhen,ModifiedByUserId,ModifiedWhen
		,OwnerId,ApprovedByUserId,EffectiveDate,ExpiryDate,ApprovedWhen,Name
		,DeletedByUserId, IsHiddenModePublished, IsRobotFollowable, IsRobotIndexable, UserRoleType
		)
VALUES(0, 0, 0, 1, 1
	   ,0, 0, 0, 0, 0, 1
	   ,16384, 0, '{E4D19122-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, 1, @dateGMT
	   ,1, 1, @dateGMT, '3000-01-01 00:00:00.000', @dateGMT, 'Deleted Items'
	   ,1, NULL, NULL, NULL, NULL) 	 	     	   
	   	   
insert into dbo.ChangeTable (
		NodeGUID, ParentGUID, Reason, LastChangeTime, CommitTime, Type, IsShortcut, Name
		)
values ('{E4D19122-9DD3-11D1-B44E-006097071264}', '{9673B503-9C31-11D1-B449-006097071264}', 1, @dateGMT, @dateGMT, 16384, 0, 'Deleted Items')
  		   	      		      	   	   

 
  
 /* _UserGalleryRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 1, '_UserGalleryRoot', '{6A33E801-9D05-11D1-B44A-006097071264}', 0
	, 0, 0, 0
	)
	
 /* _UserGalleryAdministrators */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 2, '_UserGalleryAdministrators', '{58313A41-9DD0-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _AdministratorRole */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 3, '_AdministratorRole', '{9673B504-9C31-11D1-B449-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _ChannelsRecycler */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 4, '_ChannelsRecycler', '{E4D1911E-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _FoldersRecycler */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 5, '_FoldersRecycler', '{E4D1911F-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _ResourceGalleryRecycler */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 6, '_ResourceGalleryRecycler', '{E4D19121-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _TemplatesRecycler */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 7, '_TemplatesRecycler', '{E4D19122-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)
	
 /* _ChannelsRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 8, '_ChannelsRoot', '{E4D19123-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)
	
 /* _FoldersRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 9, '_FoldersRoot', '{E4D19124-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _ResourceGalleryRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 10, '_ResourceGalleryRoot', '{E4D1912A-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)
	
 /* _TemplatesRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 11, '_TemplatesRoot', '{E4D1912B-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _UserGallerySubscribers */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 12, '_UserGallerySubscribers', '{E4D1912D-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _UserGalleryAuthors */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 13, '_UserGalleryAuthors', '{E4D1912F-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)
	
 /* _UserGalleryEditors */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 14, '_UserGalleryEditors', '{E4D19131-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _UserGalleryModerators */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 15, '_UserGalleryModerators', '{E4D19132-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _UserGalleryResManagers */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 16, '_UserGalleryResManagers', '{E4D19133-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)		
	
 /* _UserGalleryTempDesigners */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 17, '_UserGalleryTempDesigners', '{E4D19134-9DD3-11D1-B44E-006097071264}', 0
	, 0, 0, 0
	)	
	
 /* _UserGalleryChanManagers */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 18, '_UserGalleryChanManagers', '{58313A41-9EE0-11D1-B44E-006097071364}', 0
	, 0, 0, 0
	)
	
 /* _ArchiveFolder */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 19, '_ArchiveFolder', '{6962A730-AE9C-11D3-8097-00C04F4F5BEA}', 0
	, 0, 0, 0
	)
	
 /* _SchemasRoot */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
values(
	1, 20, '_SchemasRoot', '{128FE591-191C-46A5-B122-AAD6E49BE3C4}', 0
	, 0, 0, 0
	)	
	
 /* Administrators' description */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 1, '_Description', 'System administrator group, have rights to do anything in the system', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{58313A41-9DD0-11D1-B44E-006097071264}'


 /* Channels' description */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 1, '_Description', 'Channel which contains all other channels and all pages', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D19123-9DD3-11D1-B44E-006097071264}'

 /* Channels' _NotifyOnly */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 2, '_NotifyOnly', 'True', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D19123-9DD3-11D1-B44E-006097071264}'
															
 /* Folders' description */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 1, '_Description', 'Root folder, contains all other folders and all pages', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D19124-9DD3-11D1-B44E-006097071264}'	

 /* Folders' _DefaultPostChannel */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 2, '_DefaultPostChannel', '{E4D19123-9DD3-11D1-B44E-006097071264}', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D19124-9DD3-11D1-B44E-006097071264}'		

 /* Resources' description */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 1, '_Description', 'Gallery containing all resource galleries and all resources', 0
		,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D1912A-9DD3-11D1-B44E-006097071264}'	

 /* Templates' description */
 insert into dbo.NodeProperty (
	NodeId, Id, PropName, PropValue, PropType
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, 1, '_Description', 'Gallery containing all templates galleries and all templates', 0
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{E4D1912B-9DD3-11D1-B44E-006097071264}'																					



 /* Assign Administrator to the Server Node */
 insert into dbo.NodeRole (
	NodeId, RoleGUID
	,IsBeingInserted, IsBeingDeleted, IsBeingUpdated)
select n.Id, '{9673B504-9C31-11D1-B449-006097071264}'
	,0, 0, 0
from dbo.Node n
where NodeGUID = '{9673B503-9C31-11D1-B449-006097071264}'			 


