/* epo3.0 */

-- temp changes - schema file checked out

-------------------------------------------
--
Begin
Declare @dbname varchar(100)
Select @dbname=db_name()
Exec sp_dboption @dbname,'select into/bulkcopy','TRUE'
End
GO



---------------------------------------
-- Trigger section


-- epo3.5 Insert trigger for events table
--	Change actiontaken, virustype and counter to actual tranalation codes
--	Get rid of table joins, major performance improvement without adding new data rows

if exists (select * from sysobjects where id = object_id(N'[dbo].[TR_EPO_INSEVENTS]'))
drop trigger [dbo].[TR_EPO_INSEVENTS]
GO

CREATE TRIGGER TR_EPO_INSEVENTS ON [Events] 
for insert
as
begin

	insert EventDayResolution 
		(autoid, nodeid, actionTaken, tvdeventid, yearmonthday, 
		YearWeek,  -- YearQuarter, 
		YearMonth, -- Year,
		virusname, productname, productversion, HostName, Username)
	select autoid, nodeid, actiontaken, tvdeventid 
		,convert(char,EventDateTime,102)  
		,DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2)
--		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime)
		,Substring(convert(char,EventDateTime,120),1,7)
--		,DateName(Year, EventDateTime)
		,virusname, productname, productversion, HostName, Username
	from inserted
	where virusname > '' and ActionTaken > 0
		and TVDEventid != 1506 and TVDEventid != 4600

end
Go


if exists (select * from sysobjects where id = object_id(N'[dbo].[TR_EPO_DELEVENTS]'))
drop trigger [dbo].[TR_EPO_DELEVENTS]
GO

CREATE TRIGGER TR_EPO_DELEVENTS ON [Events] 
for delete
as
begin

	delete EventDayResolution 
		from deleted
		where EventDayResolution.autoid = deleted.autoid

end
Go




----------------------------------------------------
----------------------------------------------------
-- index section
-- do not add indexes in Populate ReportMetadataScript must add them before loading stored procedures
--	so that the stored proc can take advantage of them in execution plan

--DBCC INDEXDEFRAG (Northwind, Orders, CustomersOrders)

-- make sure the table data and indexes are populated before running stored procedures



-- eventfilterdescfast index fix

IF  EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventFilterDescFast')
	drop INDEX [dbo].[EventFilterDescFast].[IX_EventFilterDescFast]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventFilterDescFast')
	CREATE  Clustered INDEX [IX_EventFilterDescFast] ON [dbo].[EventFilterDescFast]([EventID],[Language]) ON [PRIMARY]
GO

-- ReportActionDesc index fix

IF  EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_ReportActionDesc')
	drop INDEX [dbo].[ReportActionDesc].[IX_ReportActionDesc]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_ReportActionDesc')
	CREATE  Clustered INDEX [IX_ReportActionDesc] ON [dbo].[ReportActionDesc]([ActionIntID],[LanguageID]) ON [PRIMARY]
GO

-- Branchnode index 

IF  EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_BranchNode_IDName')
	drop INDEX [dbo].[BranchNode].[IX_BranchNode_IDName]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_BranchNode_IDName')
	CREATE  INDEX [IX_BranchNode_IDName] ON [dbo].[BranchNode]([AutoID],[NodeName]) ON [PRIMARY]
GO

-- VirusType index 

IF  EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_VirusType')
	drop INDEX [dbo].[VirusType].[IX_VirusType]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_VirusType')
	CREATE  Clustered INDEX [IX_VirusType] ON [dbo].[VirusType]([VirusName],[VirusTypeTranslated]) ON [PRIMARY]
GO



-- Some EventDayResolution indexes, others loaded in EnumProcedures.sql 

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventDayResolution_AutoID')
CREATE  INDEX [IX_EventDayResolution_AutoID] ON [dbo].[EventDayResolution]([AutoID]) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventDayResolution_Day')
CREATE  INDEX [IX_EventDayResolution_Day] ON [dbo].[EventDayResolution]([YearMonthDay]) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventDayResolution_Dates')
CREATE  INDEX [IX_EventDayResolution_Dates] ON [dbo].[EventDayResolution]([YearMonth],[YearWeek]) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventDayResolution_DateDetect')
CREATE  INDEX [IX_EventDayResolution_DateDetect] ON [dbo].[EventDayResolution]([YearWeek],[YearMonth],[virusname],[productname],[productversion]) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sysindexes WHERE name = 'IX_EventDayResolution_VirusActionProduct')
CREATE  INDEX [IX_EventDayResolution_VirusActionProduct] ON [dbo].[EventDayResolution]([actionTaken],[virusname],[productname],[productversion]) ON [PRIMARY]
GO





------------------------------------------------------------------------------------------
-- start stored procedures
----------------------------------------

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetConsistentProductName
 @szProductName  VARCHAR(100),
 @szConsistentName VARCHAR(100) OUTPUT
AS
BEGIN
 /* Copyright   1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

 /* Default to the provided one*/
 SET @szConsistentName=@szProductName
 IF @szProductName LIKE 'NetShield'
  SET @szConsistentName = 'NetShield'
 IF @szProductName LIKE 'VirusScan'
  SET @szConsistentName = 'VirusScan'

 RETURN
END
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_VerifyNameSpaceRights
(
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500),
 @szEpoUserName   VARCHAR(100)
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

 RETURN 1
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO



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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Add_To_dbo_events

 (
 @EventDateTime datetime ,
 @ProductID int,
      @ProductName nvarchar (64) ,
 @ProductVersion nvarchar(16),
 @HostName nvarchar(512) ,
 @HostIPAddress nvarchar(16),
 @UserName nvarchar(32) ,
 @VirusName nvarchar(128) ,
 @FileName nvarchar(512) ,
 @EngineVersion nvarchar(16) ,
 @DATVersion nvarchar(16) ,
 @ScanTime nchar (16) ,
 @ActionTaken int,
 @TVDEventID int,
 @TVDSeverity int,
 @VirusType nvarchar(128) ,
 @TVDTaskName nvarchar(128),
 @AgentGUID uniqueidentifier
 )

AS  

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

BEGIN

 /* Map the name to a consistent name */
 DECLARE @CProductName VARCHAR(100)
 EXECUTE AVISP_GetConsistentProductName @ProductName, @CProductName OUTPUT

  INSERT INTO Events ( 
      EventDateTime,
      ProductID,
      ProductName,
      ProductVersion,
      HostName,
      HostIPAddress,
      UserName,
      VirusName,
      FileName,
      EngineVersion,
      DATVersion,
      ScanTime,
      ActionTaken,
      TVDEventID,
      TVDSeverity,
      VirusType,
      TVDTaskName,
      AgentGUID
      )
     VALUES
      ( 
      @EventDateTime,
      @ProductID,
      @ProductName,
      @ProductVersion,
      @HostName,
      @HostIPAddress,
      @UserName,
      @VirusName,
      @FileName,
      @EngineVersion,
      @DATVersion,
      @ScanTime,
      @ActionTaken,
      @TVDEventID,
      @TVDSeverity,
      @VirusType,
      @TVDTaskName,
      @AgentGUID
      )
 RETURN 1
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

/* Used by all report procs to check if a filter node and the enum */
/*  table is needed */
CREATE PROCEDURE dbo.AVIDALSP_GetNodeIDFilter
(
 @iNameSpaceName  int,
 @iNameSpaceNode  int,
 @FilterID   int   OUTPUT
)
AS
BEGIN

      Declare @iFilterNode int
      Declare @iFilterNodeType int
      Declare @iTopNode int
      Declare @iTopNodeType int
      Declare @szFilterNode varchar(100)

 

      Set @iFilterNode =0
      Set @iFilterNodeType =0
      Set @iTopNode =0
      Set @iTopNodeType =0

     select @iTopNode = AutoID, @iTopNodeType = Type  from BranchNode where AutoID = @iNameSpaceName

     IF @iNameSpaceNode > 0
           select @iFilterNode = AutoID,  @iFilterNodeType = Type from BranchNode where AutoID = @iNameSpaceNode 
  and AutoID in 
   (Select EndAutoID from BranchNodeEnum where StartAutoID = @iTopNode)

/*     select @iTopNode, @iTopNodeType, @iFilterNode */

    /* return either the top node, the users selected filter node, or zero if either equals the root node (no filtering needed) */
    IF @iFilterNode > 0 and  @iFilterNodeType != 4 and @iFilterNodeType != 7
 set @FilterID=@iFilterNode
    ELSE IF @iTopNode > 0 and  @iTopNodeType != 4 and @iTopNodeType != 7
 set @FilterID=@iTopNode
    ELSE
 set @FilterID=0 

END


SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

/* Used by all report procs to check if a filter node and the enum */
/*  table is needed */
CREATE PROCEDURE dbo.AVISP_GetReportParms
(
  @szOptionalReportParms VARCHAR(500),
  @szLang VARCHAR(3) OUTPUT,
  @szTime VARCHAR(10) OUTPUT,
  @szFilter VARCHAR(50) OUTPUT
)
AS
BEGIN

	Declare @pstart int
	Declare @pend int


	/* Get TIME parm */
	Set @pstart = CHARINDEX( '|TIME', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )
		Set @szTime = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szTime = 'GMT'


	/* Get LANG parm */
	Set @pstart = CHARINDEX( '|LANG', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )	
		Set @szLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szLang = '09'


	/* Get FILTER parm */
	Set @pstart = CHARINDEX( '|FILTER', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szFilter = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szFilter = ''


/*
select @szLang, @szTime, @szFilter
*/


END
GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

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


/* Used by all report procs to check if a filter node and the enum */
/*  table is needed */
CREATE PROCEDURE dbo.AVISP_GetReportParms2
(
  @szOptionalReportParms VARCHAR(500),
  @szLang VARCHAR(3) OUTPUT,
  @szFullLang VARCHAR(5) OUTPUT,
  @szTime VARCHAR(10) OUTPUT,
  @szFilter VARCHAR(50) OUTPUT,
  @szReportID VARCHAR(50) OUTPUT,
  @szRptGroup VARCHAR(50) OUTPUT
)
AS
BEGIN

	Declare @pstart int
	Declare @pend int
  	Declare @szDefLang VARCHAR(5)


	/* Get TIME parm */
	Set @pstart = CHARINDEX( '|TIME', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )
		Set @szTime = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szTime = 'GMT'


	/* Get LANG parm */
	Set @pstart = CHARINDEX( '|LANG', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )	
		Set @szLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szLang = '09'

	/* Get FULLLANG parm */
	Set @pstart = CHARINDEX( '|FULLLANG', @szOptionalReportParms) + 9
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 9 )	
		Set @szFullLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szFullLang = '0'


	/* Get DEFLANG parm */
	Set @pstart = CHARINDEX( '|DEFLANG', @szOptionalReportParms) + 8
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 8 )	
		Set @szDefLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szDefLang = '0'


	/* Get FILTER parm */
	Set @pstart = CHARINDEX( '|FILTER', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szFilter = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szFilter = ''


	/* Get ReportID parm */
	Set @pstart = CHARINDEX( '|REPORT', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szReportID = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szReportID = ''


	/* Get RptGroup parm */
	Set @pstart = CHARINDEX( '|RPTGRP', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szRptGroup = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szRptGroup = ''

	-- if fulllang is not in localization lookup tables try default lang
	Declare @cntlang int
	Select @cntlang=count(*) from ReportActionDesc where LanguageID = @szFullLang

	if @cntlang = 0
	begin
		Select @cntlang=count(*) from ReportActionDesc where LanguageID = @szDefLang
		if @cntlang > 0
			Set @szFullLang = @szDefLang
		else
			Set @szFullLang = '0409'	-- default = english
	end
	
/*
select @szLang, @szTime, @szFilter
*/


END
GO

----------------
-- vs7.5 new routine (fetches eventtype fro custom infection reports)
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVISP_GetReportParms3]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVISP_GetReportParms3]
GO

/* Used by all report procs to check if a filter node and the enum */
/*  table is needed */
CREATE PROCEDURE dbo.AVISP_GetReportParms3
(
  @szOptionalReportParms VARCHAR(500),
  @szLang VARCHAR(3) OUTPUT,
  @szFullLang VARCHAR(5) OUTPUT,
  @szTime VARCHAR(10) OUTPUT,
  @szFilter VARCHAR(50) OUTPUT,
  @szReportID VARCHAR(50) OUTPUT,
  @szRptGroup VARCHAR(50) OUTPUT,
  @EventType VARCHAR(50) OUTPUT
)
AS
BEGIN

	Declare @pstart int
	Declare @pend int
  	Declare @szDefLang VARCHAR(5)


	/* Get TIME parm */
	Set @pstart = CHARINDEX( '|TIME', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )
		Set @szTime = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szTime = 'GMT'


	/* Get LANG parm */
	Set @pstart = CHARINDEX( '|LANG', @szOptionalReportParms) + 5
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 5 )	
		Set @szLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szLang = '09'

	/* Get FULLLANG parm */
	Set @pstart = CHARINDEX( '|FULLLANG', @szOptionalReportParms) + 9
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 9 )	
		Set @szFullLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szFullLang = '0'


	/* Get DEFLANG parm */
	Set @pstart = CHARINDEX( '|DEFLANG', @szOptionalReportParms) + 8
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)

	if( @pstart > 8 )	
		Set @szDefLang = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szDefLang = '0'


	/* Get FILTER parm */
	Set @pstart = CHARINDEX( '|FILTER', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szFilter = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szFilter = ''


	/* Get ReportID parm */
	Set @pstart = CHARINDEX( '|REPORT', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szReportID = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szReportID = ''


	/* Get RptGroup parm */
	Set @pstart = CHARINDEX( '|RPTGRP', @szOptionalReportParms) + 7
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 7 )
		Set @szRptGroup = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @szRptGroup = ''

	-- if fulllang is not in localization lookup tables try default lang
	Declare @cntlang int
	Select @cntlang=count(*) from ReportActionDesc where LanguageID = @szFullLang

	if @cntlang = 0
	begin
		Select @cntlang=count(*) from ReportActionDesc where LanguageID = @szDefLang
		if @cntlang > 0
			Set @szFullLang = @szDefLang
		else
			Set @szFullLang = '0409'	-- default = english
	end
	
	/* Get RptGroup parm */
	Set @pstart = CHARINDEX( '|EventType', @szOptionalReportParms) + 10
	Set @pend   = CHARINDEX( '|', @szOptionalReportParms, @pstart)
	
	if( @pstart > 10 )
		Set @EventType = SUBSTRING( @szOptionalReportParms, @pstart, (@pend - @pstart) )
	else
		Set @EventType = ''

/*
select @szLang, @szTime, @szFilter
*/


END
GO



---------------------------------------------------

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

/*  Performs filter node checks for queries */
/*    calls: AVIDALSP_GetNodeIDFilter */
CREATE PROCEDURE dbo.AVIDALSP_GetNodeIDFilterQueries
(
 @iNameSpaceName  int,
 @iNameSpaceNode  int
)
AS
BEGIN

      Declare @iFilterNode int

      EXECUTE dbo.AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @iFilterNode OUTPUT

      SELECT @iFilterNode
 
END
GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVIDALSP_GetAllSubNodeIDs
(
 @iFilterNode  int
)
 AS
 BEGIN
  /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

 /* check the user has enough rights to see this data */
      /* old avi code: reuse if we ever want to check rights based on top namespace */
 /*
      DECLARE @iRightsCheckResult   INTEGER
 EXECUTE @iRightsCheckResult=AVISP_VerifyNameSpaceRights @szNameSpaceName, @szNameSpaceNode, @szEpoUserName
 IF(@iRightsCheckResult=1)
      BEGIN
      */

  /* All sub nodes */
  SELECT EndAutoID as AutoID 
                 FROM BranchNodeEnum 
    WHERE StartAutoID =  @iFilterNode
  UNION 
  /* and the node it's self */
       SELECT @iFilterNode

 /*END*/
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


-- epo3.5: Change taken from smb
-- sql server 7 sp4 suddenly doesnt allow table creates, truncates to be done from triggers
--	so change these routines to use permanent temp tables.
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVIDALSP_GetUserNodeAccessList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVIDALSP_GetUserNodeAccessList]
GO


/* used by AVISP_CalculateAllSubNodes (report filtering) */
/*   Creates a temp table of nodes below a top node input */
CREATE PROCEDURE dbo.AVIDALSP_GetUserNodeAccessList
(
 @iNameSpaceName  int,
 @iNameSpaceNode  int,
 @szEpoUserName  VARCHAR(100)
)
AS
BEGIN
      /* Try to generate code which only recreates the temp table when a node has changed
         Can compare a datetime stamp in the temp table with a touch table storing the last
          change datetime stamp for the enum table. Touch table could be trigger based off
          the enum table. 
      */ 
      Declare @iFilterNode int
      Declare @szFilterNode varchar(255)
 
      /*IF EXISTS (select * from sysobjects where name = 'UserNodeAccessList' 
   and xtype = 'U')*/
--      IF EXISTS (select * from tempdb..sysobjects where name = '##UserNodeAccessList' 
--   and xtype = 'U')
--  DROP TABLE ##UserNodeAccessList

 /* @szNameSpaceName  is the top node of the users account*/
 /* @szNameSpaceNode  is a node within the users account that they may filter from*/

     IF @iNameSpaceNode > 0
           select @iFilterNode = @iNameSpaceNode
      ELSE
           select @iFilterNode = @iNameSpaceName

    
     select @szFilterNode = NodeName from BranchNode where AutoID = @iFilterNode

 Delete from ReportTempUserNodeAccessList 
-- CREATE TABLE ##UserNodeAccessList (AutoID Integer, NodeName nvarchar(255))

 INSERT ReportTempUserNodeAccessList 
  SELECT EndAutoID as AutoID,  NodeName 
                   FROM BranchNodeEnum, BranchNode 
    WHERE 
     StartAutoID =  @iFilterNode
     AND EndAutoID = BranchNode.AutoID
  UNION 
    SELECT @iFilterNode, @szFilterNode   /* and the node it's self */

/* UPDATE ##UserNodeAccessList 
  SET NodeName = (SELECT NodeName from BranchNode where BranchNode.AutoID = ##UserNodeAccessLst.AutoID)
*/
/* EXECUTE AVIDALSP_GetAllSubNodeIDs @iFilterNode */

END
GO


SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

/* v3.0: this routine is needed by avibatch to fill in nodeids */
/*    given the full path nodenames as inputs */
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVIDALSP_GetLowestNodeIDfromPath]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVIDALSP_GetLowestNodeIDfromPath]
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO
CREATE PROCEDURE dbo.AVIDALSP_GetLowestNodeIDfromPath
 @szRootPath varchar(1024),  
 @szFilterPath varchar(1024),
 @iRootID int OUTPUT,
 @iFilterID int OUTPUT
AS 
BEGIN

SET NOCOUNT ON

 DECLARE @TopNodeID int


	SELECT @TopNodeID = AutoID
	FROM BranchNode
	WHERE Type = 4

	CREATE TABLE #Tree 
	(
		FullPathName varchar(1024),
		LowestNodeID	int		
	)

	INSERT #Tree	
		EXECUTE AVISP_CalculateAllSubNodes @TopNodeID, @TopNodeID, ''


	SELECT @iRootID = LowestNodeID
	FROM #Tree
	WHERE FullPathName = @szRootPath 

	SELECT @iFilterID = LowestNodeID
	FROM #Tree
	WHERE FullPathName = @szFilterPath 

/*	select @iRootID, @iFilterID
*/

	DROP Table #Tree

END
GO


/**/
/* xxxxx Start of Report routines xxxxx */
/**/


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_FilterASCI
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT



 SELECT 
   ComputerName, 
   DomainName, 
   IPAddress, 
   CONVERT(datetime,
   (SUBSTRING( LeafNode.LastUpdate,  1 , 4)+'-'+
   SUBSTRING( LeafNode.LastUpdate,  5 , 2)+'-'+                              
   SUBSTRING( LeafNode.LastUpdate,  7 , 2)+' '+                              
   SUBSTRING( LeafNode.LastUpdate,  9 , 2)+':'+                              
   SUBSTRING( LeafNode.LastUpdate,  11 , 2)+':'+                              
   SUBSTRING( LeafNode.LastUpdate,  13 , 2)                                    
   ), 120 )   as LastUpdate, 
/*CAST(LeafNode.LastUpdate As datetime) As LastUpdate, */
   BranchNode.NodeName AS NodeName 
   ,  ComputerProperties.UserName,
     cast((ComputerProperties.OSType  + ' ' 
         + ComputerProperties.OSServicePackVer + ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion,
   ProductVersion =
    	CASE ProductProperties.ProductVersion
     	WHEN '' THEN '---' 
     	ELSE ProductProperties.ProductVersion
     	END
	

 FROM ComputerProperties, ProductProperties,
             LeafNode, BranchNode

 WHERE   
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
          AND ComputerProperties.ParentID = LeafNode.AutoID
           AND LeafNode.LastUpdate > ''
   AND LeafNode.ParentID = BranchNode.AutoID
   AND ProductProperties.ParentID = LeafNode.AutoID
   AND ProductProperties.ProductCode LIKE '%Agent%'
   AND LeafNode.Type !=24      /* Uninstalled */ 

 UNION ALL

 SELECT 
    LeafNode.NodeName  as ComputerName, 
    '<UnConnected>'  as DomainName, 
    '<UnConnected>'  asIPAddress, 
   '01/01/1900' As LastUpdate, 
   BranchNode.NodeName AS NodeName ,
     '<UnConnected>'  as UserName,
     '<UnConnected>'  as OSVersion,
     '<UnConnected>'  as ProductVersion

 FROM 
             LeafNode, BranchNode
 WHERE   
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
           AND ( LeafNode.LastUpdate IS NULL OR LeafNode.LastUpdate = '' )
   AND LeafNode.ParentID = BranchNode.AutoID
   AND LeafNode.Type !=24      /* Uninstalled */ 

 RETURN
END
GO

SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_FilterNoAVMachines 
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT



 
 SELECT distinct
  ComputerName, 
   DomainName, 
   IPAddress,
   BranchNode.NodeName AS NodeName, 
   ComputerProperties.UserName,
   cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion,
   UnmanagedProtection = 
    CASE      WHEN  Events.ProductName > '' THEN (ProductName + ' ' + ProductVersion)
     WHEN  Events.ProductName = '' THEN '---'
     ELSE  '---'
     END

 FROM ComputerProperties,
             LeafNode, BranchNode,
	Events
 WHERE
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where  BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND LeafNode.AVInstalls = 0
   AND LeafNode.Type !=24      /* Uninstalled */ 
   AND LeafNode.AutoID = ComputerProperties.ParentID 
   AND LeafNode.ParentID = BranchNode.AutoID
   AND LeafNode.AutoID *= Events.NodeID			/* outer join gets all */
   AND
   (
      Events.ProductName like '%GroupShield%'
      OR Events.ProductName like '%WebShield%'
   )



 RETURN
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_FilterNoAgentMachines
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT




 SELECT 
   LeafNode.NodeName as ComputerName, 
   '---' as DomainName, 
   '---' as IPAddress, 
   BranchNode.NodeName AS NodeName

 FROM  
             LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where  BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND  ( LeafNode.LastUpdate = '' OR LeafNode.LastUpdate is NULL )
   AND LeafNode.ParentID = BranchNode.AutoID
   AND LeafNode.Type !=24      /* Uninstalled */ 
 
 RETURN
END
GO

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


/* 2x add ostype, username remove domainname , language (rename fields) */
/* 2x take product version from PP */
CREATE PROCEDURE dbo.AVISP_FilterAVInstalls
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 /* If Nodeid inputs not supplied, generate them from fullpath node names */
 if  @iNameSpaceName  = '' OR @iNameSpaceNode = '' OR 
	(@UsersTopNodeID = 0  AND @FilterNodeID = 0)  
 BEGIN
 	EXECUTE AVIDALSP_GetLowestNodeIDfromPath
 		@szNameSpaceName,	@szNameSpaceNode,
 		@UsersTopNodeID OUTPUT,	
		@FilterNodeID OUTPUT
 END

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT




SELECT 
   ComputerProperties.ComputerName, 
    ComputerProperties.DomainName, 
    ComputerProperties.IPAddress, 
   AVIView_Software.SoftwareName as ProductCode, 
   ProductVersion =
    	CASE ProductProperties.ProductVersion
     	WHEN '' THEN '---' 
     	ELSE ProductProperties.ProductVersion
     	END,
/*   ProductProperties.ProductVersion, */ 
   EngineVer =
    	CASE ProductProperties.EngineVer 
     	WHEN '' THEN '---' 
     	WHEN 'N/A' THEN '---' 
     	ELSE ProductProperties.EngineVer 
     	END,
   DATVer =
    	CASE ProductProperties.DATVer 
     	WHEN '' THEN '---' 
     	WHEN 'N/A' THEN '---' 
     	ELSE ProductProperties.DATVer 
     	END,
   ExtraDATNames =
    	CASE ProductProperties.ExtraDATNames 
     	WHEN 'N/A' THEN '' 
     	ELSE ProductProperties.ExtraDATNames 
     	END,
   Language =
    CASE 
     WHEN  LanguageDesc.LanguageName > '' THEN LanguageDesc.LanguageName
     WHEN  ProductProperties.Language = '' THEN '---'
     ELSE  ProductProperties.Language
     END,
   BranchNode.NodeName AS NodeName
   ,  ComputerProperties.UserName,
     cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion,
   ProductFamily =
    CASE 
     WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     ELSE  AVIView_Software.ProductFamily 
     END
   ,  LeafNode.AutoID as NodeID
   , Servicepack
   , Hotfix
   , LeafNode.LastUpdate as LastContact

 
 FROM ComputerProperties,  
   ProductProperties, AVIView_Software,
             LeafNode, BranchNode, LanguageDesc
 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where  BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND LeafNode.AutoID = ComputerProperties.ParentID
                  AND ProductProperties.ParentID = LeafNode.AutoID 
   and ProductProperties.ProductCode = AVIView_Software.ProductCode
   and (AVIView_Software.ProductFamily in ('TVD', 'TVD_NC')  
	or AVIView_Software.ProductFamily like 'TVD_NC_%' )
   AND LeafNode.ParentID = BranchNode.AutoID
   AND RIGHT(ProductProperties.Language, 2) *= LanguageDesc.ClientLanguageSuffix
   AND LanguageDesc.epoServerLanguageID = @szFullLang
   AND LeafNode.Type !=24      /* Uninstalled */ 

UNION ALL      
/* Fetch Nodes with no products */

 SELECT distinct
   ComputerProperties.ComputerName, 
  ComputerProperties.DomainName, 
   ComputerProperties.IPAddress, 
   ProductCode = 
     CASE
     WHEN  Events.ProductName > '' THEN 'Unmanaged Protection' + ' - ' + Events.ProductName
     WHEN  Events.ProductName = '' THEN 'Unprotected'
     ELSE  'Unprotected'
     END , 
   ProductVersion = 
      CASE
          WHEN Max( ProductVersion )  > '' THEN Max( ProductVersion )
          WHEN Max( ProductVersion )  = '' THEN '---'
          ELSE  '---'
          END,
   EngineVer = 
     CASE
          WHEN Max(Events.EngineVersion)  > '' THEN Max(Events.EngineVersion)
          WHEN Max(Events.EngineVersion)  = '' THEN '---'
          ELSE  '---'
          END,	
   DATVer = 
     CASE
          WHEN Max(Events.DATVersion)  > '' THEN Max(Events.DATVersion)
          WHEN Max(Events.DATVersion)  = '' THEN '---'
          ELSE  '---'
          END,
   '',
   '---',
   BranchNode.NodeName AS NodeName,
   ComputerProperties.UserName,
      cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion,
    '---'
   ,  LeafNode.AutoID as NodeID
   , '' as Servicepack
   , '' as Hotfix
   , LeafNode.LastUpdate as LastContact


 FROM ComputerProperties,
             LeafNode, BranchNode,
	Events
 WHERE
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where  BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND LeafNode.AVInstalls = 0
   AND LeafNode.Type !=24      /* Uninstalled */ 
   AND LeafNode.AutoID = ComputerProperties.ParentID 
   AND LeafNode.ParentID = BranchNode.AutoID
   AND LeafNode.AutoID *= Events.NodeID			/* outer join gets all */
   AND
   (
      Events.ProductName like '%GroupShield%'
      OR (Events.ProductName like '%NetShield%' and ProductVersion < '4.5')
      OR (Events.ProductName like '%VirusScan%' and ProductVersion < '4.5')
      OR Events.ProductName like '%WebShield%'
   )
   GROUP BY
   	BranchNode.NodeName,
   	ComputerProperties.ComputerName, 
  	ComputerProperties.DomainName, 
   	ComputerProperties.IPAddress, 
   	ComputerProperties.UserName,
	ComputerProperties.OSType,
--	ComputerProperties.OSVersion,
	ComputerProperties.OSServicePackVer,
	ComputerProperties.OSPlatform,
      	Events.ProductName
	,  LeafNode.AutoID 
	, LeafNode.LastUpdate

/* use group by to remove duplicates and return latest version, engine, dats */

 RETURN
END
GO



SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO




SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO




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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

/* 2.x fetch language names from language desc table  */
CREATE PROCEDURE dbo.AVISP_FilterLanguages
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT




 SELECT 
   ComputerProperties.ComputerName, 
   ComputerProperties.DomainName, 
   ComputerProperties.IPAddress,
   AVIView_Software.SoftwareName as ProductCode, 
   ProductVersion =
    	CASE ProductProperties.ProductVersion
     	WHEN '' THEN '---' 
     	ELSE ProductProperties.ProductVersion
     	END,
/*   ProductProperties.ProductVersion, */
   EngineVer =
    	CASE ProductProperties.EngineVer 
     	WHEN '' THEN '---' 
     	WHEN 'N/A' THEN '---' 
     	ELSE ProductProperties.EngineVer 
     	END,
   DATVer =
    	CASE ProductProperties.DATVer 
     	WHEN '' THEN '---' 
     	WHEN 'N/A' THEN '---' 
     	ELSE ProductProperties.DATVer 
     	END,
   ExtraDATNames =
    	CASE ProductProperties.ExtraDATNames 
     	WHEN 'N/A' THEN '' 
     	ELSE ProductProperties.ExtraDATNames 
     	END,
   Language =
    CASE 
     WHEN  LanguageDesc.LanguageName > '' THEN LanguageDesc.LanguageName
     WHEN  ProductProperties.Language = '' THEN '---'
     ELSE  ProductProperties.Language
     END,
/*   ProductProperties.Language, */
   BranchNode.NodeName AS NodeName, 
   ComputerProperties.UserName,
   cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion

 FROM ComputerProperties,  
   ProductProperties, AVIView_Software,
             LeafNode, BranchNode, LanguageDesc
 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND LeafNode.AutoID = ComputerProperties.ParentID
                   AND ProductProperties.ParentID = LeafNode.AutoID 
   and ProductProperties.ProductCode = AVIView_Software.ProductCode
   and AVIView_Software.ProductFamily in ( 'TVD', 'TVD_NC' )
   AND LeafNode.ParentID = BranchNode.AutoID
   AND RIGHT(ProductProperties.Language, 2) *= LanguageDesc.ClientLanguageSuffix
   AND LanguageDesc.epoServerLanguageID = @szFullLang
   AND LeafNode.Type !=24      /* Uninstalled */ 
 
 RETURN
END
GO




SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO



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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_FilterEPOAgentInstalls
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 SELECT 
   ComputerProperties.ComputerName, 
   ComputerProperties.DomainName, 
   ComputerProperties.IPAddress, 
   ProductProperties.ProductCode, 
   ProductVersion =
    AVIView_Software.SoftwareName + '/ ' +
    (CASE ProductProperties.ProductVersion
     WHEN '' THEN '---' 
     ELSE ProductProperties.ProductVersion
     END),
/*   ProductProperties.ProductVersion, */
   BranchNode.NodeName AS NodeName, 
   ComputerProperties.UserName,
   cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion,
   (case
   when LeafNode.LastUpdate > '' then CONVERT(datetime,
   (SUBSTRING( LeafNode.LastUpdate,  1 , 4)+'-'+
   SUBSTRING( LeafNode.LastUpdate,  5 , 2)+'-'+                              
   SUBSTRING( LeafNode.LastUpdate,  7 , 2)+' '+                              
   SUBSTRING( LeafNode.LastUpdate,  9 , 2)+':'+                              
   SUBSTRING( LeafNode.LastUpdate,  11 , 2)+':'+                              
   SUBSTRING( LeafNode.LastUpdate,  13 , 2)                                    
   ), 120 )   
   else convert(datetime, '01/01/1900') 
   end ) as ASCIdatetime			-- mhilandepo3: bugfix - handle empty values

 FROM ComputerProperties,  AVIView_Software,
   ProductProperties, 
             LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND ProductProperties.ParentID = LeafNode.AutoID
   AND LeafNode.AutoID = ComputerProperties.ParentID
   AND ProductProperties.ProductCode = AVIView_Software.ProductCode
   AND ProductProperties.ProductCode LIKE '%Agent%'
   AND LeafNode.ParentID = BranchNode.AutoID
   AND LeafNode.Type !=24      /* Uninstalled */ 

 RETURN
END



GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_Computer_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS 
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT




 SELECT LeafNode.AutoID 
          FROM LeafNode
     WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )

 RETURN
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_All_Comp_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 /* select statement*/
 SELECT *
 FROM ComputerProperties, LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND ComputerProperties.ParentID = LeafNode.AutoID
  AND LeafNode.ParentID = BranchNode.AutoID 

END

GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_All_Prod_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 /* select statement*/
 SELECT *
 FROM ProductProperties, LeafNode, BranchNode, AVIView_Software
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND ProductProperties.ParentID = LeafNode.AutoID
  AND LeafNode.ParentID = BranchNode.AutoID 
  AND ProductProperties.ProductCode = AVIView_Software.ProductCode

END
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_All_CompProd_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT




 /* select statement*/
 SELECT *
 FROM ComputerProperties, ProductProperties, LeafNode, BranchNode, AVIView_Software
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND ComputerProperties.ParentID = LeafNode.AutoID
  AND ProductProperties.ParentID = LeafNode.AutoID
  AND LeafNode.ParentID = BranchNode.AutoID 
  AND ProductProperties.ProductCode = AVIView_Software.ProductCode

END

GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_All_EventComp_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 /* select statement*/
 SELECT *
 FROM Events, ComputerProperties, LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND ComputerProperties.ParentID = LeafNode.AutoID
  AND LeafNode.ParentID = BranchNode.AutoID 
  AND Events.NodeID = LeafNode.AutoID

END

GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Filter_All_EventNode_Info
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN 
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 /* select statement*/
 SELECT *
 FROM Events, LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND Events.NodeID = LeafNode.AutoID
  AND LeafNode.ParentID = BranchNode.AutoID 

END

GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_FilterInstalls
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





 /* select statement*/
 SELECT   
   ComputerProperties.ComputerName, 
   ComputerProperties.DomainName, 
   ComputerProperties.IPAddress, 
   AVIView_Software.SoftwareName as ProductCode, 
   ProductProperties.ProductVersion,
   BranchNode.NodeName AS NodeName 
   ,  ComputerProperties.UserName,
     cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
	+ ' ' + ComputerProperties.OSPlatform) 
        as varchar(50)) as OSVersion
	FROM
	ComputerProperties,
   ProductProperties, 
   AVIView_Software,
             LeafNode, BranchNode
 WHERE 
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   AND ProductProperties.ProductCode = AVIView_Software.ProductCode 
   AND ProductProperties.ParentID = LeafNode.AutoID
                  AND LeafNode.AutoID = ComputerProperties.ParentID
   AND LeafNode.ParentID = BranchNode.AutoID

 RETURN
END

GO

/**/
/*** xxxxxx  infection report rotuines xxxxxxxxx */
/**/




SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO





SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

-- mhilandepo3 - End of legacy routines section
-- These are saved so that if users created custom reports based on them they will still work. 



/**/
/* xxxxx misc routines (rept filter, event filter, getuseraccessdata)  xxxxx */
/**/



/**/
/* v2.0 procedure: Used by reportfilter to return all fullpath nodenames and the leaf nodeid */
/* ePO3 - mhiland 1/13/2k2  Added option to generate ReportFullPathNode output table for use in new CoverageGroupSummary report */
/*  */
/**/

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_CalculateAllSubNodes
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @GenerateOutputTable nvarchar(5) = '' 
)
AS
BEGIN
  /* Copyright   1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/
      Declare @iFilterNode int
 Declare @szFilterName nvarchar(255)
 Declare @cnt int
 Declare @szFilterNode varchar(255)
 Declare @iFilterNode1 int

--create table temp1 ( namespacename int, namesoacenode int )
--insert temp1 select @iNameSpaceName, @iNameSpaceNode
/*  Always start with users topnode
      IF @szNameSpaceNode is not NULL  AND  @szNameSpaceNode != ''
 BEGIN
            SELECT @iFilterNode = AutoID from BranchNode where NodeName = @szNameSpaceNode
  SET @szFilterName = @szNameSpaceNode
 END
      ELSE
*/


 /* mhiland 1/13/2k2  - add default case of NameSpaceName = 0 */
 if @iNameSpaceName = 0
 Begin

	-- mhilandepo3.5: remove orphaned branchnode records if they exist
	Select @cnt=count(*) from BranchNode where Nodename = 'directory'
	if @cnt > 1
	begin	-- run three times to remove orphan site, root and global root
		-- delete orphaned Lost&Found node if it exists
		Select @cnt=count(*) from BranchNode where Nodename = 'Lost&Found' and Parentid in 
			(select autoid from Branchnode where type = 4)
		if @cnt > 1
		begin			
			declare @dircnt1 int 	declare @dirid1 int
			declare @dircnt2 int 	declare @dirid2 int
			-- determine orphaned directory node
			select @dirid1=min(autoid) from branchnode where type = 4
			select @dirid2=max(autoid) from branchnode where type = 4
			-- orphaned directory node has the fewest children
			select @dircnt1=count(*) from branchnodeenum where StartAutoID = @dirid1
			select @dircnt2=count(*) from branchnodeenum where StartAutoID = @dirid2
			if @dircnt1 > @dircnt2
				set @dirid1 = @dirid2
			-- delete lostand found from orphaned directory node
			delete branchnode where type in (5) and parentid = @dirid1
		end
		delete branchnode where type in (4,7) and autoid not in (select parentid from branchnode)
		delete branchnode where type in (4,7) and autoid not in (select parentid from branchnode)
	end

        select @szFilterName = NodeName,  @iFilterNode = AutoID
		from BranchNode where NodeName in ( 'directory', 'MergedDB' )	-- mhilandepo3: add MergedDB for dbmerge
	SET @iNameSpaceName = @iFilterNode
 END
 ELSE
 BEGIN
            select @szFilterName = NodeName from BranchNode where AutoID = @iNameSpaceName
  SET @iFilterNode = @iNameSpaceName
 END


      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
/* Declare @FilterID int */
/* EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT */

      /* refresh ##UserNodeAccessList */
     --EXECUTE AVIDALSP_GetUserNodeAccessList @iNameSpaceName, @iNameSpaceNode, @szEpoUserName
     -- mhiland 2/26/2k4 smb
     -- fix for sql7 sp4: no longer allows create statement within trigger
     -- Code from AVIDALSP_GetUserNodeAccessList, remove call to it to avoid possible contention issues
     IF @iNameSpaceNode > 0
           select @iFilterNode1 = @iNameSpaceNode
      ELSE
           select @iFilterNode1 = @iNameSpaceName
    
     select @szFilterNode = NodeName from BranchNode where AutoID = @iFilterNode1

     Delete from ReportTempUserNodeAccessList 

	INSERT ReportTempUserNodeAccessList 
	  SELECT EndAutoID as AutoID,  NodeName 
	                   FROM BranchNodeEnum, BranchNode 
	    WHERE 
	     StartAutoID =  @iFilterNode1
	     AND EndAutoID = BranchNode.AutoID
	  UNION 
	    SELECT @iFilterNode1, @szFilterNode   /* and the node it's self */


 /* step 0 */
      /* create UserNodeAccessList table with node names */
/*
 CREATE TABLE #UserNodeList(NodeID int, NodeName varchar(255))
      INSERT #UserNodeList
  SELECT BranchNode.AutoID, NodeName
  FROM ##UserNodeAccessList, BranchNode 
  WHERE ##UserNodeAccessList.AutoID = BranchNode.AutoID
*/

 /* step 1 */
      /* create subset of enum table the user has access to with branch node names in it */
 CREATE TABLE #UserEnum(ParentID int, ChildID int, PathLength int)

 INSERT #UserEnum 
    SELECT StartAutoID, EndAutoID, PathLength     /*, NULL, NULL*/
           FROM BranchNodeEnum
            WHERE StartAutoID in (SELECT AutoID FROM ReportTempUserNodeAccessList)
--            WHERE StartAutoID in (SELECT AutoID FROM ##UserNodeAccessList)


 /* step 2 */
 /* create full name path work table: will first expand out the nodeids until we have the full path */

 CREATE TABLE #FullPath(CID int, PID int,
     GPID int, GPID1 int,  
     PathLength int,
     FullPathName varchar(500),
     LowestNodeID int )

 /* create the initial parent child hierarchy */
      /* Load all enum entries with pathlength=1 so they can be traversed backwards */
 /* Each of these entries represents a node that must be traversed back to fill the pathname */
 /* Also add the LowestNodeID at this step - this is the FilterNodeID sent to the reports */
 INSERT #FullPath 
    SELECT ChildID, ParentID, 0,0,0,NULL, ChildID
           FROM #UserEnum
            WHERE PathLength = 1
  
 /* top node */
       INSERT #FullPath
  VALUES ( @iFilterNode, 0, 0,0,0,NULL, @iFilterNode )
 

 /* add pathlength from filternode to childnode */
 UPDATE #FullPath
  SET PathLength = 
   (SELECT PathLength
    FROM #UserEnum
    WHERE 
     ParentID = @iFilterNode
     and ChildID = CID)

     
 /* add new path levels until complete */
 /* add lowest child level */

 UPDATE #FullPath  SET FullPathName = (SELECT NodeName from ReportTempUserNodeAccessList where AutoID = CID) 
-- UPDATE #FullPath  SET FullPathName = (SELECT NodeName from ##UserNodeAccessList where AutoID = CID) 

 /* add parent, bumping child to the right on the pathlist */
 UPDATE #FullPath  
  SET FullPathName = rtrim((SELECT NodeName from ReportTempUserNodeAccessList where AutoID = PID))
    + ',' +FullPathName
  WHERE PID != 0
 UPDATE #FullPath  SET GPID = PID, GPID1 = NULL

 SET @cnt = 2

 /* loop through looking for lower nodes */
 WHILE EXISTS (SELECT PathLength from #FullPath WHERE PathLength = @cnt)
 BEGIN
  /* look for another round of parents */
  UPDATE #FullPath SET GPID1 = (SELECT ParentID FROM #UserEnum 
       WHERE ChildID = GPID and PathLength = 1) 
  /* if another level exists add it to the path, bumping the existing path to the right */
  UPDATE #FullPath  
   SET FullPathName = rtrim((SELECT NodeName from ReportTempUserNodeAccessList where AutoID = GPID1))
    + ',' +FullPathName
   WHERE GPID1 is not NULL 
  UPDATE #FullPath  SET GPID = GPID1, GPID1 = NULL
  SET @cnt = @cnt + 1
 END




 /* mhilandepo3 1/13/2k2 - Generate fullpatnnode table for use in reports */
 /* Generate the output table if it is asked for */
 if @GenerateOutputTable > ''
 BEGIN
	Truncate Table ReportFullPathNode
        INSERT ReportFullPathNode
 	SELECT 
		PathLength
		, FullPathName
		, LowestNodeID  
	FROM #FullPath
	 where FullPathName is not NULL
  	ORDER by FullPathName 	
 END
 ELSE
 BEGIN
 	/* present the results */
 	SELECT FullPathName, LowestNodeID  FROM #FullPath
	 where FullPathName is not NULL
  	ORDER by FullPathName 
 END


  /* cleauup */
	DROP TABLE #UserEnum
	DROP TABLE #FullPath

END

GO


SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


/* Used by epo to get users topnode, pswd, & rootnode */
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVISP_GetUserAccessData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVISP_GetUserAccessData]
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetUserAccessData
(
 @szEpoUserName  VARCHAR(100)
)
AS
BEGIN
 Declare @szRootNodeName VARCHAR(255)
 Declare @szUserTopNodeName VARCHAR(255)
 Declare @szUserPswd VARCHAR(255)
 Declare @iUserTopNodeID int
       Declare @iUserAccessMask int


 /* default settings for sql server login,  user root = root node. */
 SELECT @szRootNodeName = NodeName, @iUserTopNodeID = AutoID, @iUserAccessMask = 1, @szUserPswd = 0
  FROM BranchNode 
  WHERE Type=4;

 SELECT @iUserTopNodeID = RootNodeID, @iUserAccessMask = WriteAccess, @szUserPswd = Password
  FROM UserTable
  WHERE UserName = @szEpoUserName

 SELECT @szUserTopNodeName = NodeName
  FROM BranchNode 
  WHERE AutoID = @iUserTopNodeID;

 SELECT @szUserTopNodeName, @iUserTopNodeID, @iUserAccessMask, @szUserPswd, @szRootNodeName

END



GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetEventFilter
(
 @szLanguage VARCHAR(50)
)
AS
BEGIN

 -- epo3.5 add FilterSettingFixed which will turn off display of event in filter dialog
 SELECT f.EventID, Flag, Name, Description
  FROM EventFilter f, EventFilterDesc d
  WHERE f.EventID = d.EventID
   and Language = @szLanguage
   and HideInFilterTab != 1;
END
GO

SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_SetEventFilter
(
 @iEventID int,
 @iFlag int
)
AS
BEGIN

 UPDATE EventFilter
  SET Flag = @iFlag
  WHERE EventID = @iEventID;

 /* Update the change timestamp */
 UPDATE EventFilterControl
  SET TheTimestamp = @@dbts;

 /* must return some data so ODBS cursor is happy, sets error otherwise */
 SELECT Flag FROM EventFilter WHERE EventID = @iEventID;

END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetEventFilterControl
AS
BEGIN

 SELECT EnableAllEvents, TheTimestamp
  FROM EventFilterControl;

END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_SetEventFilterControl
(
 @iEnableAllEvents int
)
AS
BEGIN

 UPDATE EventFilterControl
  SET EnableAllEvents = @iEnableAllEvents,
   TheTimestamp = @@dbts;

 /* must return some data so ODBS cursor is happy, sets error otherwise */
 SELECT EnableAllEvents from EventFilterControl; 

END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetAllSubNodeIDs
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100)
)

 AS
BEGIN
  /* Copyright   1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

 /* check the user has enough rights to see this data */
 DECLARE @iRightsCheckResult   INTEGER
 DECLARE @iFilterNode int
      
 /* @szNameSpaceName  is the top node of the users account*/
 /* @szNameSpaceNode  is a node within the users account that they may filter on */

 IF @iNameSpaceNode > 0
             select @iFilterNode = @iNameSpaceNode
       ELSE
            select @iFilterNode = @iNameSpaceName


/* EXECUTE @iRightsCheckResult=AVISP_VerifyNameSpaceRights @iNameSpaceName, @iNameSpaceNode, @szEpoUserName

 IF(@iRightsCheckResult=1)
*/
 BEGIN
  /* All sub nodes */
  SELECT EndAutoID as AutoID 
                   FROM BranchNodeEnum 
    WHERE StartAutoID =  @iFilterNode
  UNION 
  /* and the node it's self */
       SELECT @iFilterNode
 END
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_Prepare_Query
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100)
)
AS
BEGIN
 /* Copyright   1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

 INSERT INTO #AVI_Query_NameSpace_Object_ID EXECUTE AVISP_GetAllSubNodeIDs @iNameSpaceName, @iNameSpaceNode, @szEpoUserName

 RETURN
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetSQLServerTime
(
  @time DATETIME  OUTPUT
)
AS
BEGIN
 set @time = CURRENT_TIMESTAMP
 return 
END

GO
SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


/**** xxxxxxx  webshield report procs xxxxxxx ****/

/*********** webshield reports stored procedures *********** */


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


-- epo3 similar to filtervalertgroups but has differences in where clause and fast summary
--  groups returns hostname which is the e500servername

CREATE PROCEDURE dbo.AVISP_FilterWebshieldGroups
(
 @iNameSpaceName  VARCHAR(20)
 , @iNameSpaceNode  VARCHAR(20)
 , @szEpoUserName  VARCHAR(100)
 , @szNameSpaceName  VARCHAR(100)
 , @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @szGroupName1  VARCHAR(100) = ''
 , @szGroupName2  VARCHAR(100) = ''
 , @szGroupName3  VARCHAR(100) = ''
 , @szGroupName4  VARCHAR(100) = ''
 , @InfectAfterYYYYMMDD varchar(30) = ''
 , @InfectAfterRule varchar(30) = ''
 , @szDrilldown1 	varchar(20)=''	-- layout, Drilldown, fast, printable
 , @EventType		varchar(50)='Infection'		-- All, Infection, Operational (Non-Infection), Infection-Cle, Moved, Deleted, Unresolved

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @ret int

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT

 -- Build a list of ProductEvent Guids that are not tied to a leaf node
-- select distinct AgentGUID
-- into #LostLinksEvents
-- from Events
--	where AgentGUID not in (select AgentGUID from leafnode)
--
-- Update VirusType table with any new viruses (avoids outer join - Prob in drilldown subreport)
-- select distinct VirusName, VirusType
-- into #VirusNameList
-- from Events
--	where VirusName > ''
-- 
-- insert VirusType
--	(VirusName, VirusType)
--	select VirusName, VirusType
--	from #VirusNameList
--	where VirusName not in (Select VirusName from VirusType)

  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


	-- Fetch Infect After date variables
	Declare @YYYYMMDD char(30)	
	Declare @YYYYMMDDdate datetime
	execute dbo.AVISP_GetDateConversion @InfectAfterYYYYMMDD, @InfectAfterRule, @YYYYMMDDdate output

	set @YYYYMMDD = Replace( Replace( Replace( convert(char(30), @YYYYMMDDdate,120), '-', ''), ':', ''), ' ', '')
	if @YYYYMMDD is null
		set @YYYYMMDD = ''
	-- Fetch Infect After date variables
--	Declare @YYYYMMDD datetime
--	execute dbo.AVISP_GetDateConversion @InfectAfterYYYYMMDD, @InfectAfterRule, @YYYYMMDD output

	------------------------------
	-- read in translated terms
   	Declare @Current varchar(30)			
   	Declare @Late varchar(30)			
   	Declare @Agent varchar(30)			
   	Declare @SuperAgentBroadcast varchar(100)	
   	Declare @SuperAgentRepository varchar(100)	
   	Declare @Unprotected varchar(30)		
   	Declare @Unlinked varchar(30)			
   	Declare @NoAgent varchar(30)		
   	Declare @Uncategorized varchar(50)		
	Declare @Critical varchar(50)
	Declare @Major varchar(50)			Declare @Minor varchar(50)
	Declare @Informational varchar(50)		Declare @Warning varchar(50)
	Declare @Blocked varchar(50)
	Declare @BufrOvflDetected varchar(200)
   	Declare @Server varchar(50)			
   	Declare @WorkStation varchar(50)	   	
	Declare @Professional varchar(50)	
	
   	Declare @Resolved varchar(30)	
   	Declare @Unresolved varchar(30)	





	If @Current = '' or @Current is null				-- if first is not found assume they all are
	Begin
   		Set @Current = 'Current'	Set @Late = 'Late'	Set @Agent = 'Agent'
   		Set @SuperAgentBroadcast = 'Super Agent Broadcast'	Set @SuperAgentRepository = 'Super Agent Repository'
		Set @Unprotected = 'Unprotected'	Set @Unlinked = 'Unlinked'	Set @NoAgent = 'No Agent'
		Set @Critical = 'Critical'	Set @Major = 'Major'	Set @Minor = 'Minor'
		Set @Warning = 'Warning'	Set @Informational = 'Informational'
		Set @Blocked = 'Blocked'
		if @EventType = 'BufrOvfl'
			Select 	@BufrOvflDetected = Name from EventFilterDesc 
				Where Language = '0409' and EventID='1093'	
		-- epo3.5 new string translation
   		Set @Server = 'Server'	Set @WorkStation = 'Workstation'	
		Set @Professional = 'Professional'
		
	   	Set @Resolved ='Resolved'	
   		Set @Unresolved ='Unresolved'		

	End

	-- if not english, read in translations
	if @szFullLang <> '0409' 
--		and @szFullLang <> '0411'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0412'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0404'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0804'  -- apac chars dont display in charts, keep this english
	Begin
		Select 	@Current = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Current'
		Select 	@Late = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Late'
		Select 	@Agent =  'Agent'
		Select 	@SuperAgentBroadcast = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentBroadcast'
		Select 	@SuperAgentRepository = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentRepository'
		Select 	@Unprotected = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unprotected'
		Select 	@NoAgent = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'NoAgent'
		Select 	@Unlinked = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unlinked'
		Select 	@Resolved = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Resolved'
		Select 	@UnResolved = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unresolved'
		Select 	@Uncategorized = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Uncategorized'
		Select 	@Critical = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Critical'
		Select 	@Major = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Major'
		Select 	@Minor = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Minor'
		Select 	@Warning = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Warning'
		Select 	@Informational = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Informational'
		-- vs7.5
		Select 	@Blocked = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Blocked'
		if @EventType = 'BufrOvfl'
			Select 	@BufrOvflDetected = Name from EventFilterDesc 
				Where Language = @szFullLang and EventID='1093'
		Select 	@Server = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Server'
		Select 	@WorkStation = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'WorkStation'
		Select 	@Professional = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Professional'

		-- epo3.5 action translations


	End
	


   -------------------------------------------------------------------------------------
   -- If Drilldown is set to fast, then fetch group summaries (subreport fetches detailed rows)
   -- this first option will return filename, hostname & username fields as well (needed for spam reports)
   if lower(@szDrilldown1) = 'fast' and @EventType != 'WSVirusHour'
   begin


 	SELECT   
		DateName(Year, EventDateTime) as 'Year'
		,Substring(convert(char,EventDateTime,120),1,7) as 'Month' -- yyyy-mm
		,DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2) as 'Week' -- yyyy-ww
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) as 'Quarter' -- yyyy-q
		, ''  as 'Day'
		, '' as 'Hour'

		-- product info fields
    		,CAST(ProductName As varchar(64)) AS ProductName
    		,ProductVersion =
  			CASE 
	   		WHEN ProductVersion > '' THEN  ProductVersion
	   		ELSE '---' 
	   		END
		,'' as ProductFamily
		,'' as ServicePack
		,'' as Hotfix
    		,CAST(EngineVersion As varchar(16)) AS EngineVersion
    		,CAST(DATVersion as varchar(16)) As DATVersion
		,cast('' as varchar(10)) as ExtraDATNames

		, cast( '' as varchar(10)) as Language

	        ,  '' as FullProductName
	        ,  case
		when EngineVersion + ' ' +  DATVersion > '' then cast((EngineVersion + ' ' +  DATVersion) as varchar(50)) 
		when EngineVersion > '' then cast((EngineVersion) as varchar(50)) 
		when DATVersion > '' then cast((DATVersion) as varchar(50)) 
		else '---'
		end as EngineDat 
		, '' as DatExtraDat

		-- agent fields
		, '' as AgentVersion
		, '' as AgentType
		, '' as ConnectStatus

		-- computer info fields
  		, '' as NodeName 
		, '' as Domainname
		, cast( '' as varchar(10)) as OSVersion
		, '' as OSType
		, '' as OSPlatform

		-- These fields are returned differently based on whether the report 
		-- returns group summaries or straight rows
		, count(*) as 'count'		-- fetch group summaries
--		, 1 as 'count'			-- fetch individual rows

--    		,(CASE @szTime
--			WHEN 'GMT' THEN EventDateTime
--			ELSE 		EventLocalDateTime
--			END) 
--		as EventDateTime
		, cast('1/1/1980' as DateTime) as EventDateTime
		, '' as LastContact

--		,  Events.HostName
		,  cast( HostName as varchar(50)) as HostName
--		, '' as UserName
		,  Events.UserName
		, '' as HostIPAddress
--		,  HostIPAddress
		, cast( '' as varchar(32)) as FullNodeName
--   		,cast(ReportFullPathNode.FullPathName as varchar(255))   AS FullNodeName 

--		, '' as FileName
		,  cast( FileName as varchar(255)) as FileName

		, cast( '' as varchar(32)) as  ProductCode
		, '' as NodeID
--		, NodeID
		,'' as LNAutoID
		,'' as LNParentID
		,'' as PPAutoID
		-- End of Group summary difference fields

		-- Virus Fields
    		,VirusName =
	  		CASE 
	   		WHEN Events.VirusName > '' THEN Events.VirusName
	   		ELSE '---' 
	   		END
   		, case 					-- use case incase outer join returns null
			when VirusType.VirusType > ''  then VirusType.VirusType
			else case  when Events.VirusType > '' then Events.VirusType else '---' end
			end as VirusType

		, '' as VirusSubtype

   		,ActionTaken =
	    		CASE 
	     		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		ELSE  CAST(Events.ActionTaken AS varchar(16)) 
 	    		END

		,'' as TVDEventID

		,'' as TVDSeverity
		, '' as TVDTaskName
--		,'' as TVDTaskName
    		, '' as ScanTime 
--		,'' as ScanTime

		,'' as EventDesc
		
		, '' as RuleName

		-- Product Update Fields
		,'' as Type 
		,'' as Version
		,'' as Error
		,'' as SiteName
		,'' as InitiatorID
		,'' as InitiatorType

 
 	FROM 
	(
	LeafNode Join BranchNode on(LeafNode.ParentID = BranchNode.AutoID)
	Left Outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
	)
	Right Outer Join 
	(
	Events 
	Left Outer Join VirusType on (Events.VirusName = VirusType.VirusName)
	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)
	) on(LeafNode.autoID = Events.NodeID)	

  	WHERE 
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR
  		LeafNode.ParentID in 
			(

			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        		from BranchNodeEnum 
        		where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)
  	AND    	
	(
		( @EventType = 'ContentFilter' AND TVDEventID=1506 )
		or
		( @EventType = 'ContentScanning' AND TVDEventID=1506 and events.VirusType = 'content-scanning' )
		or
		( @EventType = 'Spam' AND TVDEventID=1506 and events.VirusType in ('spam', 'deny-spam') )
		or
		( @EventType = 'URLBlocked' AND TVDEventID=4600  )
		or
		( @EventType = 'WSVirus' AND (TVDEventID=1503 or TVDEventID=1500 or TVDEventID=1515)  )
	) 
   	AND ( TVDEventID not in ( 1202, 1203, 4650, 4651 )  )	-- skip webshield events
--   	AND LeafNode.Type !=  24      -- show all events even thoughs tied to deleted nodes 
	and ( @YYYYMMDDdate is null or @YYYYMMDD = '' or Events.EventDateTime >=  @YYYYMMDDdate)
--             AND Events.ProductName != 'ePO Agent' 


	Group By
		-- postepo3 - optimize group order
		DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2)
		,Substring(convert(char,EventDateTime,120),1,7) 
		,DateName(Year, EventDateTime) 
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) 
		,Events.VirusName
		,Events.HostName
		,Events.UserName
		,Events.FileName
		,ReportActionDesc.ActionName
		,Events.ActionTaken
		,BranchNode.NodeName
		,ProductName
		,ProductVersion
		,EngineVersion
		,DATVersion
--    		, TVDEventID				-- newest groups fields
--    		, TVDSeverity
   		, VirusType.VirusType
		, Events.VirusType
		, VirusType.VirusFileType
--		, TVDTaskName
--		, EventFilterDescFast.Name 
		, ComputerProperties.Domainname
		, ComputerProperties.OSType
	    	, ComputerProperties.OSPlatform



   end

   else	if lower(@szDrilldown1) = 'drilldown' or  lower(@szDrilldown1) = 'printable'		-- fetch detailed computer rows: epo2.5 and below behavior (slow)
		or (lower(@szDrilldown1) = 'fast' and @EventType = 'WSVirusHour')		-- needed for VirusHour report
   begin

 	SELECT   
		DateName(Year, EventDateTime) as 'Year'
		,Substring(convert(char,EventDateTime,120),1,7) as 'Month' -- yyyy-mm
		,DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2) as 'Week' -- yyyy-ww
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) as 'Quarter' -- yyyy-q
		,cast('' as varchar(16)) as 'Day'
		, '' as 'Hour'

		-- Product Info Fields
    		,CAST(ProductName As varchar(64)) AS ProductName
    		,ProductVersion =
  			CASE 
	   		WHEN ProductVersion > '' THEN  ProductVersion
	   		ELSE '---' 
	   		END
		,cast('' as varchar(10)) as ProductFamily
		,cast('' as varchar(10)) as ServicePack
		,cast('' as varchar(10)) as Hotfix
    		,CAST(EngineVersion As varchar(16)) AS EngineVersion
    		,CAST(DATVersion as varchar(16)) As DATVersion
		,cast('' as varchar(10)) as ExtraDATNames
		, cast( '' as varchar(10)) as Language
	        ,  '' as FullProductName
	        ,  case
		when EngineVersion + ' ' +  DATVersion > '' then cast((EngineVersion + ' ' +  DATVersion) as varchar(50)) 
		when EngineVersion > '' then cast((EngineVersion) as varchar(50)) 
		when DATVersion > '' then cast((DATVersion) as varchar(50)) 
		else '---'
		end as EngineDat 
		, '' as DatExtraDat

		-- Agent info fields
		, '' as AgentVersion
		, '' as AgentType
		, '' as ConnectStatus

		-- Computer Info fields
  		, '' as NodeName 
		, '' as Domainname
		, cast( '' as varchar(10)) as OSVersion
		, '' as OSType
		, '' as OSPlatform


		-- These fields are returned differently based on whether the report 
		-- returns group summaries or straight rows
--		, count(*) as 'count'		-- fetch group summaries
		, 1 as 'count'			-- fetch individual rows
    		, (CASE @szTime
			WHEN 'GMT' THEN EventDateTime
			ELSE 		EventLocalDateTime
			END) 
		as EventDateTime
--		, '' as EventDateTime
		, '' as LastContact

--		,  '' as HostName
		,  cast( HostName as varchar(50)) as HostName
--		, '' as UserName
		,  Events.UserName
--		, '' as HostIPAddress
		,  HostIPAddress
		,  '' as FullNodeName
--   		,cast(ReportFullPathNode.FullPathName as varchar(255))   AS FullNodeName 

--		, '' as FileName
		,  cast( FileName as varchar(255)) as FileName

		, '' as  ProductCode
--		, '' as NodeID
		, NodeID
		, NodeID as LNAutoID
		,'' as LNParentID
		,'' as PPAutoID
		-- End of Group summary difference fields


		-- Virus info fields
    		,VirusName =
	  		CASE 
	   		WHEN Events.VirusName > '' THEN Events.VirusName
	   		ELSE '---' 
	   		END
   		, case 					-- use case incase outer join returns null
			when VirusType.VirusType > ''  then VirusType.VirusType
			else case  when Events.VirusType > '' then Events.VirusType else '---' end
			end as VirusType

		, '' as VirusSubtype

   		,ActionTaken =
	    		CASE 
	     		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		ELSE  CAST(Events.ActionTaken AS varchar(16)) 
 	    		END

    		,cast( TVDEventID as varchar(10)) as TVDEventID

		-- postepo3 bugfix 33760: convert int events.tvdseverity to varchar - crashed webhield layout=drilldown
    		,  case 
			when EventFilterDescFast.Severity > '' then EventFilterDescFast.Severity
			else cast(Events.TVDSeverity as varchar(30))
			end  as TVDSeverity
--		,'' as TVDSeverity
		, '' as TVDTaskName
--		,'' as TVDTaskName
    		, '' as ScanTime 
--		,'' as ScanTime
		, case 
			when EventFilterDescFast.Name > '' then cast(EventFilterDescFast.Name as varchar(128)) 
			else case when TVDEventID > 0 then cast(TVDEventID as varchar(128)) else '---' end
			end as EventDesc
--		,'' as EventDesc
		
		, '' as RuleName

		-- Product update fields
		,'' as Type 
		,'' as Version
		,'' as Error
		,'' as SiteName
		,'' as InitiatorID
		,'' as InitiatorType

 
 	FROM 
	(
	LeafNode Join BranchNode on(LeafNode.ParentID = BranchNode.AutoID)
	Left Outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
	)
	Right Outer Join 
	(
	Events 
	Left Outer Join EventFilterDescFast on(events.tvdeventid = EventFilterDescFast.eventid
		and EventFilterDescFast.language = @szFullLang)
	Left Outer Join VirusType on (Events.VirusName = VirusType.VirusName)
	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)
	) on(LeafNode.autoID = Events.NodeID)	
  	WHERE 
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR
  		LeafNode.ParentID in 
			(
			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        		from BranchNodeEnum 
        		where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)
  	AND    	
	(
		( @EventType = 'ContentFilter' AND TVDEventID=1506 )
		or
		( @EventType = 'ContentScanning' AND TVDEventID=1506 and events.VirusType = 'content-scanning' )
		or
		( @EventType = 'Spam' AND TVDEventID=1506 and events.VirusType in ('spam', 'deny-spam') )
		or
		( @EventType = 'URLBlocked' AND TVDEventID=4600  )
		or
		( (@EventType = 'WSVirus' or @EventType = 'WSVirusHour') AND (TVDEventID=1503 or TVDEventID=1500 or TVDEventID=1515)  )
	) 
   	AND TVDEventID not in (1202, 1203, 4650, 4651 )
--   	AND LeafNode.Type !=  24      -- show all events even thoughs tied to deleted nodes 
	and ( @YYYYMMDDdate is null or @YYYYMMDDdate = ''  or Events.EventDateTime >=  @YYYYMMDDdate)
--	AND Events.ProductName != 'ePO Agent' 


   end





	set @ret = @@rowcount

	-- cleanup
--	Drop Table #LostLinksEvents		



RETURN @ret
END
GO



SET QUOTED_IDENTIFIER  OFF    SET ANSI_NULLS  ON 
GO


SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO





-- epo3: new removeable media routine: just returns removable media events (much fast)
-- fast group summary option removed - drilldown only format

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


CREATE PROCEDURE dbo.AVISP_FilterVAlertRemovableMedia
(
 @iNameSpaceName  VARCHAR(20)
 , @iNameSpaceNode  VARCHAR(20)
 , @szEpoUserName  VARCHAR(100)
 , @szNameSpaceName  VARCHAR(100)
 , @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @szGroupName1  VARCHAR(100) = ''
 , @szGroupName2  VARCHAR(100) = ''
 , @szGroupName3  VARCHAR(100) = ''
 , @szGroupName4  VARCHAR(100) = ''
 , @InfectAfterYYYYMMDD varchar(30) = ''
 , @InfectAfterRule varchar(30) = ''
 , @szDrilldown1 	varchar(20)='Drilldown'	-- layout, Drilldown, fast, printable
 , @EventType		varchar(50)='Infection'		-- All, Infection, Operational (Non-Infection), Infection-Cle, Moved, Deleted, Unresolved
 , @RemovableMedia      varchar(50)='A:'	--removable media drive letter
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @ret int

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT

   Declare @MediaTest1 varchar(10)
   Declare @MediaTest2 varchar(10)
   Set @MediaTest1 = @RemovableMedia + '%'
   Set @MediaTest2 = '%' + @RemovableMedia + '%'

	-- Fetch Infect After date variables
	Declare @YYYYMMDD char(30)	
	Declare @YYYYMMDDdate datetime
	execute dbo.AVISP_GetDateConversion @InfectAfterYYYYMMDD, @InfectAfterRule, @YYYYMMDDdate output

	set @YYYYMMDD = Replace( Replace( Replace( convert(char(30), @YYYYMMDDdate,120), '-', ''), ':', ''), ' ', '')
	if @YYYYMMDD is null
		set @YYYYMMDD = ''
	-- Fetch Infect After date variables
--	Declare @YYYYMMDD datetime
--	execute dbo.AVISP_GetDateConversion @InfectAfterYYYYMMDD, @InfectAfterRule, @YYYYMMDD output




	-- not a group summary fetch, gets every row matching removable media
 	SELECT   
		DateName(Year, EventDateTime) as 'Year'
		,Substring(convert(char,EventDateTime,120),1,7) as 'Month' -- yyyy-mm
		,DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2) as 'Week' -- yyyy-ww
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) as 'Quarter' -- yyyy-q
		,cast('' as varchar(16)) as 'Day'
		, '' as 'Hour'

		-- Product Info Fields
    		,CAST(ProductName As varchar(64)) AS ProductName
    		,ProductVersion =
  			CASE 
	   		WHEN ProductVersion > '' THEN  ProductVersion
	   		ELSE '---' 
	   		END
		,cast('' as varchar(10)) as ProductFamily
		,cast('' as varchar(10)) as ServicePack
		,cast('' as varchar(10)) as Hotfix
    		,CAST(EngineVersion As varchar(16)) AS EngineVersion
    		,CAST(DATVersion as varchar(16)) As DATVersion
		,cast('' as varchar(10)) as ExtraDATNames
		, cast( '' as varchar(10)) as Language
	        ,  case
		when Events.ProductName + ' ' + Events.ProductVersion > '' then cast((Events.ProductName + ' ' + Events.ProductVersion) as varchar(50))
		when Events.ProductName > '' then cast((Events.ProductName) as varchar(50))
		when Events.ProductVersion > '' then cast((Events.ProductVersion) as varchar(50))
		else '---'
		end as FullProductName
	        ,  case
		when EngineVersion + ' ' +  DATVersion > '' then cast((EngineVersion + ' ' +  DATVersion) as varchar(50)) 
		when EngineVersion > '' then cast((EngineVersion) as varchar(50)) 
		when DATVersion > '' then cast((DATVersion) as varchar(50)) 
		else '---'
		end as EngineDat 
		, '' as DatExtraDat

		-- Agent info fields
		, '' as AgentVersion
		, '' as AgentType
		, '' as ConnectStatus

		-- Computer Info fields
  		, NodeName = 
			CASE
			WHEN BranchNode.NodeName > '' THEN  BranchNode.NodeName
			ELSE '(Unlinked)'
			END 
		, case
			when ComputerProperties.Domainname > '' then ComputerProperties.Domainname
			when ComputerProperties.Domainname = '' then '---'
			else '(Unlinked)'
			end as Domainname
		, cast( '' as varchar(10)) as OSVersion
		, case
			when ComputerProperties.OSType > '' then ComputerProperties.OSType
			when ComputerProperties.OSType = '' then '---'
			else '(Unlinked)'
			end as OSType
		, case
			when ComputerProperties.OSPlatform > '' then ComputerProperties.OSPlatform
			when ComputerProperties.OSPlatform = '' then '---'
			else '(Unlinked)'
			end as OSPlatform


		-- These fields are returned differently based on whether the report 
		-- returns group summaries or straight rows
--		, count(*) as 'count'		-- fetch group summaries
		, 1 as 'count'			-- fetch individual rows
    		, (CASE @szTime
			WHEN 'GMT' THEN EventDateTime
			ELSE 		EventLocalDateTime
			END) 
		as EventDateTime
--		, '' as EventDateTime
		, '' as LastContact

--		,  '' as HostName
		,  cast( HostName as varchar(50)) as HostName
--		, '' as UserName
		,  Events.UserName
--		, '' as HostIPAddress
		,  HostIPAddress
		,  '' as FullNodeName
--   		,cast(ReportFullPathNode.FullPathName as varchar(255))   AS FullNodeName 

--		, '' as FileName
		,  cast( FileName as varchar(255)) as FileName

		, '' as  ProductCode
--		, '' as NodeID
		, NodeID
		, NodeID as LNAutoID
		,'' as LNParentID
		,'' as PPAutoID
		-- End of Group summary difference fields


		-- Virus info fields
    		,VirusName =
	  		CASE 
	   		WHEN Events.VirusName > '' THEN Events.VirusName
	   		ELSE '---' 
	   		END
   		, case 					-- use case incase outer join returns null
			when VirusType.VirusType > ''  then VirusType.VirusType
			else case  when Events.VirusType > '' then Events.VirusType else '---' end
			end as VirusType

		, '' as VirusSubtype

   		,ActionTaken =
	    		CASE 
	     		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		ELSE  CAST(Events.ActionTaken AS varchar(16)) 
 	    		END

    		,cast( TVDEventID as varchar(10)) as TVDEventID

		,'' as TVDSeverity
		, TVDTaskName
--		,'' as TVDTaskName
    		, '' as ScanTime 
--		,'' as ScanTime
--		, case 
--			when EventFilterDescFast.Name > '' then cast(EventFilterDescFast.Name as varchar(128)) 
--			else case when TVDEventID > 0 then cast(TVDEventID as varchar(128)) else '---' end
--			end as EventDesc
		,'' as EventDesc
		
		, '' as RuleName

		-- Product update fields
		,'' as Type 
		,'' as Version
		,'' as Error
		,'' as SiteName
		,'' as InitiatorID
		,'' as InitiatorType

 
 	FROM 
	(
	LeafNode Join BranchNode on(LeafNode.ParentID = BranchNode.AutoID)
	Left Outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
	)
	Right Outer Join 
	(
	Events 
	Left Outer Join VirusType on (Events.VirusName = VirusType.VirusName)
	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)
	) on(LeafNode.autoID = Events.NodeID)	
  	WHERE 
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR
  		LeafNode.ParentID in 
			(
			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        		from BranchNodeEnum 
        		where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)
  	AND    	
	(
		@EventType = 'All'  or
		( @EventType = 'NotInfection' and (Events.VirusName = '' or Events.VirusName is null)) or 
		( @EventType = 'Infection' and Events.VirusName > '' AND Events.ProductName != 'ePO Agent'  ) or 
		( @EventType = 'Infection-Res' and Events.VirusName > ''  and ReportActionDesc.ResolutionID > 0 )
		or ( @EventType = 'Infection-Unr' and Events.VirusName > ''    and ReportActionDesc.ResolutionID < 0 )
		or ( @EventType = 'Infection-Cle' and Events.VirusName > ''   and ReportActionDesc.ResolutionID =1 )
		or ( @EventType = 'Infection-Del' and Events.VirusName > ''  and ReportActionDesc.ResolutionID =2 )
		or ( @EventType = 'Infection-Mov' and Events.VirusName > ''  and ReportActionDesc.ResolutionID =3 )
	) 
   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
		AND ( TVDEventID < 8500 or TVDEventID > 8999 )

--   	AND LeafNode.Type !=  24      -- show all events even thoughs tied to deleted nodes 
	and ( @YYYYMMDDdate is null or @YYYYMMDDdate = ''  or Events.EventDateTime >=  @YYYYMMDDdate)
--	AND Events.ProductName != 'ePO Agent' 
	and 
	(
		Events.Filename = @RemovableMedia
		or
		Events.Filename like @MediaTest1
		or
		Events.Filename like @MediaTest2
	)




	set @ret = @@rowcount

	-- cleanup
--	Drop Table #LostLinksEvents		



RETURN @ret
END
GO


-- xxxxxxx ePO v2.5 8/15/2001     Addon Reports - Virus Type Report xxxxxxxxxxxxxx */
-- epo 2.5.0 hf3 & 2.5.1 */
-- epo3.0 changed to give top reiority ti events.virustype field (best recognition of trojans)
-- Changed to used same inputs and outputs as custom data report, so that the custom data rpt (template) can be used to display it
-- vs7.5 handle new detections types: syware, malware, etc (bad prgms)

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO




CREATE PROCEDURE dbo.AVISP_FilterVirusType
(
	@iNameSpaceName		VARCHAR(20),
	@iNameSpaceNode		VARCHAR(20),
    	@szEpoUserName          VARCHAR(100),
	@szNameSpaceName		VARCHAR(100),
	@szNameSpaceNode		VARCHAR(500),
 	@szOptionalReportParms  VARCHAR(500) = ''
 -- these inputs are needed in order for the infections by custom daat report to call this procedure
 , @szGroupName1  VARCHAR(100) = 'VirusType'
 , @szGroupName2  VARCHAR(100) = 'VirusSubtype'
 , @szGroupName3  VARCHAR(100) = ''
 , @szGroupName4  VARCHAR(100) = ''
 , @InfectAfterYYYYMMDD varchar(30) = ''
 , @InfectAfterRule varchar(30) = ''
 , @szDrilldown1 	varchar(20)='Drilldown'	-- layout, Drilldown, fast, printable
 , @EventType		varchar(50)='Infection'		-- All, Infection, Operational (Non-Infection), Infection-Cle, Moved, Deleted, Unresolved

/*	 , @dtStartDate			DateTime */
)
AS
BEGIN
 	/* Copyright + 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

	Declare @maxid int
	Declare @ret int

/* Fetch Top Nodeid to filter data on if report filter or users TopNode indicated filtering */
	Declare @UsersTopNodeID int
 	Declare @FilterNodeID int	select @UsersTopNodeID = convert(int, @iNameSpaceName)
	select @FilterNodeID = convert(int, @iNameSpaceNode)

	Declare @FilterID int
	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


------------
-- Fetch Translated text

   	Declare @Uncategorized varchar(30)			
	Set @Uncategorized = 'Uncategorized'
	Select 	@Uncategorized = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Virustype' and TextID = 'Uncategorized'
   	Declare @MassMailer varchar(30)			
	Set @MassMailer = 'Mass Mailer'
	Select 	@MassMailer = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Virustype' and TextID = 'Mass Mailer'


----------------
-- Make sure tmp tables are cleaned up
-- postepo3 collation between epo db and tempdb can be different, therefore dont use tempdb anymore, cleanup myself

	IF EXISTS (select * from sysobjects where name = 'tmpVirusname' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusname

	IF EXISTS (select * from sysobjects where name = 'tmpVirusFileTypeCrossProduct' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusFileTypeCrossProduct

	IF EXISTS (select * from sysobjects where name = 'tmpVirusSubtypeCrossProduct' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusSubtypeCrossProduct

	IF EXISTS (select * from sysobjects where name = 'tmpVirusFileTypePriority' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusFileTypePriority

	IF EXISTS (select * from sysobjects where name = 'tmpVirusSubtypePriority' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusSubtypePriority

	IF EXISTS (select * from sysobjects where name = 'tmpVirusFileType' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusFileType

	IF EXISTS (select * from sysobjects where name = 'tmpVirusSubtype' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVirusSubtype


/* Fetch all unique VirusNames, with the latest VirusType entry */
SELECT
	VirusName
	, cast(max( DATVersion + 'VT:' + VirusType) as varchar(128)) as 'LatestVirusType'
	-- epo3.5: must cast this to a large value to make sure it will hold whatever it is overwritten with
	, cast('Blank virus type' as varchar(128)) as VirusType
--	, max( VirusType ) as DefaultVirusType
into dbo.tmpVirusname
FROM Events
where virusname > '' and virustype > '' and datversion > '' 
and TvdEventID != 1506 and TvdEventID != 4600		-- excluse webshield events using virusname field
Group by
	VirusName

/* Strip the virustype data out of the latestvirustype field */
update
dbo.tmpVirusname
set VirusType = 
substring( LatestVirusType 
	, charindex('VT:',LatestVirusType)+3 
	, Len(LatestVirusType)-charindex('VT:',LatestVirusType)+3)


--select * from dbo.tmpVirusname order by virusname

/* match virusname with cross product of all matching virus file platform type prefixes */
SELECT
	VirusName,
  	AutoID as Priority
INTO
	dbo.tmpVirusFiletypeCrossProduct
FROM
	dbo.tmpVirusname, VirusFilePlatformTypeDesc
WHERE
	SUBSTRING( dbo.tmpVirusname.VirusName, 
		CHARINDEX(VirusFilePlatformTypeDesc.VirusPrefix, dbo.tmpVirusname.VirusName), 
		len(VirusFilePlatformTypeDesc.VirusPrefix) ) = VirusFilePlatformTypeDesc.VirusPrefix


	/* Make sure every VirusName is in the Cross product table at least once */
        select @maxid=max(autoid) from VirusFilePlatformTypeDesc
	INSERT dbo.tmpVirusFiletypeCrossProduct
		SELECT VirusName, @maxid  From dbo.tmpVirusname

	/* Remove multiple matches by priority */
	SELECT
		VirusName,
	 	min(Priority) as Priority
	INTO
		dbo.tmpVirusFiletypePriority
	FROM
		dbo.tmpVirusFiletypeCrossProduct
	GROUP BY
		VirusName


	/* Generate VirusFileType Table */
	SELECT
		VirusName,
		VirusFileType,
	 	VirusPlatformType,
		VirusType
--			CASE VirusType
--				WHEN 'UnCategorized' THEN @UnCategorized
--				ELSE VirusType
--			END as VirusType
	INTO
		dbo.tmpVirusFiletype
	FROM
		dbo.tmpVirusFiletypePriority, VirusFilePlatformTypeDesc
	WHERE
		dbo.tmpVirusFiletypePriority.Priority = VirusFilePlatformTypeDesc.AutoID

	

/* match virusname with cross product of all matching virus file platform type */
SELECT
	VirusName,
  	AutoID as Priority
INTO
	dbo.tmpVirusSubtypeCrossProduct
FROM
	dbo.tmpVirusname, VirusTypeDesc
WHERE
	SUBSTRING( dbo.tmpVirusname.VirusName, 
		CHARINDEX(VirusTypeDesc.VirusSuffix, dbo.tmpVirusname.VirusName), 
		len(VirusTypeDesc.VirusSuffix) ) = VirusTypeDesc.VirusSuffix


	/* Make sure every VirusName is in the Cross product table at least once */
        select @maxid=max(autoid) from  VirusTypeDesc
	INSERT dbo.tmpVirusSubtypeCrossProduct
		SELECT VirusName, @maxid  From dbo.tmpVirusname

	/* Remove multiple matches by priority */
	SELECT
		VirusName,
	 	min(Priority) as Priority
	INTO
		dbo.tmpVirusSubtypePriority
	FROM
		dbo.tmpVirusSubtypeCrossProduct
	GROUP BY
		VirusName
		

	/* Generate VirusFileType Table */
	SELECT
		VirusName,
		VirusType
	INTO
		dbo.tmpVirusSubtype
	FROM
		dbo.tmpVirusSubtypePriority, VirusTypeDesc
	WHERE
		dbo.tmpVirusSubtypePriority.Priority = VirusTypeDesc.AutoID



/* Generate final VirusType Table from subtables */
DELETE VirusType 

INSERT 
	VirusType
(VirusName, VirusFileType, VirusPlatformType, VirusType, VirusTypeTranslated, LanguageID)
	SELECT
		 dbo.tmpVirusname.VirusName,
  		 VirusFileType,
 		 VirusPlatformType,
 		 VirusType = 
			CASE dbo.tmpVirusSubtype.VirusType
				WHEN @UnCategorized THEN dbo.tmpVirusFiletype.VirusType
				ELSE dbo.tmpVirusSubtype.VirusType
			END, 
--		 NULL, NULL,
 		 VirusTypeTranslated = 
			CASE dbo.tmpVirusSubtype.VirusType
				WHEN @UnCategorized THEN dbo.tmpVirusFiletype.VirusType
				ELSE dbo.tmpVirusSubtype.VirusType
			END, 
		 '0409' as LanguageID
	FROM
		dbo.tmpVirusname, dbo.tmpVirusFiletype, dbo.tmpVirusSubtype
	WHERE
		dbo.tmpVirusname.VirusName = dbo.tmpVirusFiletype.VirusName 
		AND	dbo.tmpVirusFiletype.VirusName = dbo.tmpVirusSubtype.VirusName 

Set @ret = @@rowcount

-- mhilandepo3 postepo3 fix: 1) make sure VirusTypeTranslated is overridden as well 2) dont overwrite if VT < 'a'
-- mhilandepo3 subtitute events.virustype where suffix prefix rules fail
/* Override VirusType derived from VirusName with certain fields from the events.virustype field */
UPDATE
	VirusType
	SET	
		VirusFileType = 
			CASE VirusType.VirusType
				WHEN 'Mass Mailer' then 'Mass Mailer'
				else VirusType.VirusFileType
			END
		,VirusType.VirusType = tmpVirusname.VirusType
		,VirusType.VirusTypeTranslated = tmpVirusname.VirusType
--		,VirusType = 
--			CASE dbo.tmpVirusname.VirusType
--				WHEN 'APP' then 'Application'
--				WHEN 'Trojan' then 'Trojan'
--				WHEN 'Joke' then 'Joke'
--				WHEN 'Test' then 'Test'
--				else VirusType.VirusType
--			END
--		,VirusTypeTranslated = 
--			CASE dbo.tmpVirusname.VirusType
--				WHEN 'APP' then 'Application'
--				WHEN 'Trojan' then 'Trojan'
--				WHEN 'Joke' then 'Joke'
--				WHEN 'Test' then 'Test'
--				WHEN 'Program' then 'Program'
--				else VirusType.VirusType
--			END
	FROM	dbo.tmpVirusname
	WHERE	dbo.tmpVirusname.VirusName = VirusType.VirusName
		-- vs7.5 handle new APP_ virustypes and create a mechanism for creating
		--	and automatically catching new virustypes
		AND (
			dbo.tmpVirusname.VirusType in ('APP','Trojan','Joke','Test','Program')
			or 
			dbo.tmpVirusname.VirusType like 'APP_%'
			or
			dbo.tmpVirusname.VirusType like 'VS_%'	-- default prefix to capture new virus type
		 )

/* Replace uncategorized viruses with data in events.virustype field */
UPDATE
	VirusType
	SET
		VirusType = 
			CASE dbo.tmpVirusname.VirusType
				WHEN 'Known Virus' then 'Virus'
				WHEN 'Virus' then 'Virus'
				WHEN '' then 'Uncategorized'
				WHEN NULL then 'Uncategorized'
				else dbo.tmpVirusname.VirusType
			END
--		VirusTypeTranslated = 
--			CASE dbo.tmpVirusname.VirusType
--				WHEN 'Known Virus' then 'Virus'
--				WHEN 'Virus' then 'Virus'
--				WHEN '' then 'UnCategorized'
--				WHEN NULL then 'UnCategorized'
--				else dbo.tmpVirusname.VirusType
--			END
	FROM	dbo.tmpVirusname
	WHERE	dbo.tmpVirusname.VirusName = VirusType.VirusName
		AND 
		   VirusType.VirusType = 'Uncategorized'
--		and dbo.tmpVirusname.VirusType > 'a'


UPDATE
	VirusType
	SET
		VirusFileType = 
			CASE dbo.tmpVirusname.VirusType
				WHEN 'Known Virus' then 'Virus'
				WHEN 'Virus' then 'Virus'
				WHEN '' then 'Uncategorized'
				WHEN NULL then 'Uncategorized'
				else dbo.tmpVirusname.VirusType
			END
	FROM	dbo.tmpVirusname
	WHERE	dbo.tmpVirusname.VirusName = VirusType.VirusName
		AND 
		   VirusType.VirusFileType = 'Uncategorized'
--		and dbo.tmpVirusname.VirusType > 'a'


-- Translate it everytime
-- Translate VirusType name
--if @szFullLang <> '0409'
--begin
UPDATE
	VirusType
	SET
		VirusTypeTranslated =  
			CASE 
				WHEN ReportTranslations.TranslatedValue = 'Uncategorized' then @UnCategorized
				WHEN ReportTranslations.TranslatedValue = 'Mass Mailer' then @MassMailer
				WHEN ReportTranslations.TranslatedValue > '' then ReportTranslations.TranslatedValue
				WHEN VirusType.VirusType = 'Uncategorized' then @UnCategorized
				WHEN VirusType.VirusType = 'Mass Mailer' then @MassMailer
				else VirusType.VirusType
			END
	FROM	ReportTranslations
	WHERE	ReportTranslations.TextID = VirusType.VirusType
		AND ReportTranslations.Subject = 'Virustype'
		AND ReportTranslations.LanguageID = @szFullLang

Update VirusType
	Set LanguageID = @szFullLang
--end


/*select * from virustype*/




-----------------------------------------------------------------------------------------
-- Output results if not set to batch mode (otherwise it only updates the virustype table
IF @szOptionalReportParms <> 'BatchModeUpdateTableOnly'
Begin

	
/* Final Selection getting all Event data for report */
-- virus type report works in fast group summary fetch mode only


 	SELECT   

		DateName(Year, EventDateTime) as 'Year'
		,Substring(convert(char,EventDateTime,120),1,7) as 'Month' -- yyyy-mm
		,DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2) as 'Week' -- yyyy-ww
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) as 'Quarter' -- yyyy-q
		,cast('' as varchar(16)) as 'Day'
		, '' as 'Hour'

		-- Product Info Fields
    		,CAST(ProductName As varchar(64)) AS ProductName
    		,ProductVersion =
  			CASE 
	   		WHEN ProductVersion > '' THEN  ProductVersion
	   		ELSE '---' 
	   		END
		,cast('' as varchar(10)) as ProductFamily
		,cast('' as varchar(10)) as ServicePack
		,cast('' as varchar(10)) as Hotfix
    		,CAST(EngineVersion As varchar(16)) AS EngineVersion
    		,CAST(DATVersion as varchar(16)) As DATVersion
		,cast('' as varchar(10)) as ExtraDATNames
		, cast( '' as varchar(10)) as Language
	        ,  case
		when Events.ProductName + ' ' + Events.ProductVersion > '' then cast((Events.ProductName + ' ' + Events.ProductVersion) as varchar(50))
		when Events.ProductName > '' then cast((Events.ProductName) as varchar(50))
		when Events.ProductVersion > '' then cast((Events.ProductVersion) as varchar(50))
		else '---'
		end as FullProductName
	        ,  case
		when EngineVersion + ' ' +  DATVersion > '' then cast((EngineVersion + ' ' +  DATVersion) as varchar(50)) 
		when EngineVersion > '' then cast((EngineVersion) as varchar(50)) 
		when DATVersion > '' then cast((DATVersion) as varchar(50)) 
		else '---'
		end as EngineDat 
		, '' as DatExtraDat

		-- Agent info fields
--		, LeafNode.AgentVersion
		, '' as AgentVersion
		, '' as AgentType
		, '' as ConnectStatus

		-- Computer Info fields
  		, NodeName = 
			CASE
			WHEN BranchNode.NodeName > '' THEN  BranchNode.NodeName
			ELSE '---'
			END 
		, case
			when ComputerProperties.Domainname > '' then ComputerProperties.Domainname
			else '---'
			end as Domainname
		, cast( '' as varchar(10)) as OSVersion
		, case
			when ComputerProperties.OSType > '' then ComputerProperties.OSType
			else '---'
			end as OSType
		, case
			when ComputerProperties.OSPlatform > '' then ComputerProperties.OSPlatform
			else '---'
			end as OSPlatform


		-- These fields are returned differently based on whether the report 
		-- returns group summaries or straight rows
		, count(*) as 'count'		-- fetch group summaries
--		, 1 as 'count'			-- fetch individual rows
--    		, (CASE @szTime
--			WHEN 'GMT' THEN EventDateTime
--			ELSE 		EventLocalDateTime
--			END) 
--		as EventDateTime
		, '' as EventDateTime
--		, LeafNode.LastUpdate as LastContact
		, '' as LastContact

		,  '' as HostName
--		,  cast( HostName as varchar(50)) as HostName
		, '' as UserName
--		,  Events.UserName
		, '' as HostIPAddress
--		,  HostIPAddress
		,  '' as FullNodeName
--   		,cast(ReportFullPathNode.FullPathName as varchar(255))   AS FullNodeName 

		, '' as FileName
--		,  cast( FileName as varchar(255)) as FileName

		, '' as  ProductCode
		, '' as NodeID
--		, NodeID
		, '' as LNAutoID
		,'' as LNParentID
		,'' as PPAutoID
		-- End of Group summary difference fields


		-- Virus info fields
    		,VirusName =
	  		CASE 
	   		WHEN Events.VirusName > '' THEN Events.VirusName
	   		ELSE '---' 
	   		END
--		,'' as VirusName
--   		, case 					-- use case incase outer join returns null
--			when VirusType.VirusType > ''  then VirusType.VirusType
--			else case  when Events.VirusType > '' then Events.VirusType else '---' end
--			end as VirusType
--		,'' as VirusType 
		, case
			when VirusType.VirusTypeTranslated = 'Uncategorized' then @Uncategorized
			when VirusType.VirusTypeTranslated = 'Mass Mailer' then @MassMailer
			when VirusType.VirusTypeTranslated = '' then @Uncategorized
			when VirusType.VirusTypeTranslated is null then @Uncategorized
			else VirusType.VirusTypeTranslated 
			end as VirusType
		, case
			when VirusType.VirusFileType = 'Uncategorized' then @Uncategorized
			when VirusType.VirusFileType = '' then @Uncategorized
			when VirusType.VirusFileType is null then @Uncategorized
			else VirusType.VirusFileType
			end as VirusSubtype
   		,ActionTaken =
	    		CASE 
	     		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		ELSE  CAST(Events.ActionTaken AS varchar(16)) 
 	    		END
--		,'' as ActionTaken
    		,cast( TVDEventID as varchar(10)) as TVDEventID
--		,'' as TVDEventID
    		,  case TVDSeverity
			when 0 then 'Informational'
			when 1 then 'Warning'
			when 2 then 'Minor'
			when 3 then 'Major'
			when 4 then 'Critical'
			else '---'
			end  as TVDSeverity
--		,'' as TVDSeverity
		, TVDTaskName
--		,'' as TVDTaskName
--    		, ScanTime 
		,'' as ScanTime
		,'' as EventDesc
		
		, '' as RuleName

		-- Product update fields
		,'' as Type 
		,'' as Version
		,'' as Error
		,'' as SiteName
		,'' as InitiatorID
		,'' as InitiatorType

 
 	FROM 
   	(
	BranchNode Join LeafNode on (LeafNode.ParentID = BranchNode.AutoID) 
	Join ComputerProperties on (ComputerProperties.ParentID = LeafNode.AutoID)
	)
	Right Outer Join 
	(
	Events 
	Left Outer Join VirusType on (Events.VirusName = VirusType.VirusName)
	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
   		AND ReportActionDesc.LanguageID = @szFullLang)
	) on (Events.NodeID = LeafNode.AutoID)	
  	WHERE 
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR

  		LeafNode.ParentID in 
			(
			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        		from BranchNodeEnum 
        		where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)
  	AND 
  	(
   		Events.VirusName > '' 
    		OR
		Events.VirusType > ''
  	)
   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   	AND (  TVDEventID < 8500 or TVDEventID > 8999  )
	and
	(
		(@EventType = 'All' )  
		or ( @EventType = 'Infection' and Events.VirusName > '' AND Events.ProductName != 'ePO Agent' ) 
		or ( @EventType = 'WSVirus' AND (TVDEventID=1503 or TVDEventID=1500 or TVDEventID=1515)  )
	)
        AND Events.ProductName != 'ePO Agent' 

	-- fast group summary group by clause
	Group By
		DateName(Year, EventDateTime) + '-' + substring(convert(char(3), datepart( wk, EventDateTime) + 100), 2, 2)
		,Substring(convert(char,EventDateTime,120),1,7) 
		,DateName(Year, EventDateTime) 
		,DateName(Year, EventDateTime) + '-' + Datename(Quarter, EventDateTime) 
--		DateName(Year, EventDateTime)
--		,Cast(DatePart(Month, EventDateTime) as char(5)) as 'Month'
--		,Datename(Week, EventDateTime)
--		,Datename(Quarter, EventDateTime) 
		,Events.VirusName
		,ReportActionDesc.ActionName
		,Events.ActionTaken
		,BranchNode.NodeName
		,ProductName
		,ProductVersion
		,EngineVersion
		,DATVersion
    		, TVDEventID				-- newest groups fields
    		, TVDSeverity
   		, VirusType.VirusTypeTranslated
		, Events.VirusType
		, VirusType.VirusFileType
		, TVDTaskName
--		, EventFilterDescFast.Name 
		, ComputerProperties.Domainname
		, ComputerProperties.OSType
	    	, ComputerProperties.OSPlatform


--END	-- FilterID

Set @ret = @@rowcount

END	-- BatchModeUpdateTableOnly


/* cleanup */
	DROP TABLE dbo.tmpVirusname
	DROP TABLE dbo.tmpVirusFiletypeCrossProduct
	DROP TABLE dbo.tmpVirusSubtypeCrossProduct
	DROP TABLE dbo.tmpVirusFiletypePriority
	DROP TABLE dbo.tmpVirusSubtypePriority
	DROP TABLE dbo.tmpVirusFiletype
	DROP TABLE dbo.tmpVirusSubtype


RETURN @ret
END
GO



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

CREATE PROCEDURE dbo.AVISP_TranslateVirusType
(
	@szFullLang		VARCHAR(10)
)
as
BEGIN
-- Translate VirusType name

Declare @CurrentLanguage varchar(10)

select top 1 @CurrentLanguage=LanguageID 
from VirusType

-- retranslate virustype table if it differs
if @CurrentLanguage <> @szFullLang
begin
UPDATE
	VirusType
	SET
		VirusTypeTranslated =  
			CASE 
				WHEN ReportTranslations.TranslatedValue > '' then ReportTranslations.TranslatedValue
				else VirusType.VirusType
			END
	FROM	ReportTranslations
	WHERE	ReportTranslations.TextID = VirusType.VirusType
		AND ReportTranslations.Subject = 'Virustype'
		AND ReportTranslations.LanguageID = @szFullLang

Update VirusType
	Set LanguageID = @szFullLang
end

end
GO

/**** xxxxxxx  outbreak report procs xxxxxxx ****/


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

/* mhilandepo3 - The above stored procedure has been retired */
/* Original old outbreak report */

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO





/**/
/* xxxxxxx ePO v2.5 8/15/2001     Addon Reports - Outbreak History Report xxxxxxxxxxxxxx */
/* epo 2.5.0 hf3 & 2.5.1 */
/**/


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_FilterVirusAttacks
(
	@iNameSpaceName		VARCHAR(20)
	,@iNameSpaceNode		VARCHAR(20)
    	,@szEpoUserName          VARCHAR(100)
	,@szNameSpaceName		VARCHAR(100)
	,@szNameSpaceNode		VARCHAR(500)
	, @szMinMachineCount		VARCHAR(20)= '5'
	, @szMinFilenameCount		VARCHAR(20)= '5'
--	@iMinMachineCount		int, 
--	@iMinFilenameCount		int
 , @szOptionalReportParms  VARCHAR(500) = ''
/*	 , @dtStartDate			DateTime */
)
AS
BEGIN
 	/* Copyright + 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
	Declare @UsersTopNodeID int
	Declare @FilterNodeID int
	Declare @DayofWeek int



	select @UsersTopNodeID = convert(int, @iNameSpaceName)
	select @FilterNodeID = convert(int, @iNameSpaceNode)

	Declare @FilterID int
	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
 
	-- epo3.5 if bad values entered convert to defaults
	if ISNUMERIC(@szMinMachineCount) = 0 or @szMinMachineCount <= '0' 
		set @szMinMachineCount = '5'
	if ISNUMERIC(@szMinFilenameCount) = 0 or @szMinFilenameCount <= '0' 
		set @szMinFilenameCount = '5' 

	Declare @iMinMachineCount int		
	Declare @iMinFilenameCount int		
	select @iMinMachineCount = convert(int, @szMinMachineCount)
	select @iMinFilenameCount = convert(int, @szMinFilenameCount)


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


------------------------
-- temp table cleanup

	IF EXISTS (select * from sysobjects where name = 'tmpOutbreakGroup' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOutbreakGroup

	IF EXISTS (select * from sysobjects where name = 'tmpOutbreakGroupLocal' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOutbreakGroupLocal


	
/*
 Output select listing details of each occurrence 
*/
/*
*/
IF @szTime = 'GMT'			
BEGIN

	select 
		Events.Virusname,
   		case VirusType.VirusType
			when '' then	case Events.VirusType when '' then '---' else Events.VirusType end
			when null then	case Events.VirusType when '' then '---' else Events.VirusType end
			else VirusType.VirusType
			end as VirusType,
		datepart(year, eventdatetime) as dtyear,
		datepart(week, eventdatetime) as dtweek,
		count(*) as 'Total Events',
		count(distinct (hostname + filename)) as 'MachineFileCnt',
		count(distinct hostname) as 'MachinesCnt',
		count(distinct filename) as 'FilesCnt',
		min(Eventdatetime) as 'OutbreakStart',
		max(eventdatetime) as 'OutbreakEnd'

	into dbo.tmpOutbreakGroup 
	from 		-- use english entry
--		Events 
		Events Left Outer Join VirusType on (events.VirusName = VirusType.VirusName)
	where
 
		events.virusname > '' and HostName > ''
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
	group by
		events.virusname,
		datepart(year, eventdatetime),
		datepart(week, eventdatetime),
		events.virustype,
		virustype.virustype
	having 
		count(distinct filename) > @iMinFilenameCount
		or
		count(distinct hostname) > @iMinMachineCount
	order by 
		events.virusname, 
		dtweek

/*
select * from dbo.tmpOutbreakGroup order by  outbreakname
*/

IF @FilterID = 0			/* admin user, must see all events, dont join to nodename   */
BEGIN


	select 
		Events.Virusname as 'OutbreakVirus'
		,dbo.tmpOutbreakGroup.VirusType as 'VirusType'
		,dbo.tmpOutbreakGroup.OutbreakStart as 'OutbreakStart'
		,dbo.tmpOutbreakGroup.OutbreakEnd as 'OutbreakEnd'
		,min(Events.Eventdatetime) as 'WeekStarting'
		,'' as NumberofOutbreakPeriods
		,min(Events.Eventdatetime) as FirstOutbreakEvent 
		,'' as LastOutbreakEvent
		,dbo.tmpOutbreakGroup.MachineFileCnt as 'TotalEvents'
		,dbo.tmpOutbreakGroup.MachinesCnt as 'MachinesCnt'
		,dbo.tmpOutbreakGroup.FilesCnt as 'FilesCnt'
		,dbo.tmpOutbreakGroup.MachineFileCnt as 'MachineFileCnt'
		,CAST('' as varchar(100)) AS NodeName
		,min(Events.Eventdatetime) as EventDateTime
		,cast(Events.HostName as varchar(50)) As HostName
		,Events.HostIPAddress
		,Events.VirusName
		,cast(Events.FileName as varchar(200)) As FileName
		,Events.EngineVersion
		,Events.DATVersion
   		,ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END
		,Events.username
		,Events.productname
		,Events.productversion
		,datepart(year, Events.eventdatetime) as evdtyear
		,datepart(week, Events.eventdatetime) as evdtweek
		,(convert( varchar(5), datepart(year, Events.eventdatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventdatetime)) + 'Q')
			as evdtquarter

	from 
		Events Join dbo.tmpOutbreakGroup on (Events.Virusname = dbo.tmpOutbreakGroup.Virusname)
	  	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
	   		AND ReportActionDesc.LanguageID = @szFullLang)
	where

		Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
		AND datepart(year, Events.eventdatetime) = dbo.tmpOutbreakGroup.dtyear
		AND datepart(week, Events.eventdatetime) = dbo.tmpOutbreakGroup.dtweek

	group by
		Events.virusname,
		dbo.tmpOutbreakGroup.VirusType,
		dbo.tmpOutbreakGroup.OutbreakStart,
		dbo.tmpOutbreakGroup.OutbreakEnd,
		datepart(year, Events.eventdatetime),
		convert( varchar(5), datepart(year, Events.eventdatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventdatetime)) + 'Q',
		datepart(week, Events.eventdatetime),
		Events.hostname,
		Events.hostipaddress,
		Events.username,
		Events.productname,
		Events.productversion,
		Events.engineversion,
		Events.datversion,
		Events.filename,
		Events.ActionTaken,
		ReportActionDesc.ActionName,
		dbo.tmpOutbreakGroup.MachineFileCnt,
		dbo.tmpOutbreakGroup.MachinesCnt,
		dbo.tmpOutbreakGroup.FilesCnt

/*	
Dont include this order by clause in production - test only

		ORDER BY OutbreakName, EventTime 

*/

END
ELSE
BEGIN



	select 
		Events.Virusname as 'OutbreakVirus'
		,dbo.tmpOutbreakGroup.VirusType as 'VirusType'
		,dbo.tmpOutbreakGroup.OutbreakStart as 'OutbreakStart'
		,dbo.tmpOutbreakGroup.OutbreakEnd as 'OutbreakEnd'
		,min(Events.Eventdatetime) as 'WeekStarting'
		,'' as NumberofOutbreakPeriods
		,min(Events.Eventdatetime) as FirstOutbreakEvent 
		,'' as LastOutbreakEvent
		,dbo.tmpOutbreakGroup.MachineFileCnt as 'TotalEvents'
		,dbo.tmpOutbreakGroup.MachinesCnt as 'MachinesCnt'
		,dbo.tmpOutbreakGroup.FilesCnt as 'FilesCnt'
		,dbo.tmpOutbreakGroup.MachineFileCnt as 'MachineFileCnt'
		,CAST('' as varchar(100)) AS NodeName
		,min(Events.Eventdatetime) as EventDateTime
		,cast(Events.HostName as varchar(50)) As HostName
		,Events.HostIPAddress
		,Events.VirusName
		,cast(Events.FileName as varchar(200)) As FileName
		,Events.EngineVersion
		,Events.DATVersion
   		,ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END
		,Events.username
		,Events.productname
		,Events.productversion
		,datepart(year, Events.eventdatetime) as evdtyear
		,datepart(week, Events.eventdatetime) as evdtweek
		,(convert( varchar(5), datepart(year, Events.eventdatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventdatetime)) + 'Q')
			as evdtquarter
	from 
		LeafNode Join BranchNode on (LeafNode.ParentID = BranchNode.AutoID)
		Join Events on (Events.NodeID = LeafNode.AutoID)
		Join dbo.tmpOutbreakGroup on (Events.Virusname = dbo.tmpOutbreakGroup.Virusname)
	  	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
	   		AND ReportActionDesc.LanguageID = @szFullLang)

	where
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR
  		LeafNode.ParentID in 
			(
			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        				from BranchNodeEnum 
        				where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)	
		AND Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
		AND datepart(year, Events.eventdatetime) = dbo.tmpOutbreakGroup.dtyear
		AND datepart(week, Events.eventdatetime) = dbo.tmpOutbreakGroup.dtweek

	group by
		Events.virusname,
		dbo.tmpOutbreakGroup.VirusType,
		dbo.tmpOutbreakGroup.OutbreakStart,
		dbo.tmpOutbreakGroup.OutbreakEnd,
		datepart(year, Events.eventdatetime),
		convert( varchar(5), datepart(year, Events.eventdatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventdatetime)) + 'Q',
		datepart(week, Events.eventdatetime),
		Events.hostname,
		Events.hostipaddress,
		Events.username,
		Events.productname,
		Events.productversion,
		Events.engineversion,
		Events.datversion,
		Events.filename,
		Events.ActionTaken,
		ReportActionDesc.ActionName,
		dbo.tmpOutbreakGroup.MachineFileCnt,
		dbo.tmpOutbreakGroup.MachinesCnt,
		dbo.tmpOutbreakGroup.FilesCnt,
		BranchNode.NodeName



END


END		/* IF @szTime = 'GMT' */
ELSE
BEGIN		/* use EventLocalDateTime */

	select 
		Virusname,
		min(Events.VirusType) as VirusType,
		datepart(year, eventlocaldatetime) as dtyear,
		datepart(week, eventlocaldatetime) as dtweek,
		count(*) as 'Total Events',
		count(distinct (hostname + filename)) as 'MachineFileCnt',
		count(distinct hostname) as 'MachinesCnt',
		count(distinct filename) as 'FilesCnt',
		min(Eventlocaldatetime) as 'OutbreakStart',
		max(eventlocaldatetime) as 'OutbreakEnd'

	into dbo.tmpOutbreakGroupLocal 
	from Events
	where 
		virusname > '' and HostName > ''
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 	

	group by
		virusname,
		datepart(year, eventlocaldatetime),
		datepart(week, eventlocaldatetime)
	having 
		count(distinct filename) > @iMinFilenameCount
		or
		count(distinct hostname) > @iMinMachineCount
	order by 
		virusname, dtweek


IF @FilterID = 0			/* admin user, must see all events, dont join to nodename   */
BEGIN




	select 
		Events.Virusname as OutbreakVirus,
		dbo.tmpOutbreakGroupLocal.VirusType as VirusType,
		dbo.tmpOutbreakGroupLocal.OutbreakStart,
		dbo.tmpOutbreakGroupLocal.OutbreakEnd,
		min(Events.Eventlocaldatetime) as 'WeekStarting',
		'' as NumberofOutbreakPeriods,
		'' as FirstOutbreakEvent, 
		'' as LastOutbreakEvent,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt as 'TotalEvents',
		dbo.tmpOutbreakGroupLocal.MachinesCnt,
		dbo.tmpOutbreakGroupLocal.FilesCnt,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt as 'MachineFileCnt',
		CAST('' as varchar(100)) AS NodeName,
		min(Events.Eventlocaldatetime) as 'EventDateTime',
		   		cast(Events.HostName as varchar(50)) As HostName, 
		Events.HostIPAddress,
		Events.VirusName,
		   		cast(Events.FileName as varchar(200)) As FileName, 
		Events.EngineVersion,
		Events.DATVersion,
   		ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END,
		Events.username,
		Events.productname,
		Events.productversion,
		datepart(year, Events.eventlocaldatetime) as evdtyear,
		datepart(week, Events.eventlocaldatetime) as evdtweek,
		(convert( varchar(5), datepart(year, Events.eventlocaldatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventlocaldatetime)) + 'Q')
		as evdtquarter
	from 
		Events Join dbo.tmpOutbreakGroupLocal on (Events.Virusname = dbo.tmpOutbreakGroupLocal.Virusname)
	  	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
	   		AND ReportActionDesc.LanguageID = @szFullLang)

	where
		Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
		AND datepart(year, Events.eventlocaldatetime) = dbo.tmpOutbreakGroupLocal.dtyear
		AND datepart(week, Events.eventlocaldatetime) = dbo.tmpOutbreakGroupLocal.dtweek

	group by
		Events.virusname,
		dbo.tmpOutbreakGroupLocal.VirusType,
		dbo.tmpOutbreakGroupLocal.OutbreakStart,
		dbo.tmpOutbreakGroupLocal.OutbreakEnd,
		datepart(year, Events.eventlocaldatetime),
		convert( varchar(5), datepart(year, Events.eventlocaldatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventlocaldatetime)) + 'Q',
		datepart(week, Events.eventlocaldatetime),
		Events.hostname,
		Events.hostipaddress,
		Events.username,
		Events.productname,
		Events.productversion,
		Events.engineversion,
		Events.datversion,
		Events.filename,
		Events.ActionTaken,
		ReportActionDesc.ActionName,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt,
		dbo.tmpOutbreakGroupLocal.MachinesCnt,
		dbo.tmpOutbreakGroupLocal.FilesCnt

/*	
Dont include this order by clause in production - test only

		ORDER BY OutbreakName, EventTime 

*/

END
ELSE
BEGIN



	select 
		Events.Virusname as OutbreakVirus,
		dbo.tmpOutbreakGroupLocal.VirusType as VirusType,
--		'' as VirusType,
		dbo.tmpOutbreakGroupLocal.OutbreakStart,
		dbo.tmpOutbreakGroupLocal.OutbreakEnd,
		min(Events.Eventlocaldatetime) as 'WeekStarting',
		'' as NumberofOutbreakPeriods,
		'' as FirstOutbreakEvent, 
		'' as LastOutbreakEvent,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt as 'TotalEvents',
		dbo.tmpOutbreakGroupLocal.MachinesCnt,
		dbo.tmpOutbreakGroupLocal.FilesCnt,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt as 'MachineFileCnt',
		CAST('' as varchar(100)) AS NodeName,
		min(Events.Eventlocaldatetime) as 'EventDateTime',
		   		cast(Events.HostName as varchar(50)) As HostName, 
		Events.HostIPAddress,
		Events.VirusName,
		   		cast(Events.FileName as varchar(200)) As FileName, 
		Events.EngineVersion,
		Events.DATVersion,
   		ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END,
		Events.username,
		Events.productname,
		Events.productversion,
		datepart(year, Events.eventlocaldatetime) as evdtyear,
		datepart(week, Events.eventlocaldatetime) as evdtweek,
		(convert( varchar(5), datepart(year, Events.eventlocaldatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventlocaldatetime)) + 'Q')
		as evdtquarter


	from
		LeafNode Join BranchNode on (LeafNode.ParentID = BranchNode.AutoID)
		Join Events on (Events.NodeID = LeafNode.AutoID)
		Join dbo.tmpOutbreakGroupLocal on (Events.Virusname = dbo.tmpOutbreakGroupLocal.Virusname)
	  	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
	   		AND ReportActionDesc.LanguageID = @szFullLang)
	where
  	(
   		@FilterID = 0 OR
    		LeafNode.ParentID = @FilterID OR
  		LeafNode.ParentID in 
			(
			select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        				from BranchNodeEnum 
        				where BranchNodeEnum.StartAutoID = @FilterID
			)
  	)	
		AND Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
		AND datepart(year, Events.eventlocaldatetime) = dbo.tmpOutbreakGroupLocal.dtyear
		AND datepart(week, Events.eventlocaldatetime) = dbo.tmpOutbreakGroupLocal.dtweek

	group by
		Events.virusname,
		dbo.tmpOutbreakGroupLocal.VirusType,
		dbo.tmpOutbreakGroupLocal.OutbreakStart,
		dbo.tmpOutbreakGroupLocal.OutbreakEnd,
		datepart(year, Events.eventlocaldatetime),
		convert( varchar(5), datepart(year, Events.eventlocaldatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventlocaldatetime)) + 'Q',
		datepart(week, Events.eventlocaldatetime),
		Events.hostname,
		Events.hostipaddress,
		Events.username,
		Events.productname,
		Events.productversion,
		Events.engineversion,
		Events.datversion,
		Events.filename,
		Events.ActionTaken,
		ReportActionDesc.ActionName,
		dbo.tmpOutbreakGroupLocal.MachineFileCnt,
		dbo.tmpOutbreakGroupLocal.MachinesCnt,
		dbo.tmpOutbreakGroupLocal.FilesCnt,
		BranchNode.NodeName



END


END		/* GMT/LOCAL time */



/* cleanup */

IF @szTime = 'GMT'			/* admin user, must see all events, dont join to nodename   */
BEGIN
	DROP TABLE dbo.tmpOutbreakGroup
END
ELSE
BEGIN
	DROP TABLE dbo.tmpOutbreakGroupLocal
END

/*
*/

END
GO








/***************************************************************/
/* xxxxxxx epo3.0 reports - 5/14/2k2 xxxxxxx */



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

CREATE PROCEDURE dbo.AVISP_GetDateConversion
(
 @InfectAfterYYYYMMDD nvarchar(30) 
 , @InfectAfterRule nvarchar(30) 
 , @YYYYMMDD datetime output

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

	Declare @ret int
	Set @ret = 1

	-- Fetch Infect After date variables
--	Declare @YYYYMMDD datetime
	Declare @year nchar(4)
	set @year = convert(nchar(4),DatePart(year,GetDate())) 
	if @InfectAfterYYYYMMDD > ''
		set @YYYYMMDD = convert( datetime, @InfectAfterYYYYMMDD, 120)
	else
	begin
		if lower(@InfectAfterRule) = 'all'
--			set @YYYYMMDD = DateAdd(year, -100, GetDate());
			set @YYYYMMDD = null;
		else if lower(@InfectAfterRule) = 'day1'
			set @YYYYMMDD = DateAdd(day, -1, GetDate());
		else if lower(@InfectAfterRule) = 'day2'
			set @YYYYMMDD = DateAdd(day, -2, GetDate());
		else if lower(@InfectAfterRule) = 'day3'
			set @YYYYMMDD = DateAdd(day, -3, GetDate());
		else if lower(@InfectAfterRule) = 'day4'
			set @YYYYMMDD = DateAdd(day, -4, GetDate());
		else if lower(@InfectAfterRule) = 'day5'
			set @YYYYMMDD = DateAdd(day, -5, GetDate());
		else if lower(@InfectAfterRule) = 'day6'
			set @YYYYMMDD = DateAdd(day, -6, GetDate());
		else if lower(@InfectAfterRule) = 'week1'
			set @YYYYMMDD = DateAdd(week, -1, GetDate());
		else if lower(@InfectAfterRule) = 'week2'
			set @YYYYMMDD = DateAdd(week, -2, GetDate());
		else if lower(@InfectAfterRule) = 'week3'
			set @YYYYMMDD = DateAdd(week, -3, GetDate());
		else if lower(@InfectAfterRule) = 'week4'
			set @YYYYMMDD = DateAdd(week, -4, GetDate());
		else if lower(@InfectAfterRule) = 'month1'
			set @YYYYMMDD = DateAdd(month, -1, GetDate());
		else if lower(@InfectAfterRule) = 'month2'
			set @YYYYMMDD = DateAdd(month, -2, GetDate());
		else if lower(@InfectAfterRule) = 'month3'
			set @YYYYMMDD = DateAdd(month, -3, GetDate());
		else if lower(@InfectAfterRule) = 'year1'
			set @YYYYMMDD = DateAdd(year, -1, GetDate());
		else if lower(@InfectAfterRule) = 'CurrentDay'
			set @YYYYMMDD = DateAdd(hour, -(DatePart(hour,GetDate())), DateAdd(minute, -(DatePart(minute,GetDate())), GetDate()) );
		else if lower(@InfectAfterRule) = 'CurrentWeek'
			set @YYYYMMDD = DateAdd(day, -(DatePart(weekday,GetDate())-1), GetDate());
		else if lower(@InfectAfterRule) = 'CurrentMonth'
			set @YYYYMMDD = DateAdd(day, -(DatePart(day,GetDate())-1), GetDate());
		else if lower(@InfectAfterRule) = 'CurrentQuarter'
		begin
			if DatePart(quarter,GetDate()) =1
				 set @YYYYMMDD = convert( datetime, (@Year+'0101'), 112)	
			else if DatePart(quarter,GetDate()) =2
				 set @YYYYMMDD = convert( datetime, (@Year+'0401'), 112)		
			else if DatePart(quarter,GetDate()) =3
				 set @YYYYMMDD = convert( datetime, (@Year+'0701'), 112)		
			else if DatePart(quarter,GetDate()) =4
				 set @YYYYMMDD = convert( datetime, (@Year+'1001'), 112)			
		end			
		else if lower(@InfectAfterRule) = 'CurrentYear'
			set @YYYYMMDD = convert( datetime, (@Year+'0101'), 112)	
		else if lower(@InfectAfterRule) > ''	-- rule not found
			set @ret = 0
	end

RETURN @ret
END
GO


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

CREATE PROCEDURE dbo.AVISP_GetDateConversion1
(
 @InfectAfterYYYYMMDD 	nvarchar(30) 
 , @InfectAfterRule 	nvarchar(30) 
 , @DataFilter		varchar(255)	-- inactive - means data filter > 255 chars
 , @YYYYMMDD 		datetime output
 , @DFYYYYMMDD 		datetime output
 , @week 		nvarchar(30) output	-- yyyy-ww format, returned to make use of index
 , @month 		nvarchar(30) output	-- yyyy-mm format, returned to make use of index

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

	Declare @ret int
	Set @ret = 1
	Set @week = '' -- defaults
	Set @month = ''
	set @YYYYMMDD = ''
	set @DFYYYYMMDD = ''
	Declare @DateFilterExists int
	Declare @Midnight int

	Declare @year nchar(4)
	set @year = convert(nchar(4),DatePart(year,GetDate())) 

	-- check if data filter set on datetime field
	set @DateFilterExists = charindex('.EventDateTime} > DateTime',@DataFilter)
	set @Midnight = charindex('0, 0, 0)',@DataFilter)
	if @DateFilterExists > 0 and @Midnight > 0 and len(@DataFilter) < 100
	begin
		Declare @Fyyyymmdd char(20)
		-- just fetch the date
		set @Fyyyymmdd = substring(@DataFilter,@DateFilterExists+27,12)
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 1,', '01,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 2,', '02,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 3,', '03,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 4,', '04,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 5,', '05,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 6,', '06,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 7,', '07,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 8,', '08,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ' 9,', '09,')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ', ', '')
		set @Fyyyymmdd = replace(@Fyyyymmdd, ',', '')
		set @DFYYYYMMDD = convert( datetime, @Fyyyymmdd, 112)
--		if day(@DFYYYYMMDD) = '01'	
--		begin
--			set @week = DateName(Year, @DFYYYYMMDD) + '-' + substring(convert(char(3), datepart( wk, @DFYYYYMMDD) + 100), 2, 2)
--			set @month = Substring(convert(char,@DFYYYYMMDD,120),1,7)
--		end	
	end

	-- Fetch Infect After date variables
--	Declare @YYYYMMDD datetime
	-- dont use DF datafile value if less than 2 days old (allow time parm to be used)
	if @DFYYYYMMDD = '' or Datediff(day, @DFYYYYMMDD, getdate()) < 2
	begin
  
	set @DFYYYYMMDD = ''

	if @InfectAfterYYYYMMDD > ''
		set @YYYYMMDD = convert( datetime, @InfectAfterYYYYMMDD, 120)
	else
	begin
		if lower(@InfectAfterRule) = 'all'
--			set @YYYYMMDD = DateAdd(year, -100, GetDate());
			set @YYYYMMDD = null;
		else if lower(@InfectAfterRule) = 'day1'
			set @YYYYMMDD = DateAdd(day, -1, GetDate());
		else if lower(@InfectAfterRule) = 'day2'
			set @YYYYMMDD = DateAdd(day, -2, GetDate());
		else if lower(@InfectAfterRule) = 'day3'
			set @YYYYMMDD = DateAdd(day, -3, GetDate());
		else if lower(@InfectAfterRule) = 'day4'
			set @YYYYMMDD = DateAdd(day, -4, GetDate());
		else if lower(@InfectAfterRule) = 'day5'
			set @YYYYMMDD = DateAdd(day, -5, GetDate());
		else if lower(@InfectAfterRule) = 'day6'
			set @YYYYMMDD = DateAdd(day, -6, GetDate());
		else if lower(@InfectAfterRule) = 'week1'
			set @YYYYMMDD = DateAdd(week, -1, GetDate());
		else if lower(@InfectAfterRule) = 'week2'
			set @YYYYMMDD = DateAdd(week, -2, GetDate());
		else if lower(@InfectAfterRule) = 'week3'
			set @YYYYMMDD = DateAdd(week, -3, GetDate());
		else if lower(@InfectAfterRule) = 'week4'
			set @YYYYMMDD = DateAdd(week, -4, GetDate());
		else if lower(@InfectAfterRule) = 'month1'
			set @YYYYMMDD = DateAdd(month, -1, GetDate());
		else if lower(@InfectAfterRule) = 'month2'
			set @YYYYMMDD = DateAdd(month, -2, GetDate());
		else if lower(@InfectAfterRule) = 'month3'
			set @YYYYMMDD = DateAdd(month, -3, GetDate());
		else if lower(@InfectAfterRule) = 'year1'
			set @YYYYMMDD = DateAdd(year, -1, GetDate());
		else if lower(@InfectAfterRule) = 'CurrentDay'
			set @YYYYMMDD = DateAdd(hour, -(DatePart(hour,GetDate())), DateAdd(minute, -(DatePart(minute,GetDate())), GetDate()) );
		else if lower(@InfectAfterRule) = 'CurrentWeek'
		begin
			set @YYYYMMDD = DateAdd(day, -(DatePart(weekday,GetDate())-1), GetDate());
			set @week = DateName(Year, GetDate()) + '-' + substring(convert(char(3), datepart( wk, GetDate()) + 100), 2, 2)
			set @month = Substring(convert(char,dateadd(month,-1,GetDate()),120),1,7) -- current week could be last month
		end
		else if lower(@InfectAfterRule) = 'CurrentMonth'
		begin
			set @YYYYMMDD = DateAdd(day, -(DatePart(day,GetDate())-1), GetDate());
			set @week = DateName(Year, GetDate()) + '-' + substring(convert(char(3), datepart( wk, GetDate()) + 100), 2, 2)
			set @month = Substring(convert(char,GetDate(),120),1,7)
		end
		else if lower(@InfectAfterRule) = 'CurrentQuarter'
		begin
			if DatePart(quarter,GetDate()) =1
			begin
				set @YYYYMMDD = convert( datetime, (@Year+'0101'), 112)	
				set @week = @Year + '-01'
				set @month = @Year + '-01' 
			end
			else if DatePart(quarter,GetDate()) =2
			begin
				set @YYYYMMDD = convert( datetime, (@Year+'0401'), 112)	
				set @week = @Year + '-' + convert(char(3), datepart( wk, convert( datetime, (@Year+'0401'), 112)))
				set @month = @Year + '-04' 
			end	
			else if DatePart(quarter,GetDate()) =3
			begin
				set @YYYYMMDD = convert( datetime, (@Year+'0701'), 112)	
				set @week = @Year + '-' + convert(char(3), datepart( wk, convert( datetime, (@Year+'0701'), 112)))
				set @month = @Year + '-07' 
			end	
			else if DatePart(quarter,GetDate()) =4
			begin
				set @YYYYMMDD = convert( datetime, (@Year+'1001'), 112)
				set @week = @Year + '-' + convert(char(3), datepart( wk, convert( datetime, (@Year+'1001'), 112)))
				set @month = @Year + '-10' 
			end			
		end			
		else if lower(@InfectAfterRule) = 'CurrentYear'
		begin
			set @YYYYMMDD = convert( datetime, (@Year+'0101'), 112)	
			set @week = @Year + '-01' 
			set @month = @Year + '-01'
		end
		else if lower(@InfectAfterRule) > ''	-- rule not found
			set @ret = 0
	end
	end

RETURN @ret
END
GO


-------------------------------
-- AVISP_FieldGetInfectionGroup

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


CREATE PROCEDURE dbo.AVISP_FieldGetInfectionGroup
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @szFilter		VARCHAR(64) = '',
    @szOptionalReportParms 	 VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @ret int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang




	-- Fetch translated text strings for localized parameter value

 	UPDATE
		ReportInputParameterValues
	SET
		Prompt = TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	 ReportTextPromptStrings.TextID like ReportInputParameterValues.ParmValue	-- uses like operator
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
			)


 --------------------------------------------
 -- Select field values
 -- First column must be called: Value
 -- second column must be called: Prompt

 IF @szFilter = 'ChartType'
 BEGIN 
	
	-- Fetch Localized names
	-- Trick - combine localized value with textid and send to report, the report will key off the textid
	-- Original idea
/*
	SELECT Distinct TextValue + '(' + TextID + ')'as Value 
	FROM	
		ReportTextPromptStrings
	WHERE
		TextID in ( 'Bar', 'Pie', 'SBar', 'PieBar', '3D Bar', 'CrossTab'  )
		AND	LanguageID = @szLanguageID
		AND	
			(ReportTextPromptStrings.ReportID = @szReportID
			OR
			ReportTextPromptStrings.RptGroupID = @szRptGroup)
*/

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = 'ChartType'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)


 END
 ELSE IF @szFilter = 'NumGroupsOnMainPage'
 BEGIN
	SELECT '2' as Value, '2' as Prompt
 END
 ELSE IF @szFilter = '@szDrilldown'
 BEGIN
	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = '@szDrilldown'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

 END
 ELSE IF @szFilter = '@szGroupName1'
 BEGIN

	-- Fetch Localized names
	-- Trick - combine localized value with textid and send to report, the report will key off the textid
--	SELECT Distinct TextValue + '(' + TextID + ')'as '@szGroupName1'
--	FROM	
--		ReportTextPromptStrings
--	WHERE
--		TextID in ( 'Year', 'Quarter', 'Month', 'Week', 'Virusname', 'Action', 'Filename', 'Hostname', 'Nodename', 'Productnameversion', 'Enginedat'  )
--		AND	LanguageID = @szLanguageID
--		AND	
--			(ReportTextPromptStrings.ReportID = @szReportID
--			OR
--			ReportTextPromptStrings.RptGroupID = @szRptGroup)
	

	SELECT Distinct ParmValue as Value, Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = '@szGroupName_'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)


 END
 ELSE IF @szFilter = '@szGroupName2'
 BEGIN

	-- Fetch Localized names

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = '@szGroupName_'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

	
 END
 ELSE IF @szFilter = '@szGroupName3'
 BEGIN

	-- Fetch Localized names

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = '@szGroupName_'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

	
 END
 ELSE IF @szFilter = '@szGroupName4'
 BEGIN

	-- Fetch Localized names

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = '@szGroupName_'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

	
 END
 ELSE
 BEGIN

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = @szFilter
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

 END


 Set @ret = @@rowcount
 if @ret = 0
		SELECT '---' as Value , '---' as Prompt

 RETURN @ret 

END
GO


----------------------------------------------------------------



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



CREATE PROCEDURE dbo.AVISP_FieldPutInfectionGroup
(
    @iNameSpaceName  int
    ,@iNameSpaceNode         int
    ,@szEpoUserName           VARCHAR(100)
    ,@szOptionalReportParms 	 VARCHAR(500) = ''
    ,@szFieldName		VARCHAR(64) = ''
    ,@szFieldValue		VARCHAR(256) = ''
    ,@szFieldValuePrompt		VARCHAR(256) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @rec int
 Set @rec = 0

 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang     VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID  VARCHAR(5)
   Declare @szTime     VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'

   -- Output message
   Declare @szResult   VARCHAR(64)
   Set @szResult = ''


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


 ----------------------------------------------------------------
 -- Make sure both values are input otherwise use one to set the other
	if @szFieldValue > '' and ( @szFieldValuePrompt = '' or @szFieldValuePrompt is NULL)
		set @szFieldValuePrompt = @szFieldValue

	if @szFieldValuePrompt > '' and ( @szFieldValue = '' or @szFieldValue is NULL)
		set @szFieldValue = @szFieldValuePrompt




 -- These updates are all the same, but this is how the code would look if the field needed to be handled differently

 IF @szFieldName = 'ChartType'
 BEGIN 
	
 	UPDATE
		ReportInputParameters
	SET
		ReportInputParameters.ParmValue = @szFieldValue
		, ReportInputParameters.ParmValuePrompt = @szFieldValuePrompt
	WHERE
		ReportInputParameters.ParmName = @szFieldName
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)
	
	Set @rec = @@rowcount
 END 
 ELSE
 BEGIN
 	UPDATE
		ReportInputParameters
	SET
		ReportInputParameters.ParmValue = @szFieldValue
		, ReportInputParameters.ParmValuePrompt = @szFieldValuePrompt
	WHERE
		ReportInputParameters.ParmName = @szFieldName
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)
	Set @rec = @@rowcount

	-- check for error
	if @rec = 0
	begin
		Select @szResult = TranslatedValue
			from ReportTranslations
			where Subject = 'General' and TextID = 'Parameter not saved to Database'
				and LanguageID = @szFullLang
		if @@rowcount = 0    Set @szResult = 'Parameter not saved to Database'
		SELECT @szResult + ': ' + @szReportID + ': ' + @szRptGroup + ': ' + @szFieldValue + ': ' + @szFieldValue
	end 
END

 -- Return Result String
 SELECT @szResult as szResult

 RETURN @rec

END

GO


------------------------------------------------------------------------------
------------------------------------------------------------------------------
--  AVISP_FieldGetDATEng
-- vs7.5 support new buffer overflow dat type

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

CREATE PROCEDURE dbo.AVISP_FieldGetDATEng
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @szFilter		VARCHAR(64) = '',
    @szOptionalReportParms 	 VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @ret int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang




	-- Fetch translated text strings for localized parameter value

 	UPDATE
		ReportInputParameterValues
	SET
		Prompt= TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	 ReportTextPromptStrings.TextID like ReportInputParameterValues.ParmValue	-- uses like operator
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
			)

 

 ----------------------------------------------------------------
 -- Lookup Parameter values 
 -- First column must be called: Value
 -- second column must be called: Prompt

 
-- check for product based on @szFilter=software name 
 Declare @prodcnt int
 Declare @datcnt int
 Declare @bfdatcnt int
 Declare @engcnt int
 Declare @Filter nvarchar(50)

-- set @Filter = substring


 select @datcnt=count(*)
	from AVIView_Software
	where 
	@szFilter like (ProductFamily + 'DAT%')

 select @engcnt=count(*)
	from AVIView_Software
	where 
	@szFilter like (ProductFamily + 'Engine%')

 -- vs7.5 Buffer Overflow dat version
 select @bfdatcnt=count(*)
	from AVIView_Software
	where 
	@szFilter like (ProductFamily + '%DAT%')		-- additional Dats: %DAT


-- check for DAT version based on @szFilter=ProductFamily + '_dats' 

 IF @datcnt > 0  -- fetch DAT versions
 BEGIN 

    -- postepo3: exclude ver = N/A
    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer
     			ELSE '---'
     			END)
		, '' as Prompt
       FROM ProductProperties, AVIView_Software
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
	and DATVer not in ('5000', 'N/A')
	and @szFilter like (ProductFamily + 'DAT%')
--    UNION
--	select '1st Most Recent Version' as value , '' as Prompt
--    UNION
--	select '2nd Most Recent Version' as value , '' as Prompt
--    UNION
--	select '3rd Most Recent Version' as value, '' as Prompt
    ORDER BY Value desc	

 END


-- check for Engine version based on @szFilter=ProductFamily + '_Engines' 


 else
 IF @engcnt > 0  -- fetch Engine versions
 BEGIN 
	
    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer 
     			ELSE '---'
     			END)
		, '' as Prompt
       FROM ProductProperties, AVIView_Software
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
--	and EngineVer != 'N/A'
	and EngineVer not in ('5000', 'N/A')
	and @szFilter like (ProductFamily + 'Engine%')
--    UNION
--	select '1st Most Recent Version' as value , '' as Prompt
--    UNION
--	select '2nd Most Recent Version' as value , '' as Prompt
--    UNION
--	select '3rd Most Recent Version' as value, '' as Prompt
    ORDER BY Value desc	

 END

 IF @bfdatcnt > 0  -- vs7.5 fetch buffer overflow DAT versions
 BEGIN 

    -- postepo3: exclude ver = N/A
    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductSettings.Value > '' THEN ProductSettings.Value
     			ELSE '---'
     			END)
		, '' as Prompt
       FROM ProductProperties, AVIView_Software, ProductSettings
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
	    and ProductFamily = 'TVD'
	    and ProductSettings.parentid = ProductProperties.autoid
	    and ProductSettings.SectionName = 'General'
	    and @szFilter like (ProductFamily + ProductSettings.SettingName + '%')
	 
--	and DATVer not in ('5000', 'N/A')
--	and @szFilter like (ProductFamily + 'szBufferOverflowDAT')
--    UNION
--	select '1st Most Recent Version' as value , '' as Prompt
--    UNION
--	select '2nd Most Recent Version' as value , '' as Prompt
--    UNION
--	select '3rd Most Recent Version' as value, '' as Prompt
    ORDER BY Value desc	

 END

----------------------------
	
 ELSE
 BEGIN

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = @szFilter
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

	
 END

 Set @ret = @@rowcount
 if @ret = 0
		SELECT '---' as Value , '---' as Prompt

 RETURN @ret 

END
GO



------------------------------------------------------------------------------
------------------------------------------------------------------------------


-- epo3.5 Sometimes complianceissue inputs are misteriously absent after an install
--	this routine reinserts them.
-- This is a cludge, need to locate problem and remove this.
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVISP_AddComplianceIssuesInputs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVISP_AddComplianceIssuesInputs]
GO


CREATE PROCEDURE dbo.AVISP_AddComplianceIssuesInputs as
Begin
------------------------------
-- Compliance issues
-- ReportInputParameters table


if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='@AsciCheckPoint')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, '@AsciCheckPoint', '', '', ''
	, 'Late Agent Connection Date', 'Defines Late Computers as connecting after this absolute date (This overrides the Late Agent Connection Rule parameter)'
	, 'ComplianceRules'
	, 4 ,0 ,0 ,0
	, 1 ,0 ,0 ,0
)




if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='@AsciRule')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, '@AsciRule', '', 'ALL', 'All Values'
	, 'Late Agent Connection Rule', 'Defines Late Computers as connecting after this relative rule'
	, 'ComplianceRules'
	, 0 ,1 ,0 ,0
	, 1 ,0 ,1 ,0
)



if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='@InfectionCheckPoint')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, '@InfectionCheckPoint', '', '', ''
	, 'Recent Infection Date', 'Defines Recent Infections as ocurring after this absolute date (This overrides the Recent Infection Rule parameter)'
	, 'ComplianceRules'
	, 4 ,0 ,0 ,0
	, 1 ,0 ,0 ,0
)


-- postepo3 33401 - change CI parm name to @ciInfectAfterRule, so its no longer a dup with CustGroup parmname
--	Also requires a similar change to all language specific localization string files.
if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='@ciInfectAfterRule')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, '@ciInfectAfterRule', '', 'week4', '4 Weeks Past'
	, 'Recent Infection Rule', 'Defines Recent Infections as ocurring after this relative rule'
	, 'ComplianceRules'
	, 0 ,1 ,0 ,0
	, 1 ,0 ,1 ,0
)



-- Save settings
if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='RestoreSettings')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, 'RestoreSettings', '', '', ''
	, 'Open', 'Open a previously saved set of input settings'
	, 'SaveSettings'
	, 0 ,1 ,0 ,0
	, 0 ,0 ,1 ,0
)


if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='SaveSettingsVar')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, 'SaveSettingsVar', '', '', ''
	, 'Save', 'Save the current input settings to an existing name'
	, 'SaveSettings'
	, 0 ,1 ,0 ,0
	, 0 ,0 ,1 ,0
)


if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='SaveSettingsAs')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, 'SaveSettingsAs', '', '', ''
	, 'Save As', 'Save the current input settings (type a new name and press save)'
	, 'SaveSettings'
	, 6 ,1 ,0 ,0
	, 0 ,0 ,0 ,0
)


if not exists( select * from ReportInputParameters where reportid='COMPLIANCEISSUES' and parmname='DeleteSettings')
INSERT ReportInputParameters 
( 	ReportID, RptGroupID, ReportSavedSettingsName
	, ParmName, DBFldName, ParmValue, ParmValuePrompt
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
VALUES(
	'COMPLIANCEISSUES',  '', ''
	, 'DeleteSettings', '', '', ''
	, 'Delete', 'Delete a previously saved set of input settings'
	, 'SaveSettings'
	, 0 ,1 ,0 ,0
	, 0 ,0 ,1 ,0
)

if @@rowcount > 0
update ReportInputParameters set LangID = '0409' where reportid='COMPLIANCEISSUES'
end
GO

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


CREATE PROCEDURE dbo.AVISP_FieldGetComplianceIssues
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @szFilter		VARCHAR(64) = '',
    @szOptionalReportParms 	 VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @ret int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


	-- Fetch translated text strings for localized parameter value

 	UPDATE
		ReportInputParameterValues
	SET
		Prompt= TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	 ReportTextPromptStrings.TextID like ReportInputParameterValues.ParmValue	-- uses like operator
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
			)

 

 ----------------------------------------------------------------
 -- Lookup Parameter values 
 -- First column must be called: Value
 -- second column must be called: Prompt

 
-- check for product based on @szFilter=software name 
 Declare @prodcnt int
 Declare @datcnt int
 Declare @engcnt int

 select @prodcnt=count(*)
	from AVIView_Software
	where 
	( ProductFamily in ('TVD', 'TVD_NC', 'SECURE')
		or (ProductFamily = 'EPO' and ProductCode Like 'EPOAGENT%') 
		or ProductFamily like ('TVD_NC_%'))
	and SoftwareName = @szFilter


 select @datcnt=count(*)
	from AVIView_Software
	where 
	 (ProductFamily in ('TVD', 'TVD_NC')
		or ProductFamily like ('TVD_NC_%'))
	and (ProductFamily + '_DATs') = @szFilter

 select @engcnt=count(*)
	from AVIView_Software
	where 
	 (ProductFamily in ('TVD', 'TVD_NC')
		or ProductFamily like ('TVD_NC_%'))
	and (ProductFamily + '_Engines') = @szFilter



 IF @prodcnt > 0  -- fetch product versions
 BEGIN 
	
	-- Fetch Localized names

    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion
     			ELSE '---' 
     			END)
--		, '' as Prompt
	INTO #TmpProdVer	
       FROM ProductProperties, AVIView_Software
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
          AND AVIView_Software.SoftwareName = @szFilter
	and ProductProperties.ProductVersion not in ('5000', 'N/A')

	ORDER BY Value desc	

	-- special case processing, remove virusscan wrk and svr suffix from product version)
	update  #TmpProdVer Set Value = Replace(Value, '.wrk', '') 
	update  #TmpProdVer Set Value = Replace(Value, '.srv', '') 

	Select distinct Value, '' as Prompt from #TmpProdVer
	ORDER BY Value desc	

	Drop Table #TmpProdVer

 END


-- check for DAT version based on @szFilter=ProductFamily + '_dats' 


 else
 IF @datcnt > 0  -- fetch DAT versions
 BEGIN 

    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer
     			ELSE '---' 
     			END)
		, '' as Prompt
       FROM ProductProperties, AVIView_Software
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
	and ProductProperties.DATVer not in ('5000', 'N/A')
          AND (AVIView_Software.ProductFamily + '_DATs') = @szFilter
--    UNION
--	select '1st Most Recent Version' as value , '' as Prompt
--    UNION
--	select '2nd Most Recent Version' as value , '' as Prompt
--    UNION
--	select '3rd Most Recent Version' as value, '' as Prompt
    ORDER BY Value desc	

 END


-- check for Engine version based on @szFilter=ProductFamily + '_Engines' 


 else
 IF @engcnt > 0  -- fetch Engine versions
 BEGIN 
	
    SELECT DISTINCT 
	   Value =
    			(CASE 
     			WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer
     			ELSE '---'
     			END)
		, '' as Prompt
       FROM ProductProperties, AVIView_Software
       WHERE 
	    ProductProperties.ProductCode = AVIView_Software.ProductCode
--	  AND ProductProperties.EngineVer != 'N/A'
	and ProductProperties.EngineVer not in ('5000', 'N/A')
          AND (AVIView_Software.ProductFamily + '_Engines') = @szFilter
--    UNION
--	select '1st Most Recent Version' as value , '' as Prompt
--    UNION
--	select '2nd Most Recent Version' as value , '' as Prompt
--    UNION
--	select '3rd Most Recent Version' as value, '' as Prompt
    ORDER BY Value desc	

 END

----------------------------
	
 ELSE
 BEGIN

	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = @szFilter
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

 END

 Set @ret = @@rowcount
 if @ret = 0
		SELECT '---' as Value , '---' as Prompt

 RETURN @ret 


END
GO


----------------------------------------------------------------_
------------------------------------------------------------------

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




CREATE PROCEDURE dbo.AVISP_FieldPutComplianceIssues
(
    @iNameSpaceName  int
    ,@iNameSpaceNode         int
    ,@szEpoUserName           VARCHAR(100)
    ,@szOptionalReportParms 	 VARCHAR(500) = ''
    ,@szFieldName		VARCHAR(64) = ''
    ,@szFieldValue		VARCHAR(256) = ''
    ,@szFieldValuePrompt		VARCHAR(256) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'

   -- Output message
   Declare @szResult   VARCHAR(64)
   Set @szResult = ''
   Declare @ret int

   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang



 ----------------------------------------------------------------
 -- Make sure both values are input otherwise use one to set the other
	if @szFieldValue > '' and ( @szFieldValuePrompt = '' or @szFieldValuePrompt is NULL)
		set @szFieldValuePrompt = @szFieldValue

	if @szFieldValuePrompt > '' and ( @szFieldValue = '' or @szFieldValue is NULL)
		set @szFieldValue = @szFieldValuePrompt



 ----------------------------------------------------------------
 -- Lookup Parameter values 
 -- second column must to be called: Prompt


 	UPDATE
		ReportInputParameters
	SET
		ReportInputParameters.ParmValue = @szFieldValue
		, ReportInputParameters.ParmValuePrompt = @szFieldValuePrompt
	WHERE
		ReportInputParameters.ParmName = @szFieldName
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)
	
	set @ret = @@rowcount

	if @ret = 0
	begin
		Select @szResult = TranslatedValue
			from ReportTranslations
			where Subject = 'General' and TextID = 'Parameter not saved to Database'
				and LanguageID = @szFullLang
		if @@rowcount = 0    Set @szResult = 'Parameter not saved to Database'
		SELECT @szResult + ': ' + @szReportID + ': ' + @szRptGroup + ': ' + @szFieldValue + ': ' + @szFieldValue
	end

 -- Return Result String
 SELECT @szResult as szResult


 RETURN @ret

END
GO



----------------------------------------------------------------
----------------------------------------------------------------
-- AVISP_FieldGetProductSettingIssues

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_FieldGetProductSettingIssues
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @szFilter		VARCHAR(64) = '',
    @szOptionalReportParms 	 VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang




	-- Fetch translated text strings for localized parameter value

 	UPDATE
		ReportInputParameterValues
	SET
		Prompt= TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	 ReportTextPromptStrings.TextID like ReportInputParameterValues.ParmValue	-- uses like operator
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
			)

 

 ----------------------------------------------------------------
 -- Lookup Parameter values 
-- Currently all fields look the same (bools)

 IF @szFilter like 'VirusScan%'
 BEGIN 
	
	-- Fetch Localized names

	SELECT 
		ParmValue as Value
		, Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName like '%'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)


 END
 ELSE
 IF @szFilter like 'NetShield%'
 BEGIN 
	
	-- Fetch Localized names

	SELECT 
		ParmValue as Value
		, Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName like '%'
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)


 END
 ELSE
 IF @szFilter like '%'
 BEGIN 
	
	-- Fetch Localized names

	Declare @cnt int
	SELECT 
		@cnt=count(*) 
	FROM ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName like @szFilter
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

	-- Are parameter values defined in ReportInputParameterValues?
	IF @cnt > 0
	BEGIN 
		SELECT 
			ParmValue as Value
			, Prompt as Prompt
		FROM	
			ReportInputParameterValues
		WHERE
			ReportInputParameterValues.ParmName like @szFilter
			AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)
	END
	ELSE
	BEGIN
		
		-- Split up filter (format= Product:Section:Setting, find values in ProductSetting table using Product Section Setting
		Declare @pstart int
		Declare @pend int
		Declare @product varchar(50)
		Declare @section varchar(50)
		Declare @setting varchar(50)

		/* Get TIME parm */
		Set @pstart = CHARINDEX( ':', @szFilter) + 1
		Set @pend   = CHARINDEX( ':', @szFilter, @pstart)

		Set @product = SUBSTRING( @szFilter, 0, @pstart )
		Set @section = SUBSTRING( @szFilter, @pstart, (@pend - @pstart) )	
		Set @setting = SUBSTRING( @szFilter, (@pend+1), (len(@szFilter - @pend) ) )

		SELECT 
			distinct Value as Value
			, Value as Prompt
		FROM	
			ProductSettings, ProductProperties, AVIView_Software
		WHERE
			ProductSettings.ParentID = ProductProperties.AutoID
			and ProductProperties.ProductCode = AVIView_Software.ProductCode
			and AVIView_Software.SoftwareName = @product
			and ProductSettings.SectionName = @section
			and ProductSettings.SettingName = @setting

	END

 END
 ELSE
 BEGIN
	SELECT '---' as Value , '---' as Prompt
 END

 RETURN @@rowcount

END
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO



CREATE PROCEDURE dbo.AVISP_FieldPutProductSettingIssues
(
    @iNameSpaceName  int
    ,@iNameSpaceNode         int
    ,@szEpoUserName           VARCHAR(100)
    ,@szOptionalReportParms 	 VARCHAR(500) = ''
    ,@szFieldName		VARCHAR(64) = ''
    ,@szFieldValue		VARCHAR(256) = ''
    ,@szFieldValuePrompt		VARCHAR(256) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'

   -- Output message
   Declare @szResult   VARCHAR(64)
   Set @szResult = ''


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang



 ----------------------------------------------------------------
 -- Make sure both values are input otherwise use one to set the other
	if @szFieldValue > '' and ( @szFieldValuePrompt = '' or @szFieldValuePrompt is NULL)
		set @szFieldValuePrompt = @szFieldValue

	if @szFieldValuePrompt > '' and ( @szFieldValue = '' or @szFieldValue is NULL)
		set @szFieldValue = @szFieldValuePrompt



 ----------------------------------------------------------------
 -- write out Parameter values (all are the same)


 IF @szFieldName like '%'
 BEGIN 
	
 	UPDATE
		ReportInputParameters
	SET
		ReportInputParameters.ParmValue = @szFieldValue
		, ReportInputParameters.ParmValuePrompt = @szFieldValuePrompt
	WHERE
		ReportInputParameters.ParmName = @szFieldName
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)


 END


 -- Return Result String
 SELECT @szResult as szResult


 RETURN

END
GO


------------------------------------------------------------------------------


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


CREATE PROCEDURE dbo.AVISP_FieldGetOutbreak
(
    @iNameSpaceName  int,
    @iNameSpaceNode         int,
    @szEpoUserName           VARCHAR(100),
    @szFilter		VARCHAR(64) = '',
    @szOptionalReportParms 	 VARCHAR(500) = ''
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @ret int
 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang



 

 ----------------------------------------------------------------
 -- Lookup Parameter values 
 -- First column must be called: Value
 -- second column must be called: Prompt


 IF @szFilter = '@iMinMachineCount'
 BEGIN 
    SELECT 
	   Value = '10'
		, '' as Prompt
 END
 ELSE IF @szFilter = '@iMinFilenameCount'
 BEGIN
    SELECT 
	   Value = '20'
		, '' as Prompt
 END
 ELSE IF @szFilter = 'Minimum Users Affected'
 BEGIN
    SELECT 
	   Value = '10'
		, '' as Prompt
 END
 ELSE IF @szFilter = 'Minimum Files Affected'
 BEGIN
    SELECT 
	   Value = '20'
		, '' as Prompt
 END
 ELSE IF @szFilter = '@iHourRange'
 BEGIN
    SELECT 
	   Value = '1'
		, '' as Prompt
 END
 ELSE
 BEGIN
	SELECT Distinct ParmValue as Value , Prompt as Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportInputParameterValues.ParmName = @szFilter
		AND	
			(ReportInputParameterValues.ReportID = @szReportID
			OR
			ReportInputParameterValues.RptGroupID = @szRptGroup)

 END

 Set @ret = @@rowcount
 if @ret = 0
		SELECT '---' as Value , '---' as Prompt

 RETURN @ret 

END
GO

-----------------------------------------------------------------


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



CREATE PROCEDURE dbo.AVISP_FieldPutOutbreak
(
    @iNameSpaceName  int
    ,@iNameSpaceNode         int
    ,@szEpoUserName           VARCHAR(100)
    ,@szOptionalReportParms 	 VARCHAR(500) = ''
    ,@szFieldName		VARCHAR(64) = ''
    ,@szFieldValue		VARCHAR(256) = ''
    ,@szFieldValuePrompt		VARCHAR(256) = ''

)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @FilterID int
 Declare @rec int
 Set @rec = 0

 EXECUTE AVIDALSP_GetNodeIDFilter @iNameSpaceName, @iNameSpaceNode, @FilterID OUTPUT

   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'
   Declare @cnt int

   -- Output message
   Declare @szResult   VARCHAR(64)
   Set @szResult = ''


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang



 ----------------------------------------------------------------
 -- Make sure both values are input otherwise use one to set the other
	if @szFieldValue > '' and ( @szFieldValuePrompt = '' or @szFieldValuePrompt is NULL)
		set @szFieldValuePrompt = @szFieldValue

	if @szFieldValuePrompt > '' and ( @szFieldValue = '' or @szFieldValue is NULL)
		set @szFieldValue = @szFieldValuePrompt


 ----------------------------------------------------------------
 -- Lookup Parameter values 
 -- second column must to be called: Prompt


	select @cnt=Count(*) from 
		ReportInputParameters
	WHERE
		ReportInputParameters.ParmName = @szFieldName
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)


	IF @@rowcount > 0
	BEGIN	
 		UPDATE
			ReportInputParameters
		SET
			ReportInputParameters.ParmValue = @szFieldValue
			, ReportInputParameters.ParmValuePrompt = @szFieldValuePrompt
		WHERE
			ReportInputParameters.ParmName = @szFieldName
			AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
			)
		Set @rec = @@rowcount	
	END
 	ELSE
 	BEGIN
		Select @szResult = TranslatedValue
			from ReportTranslations
			where Subject = 'General' and TextID = 'Parameter not saved to Database'
				and LanguageID = @szFullLang
		if @@rowcount = 0    Set @szResult = 'Parameter not saved to Database'
		SELECT @szResult + ': ' + @szReportID + ': ' + @szRptGroup + ': ' + @szFieldValue + ': ' + @szFieldValue
 	END

 -- Return Result String
 SELECT @szResult as szResult


 RETURN @rec

END
GO


/**/
/* xxxxxxx ePO v2.5 8/15/2001     Report Text Strings routines xxxxxxxxxxxxxx */
/* reads translated text string for crystal reports from database - no more hardcoded lang specific rpt files */
/* mhilandepo3 - return rows of textid & translated values, rather than a flat table of fixed textids */
/**/


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


-- localized prompt text for all report metadata tables 
-- localized prompt text for all report metadata tables 
CREATE PROCEDURE dbo.AVISP_ReportSetMetadataLocalizedText
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved. */

   Declare @ret int
   Declare @doit int
   Declare @szLang 		VARCHAR(3)
   Declare @szFullLang 		VARCHAR(5)
   Declare @szDefaultLang 	VARCHAR(5)
   Declare @szLanguageID 	VARCHAR(5)
   Declare @szTime 		VARCHAR(10)
   Declare @szFilter 		VARCHAR(50)
   Declare @szReportID 		VARCHAR(50)
   Declare @szRptGroup 		VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'
   Set @ret=0
   Set @doit=0

   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


	-- epo3.5 cludge: add inputs if missing (sometimes they are missing after upgrade)
	if @szReportID = 'ComplianceIssues'
		execute AVISP_AddComplianceIssuesInputs

   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang

--select @szLanguageID
	-----------------------------------------------------
	-- set localized values if the langids differ for all metadata tables

	-------------------------------------
	-- set ReportInputParamaters
	-- localized ParmValuePrompt from ReportTextPromptStrings table

	-- check if translation needs to be done on ReportInputParameters
	Select @doit = count(*) from ReportInputParameters where ReportInputParameters.LangID <> @szLanguageID
				and ReportInputParameters.LangID > ''
		AND	
			(
				ReportInputParameters.ReportID = @szReportID
				OR
				ReportInputParameters.RptGroupID = @szRptGroup
				OR
				(ReportInputParameters.ReportID = ''
				AND	ReportInputParameters.RptGroupID = '')
				OR ReportInputParameters.RptGroupID = 'CustGroup'	
			)


	if @doit > 0
	begin

 	UPDATE
		ReportInputParameters
	SET
		ParmValuePrompt = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParameters.LangID <> @szLanguageID		-- do all of them
		AND	ReportInputParameters.ParmValue = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount



	-- Set Parameter Name Prompt text
	-- Substitute localized Parm Prompt value
	-- These are read from the ReportTextPromptStrings table
 	UPDATE
		ReportInputParameters
	SET
		Prompt = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParameters.LangID <> @szLanguageID
		AND	ReportInputParameters.Parmname = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

	-- Substitute localized Parm PDesc value
 	UPDATE
		ReportInputParameters
	SET
		PDesc = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParameters.LangID <> @szLanguageID
		AND	ReportInputParameters.Parmname+'PDesc' = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount


	end

	-- default: Translate dynamic version field descriptions
	-- These fields are dynamically added by compliance issues and dat/engine
	-- This just translates the field to a generic descirption: Enter minimum Compliant Version
	-- Do this every time just to be safe

	-- If extra product found for compliance issue, make sure its desc gets translated
 	UPDATE
		ReportInputParameters
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.ReportID = 'COMPLIANCEISSUES'
				and ReportTextPromptStrings.TextID = 'ParmPDesc'
			)
	Where	
		ReportInputParameters.Langid = '' or ReportInputParameters.Langid is null 

 	UPDATE
		ReportInputParameters
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.RptGroupID = 'DATENG'
				and ReportTextPromptStrings.TextID = 'ParmPDesc'
			)
	Where	
		ReportInputParameters.ReportID in ('DAT','ENG','DATENG','BFDAT')
		and ParmName like 'TVD%'



	-------------------------------------------------------------
	-- check if translation needs to be done on ReportInputParameterValues
	Select @doit = count(*) from ReportInputParameterValues where ReportInputParameterValues.LangID <> @szLanguageID
				and ReportInputParameterValues.LangID > ''
		AND	
			(
				ReportInputParameterValues.ReportID = @szReportID
				OR
				ReportInputParameterValues.RptGroupID = @szRptGroup
				OR
				(ReportInputParameterValues.ReportID = ''
				AND	ReportInputParameterValues.RptGroupID = '')
				OR ReportInputParameterValues.RptGroupID = 'CustGroup'	
			)


	if @doit > 0
	begin

--select * from ReportInputParameters where ReportID = @szReportID
	-------------------------------------
	-- set ReportInputParamaterValues
	-- localized ParmValuePrompt from ReportTextPromptStrings table
 	UPDATE
		ReportInputParameterValues
	SET
		Prompt = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParameterValues.LangID <> @szLanguageID
		AND	ReportInputParameterValues.ParmValue = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

--select * from ReportInputParameterValues where ReportID = @szReportID
	end


	-------------------------------------------------------------
	-- check if translation needs to be done on ReportInputParametersSaved
	Select @doit = count(*) from ReportInputParametersSaved where ReportInputParametersSaved.LangID <> @szLanguageID
		AND	
			(
				ReportInputParametersSaved.ReportID = @szReportID
				OR
				ReportInputParametersSaved.RptGroupID = @szRptGroup
				OR
				(ReportInputParametersSaved.ReportID = ''
				AND	ReportInputParametersSaved.RptGroupID = '')
				OR ReportInputParametersSaved.RptGroupID = 'CustGroup'	
			)


	if @doit > 0
	begin

	-------------------------------------
	-- set ReportInputParamatersSaved
	-- localized ParmValuePrompt from ReportTextPromptStrings table
 	UPDATE
		ReportInputParametersSaved
	SET
		ParmValuePrompt = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParametersSaved.LangID <> @szLanguageID
		AND	ReportInputParametersSaved.ParmValue = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

	-- localize name of saved report setting
 	UPDATE
		ReportInputParametersSaved
	SET
		PDesc = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportInputParametersSaved.LangID <> @szLanguageID
		AND	ReportInputParametersSaved.ReportSavedSettingsName = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

	-- default name to english if no translated value available
	Update 
		ReportInputParametersSaved
	Set
		PDesc = ReportSavedSettingsName
	Where
		Pdesc = '' or Pdesc is null

	Set @ret = @ret + @@RowCount

--select * from ReportInputParametersSaved where ReportID = @szReportID

	end



	-------------------------------------------------------------
	-- check if translation needs to be done on ReportUICustPages
	Select @doit = count(*) from ReportUICustPages where ReportUICustPages.LangID <> @szLanguageID
				and ReportUICustPages.LangID > ''
		AND	
			(
				ReportUICustPages.ReportID = @szReportID
				OR
				ReportUICustPages.RptGroupID = @szRptGroup
				OR
				(ReportUICustPages.ReportID = ''
				AND	ReportUICustPages.RptGroupID = '')
				OR ReportUICustPages.RptGroupID = 'CustGroup'	
			)


	if @doit > 0
	begin

	---------------------------
	-- set ReportUICustPages
	-- Substitute localized Cust Prompt value
 	UPDATE
		ReportUICustPages
	SET
		Prompt = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportUICustPages.LangID <> @szLanguageID
		AND	ReportUICustPages.Name = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

	-- Substitute localized Cust PDesc value
 	UPDATE
		ReportUICustPages
	SET
		PDesc = TextValue, LangID = @szLanguageID
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
--		AND ReportUICustPages.LangID <> @szLanguageID
		AND	ReportUICustPages.Name+'PDesc' = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(
					ReportTextPromptStrings.ReportID <> @szReportID
					and
					ReportTextPromptStrings.RptGroupID <> @szRptGroup	
					and
					ReportTextPromptStrings.RptGroupID = 'CustGroup'				
				)
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)
	Set @ret = @ret + @@RowCount

--select * from ReportUICustPages where ReportID = @szReportID

	end

	-- special code to translate Dat/Engine tab descriptions when a new product is recognized 
 	UPDATE
		ReportUICustPages
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.ReportID = 'DAT'
				and ReportTextPromptStrings.TextID = 'TVDPDesc'
			)
	Where	
		ReportUICustPages.ReportID = 'DAT'

	-- special code to translate Dat/Engine tab descriptions when a new product is recognized 
 	UPDATE
		ReportUICustPages
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.ReportID = 'ENG'
				and ReportTextPromptStrings.TextID = 'TVDPDesc'
			)
	Where	
		ReportUICustPages.ReportID = 'ENG'

	-- special code to translate Dat/Engine tab descriptions when a new product is recognized 
 	UPDATE
		ReportUICustPages
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.ReportID = 'DATENG'
				and ReportTextPromptStrings.TextID = 'TVDPDesc'
			)
	Where	
		ReportUICustPages.ReportID = 'DATENG'

 	UPDATE
		ReportUICustPages
	SET
		PDesc = ( Select TextValue
				FROM	
				ReportTextPromptStrings
				WHERE
				ReportTextPromptStrings.LanguageID = @szLanguageID
				and ReportTextPromptStrings.ReportID = 'BFDAT'
				and ReportTextPromptStrings.TextID = 'TVDPDesc'
			)
	Where	
		ReportUICustPages.ReportID = 'BFDAT'


	-- done translating

Return @ret
end
GO





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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_TranslateReportText
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved. */

   Declare @ret int
   Declare @szLang 		VARCHAR(3)
   Declare @szFullLang 		VARCHAR(5)
   Declare @szDefaultLang 	VARCHAR(5)
   Declare @szLanguageID 	VARCHAR(5)
   Declare @szTime 		VARCHAR(10)
   Declare @szFilter 		VARCHAR(50)
   Declare @szReportID 		VARCHAR(50)
   Declare @szRptGroup 		VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang



	-- Check if this is a report which does dynamic report parm loading (Property Setting Monitor)
	 EXECUTE AVISP_ReportParmLoading @szOptionalReportParms


	-- postepo3: Must clear open and savesetting values when ever a new report is fun
	-- Set name of open settings in open and save fields
 	UPDATE
		ReportInputParameters
	SET
		ReportInputParameters.ParmValue= ''
	WHERE	
		ReportInputParameters.ParmName in ('RestoreSettings', 'SaveSettingsVar')


   	Truncate Table ReportTextWorkTable

	-- mhilandepo3 - changed to return rows of parameter value pairs instead of a flat table with fixed parameter names
	-- Maintain backward compatibility by reading in old and new data formats and selecting highest priority for duplicate matches

	-- old format: read constant header, priority 0 
	INSERT INTO
		ReportTextWorkTable
		(ReportID, ParmName, ParmValue,  iCrystalParm, Priority)
	    SELECT	@szReportID as ReportID, TextID as ParmName, TextValue as ParmValue, 1, 0
	    FROM	ReportTextStrings
	    WHERE
		LanguageID = @szLanguageID
		AND 
		(
			TextID = 'HEADER'
			OR TextID = 'NODATAMSG'
			OR (RptGroupID = 'xxxx'
				AND ReportID = 'xxxx')
		)


	-- old format, read data from report group, priority 2 
	   INSERT INTO
		ReportTextWorkTable
		(ReportID, ParmName, ParmValue,  iCrystalParm, Priority)
	    SELECT	@szReportID as ReportID,  TextID as ParmName, TextValue as ParmValue, 1, 2
	    FROM	ReportTextStrings
	    WHERE
		LanguageID = @szLanguageID
                	AND RptGroupID = @szRptGroup

	-- old format, read data from reportID, priority 3 (allows report specific overrides for same parms names used in separate reports but having different values) 
	INSERT INTO
		ReportTextWorkTable
		(ReportID, ParmName, ParmValue, iCrystalParm, Priority)
	    SELECT	@szReportID as ReportID,  TextID as ParmName, TextValue as ParmValue, 1, 3
	    FROM	ReportTextStrings
	    WHERE
		LanguageID = @szLanguageID
		AND	ReportID = @szReportID



	-------------------------------------------------------------------------------
	-- New format
	-- set localized text fields in metadata tables
	EXECUTE dbo.AVISP_ReportSetMetadataLocalizedText  @szOptionalReportParms 


	--------------------------------------------------------------------------------
	-- New format, get parms report needs by merging with ReportInputParameters
	--		& ReportUICustPages table, priority 4
	-- load all values for this report, fetch update with localized text further down
	INSERT INTO
		ReportTextWorkTable


	    SELECT	
			@szReportID as ReportID
			, ReportInputParameters.RptGroupID
			, 4 as Priority
			, ReportInputParameters.ParmName 
			, ReportInputParameters.DBFldName  as DBFldName
			, ReportInputParameters.ParmValue  as ParmValue
--			, ReportInputParameters.ParmValue  as ParmValuePrompt
			, ReportInputParameters.ParmValuePrompt  as ParmValuePrompt
			, ReportInputParameters.Prompt  as Prompt
			, ReportInputParameters.PDesc  as PDesc
			, ReportInputParameters.iType  as iType
			, ReportInputParameters.iSaveUserEntry  as iSaveUserEntry
			, ReportInputParameters.iDefaultFlag  as iDefaultFlag
			, ReportInputParameters.iUseDefault  as iUseDefault
--			, ReportInputParameters.iCrystalParm  as iCrystalParm
			, 1 as iCrystalParm
			, ReportInputParameters.iCrystalFieldCust  as iCrystalFieldCust
			, ReportInputParameters.iLocalizedField  as iLocalizedField
			, ReportInputParameters.iDBField  as iDBField
			, ReportUICustPages.Name  as CustPageName
			, ReportUICustPages.Type  as CustType
			, ReportUICustPages.Prompt  as CustPrompt
			, ReportUICustPages.PDesc  as CustDesc
			, ReportUICustPages.Storedproc  as CustStoredproc
			, ReportUICustPages.WritebackStoredproc  as CustWritebackStoredproc
			, ReportUICustPages.Dll  as CustDll
			, ReportUICustPages.iOptionalPage  as CustiOptionalPage
	
	    FROM	
		ReportInputParameters Left Outer Join ReportUICustPages on
		(ReportInputParameters.CustPageName = ReportUICustPages.Name)	
--		AND	
--			( ReportInputParameters.ReportID = @szReportID
--			OR
--			 ReportInputParameters.RptGroupID = @szRptGroup
--			)
--		AND	
--			( ReportUICustPages.ReportID = @szReportID
--			OR
--			 ReportUICustPages.RptGroupID = @szRptGroup
--			)
--		)
--		ReportInputParameters, ReportUICustPages
	    WHERE
--		ReportInputParameters.CustPageName *= ReportUICustPages.Name	-- left join
--		AND	
			( ReportInputParameters.ReportID = @szReportID
			OR
			 ReportInputParameters.RptGroupID = @szRptGroup
			)
		AND	
			( ReportUICustPages.ReportID = @szReportID
			OR
			 ReportUICustPages.RptGroupID = @szRptGroup
			)
	ORDER BY
		ReportUICustPages.AutoID, ReportInputParameters.AutoID


--select @szReportID, @szRptGroup
--select * from ReportTextWorkTable

	-- Remove Prompt% and Desc% entries, these are label text and not report parms
	-- These fields should have ReportTextStrings.TextID = 'Prompt%' or 'Desc%' so they can be removed here
	-- These fields were moved to reporttextpromptstrings table
--	DELETE FROM ReportTextWorkTable
--		WHERE ReportID = @szReportID
--			AND ParmName like 'Prompt%'

--	DELETE FROM ReportTextWorkTable
--		WHERE ReportID = @szReportID
--			AND ParmName like 'Desc%'




	-- select highest priority values 
	SELECT
		ParmName
		, max( Priority ) as Priority
	INTO #TempTextStringPriority
	FROM ReportTextWorkTable
	Group BY
		 ParmName



	-- New format - run updates to set localized text fields into ParmValue, Prompt, PDesc, CustPrompt, CustDesc fields fields
	-- Text fields can be found by TextID, TextID & RptGroup, TextID & ReportID
 	UPDATE
		ReportTextWorkTable
	SET
		ParmValue = TextValue
	FROM	
		ReportTextStrings
	WHERE
		LanguageID = @szLanguageID
		AND	ReportTextWorkTable.ParmName = ReportTextStrings.TextID
		AND	
			(
				ReportTextStrings.ReportID = @szReportID
				OR
				ReportTextStrings.RptGroupID = @szRptGroup
				OR
				(ReportTextStrings.ReportID = ''
				AND	ReportTextStrings.RptGroupID = '')
			)



	-- Try setting value from ReportTextPromptStrings table as well
 	UPDATE
		ReportTextWorkTable
	SET
		ParmValue = TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	ReportTextWorkTable.Prompt = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)


	-- Check if any parameters need to have default values loaded using a special report specific algortithm
	 EXECUTE AVISP_ReportParmDefaults @szOptionalReportParms

	-- Set ParmValuePrompt default from from ReportInputParameter table - the above defaults routine may have changed things
 	UPDATE
		ReportTextWorkTable
	SET
			ParmValue = ReportInputParameters.ParmValue
			, ParmValuePrompt = ReportInputParameters.ParmValuePrompt

	FROM	
		ReportInputParameters
	WHERE
		ReportTextWorkTable.ParmName = ReportInputParameters.ParmName
		AND	
			(
				ReportTextWorkTable.ReportID = ReportInputParameters.ReportID
				OR
				ReportTextWorkTable.RptGroupID = ReportInputParameters.RptGroupID
			)
		AND	
			( ReportInputParameters.ReportID = @szReportID
			OR
			 ReportInputParameters.RptGroupID = @szRptGroup
			)

--select * from ReportTextWorkTable

	-- Set ParmValuePrompt default from from ReportInputParameterValues table - must redo lookups
 	UPDATE
		ReportTextWorkTable
	SET
		ParmValuePrompt = ReportInputParameterValues.Prompt
	FROM	
		ReportInputParameterValues
	WHERE
		ReportTextWorkTable.ParmValue = ReportInputParameterValues.ParmValue
		AND	
			(
				ReportTextWorkTable.ReportID = ReportInputParameterValues.ReportID
				OR
				ReportTextWorkTable.RptGroupID = ReportInputParameterValues.RptGroupID
			)
		AND	
			( ReportInputParameterValues.ReportID = @szReportID
			OR
			 ReportInputParameterValues.RptGroupID = @szRptGroup
			)

	-- localized ParmValuePrompt from ReportTextPromptStrings table
 	UPDATE
		ReportTextWorkTable
	SET
		ParmValuePrompt = TextValue
	FROM	
		ReportTextPromptStrings
	WHERE
		LanguageID = @szLanguageID
		AND	ReportTextWorkTable.ParmValue = ReportTextPromptStrings.TextID
		AND	
			(
				ReportTextPromptStrings.ReportID = @szReportID
				OR
				ReportTextPromptStrings.RptGroupID = @szRptGroup
				OR
				(ReportTextPromptStrings.ReportID = ''
				AND	ReportTextPromptStrings.RptGroupID = '')
			)








	-- Final select (uses highest priority matches)
	SELECT
		@szReportID as ReportID
		, @szRptGroup as RptGroupID
		, @szLanguageID as LanguageID
			, ReportTextWorkTable.ParmName as TextID
			, ReportTextWorkTable.ParmValue  as TextValue
			, ReportTextWorkTable.ParmValuePrompt  as TextValuePrompt
			, ReportTextWorkTable.DBFldName  as DBFldName
			, ReportTextWorkTable.Prompt  as Prompt
			, ReportTextWorkTable.PDesc  as PDesc
			, ReportTextWorkTable.iType  as iType
			, ReportTextWorkTable.iSaveUserEntry  as iSaveUserEntry
			, ReportTextWorkTable.iDefaultFlag  as iDefaultFlag
			, ReportTextWorkTable.iUseDefault  as iUseDefault
			, ReportTextWorkTable.iCrystalParm  as iCrystalParm
			, ReportTextWorkTable.iCrystalFieldCust  as iCrystalFieldCust
			, ReportTextWorkTable.iLocalizedField  as iLocalizedField
			, ReportTextWorkTable.iDBField  as iDBField
			, ReportTextWorkTable.CustPageName  as CustPageName
			, ReportTextWorkTable.CustType  as CustType
			, ReportTextWorkTable.CustPrompt  as CustPrompt
			, ReportTextWorkTable.CustDesc  as CustDesc
			, ReportTextWorkTable.CustStoredproc  as CustStoredproc
			, ReportTextWorkTable.CustWritebackStoredproc  as CustWritebackStoredproc
			, ReportTextWorkTable.CustDll  as CustDll
			, ReportTextWorkTable.CustiOptionalPage  as CustiOptionalPage
--			, ReportTextWorkTable.Priority				-- comment out for production
--		, ReportTextWorkTable.ParmName
--		, ParmValue
	FROM ReportTextWorkTable, #TempTextStringPriority
	WHERE
		ReportTextWorkTable.ParmName =  #TempTextStringPriority.ParmName
		AND ReportTextWorkTable.Priority =  #TempTextStringPriority.Priority

	set @ret = @@rowcount

	DROP TABLE #TempTextStringPriority


--   	DELETE ReportTextWorkTable
--			WHERE ReportID = @szReportID


RETURN @ret
END
GO



--------------------------------------------------------------------------------
-- Loads default values (used by dat engine reports)

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

CREATE PROCEDURE dbo.AVISP_ReportParmDefaults
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


 
	IF @szRptGroup = 'DATEng'
	BEGIN

		Execute AVISP_ReportParmDefaultDATEngine @szOptionalReportParms

	END

/*
	ELSE	-- dynamic sql to call any newly added reports using dynamic parameter generation
		-- Must follow the naming convention below in order to get your new routine called
	BEGIN
		Declare @routine nvarchar(255)
		Set @routine = 'AVISP_ReportParmDefaults' + @szReportID 

		Declare @ifexists nvarchar(512)
		-- the following format works for both sql7 and sql2000
		Set @ifexists = 'select * from sysobjects where id = object_id(N''' + @routine + ''') and OBJECTPROPERTY(id, N''IsProcedure'')=1'

		EXECUTE(@ifexists) 

		if @@rowcount > 0	-- if exists run it
		begin
			Set @routine =  @routine + ' ' + '''' + @szOptionalReportParms + ''''
			execute(@routine)
		end

	END
*/

END
GO



----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
-- AVISP_ReportParmDefaultDATEngine
-- vs7.5 handle new buffer overflow event

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


CREATE PROCEDURE dbo.AVISP_ReportParmDefaultDATEngine
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


 
IF @szRptGroup = 'DATEng'
BEGIN

--	Close ProdFams
--	Deallocate ProdFams

	IF EXISTS (select * from sysobjects where name = 'tmpVer' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVer

	CREATE TABLE [dbo].[tmpVer] (
	 [AutoID] [int] IDENTITY (1, 1) NOT NULL ,
	 [Version] [nvarchar] (100) NULL,
	 [SettingName] [nvarchar] (100) NULL	-- used for productsettings dats
	) 

	IF EXISTS (select * from sysobjects where name = 'dbo.tmpProdFamVer' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpProdFamVer

	CREATE TABLE [dbo].[tmpProdFamVer] (
	ProductFamily nvarchar(50)
	 ,[AutoID] [int] NULL 
	 ,[Version] [nvarchar] (100) NULL
	,ParmName nvarchar(128)
	 ,[SettingName] [nvarchar] (100) NULL	-- used for productsettings dats
	) 

	Declare @ProdFam nvarchar(50)

	Declare ProdFams Cursor Forward_only static for
	select ProductFamily 
	from ProductProperties, AVIView_Software
	where 
	ProductProperties.ProductCode =  AVIView_Software.ProductCode
	and (ProductFamily in ('TVD', 'TVD_NC')
	or ProductFamily like 'TVD_NC%')
	Group By
	AVIView_Software.ProductFamily

	Open ProdFams

	Fetch Next from ProdFams into @ProdFam

	-- create table with all top dat/engine versions for each product family
	While @@Fetch_Status = 0
	begin
		truncate table dbo.tmpVer

		-- postepo3: exclude datver & engver = N/A in here and avisp_fieldget* routines
		-- get top dats
		insert dbo.tmpVer
		(Version)
		select top 5 DATVer as Version
		from ProductProperties, AVIView_Software
		where 
		ProductProperties.ProductCode =  AVIView_Software.ProductCode
		and ProductFamily = @ProdFam
		and DATVer not in ('5000', 'N/A')
		group by ProductFamily, DATVer
		order by DATVer Desc

		-- Top 5 DATs
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, autoid
			, Version
			, @ProdFam + 'DAT' + convert(nvarchar(10),autoid) as ParmName
			, ''
			from dbo.tmpVer

		-- DATEng top DAT
		insert dbo.tmpProdFamVer
		select top 1
			@ProdFam as ProductFamily
			, 1 as autoid
			, max(Version) as Version
			, @ProdFam + 'DAT1DE' as ParmName, ''
			from dbo.tmpVer

		-- get top engines
		truncate table dbo.tmpVer

		insert dbo.tmpVer
		(Version)
		select top 3 EngineVer as Version
		from ProductProperties, AVIView_Software
		where 
		ProductProperties.ProductCode =  AVIView_Software.ProductCode
		and ProductFamily = @ProdFam
		and EngineVer not in ('5000', 'N/A')
--		and EngineVer != 'N/A'
		group by ProductFamily, EngineVer
		order by EngineVer Desc

		-- Top 3 engines
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, autoid
			, Version 
			, @ProdFam + 'Engine' + convert(nvarchar(10),autoid)  as ParmName
			, ''
			from dbo.tmpVer

		-- DATEng top engine
		insert dbo.tmpProdFamVer
		select top 1
			@ProdFam as ProductFamily
			, 1 as autoid
			, max(Version) as Version
			, @ProdFam + 'Engine1DE' as ParmName, ''
			from dbo.tmpVer

		-- If TVD find the top 3 Buffer overflow Dats
		if @ProdFam = 'TVD'
		Begin
			truncate table dbo.tmpVer
	
			insert dbo.tmpVer
			(Version, SettingName)
			select top 3 Value as Version, SettingName
			from ProductProperties, AVIView_Software, ProductSettings
			where 
			ProductProperties.ProductCode =  AVIView_Software.ProductCode
			and ProductFamily = 'TVD'
			and ProductSettings.ParentID = ProductProperties.AutoID
			and SectionName = 'General'
			and SettingName in ('szBufferOverflowDAT')
			group by Value, SettingName
			order by Value Desc
	
			insert dbo.tmpProdFamVer
			select 
				@ProdFam as ProductFamily
				, autoid
				, Version 
				, @ProdFam + SettingName + convert(nvarchar(10),autoid)  as ParmName
				, SettingName as SettingName
				from dbo.tmpVer
		End

		-- get next product family
		Fetch Next from ProdFams into @ProdFam

	end

	Close ProdFams
	Deallocate ProdFams
 
	-- update all dateng defaults

	update ReportInputParameters 
	set ParmValue = Version, ParmValuePrompt = Version
	from dbo.tmpProdFamVer
	where 
		(
			ReportInputParameters.CustPageName = dbo.tmpProdFamVer.ProductFamily
			or ReportInputParameters.CustPageName =  (dbo.tmpProdFamVer.ProductFamily + dbo.tmpProdFamVer.SettingName)
		)
		and ReportInputParameters.ParmName = dbo.tmpProdFamVer.ParmName

	drop table dbo.tmpProdFamVer
	drop table dbo.tmpVer
END



END
GO


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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_ReportParmLoading
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


	Declare @ret int
	set @ret = 0
 
	IF @szReportID = 'PROPERTYSETTINGISSUES'
	BEGIN

		Execute @ret= AVISP_ReportParmLoadProductSettingMonitor @szOptionalReportParms

	END


	ELSE IF @szRptGroup = 'DATENG'
	BEGIN

		Execute @ret= AVISP_ReportParmLoadDATEngine @szOptionalReportParms

	END

	ELSE IF @szReportID = 'COMPLIANCEISSUES'
	BEGIN

		Execute @ret= AVISP_ReportParmLoadComplianceIssues @szOptionalReportParms

	END

/*
	ELSE	-- dynamic sql to call any newly added reports using dynamic parameter generation
		-- Must follow the naming convention below in order to get your new routine called
	BEGIN
		Declare @routine nvarchar(255)
		Set @routine = 'AVISP_ReportParmLoad' + @szReportID 

		Declare @ifexists nvarchar(512)
		-- the following format works for both sql7 and sql2000
		Set @ifexists = 'select * from sysobjects where id = object_id(N''' + @routine + ''') and OBJECTPROPERTY(id, N''IsProcedure'')=1'

		EXECUTE(@ifexists) 

		if @@rowcount > 0	-- if exists run it
		begin
			Set @routine =  @routine + ' ' + '''' + @szOptionalReportParms + ''''
			execute(@routine)
		end

	END
*/


Return @ret
END
GO


---------------------------------------------------------------------------
---------------------------------------------------------------------------
--  AVISP_ReportParmLoadComplianceIssues

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

CREATE PROCEDURE dbo.AVISP_ReportParmLoadComplianceIssues
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

/*AVISP_ReportParmLoadProductSettingMonitor*/
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


-----------------------------------------
-- Dynamically check DB for any new products that needs to be added to the compliance list

 
IF @szReportID = 'COMPLIANCEISSUES'
BEGIN

-- Check for any new products that need to have their settings loaded in the report metadata tables

------------------------------
-- ReportInputParameters table
-- Create any new inputs dynamically for now

--truncate table ReportPropertySettings 
--GO


Declare @cnt int
Declare @ret int
set @ret=0

------------------------------------------------------------------------------------------
-- get product version list, assume everything is new

IF EXISTS (select * from sysobjects where name = 'tmpProdVerList' 
   and xtype = 'U')
  DROP TABLE dbo.tmpProdVerList

select distinct SoftwareName, max(ProductProperties.ProductVersion) as ProductVersion, 1 as new
into dbo.tmpProdVerList
from ProductProperties, AVIView_Software
where 
ProductProperties.ProductCode =  AVIView_Software.ProductCode
and 				-- (ProductFamily in ('TVD', 'TVD_NC', 'SECURE', 'EPO')
	( ProductFamily in ('TVD', 'TVD_NC', 'SECURE')
		or (ProductFamily = 'EPO' and AVIView_Software.ProductCode Like 'EPOAGENT%') 
		or ProductFamily like ('TVD_NC_%') )
	and ProductProperties.ProductVersion != '5000'
	and SoftwareName > ''
Group By
SoftwareName


-- special code: remove virusscan7 .wrk & .srv suffix
Update dbo.tmpProdVerList
	Set ProductVersion = Replace(Replace(ProductVersion,'.wrk',''),'.srv','')


-- check if any products are not in the compliance report product list
-- set all matches back to zero (not new)

update dbo.tmpProdVerList
set new = 0
from ReportInputParameters
where 
ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
and ReportInputParameters.CustPageName  = 'ProductVersions'
and ReportInputParameters.ParmName = dbo.tmpProdVerList.SoftwareName

-- eposp2 
-- Update existing products whose versions have changed
update ReportInputParameters
set ReportInputParameters.ParmValue = dbo.tmpProdVerList.ProductVersion,
ReportInputParameters.ParmValuePrompt = dbo.tmpProdVerList.ProductVersion
from dbo.tmpProdVerList
where 
ReportInputParameters.ParmName = dbo.tmpProdVerList.SoftwareName
--and #tmpProdVerList.ProductVersion > ReportInputParameters.ParmValue


-- add any new products

INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'COMPLIANCEISSUES', '' 
, dbo.tmpProdVerList.SoftwareName as ParmName, '', dbo.tmpProdVerList.ProductVersion as ParmValue
, dbo.tmpProdVerList.SoftwareName as Prompt, 'Enter Minimum Compliant Version' as PDesc
, 'ProductVersions'
, 0, 1, 0, 0
, 0, 0, 0, 0
from dbo.tmpProdVerList
where 
	new = 1

set @ret = @ret + @@rowcount

-- cleanup

drop table dbo.tmpProdVerList



---------------------------------------------------------------------------------------------------
-- get DAT version list, assume everything is new
-- Gets version for each productfamily, not each product
-- load any future dat/engines with productfamily = 'TVD_NC%' naming convention

IF EXISTS (select * from sysobjects where name = 'tmpDATVerList' 
   and xtype = 'U')
  DROP TABLE dbo.tmpDATVerList

select distinct AVIView_Software.ProductFamily as ProductFamily
	, min(AVIView_Software.SoftwareName) as SoftwareName
	, max(ProductProperties.DATVer) as DATVer, 1 as new
into dbo.tmpDATVerList
from ProductProperties, AVIView_Software
where 
ProductProperties.ProductCode =  AVIView_Software.ProductCode
and ProductProperties.DATVer not in ('5000', 'N/A')
and 
(ProductFamily in ('TVD', 'TVD_NC')
or ProductFamily like 'TVD_NC%')

Group By
AVIView_Software.ProductFamily


-- check if any products are not in the compliance report product list
-- set all matches back to zero (not new)

update dbo.tmpDATVerList
set new = 0
from ReportInputParameters
where 
ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
and ReportInputParameters.CustPageName  = 'EngineDATs'
and
ReportInputParameters.ParmName = dbo.tmpDATVerList.ProductFamily + '_DATs'

-- eposp2 
-- Update existing products whose versions have changed
update ReportInputParameters
set ReportInputParameters.ParmValue = dbo.tmpDATVerList.DATVer,
ReportInputParameters.ParmValuePrompt = dbo.tmpDATVerList.DATVer
from dbo.tmpDATVerList
where 
ReportInputParameters.ParmName = dbo.tmpDATVerList.ProductFamily + '_DATs'


-- add any new products

INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'COMPLIANCEISSUES', '' 
, dbo.tmpDATVerList.ProductFamily + '_DATs' as ParmName, '', dbo.tmpDATVerList.DATVer as ParmValue
, dbo.tmpDATVerList.SoftwareName + '_DATs'  as Prompt, 'Enter Minimum Compliant Version' as PDesc
, 'EngineDATs'
, 0, 1, 0, 0
, 0, 0, 0, 0
from dbo.tmpDATVerList
where 
	new = 1

set @ret = @ret + @@rowcount

-- cleanup

drop table dbo.tmpDATVerList





---------------------------------------------------------------------------------------------------
-- get Engine version list, assume everything is new
-- Gets version for each productfamily, not each product

IF EXISTS (select * from sysobjects where name = 'tmpEngineVerList' 
   and xtype = 'U')
  DROP TABLE dbo.tmpEngineVerList

select distinct AVIView_Software.ProductFamily as ProductFamily
	, min(AVIView_Software.SoftwareName) as SoftwareName
	, max(ProductProperties.EngineVer) as EngineVer, 1 as new
into dbo.tmpEngineVerList
from ProductProperties, AVIView_Software
where 
ProductProperties.ProductCode =  AVIView_Software.ProductCode
--and ProductProperties.EngineVer != 'N/A'
and ProductProperties.EngineVer not in ('5000', 'N/A')
and (ProductFamily in ('TVD', 'TVD_NC')
or ProductFamily like 'TVD_NC%')
Group By
AVIView_Software.ProductFamily


-- check if any products are not in the compliance report product list
-- set all matches back to zero (not new)

update dbo.tmpEngineVerList
set new = 0
from ReportInputParameters
where 
ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
and ReportInputParameters.CustPageName  = 'EngineDATs'
and ReportInputParameters.ParmName = dbo.tmpEngineVerList.ProductFamily + '_Engines'

-- eposp2 
-- Update existing products whose versions have changed
update ReportInputParameters
set ReportInputParameters.ParmValue = dbo.tmpEngineVerList.EngineVer,
ReportInputParameters.ParmValuePrompt = dbo.tmpEngineVerList.EngineVer 
from dbo.tmpEngineVerList
where 
ReportInputParameters.ParmName = dbo.tmpEngineVerList.ProductFamily + '_Engines'


-- add any new products

INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'COMPLIANCEISSUES', '' 
, dbo.tmpEngineVerList.ProductFamily  + '_Engines' as ParmName, '', dbo.tmpEngineVerList.EngineVer as ParmValue
, dbo.tmpEngineVerList.SoftwareName  + '_Engines'  as Prompt, 'Enter Minimum Compliant Version' as PDesc
, 'EngineDATs'
, 0, 1, 0, 0
, 0, 0, 0, 0
from dbo.tmpEngineVerList
where 
	new = 1

set @ret = @ret + @@rowcount

-- cleanup

drop table dbo.tmpEngineVerList



-- need to create ProductFamilyDesc table, until then update the product family descriptions manually

update ReportInputParameters
set Prompt = 'McAfee (DAT)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName = 'TVD_DATs' 

update ReportInputParameters
set Prompt = 'McAfee (ENG)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName = 'TVD_Engines' 

update ReportInputParameters
set Prompt = substring(ParmName, 8, len(ParmName)-12) + ' (DAT)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName like ('TVD_NC_%DATs') 
and ParmName <> 'TVD_NC_DATs'

update ReportInputParameters
set Prompt = substring(ParmName, 8, len(ParmName)-15) + ' (ENG)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName like ('TVD_NC_%Engines') 
and ParmName <> 'TVD_NC_Engines'

update ReportInputParameters
set Prompt = 'Symantec (DAT)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName = 'TVD_NC_DATs' 

update ReportInputParameters
set Prompt = 'Symantec (ENG)'
where 
ReportID = 'COMPLIANCEISSUES'
and ParmName = 'TVD_NC_Engines' 



-- test

--select * 
--from ReportInputParameters
--where 
--    ReportInputParameters.ReportID =  'COMPLIANCEISSUES'



END

--return @ret

END
GO


----------------------------------------------------------------------------
-- dbo.AVISP_ReportParmLoadDATEngine

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

CREATE PROCEDURE dbo.AVISP_ReportParmLoadDATEngine
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

/*AVISP_ReportParmLoadProductSettingMonitor*/
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


 
IF @szRptGroup = 'DATEng'
BEGIN

-- Check for any new products that need to have their settings loaded in the report metadata tables

------------------------------
-- ReportInputParameters table
-- Create any new inputs dynamically for now


Declare @cnt int
Declare @SymantecCnt int
Declare @ret int
set @ret=0

------------------------------------------------------------------------------------------
-- Check if any products have a product family of TVD_NC - symantec 

----------------------------------------------------------------------------
-- Look for other competitor products: ProductFamily of TVD_NC_%

IF EXISTS (select * from sysobjects where name = 'tmpVerList' 
   and xtype = 'U')
  DROP TABLE dbo.tmpVerList

select distinct AVIView_Software.ProductFamily as ProductFamily
	, min(AVIView_Software.SoftwareName) as SoftwareName
	, max(ProductProperties.EngineVer) as EngineVer
	, 1 as new
into dbo.tmpVerList
from ProductProperties, AVIView_Software
where 
ProductProperties.ProductCode =  AVIView_Software.ProductCode
and ProductProperties.EngineVer not in ('N/A', '5000')
and (ProductFamily in ('TVD_NC')
or ProductFamily like 'TVD_NC%')
Group By
AVIView_Software.ProductFamily


-- check if any products are not in the compliance report product list
-- set all matches back to zero (not new)

update dbo.tmpVerList
set new = 0
from ReportUICustPages
where 
ReportUICustPages.ReportID in ('DAT', 'ENG', 'DATENG')
and ReportUICustPages.Name  = dbo.tmpVerList.ProductFamily


select @cnt=count(*)
from dbo.tmpVerList
where new =1

-- check if new products found
if @cnt > 0 
Begin

	set @ret=1
	
	-- add symantec input tab
	
	INSERT ReportUICustPages
	( 	ReportID, RptGroupID
		, Name, Type
		, Prompt, PDesc 
		, Storedproc, dll 
		, WritebackStoredproc, iOptionalPage
	)
	Select
		'DAT' as ReportID, '' as RptGroupID
		, ProductFamily as Name, 'Parameters' as Type
		, Prompt = case ProductFamily		-- take suffix characters as product family name
			when 'TVD_NC'  then 'Symantec'
			else substring( ProductFamily, 8, len(ProductFamily)-7 )
			end
		, 'Enter Top 5 DAT/Definition (DAT) versions, by default the most recent values are loaded' 
		, '{CALL dbo.AVISP_FieldGetDATEng (?,?,?,?)}', ''
		, '', 0 
	from dbo.tmpVerList
	where new = 1

	INSERT ReportUICustPages
	( 	ReportID, RptGroupID
		, Name, Type
		, Prompt, PDesc 
		, Storedproc, dll 
		, WritebackStoredproc, iOptionalPage
	)
	Select
		'ENG' as ReportID, '' as RptGroupID
		, ProductFamily as Name, 'Parameters' as Type
		, Prompt = case ProductFamily		-- take suffix characters as product family name
			when 'TVD_NC'  then 'Symantec'
			else substring( ProductFamily, 8, len(ProductFamily)-7 )
			end
		, 'Enter Top 3 Engine (ENG) versions, by default the most recent values are loaded' 
		, '{CALL dbo.AVISP_FieldGetDATEng (?,?,?,?)}', ''
		, '', 0 
	from dbo.tmpVerList
	where new = 1

	INSERT ReportUICustPages
	( 	ReportID, RptGroupID
		, Name, Type
		, Prompt, PDesc 
		, Storedproc, dll 
		, WritebackStoredproc, iOptionalPage
	)
	Select
		'DATENG' as ReportID, '' as RptGroupID
		, ProductFamily as Name, 'Parameters' as Type
		, Prompt = case ProductFamily		-- take suffix characters as product family name
			when 'TVD_NC'  then 'Symantec'
			else substring( ProductFamily, 8, len(ProductFamily)-7 )
			end
		, 'Enter compliant DAT/Definition (DAT) and Engine (ENG) versions, by default the most recent values are loaded' 
		, '{CALL dbo.AVISP_FieldGetDATEng (?,?,?,?)}', ''
		, '', 0 
	from dbo.tmpVerList
	where new = 1
	
	-- add individual parm entries
	
	
	--DAT
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DAT', '', ''
		, ProductFamily + 'DAT1' as Name, '', ''
		, '(DAT) - 1', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DAT', '', ''
		, ProductFamily + 'DAT2' as Name, '', ''
		, '(DAT) - 2', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DAT', '', ''
		, ProductFamily + 'DAT3' as Name, '', ''
		, '(DAT) - 3', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DAT', '', ''
		, ProductFamily + 'DAT4' as Name, '', ''
		, '(DAT) - 4', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DAT', '', ''
		, ProductFamily + 'DAT5' as Name, '', ''
		, '(DAT) - 5', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	-- ENG
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'ENG', '', ''
		, ProductFamily + 'Engine1' as Name, '', ''
		, '(ENG) - 1', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'ENG', '', ''
		, ProductFamily + 'Engine2' as Name, '', ''
		, '(ENG) - 2', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'ENG', '', ''
		, ProductFamily + 'Engine3' as Name, '', ''
		, '(ENG) - 3', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	-- DATENG
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DATENG', '', ''
		, ProductFamily + 'DAT1DE' as Name, '', ''
		, '(DAT)', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1
	
	INSERT ReportInputParameters 
	( 	ReportID, RptGroupID, ReportSavedSettingsName
		, ParmName, DBFldName, ParmValue
		, Prompt, PDesc 
		, CustPageName 
		, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
		, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
	)
	select
		'DATENG', '', ''
		, ProductFamily + 'Engine1DE' as Name, '', ''
		, '(ENG)', 'Enter minimum compliant version'
		, ProductFamily as CustPageName
		, 0 ,1 ,0 ,1
		, 0 ,0 ,0 ,0
	from dbo.tmpVerList
	where new = 1



----------------------------------------------------
-- Readd within tab to assure this tab appears at the end


--	Delete ReportUICustPages where RptGrp = 'DatEng' and Name = 'Within'

--	INSERT ReportUICustPages
--	( 	ReportID, RptGroupID
--		, Name, Type
--		, Prompt, PDesc 
--		, Storedproc, dll 
--		, WritebackStoredproc, iOptionalPage
--	)
--	VALUES(
--		@Reportid, 'DatEng'
--		, 'Within', 'Parameters'
--		, 'Within', ''
--		, '{CALL dbo.AVISP_FieldGetDATEng (?,?,?,?)}', ''
--		, '', 0
--	)
	
	


-- within tab added
--------------------------------------------------

end
-- new product tab added


drop table dbo.tmpVerList

end

return @ret
END
GO




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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_ReportParmLoadProductSettingMonitor
(
 @szOptionalReportParms  VARCHAR(500)
)
AS
BEGIN

/*AVISP_ReportParmLoadProductSettingMonitor*/
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(50)
   Declare @szReportID VARCHAR(50)
   Declare @szRptGroup VARCHAR(50)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


   SELECT 	@szDefaultLang = DefaultLanguageID 
      FROM	ReportLanguageID
      WHERE	ActualLanguageID = @szFullLang


   /* determine language to use */
        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szDefaultLang

        select @szLanguageID=LanguageID from ReportTextPromptStrings where LanguageID = @szFullLang


 
IF @szReportID = 'PROPERTYSETTINGISSUES'
BEGIN

-- Check for any new products that need to have their settings loaded in the report metadata tables

------------------------------
-- Property Settings Issues Report
-- ReportInputParameters table
-- Create these inputs dynamically for now

--truncate table ReportPropertySettings 
--GO


-- Does Groupshield and webshield pass product settings over to epo?


Declare @cnt int

--------------------------------------------------------------------
-- Check for Netshield - load only once

select @cnt=count(*)
from ReportPropertySettings
where Product = 'NetShield'

IF @cnt = 0
BEGIN

INSERT ReportPropertySettings 
select 'NetShield' as product
, productcode
, 'NetShield' + ':' + sectionname + ':' + settingname as ParmName
, sectionname
, settingname
from productsettings, productproperties
where productproperties.autoid = productsettings.parentid
and (productcode like 'NETSHLD%')
group by productcode, sectionname, settingname
having max(value) = '1' or max(value) = '0'
order by productcode, sectionname, settingname


INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'PROPERTYSETTINGISSUES', '' 
, 'NetShield' + ':' + sectionname + ':' + settingname as ParmName, '', ''
, sectionname + ':' + settingname as Prompt, 'Setting for NetShield: ' + sectionname + ', ' + settingname as PDesc
, 'NetShield'
, 0, 1, 0, 0
, 0, 0, 1, 0
from ReportPropertySettings
where 
	product = 'NetShield'
group by product, sectionname, settingname

END

------------------------------------------------------------------------------------
-- Check for VirusScan - Load only once

select @cnt=count(*)
from ReportPropertySettings
where Product = 'VirusScan'

IF @cnt = 0
BEGIN

INSERT ReportPropertySettings 
select 
'VirusScan' as product
, productcode
, 'VirusScan' + ':' + sectionname + ':' + settingname as ParmName
, sectionname
, settingname
from productsettings, productproperties
where productproperties.autoid = productsettings.parentid
and (productcode like 'VIRUSCAN%')
and productcode != 'VIRUSCAN4000WNTW'
group by productcode, sectionname, settingname
having max(value) = '1' or max(value) = '0'
order by productcode, sectionname, settingname


INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'PROPERTYSETTINGISSUES' as ReportID, '' as RptGroupID 
, 'VirusScan' + ':' + sectionname + ':' + settingname as ParmName, '' as DBFldName, '' as ParmValue
, sectionname + ':' + settingname as Prompt, 'Setting for VirusScan: ' + sectionname + ', ' + settingname as PDesc
, 'VirusScan'
, 0, 1, 0, 0
, 0, 0, 1, 0
from ReportPropertySettings
where 
	product = 'VirusScan'
group by product, sectionname, settingname


-- Divide Virusscan parms into groups by scan type


UPDATE ReportInputParameters 
SET CustPageName = 'VirusScanEmail'
WHERE 
	CustPageName = 'VirusScan'
	AND Prompt like 'Email%'


UPDATE ReportInputParameters 
SET CustPageName = 'VirusScanDownload'
WHERE 
	CustPageName = 'VirusScan'
	AND Prompt like 'Download%'



UPDATE ReportInputParameters 
SET CustPageName = 'VirusScanInet'
WHERE 
	CustPageName = 'VirusScan'
	AND Prompt like 'Inet%'

END

----------------------------------------------------------------------------
-- Check for Norton - load only once

select @cnt=count(*)
from ReportPropertySettings
where Product = 'NortonAV'

IF @cnt = 0
BEGIN

INSERT ReportPropertySettings 
select 
'NortonAV' as product
, productcode
, 'NortonAV' + ':' + sectionname + ':' + settingname as ParmName
, sectionname
, settingname
from productsettings, productproperties
where productproperties.autoid = productsettings.parentid
and (productcode like 'NORTONAV%')
group by productcode, sectionname, settingname
having max(value) = '1' or max(value) = '0'
order by productcode, sectionname, settingname



INSERT ReportInputParameters 
( 	ReportID, RptGroupID
	, ParmName, DBFldName, ParmValue
	, Prompt, PDesc 
	, CustPageName 
	, iType, iSaveUserEntry, iDefaultFlag ,iUseDefault
	, iCrystalParm, iCrystalFieldCust, iLocalizedField, iDBField 
)
select 'PROPERTYSETTINGISSUES', '' 
, 'NortonAV' + ':' + sectionname + ':' + settingname as ParmName, '', ''
, sectionname + ':' + settingname as Prompt, 'Setting for NortonAV: ' + sectionname + ', ' + settingname as PDesc
, 'NetShield'
, 0, 1, 0, 0
, 0, 0, 1, 0
from ReportPropertySettings
where 
	product = 'NortonAV'
group by product, sectionname, settingname

END


END

return 0

END
GO



----------------------------------------------------------------
----------------------------------------------------------------
--  AVISP_GetRuleDATEngine
--  vs7.5 handle new buffer overflow signature version

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO

CREATE PROCEDURE dbo.AVISP_GetRuleDATEngine
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/
 /* Shows AV installs and computers having no AV */

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 Declare @ret int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
     

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'

   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT

 -------------------------------------------------------------
 -- fetch dat engine rules

 IF EXISTS (select * from sysobjects where name = 'tmpProductFamily' 
   and xtype = 'U')
  DROP TABLE dbo.tmpProductFamily

 select distinct ProductFamily into dbo.tmpProductFamily from AVIView_Software 


 IF EXISTS (select * from sysobjects where name = 'tmpDATEngRules' 
   and xtype = 'U')
  DROP TABLE dbo.tmpDATEngRules


 select
	cast('test' as nvarchar(20)) as Rulename
	, cast('test' as nvarchar(20)) as ProductFamily
	, cast('test' as nvarchar(20))  as DAT1
	, cast('test' as nvarchar(20))  as DAT2
	, cast('test' as nvarchar(20))  as DAT3
	, cast('test' as nvarchar(20))  as DAT4
	, cast('test' as nvarchar(20))  as DAT5
	, cast('' as nvarchar(30)) as Eng1
	, cast('' as nvarchar(30)) as Eng2
	, cast('' as nvarchar(30)) as Eng3
	, cast('' as nvarchar(30)) as DAT1DE
	, cast('' as nvarchar(30)) as Eng1DE
 into dbo.tmpDATEngRules


-- default
--if @szOptionalReportParms = ''
--Begin
--select * from dbo.tmpDERules

if @szReportID = 'DAT'
begin

-- truncate table dbo.tmpDATEngRules
 -- dat rules
 insert dbo.tmpDATEngRules
 select
	cast('DAT' as nvarchar(20)) as Rulename
	, cast(ProductFamily as nvarchar(20)) as ProductFamily
	, cast(ParmValue as nvarchar(20))  as DAT1
	, cast(ParmValue as nvarchar(20))  as DAT2
	, cast(ParmValue as nvarchar(20))  as DAT3
	, cast(ParmValue as nvarchar(20))  as DAT4
	, cast(ParmValue as nvarchar(20))  as DAT5
	, cast('' as nvarchar(30)) as Eng1
	, cast('' as nvarchar(30)) as Eng2
	, cast('' as nvarchar(30)) as Eng3
	, cast('' as nvarchar(30)) as DAT1DE
	, cast('' as nvarchar(30)) as Eng1DE
-- into dbo.tmpDATEngRules
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DAT'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT1'


 update dbo.tmpDATEngRules
 set DAT2 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DAT'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT2'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'DAT'

 update dbo.tmpDATEngRules
 set DAT3 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DAT'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT3'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'DAT'

 update dbo.tmpDATEngRules
 set DAT4 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DAT'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT4'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'DAT'

 update dbo.tmpDATEngRules
 set DAT5 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DAT'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT5'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'DAT'

end
else
if @szReportID = 'ENG'
begin

 -- eng rules
 insert dbo.tmpDATEngRules
 select
	'ENG' as Rulename
	, ProductFamily
	, cast('' as nvarchar(30)) as DAT1
	, cast('' as nvarchar(30)) as DAT2
	, cast('' as nvarchar(30)) as DAT3
	, cast('' as nvarchar(30)) as DAT4
	, cast('' as nvarchar(30)) as DAT5
	, ParmValue as Eng1
	, ParmValue as Eng2
	, ParmValue as Eng3
	, cast('' as nvarchar(30)) as DAT1DE
	, cast('' as nvarchar(30)) as Eng1DE
-- into dbo.tmpDATEngRules
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'ENG'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'Engine1'


 update dbo.tmpDATEngRules
 set Eng2 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'ENG'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'Engine2'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'ENG'

 update dbo.tmpDATEngRules
 set Eng3 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'ENG'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'Engine3'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'ENG'

end
else
if @szReportID = 'DATENG'
begin

 -- dateng rules
 insert dbo.tmpDATEngRules
 select
	'DATENG' as Rulename
	, ProductFamily
	, cast('' as nvarchar(30)) as DAT1
	, cast('' as nvarchar(30)) as DAT2
	, cast('' as nvarchar(30)) as DAT3
	, cast('' as nvarchar(30)) as DAT4
	, cast('' as nvarchar(30)) as DAT5
	, cast('' as nvarchar(30)) as Eng1
	, cast('' as nvarchar(30)) as Eng2
	, cast('' as nvarchar(30)) as Eng3
	, ParmValue as DAT1DE
	, ParmValue as Eng1DE
-- into dbo.tmpDATEngRules
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DATENG'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'DAT1DE'


 update dbo.tmpDATEngRules
 set Eng1DE = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'DATENG'
  	and ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'Engine1DE'
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'DATENG'

End


if @szOptionalReportParms = 'PRODPROPDAT'
Begin

 -- vs7.5 buffer overflow dat rules
-- insert dbo.tmpDATEngRules
 insert dbo.tmpDATEngRules
 select
	cast('BFDAT' as nvarchar(20)) as Rulename
	, cast(ProductFamily as nvarchar(20)) as ProductFamily
	, cast(ParmValue as nvarchar(20))  as DAT1
	, cast(ParmValue as nvarchar(20))  as DAT2
	, cast(ParmValue as nvarchar(20))  as DAT3
	, cast('' as nvarchar(20))  as DAT4
	, cast('' as nvarchar(20))  as DAT5
	, cast('' as nvarchar(30)) as Eng1
	, cast('' as nvarchar(30)) as Eng2
	, cast('' as nvarchar(30)) as Eng3
	, cast('' as nvarchar(30)) as DAT1DE
	, cast('' as nvarchar(30)) as Eng1DE
-- into dbo.tmpDATEngRules
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'BFDAT'
  	and 
	(
		ReportInputParameters.ParmName = dbo.tmpProductFamily.ProductFamily + 'szBufferOverflowDAT1'
	)

 update dbo.tmpDATEngRules
 set DAT2 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'BFDAT'
  	and ReportInputParameters.ParmName in ('TVDszBufferOverflowDAT2')
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'BFDAT'

 update dbo.tmpDATEngRules
 set DAT3 = ParmValue
 from 	ReportInputParameters, dbo.tmpProductFamily 
 where
	ReportInputParameters.ReportID = 'BFDAT'
  	and ReportInputParameters.ParmName in ('TVDszBufferOverflowDAT3')
	and dbo.tmpProductFamily.ProductFamily = dbo.tmpDATEngRules.productFamily
	and dbo.tmpDATEngRules.Rulename = 'BFDAT'

End

 -- dump output
 select * from dbo.tmpDATEngRules
 set @ret = @@rowcount

 -- cleanup
 Drop Table dbo.tmpProductFamily
 Drop Table dbo.tmpDATEngRules

-- debug only
--select * from dbo.tmpDATEngRules
--select @szReportID

Return @ret
end
GO


---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
-- epo3.0 added nodeid for subreport drilldown (filteravinstalls got this too)
-- epo3.0 added dynamic recognition of new scanning products dat & engines: TVD_NC_%
-- vs7.5 handle new buffer overflow signature (DAT) version

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

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_FilterDATEngine
(
 @iNameSpaceName  VARCHAR(20),
 @iNameSpaceNode  VARCHAR(20),
 @szEpoUserName  VARCHAR(100),
 @szNameSpaceName  VARCHAR(100),
 @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @ConnectAfterYYYYMMDD varchar(30) = ''
 , @ConnectAfterRule varchar(30) = 'All'
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/
 /* Shows AV installs and computers having no AV */

      /* Get ID to filter on: Users top node, user selected filter node (< top node), */
 /*    or no filtering (0) if users top node = root node and no filter selected */
 Declare @UsersTopNodeID int
 Declare @FilterNodeID int
 Declare @ret int
 select @UsersTopNodeID = convert(int, @iNameSpaceName)
 select @FilterNodeID = convert(int, @iNameSpaceNode)

 Declare @FilterID int
 EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
     

	/* Stored procedure to recreate table of nodepaths and node ids */
	/* This table persists and is recreated each time the report runs */
-- epo3.5 no longer need to call this because the ReportFullPathNodeID table is maintained real time
--	Execute AVISP_CalculateAllSubNodes 0, 0, '', 'GenerateOutputTable'


  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szOPFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'

   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szOPFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


	-- Fetch Infect After date variables
	Declare @YYYYMMDD char(30)	
	Declare @YYYYMMDDdate datetime
	execute dbo.AVISP_GetDateConversion @ConnectAfterYYYYMMDD, @ConnectAfterRule, @YYYYMMDDdate output

	set @YYYYMMDD = Replace( Replace( Replace( convert(char(30), @YYYYMMDDdate,120), '-', ''), ':', ''), ' ', '')
	if @YYYYMMDD is null
		set @YYYYMMDD = ''

	-- If no data exists in ReportComplianceComparison table then run routine to fill it
	-- Do this so that there is data in the compliance subreports
	Declare @dtInfectionCheckPoint DateTime
	Set @dtInfectionCheckPoint = DateAdd( day, -1, GetDate())
	if not exists ( select * from ReportComplianceComparison )
		Execute dbo.AVISP_SetComplianceComparison
			 @iNameSpaceName  
			 , @iNameSpaceNode  
			 , @szEpoUserName  
			 , @szOptionalReportParms  
			 , @dtInfectionCheckPoint 



	------------------------------
	-- read in translated terms
   	Declare @Current varchar(30)			
   	Declare @Late varchar(30)			
   	Declare @Agent varchar(30)			
   	Declare @SuperAgentBroadcast varchar(100)	
   	Declare @SuperAgentRepository varchar(100)	
   	Declare @Unprotected varchar(30)		
   	Declare @Unlinked varchar(30)			
   	Declare @NoAgent varchar(30)			
   	Declare @Server varchar(50)			
   	Declare @WorkStation varchar(50)			
	Declare @Professional varchar(50)	

	If @Current = '' or @Current is null				-- if first is not found assume they all are
	Begin
   		Set @Current = 'Current'	Set @Late = 'Late'	Set @Agent = 'Agent'
   		Set @SuperAgentBroadcast = 'Super Agent Broadcast'	Set @SuperAgentRepository = 'Super Agent Repository'
		Set @Unprotected = 'Unprotected'	Set @Unlinked = 'Unlinked'	Set @NoAgent = 'No Agent'
   		Set @Server = 'Server'	Set @WorkStation = 'Workstation'	
		Set @Professional = 'Professional'
	End

	-- if not english, read in translations
	if @szFullLang <> '0409' 
--		and @szFullLang <> '0411'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0412'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0404'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0804'  -- apac chars dont display in charts, keep this english
	Begin
		Select 	@Current = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Current'
		Select 	@Late = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Late'
		Select 	@Agent = 'Agent'
		Select 	@SuperAgentBroadcast = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentBroadcast'
		Select 	@SuperAgentRepository = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentRepository'
		Select 	@Unprotected = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unprotected'
		Select 	@NoAgent = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'NoAgent'
		Select 	@Unlinked = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unlinked'
		Select 	@Server = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Server'
		Select 	@WorkStation = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'WorkStation'
		Select 	@Professional = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Professional'
	End
	

	

 -------------------------------------------------------------
 -- fetch dat engine rules


	IF EXISTS (select * from sysobjects where name = 'tmpDERules' 
	   and xtype = 'U')
	 DROP TABLE dbo.tmpDERules
	
	create table dbo.tmpDERules
	(
		RuleName nvarchar(50) null
		,ProductFamily nvarchar(50) null
		,DAT1 nvarchar(100) null
		,DAT2 nvarchar(100) null
		,DAT3 nvarchar(100) null
		,DAT4 nvarchar(100) null
		,DAT5 nvarchar(100) null
		,Eng1 nvarchar(100) null
		,Eng2 nvarchar(100) null
		,Eng3 nvarchar(100) null
		,DAT1DE nvarchar(100) null
		,Eng1DE nvarchar(100) null
	)

	if @szReportID = 'DAT' or @szReportID = 'ENG' or @szReportID = 'DATENG'
		insert dbo.tmpDERules
		exec @ret= dbo.AVISP_GetRuleDATEngine
		 @iNameSpaceName  = ''
		 ,@iNameSpaceNode = ''
		 ,@szEpoUserName  = ''
		 ,@szNameSpaceName  = ''
		 ,@szNameSpaceNode  = ''
		 ,@szOptionalReportParms  = @szOptionalReportParms


-- debug only
--select * from dbo.tmpDERules
--select @szReportID

 --------------------------------------------------------------
 -- Start main queries

--select * from dbo.tmpDERules
 if @szReportID = 'DAT'
 begin

 -- DAT report 
 SELECT

   	RuleName = 
	CASE 
	when DATVer >=  dbo.tmpDERules.DAT1 then 'Current or Newer'
	when DATVer >=  dbo.tmpDERules.DAT2 then 'Out of Date 1 Version'
	when DATVer >=  dbo.tmpDERules.DAT3 then 'Out of Date 2 Versions'
	when DATVer >=  dbo.tmpDERules.DAT4 then 'Out of Date 3 Versions'
	when DATVer >=  dbo.tmpDERules.DAT5 then 'Out of Date 4 Versions'
	when DATVer <  dbo.tmpDERules.DAT5   then 'Out of Date 5 or More Versions'
     	when DATVer = 'N/A' then '---'
 	else Case
			When LeafNode.AgentVersion > '' Then 'Unprotected'
			Else 'Uninstalled Agent'
			End 
	end	
	, '' as RuleDescription
   	, ReportFullPathNodeID.NodeName AS NodeName
	, cast(ReportFullPathNodeID.FullPathShortName as varchar(255)) as FullNodePath
   	, LeafNode.AgentVersion
   	, Case
		When AVIView_Software.SoftwareName > '' then AVIView_Software.SoftwareName
		else	Case
			When LeafNode.AgentVersion > '' Then @Unprotected 
			Else @NoAgent
			End 
		End as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion 
     		ELSE '---'
     		END
   	, EngineVer =
    		CASE  
     		WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer
     		WHEN ProductProperties.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
  	 , DATVer =
    		CASE  
     		WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer
     		WHEN ProductProperties.DATVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, ExtraDATNames =
    		CASE ProductProperties.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ProductProperties.ExtraDATNames 
     		END
	,    ProductFamily =
    		CASE 
     		WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     		WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     		ELSE  AVIView_Software.ProductFamily 
     		END
	, ComputerProperties.DomainName
--	postepo3 - make sure leafnode.nodename used for computername if computerprop entry not existong (NoAgent)
--	epo3.5 - Due to Netware multiple computername issue, always use LN.nodename for computername
	, LeafNode.NodeName as ComputerName
--	, Case
--		When ComputerProperties.ComputerName > '' then ComputerProperties.ComputerName
--		else	LeafNode.NodeName
--		End as ComputerName
--	, ComputerProperties.ComputerName  -- Use leafnode nodename for noagent since they usually dont have computer props
	, ComputerProperties.IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, ComputerProperties.UserName
--    	, CAST('' As varchar(255)) As FileName
  	, '' as FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
   	, RuleNumber = 
		CASE 
		when DATVer >=  dbo.tmpDERules.DAT1 then 0
		when DATVer >=  dbo.tmpDERules.DAT2 then 1
		when DATVer >=  dbo.tmpDERules.DAT3 then 2
		when DATVer >=  dbo.tmpDERules.DAT4 then 3
		when DATVer >=  dbo.tmpDERules.DAT5 then 4
		when DATVer <  dbo.tmpDERules.DAT5   then 5
  	   	when DATVer = 'N/A' then 6
 		else Case
			When LeafNode.AgentVersion > '' Then 7
			Else 8
			End 
		end	
--	, 1 as RuleNumber
	, LeafNode.LastUpdate as LastContact
     	, cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
		+ ' ' + ComputerProperties.OSPlatform) 
        	as varchar(50)) as OSVersion
   	,  LeafNode.AutoID as NodeID
	, Servicepack
	, Hotfix
    	, AVIView_Software.ProductCode
	, '' as Language

		,case 
			when ComputerProperties.OSPlatform = 'Server' then @Server
			when ComputerProperties.OSPlatform = 'Workstation' then @Workstation
			when ComputerProperties.OSPlatform = 'Professional' then @Professional
			else ComputerProperties.OSPlatform
			end 
			as OSPlatform
	, ComputerProperties.OSType



 FROM 
	(LeafNode Join ReportFullPathNodeID on(LeafNode.ParentID = ReportFullPathNodeID.LowestNodeID
		  and (LeafNode.LastUpdate  >=  @YYYYMMDD or LeafNode.LastUpdate = '' or LeafNode.LastUpdate is null)
		   AND LeafNode.Type !=24  )    /* Uninstalled */ 
		left outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
--		Join ReportFullPathNodeID on (BranchNode.AutoID = ReportFullPathNode.LowestNodeID)
	)
   	left outer Join
   	(ProductProperties 
		Join 
		( AVIView_Software 
		  Join dbo.tmpDERules on (dbo.tmpDERules.ProductFamily = AVIView_Software.ProductFamily
			  			AND dbo.tmpDERules.Rulename = @szReportID  
						and dbo.tmpDERules.DAT1 > '' )
		) on (ProductProperties.ProductCode = AVIView_Software.ProductCode and DATVer != '5000')
	)
	on( leafnode.autoid = productproperties.parentid )  -- run only for dat report

 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   and @szReportID = 'DAT'


 end
 
 else if @szReportID = 'ENG'

 begin

-- UNION ALL

 -- Eng report 
 SELECT
   	RuleName = 
	CASE 
	when EngineVer >=  dbo.tmpDERules.Eng1 then 'Current or Newer'
	when EngineVer >=  dbo.tmpDERules.Eng2 then 'Out of Date 1 Version'
	when EngineVer >=  dbo.tmpDERules.Eng3 then 'Out of Date 2 Versions'
	when EngineVer <  dbo.tmpDERules.Eng3   then 'Out of Date 3 or More Versions'
     	when EngineVer = 'N/A' then '---'
 	else Case
			When LeafNode.AgentVersion > '' Then 'Unprotected'
			Else 'Uninstalled Agent'
			End 
	end	
	, '' as RuleDescription
   	, ReportFullPathNodeID.NodeName AS NodeName
	, cast(ReportFullPathNodeID.FullPathShortName as varchar(255)) as FullNodePath
   	, LeafNode.AgentVersion
   	, Case
		When AVIView_Software.SoftwareName > '' then AVIView_Software.SoftwareName
		else	Case
			When LeafNode.AgentVersion > '' Then @Unprotected 
			Else @NoAgent
			End 
		End as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion 
     		ELSE '---'
     		END
   	, EngineVer =
    		CASE  
     		WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer
     		WHEN ProductProperties.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
  	 , DATVer =
    		CASE  
     		WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer
     		WHEN ProductProperties.DATVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, ExtraDATNames =
    		CASE ProductProperties.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ProductProperties.ExtraDATNames 
     		END
	,    ProductFamily =
    		CASE 
     		WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     		WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     		ELSE  AVIView_Software.ProductFamily 
     		END
	, ComputerProperties.DomainName
--	postepo3 - make sure leafnode.nodename used for computername if computerprop entry not existong (NoAgent)
--	epo3.5 - Due to Netware multiple computername issue, always use LN.nodename for computername
	, LeafNode.NodeName as ComputerName
--	, Case
--		When ComputerProperties.ComputerName > '' then ComputerProperties.ComputerName
--		else	LeafNode.NodeName
--		End as ComputerName
--	, ComputerProperties.ComputerName  -- Use leafnode nodename for noagent since they usually dont have computer props
	, ComputerProperties.IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, ComputerProperties.UserName
--    	, CAST('' As varchar(255)) As FileName
  	, '' as FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
   	, RuleNumber = 
		CASE 
		when EngineVer >=  dbo.tmpDERules.Eng1 then 0
		when EngineVer >=  dbo.tmpDERules.Eng2 then 1
		when EngineVer >=  dbo.tmpDERules.Eng3 then 2
		when EngineVer <  dbo.tmpDERules.Eng3   then 13
   	  	when EngineVer = 'N/A' then 6
 		else Case
			When LeafNode.AgentVersion > '' Then 7
			Else 8
			End 
		end	
--	, 1 as RuleNumber
	, LeafNode.LastUpdate as LastContact
     	, cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
		+ ' ' + ComputerProperties.OSPlatform) 
        	as varchar(50)) as OSVersion
   	,  LeafNode.AutoID as NodeID
	, Servicepack
	, Hotfix
    	, AVIView_Software.ProductCode
	, '' as Language

		,case 
			when ComputerProperties.OSPlatform = 'Server' then @Server
			when ComputerProperties.OSPlatform = 'Workstation' then @Workstation
			when ComputerProperties.OSPlatform = 'Professional' then @Professional
			else ComputerProperties.OSPlatform
			end 
			as OSPlatform
	, ComputerProperties.OSType


 FROM
	(LeafNode Join ReportFullPathNodeID on(LeafNode.ParentID = ReportFullPathNodeID.LowestNodeID
		  and (LeafNode.LastUpdate  >=  @YYYYMMDD or LeafNode.LastUpdate = '' or LeafNode.LastUpdate is null)
		   AND LeafNode.Type !=24  )    /* Uninstalled */ 
		left outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
--		Join ReportFullPathNode on (BranchNode.AutoID = ReportFullPathNode.LowestNodeID)
	)
   	left outer Join
   	(ProductProperties 
		Join 
		( AVIView_Software 
			Join dbo.tmpDERules on (dbo.tmpDERules.ProductFamily = AVIView_Software.ProductFamily
			  	AND dbo.tmpDERules.Rulename = @szReportID  and dbo.tmpDERules.Eng1 > '' )
		) on (ProductProperties.ProductCode = AVIView_Software.ProductCode AND DATVer != '5000')
	)
	on( leafnode.autoid = productproperties.parentid )  -- run only for dat report
 
 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   and @szReportID = 'ENG'


 end

 else if @szReportID = 'DATENG'
 begin

-- UNION ALL

 -- DATEng report 

  SELECT
   	RuleName = 
	CASE 
	when (EngineVer >=  dbo.tmpDERules.Eng1DE and DATVer >=  dbo.tmpDERules.DAT1DE) then 'Current or Newer'
	when (EngineVer <  dbo.tmpDERules.Eng1DE and DATVer >=  dbo.tmpDERules.DAT1DE) then 'Out of Date Engine'
	when (EngineVer >=  dbo.tmpDERules.Eng1DE and DATVer <  dbo.tmpDERules.DAT1DE) then 'Out of Date DAT'
	when (EngineVer <  dbo.tmpDERules.Eng1DE and DATVer <  dbo.tmpDERules.DAT1DE) then 'Out of Date Engine and DAT'
	else Case
		When LeafNode.AgentVersion > '' Then 'Unprotected' 
		Else 'UninstalledAgent'
		End 
	end	--as RuleName
	, '' as RuleDescription
   	, ReportFullPathNodeID.NodeName AS NodeName
	, cast(ReportFullPathNodeID.FullPathShortName as varchar(255)) as FullNodePath
   	, LeafNode.AgentVersion
   	, Case
		When AVIView_Software.SoftwareName > '' then AVIView_Software.SoftwareName
		else	Case
			When LeafNode.AgentVersion > '' Then @Unprotected 
			Else @NoAgent
			End 
		End as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion 
     		ELSE '---'
     		END
   	, EngineVer =
    		CASE  
     		WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer
     		WHEN ProductProperties.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
  	 , DATVer =
    		CASE  
     		WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer
     		WHEN ProductProperties.DATVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, ExtraDATNames =
    		CASE ProductProperties.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ProductProperties.ExtraDATNames 
     		END
	,    ProductFamily =
    		CASE 
     		WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     		WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     		ELSE  AVIView_Software.ProductFamily 
     		END
	, ComputerProperties.DomainName
--	postepo3 - make sure leafnode.nodename used for computername if computerprop entry not existong (NoAgent)
--	epo3.5 - Due to Netware multiple computername issue, always use LN.nodename for computername
	, LeafNode.NodeName as ComputerName
--	, Case
--		When ComputerProperties.ComputerName > '' then ComputerProperties.ComputerName
--		else	LeafNode.NodeName
--		End as ComputerName
--	, ComputerProperties.ComputerName  -- Use leafnode nodename for noagent since they usually dont have computer props
	, ComputerProperties.IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, ComputerProperties.UserName
--    	, CAST('' As varchar(255)) As FileName
  	, '' as FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
   	, RuleNumber = 
		CASE 
		when (EngineVer >=  dbo.tmpDERules.Eng1DE and DATVer >=  dbo.tmpDERules.DAT1DE) then 0
		when (EngineVer <  dbo.tmpDERules.Eng1DE and DATVer >=  dbo.tmpDERules.DAT1DE) then 21
		when (EngineVer >=  dbo.tmpDERules.Eng1DE and DATVer <  dbo.tmpDERules.DAT1DE) then 22
		when (EngineVer <  dbo.tmpDERules.Eng1DE and DATVer <  dbo.tmpDERules.DAT1DE) then 23
 		else Case
			When LeafNode.AgentVersion > '' Then 7
			Else 8
			End 
		end	
--	, 1 as RuleNumber
	, LeafNode.LastUpdate as LastContact
     	, cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
		+ ' ' + ComputerProperties.OSPlatform) 
        	as varchar(50)) as OSVersion
   	,  LeafNode.AutoID as NodeID
	, Servicepack
	, Hotfix
    	, AVIView_Software.ProductCode
	, '' as Language
		,case 
			when ComputerProperties.OSPlatform = 'Server' then @Server
			when ComputerProperties.OSPlatform = 'Workstation' then @Workstation
			when ComputerProperties.OSPlatform = 'Professional' then @Professional
			else ComputerProperties.OSPlatform
			end 
			as OSPlatform
	, ComputerProperties.OSType

 FROM 
	(LeafNode Join ReportFullPathNodeID on(LeafNode.ParentID = ReportFullPathNodeID.LowestNodeID
		  and (LeafNode.LastUpdate  >=  @YYYYMMDD or LeafNode.LastUpdate = '' or LeafNode.LastUpdate is null)
		   AND LeafNode.Type !=24  )    /* Uninstalled */ 
		left outer Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
--		Join ReportFullPathNode on (BranchNode.AutoID = ReportFullPathNode.LowestNodeID)
	)
   	left outer Join
   	(ProductProperties 
		Join 
		( AVIView_Software 
			Join dbo.tmpDERules on (dbo.tmpDERules.ProductFamily = AVIView_Software.ProductFamily
			  AND dbo.tmpDERules.Rulename = @szReportID  and dbo.tmpDERules.DAT1DE > '')
		) on (ProductProperties.ProductCode = AVIView_Software.ProductCode AND DATVer != '5000')
	)
	on( leafnode.autoid = productproperties.parentid )  -- run only for dat report


 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
   and @szReportID = 'DATENG'

  end

  else if @szReportID = 'BFDAT'
  begin

	-- get dat rules
	insert dbo.tmpDERules
	exec @ret= dbo.AVISP_GetRuleDATEngine
	 @iNameSpaceName  = ''
	 ,@iNameSpaceNode = ''
	 ,@szEpoUserName  = ''
	 ,@szNameSpaceName  = ''
	 ,@szNameSpaceNode  = ''
	 ,@szOptionalReportParms  = 'PRODPROPDAT'

 -- Run a pass to determine which productcodes should have a dat of this type
	IF EXISTS (select * from sysobjects where name = 'tmpBFProdCodes' 
	   and xtype = 'U')
	 DROP TABLE dbo.tmpBFProdCodes
	
	Select
		distinct ProductCode as ProductCode
		Into dbo.tmpBFProdCodes
		From ProductSettings, ProductProperties
		where ProductSettings.ParentID = ProductProperties.AutoID
					and SectionName = 'General' 
					and SettingName in ('szBufferOverflowDAT')

	

 -- vs7.5 Buffer Overflow DAT report 
 SELECT

   	RuleName = 
	CASE 
	when ProductSettings.Value >=  dbo.tmpDERules.DAT1 then 'Current or Newer'
	when ProductSettings.Value >=  dbo.tmpDERules.DAT2 then 'Out of Date 1 Version'
	when ProductSettings.Value >=  dbo.tmpDERules.DAT3 then 'Out of Date 2 Versions'
--	when ProductSettings.Value >=  dbo.tmpDERules.DAT4 then 'Out of Date 3 Versions'
--	when ProductSettings.Value >=  dbo.tmpDERules.DAT5 then 'Out of Date 4 Versions'
	when ProductSettings.Value <  dbo.tmpDERules.DAT3   then 'Out of Date 3 or More Versions'
     	when ProductSettings.Value = 'N/A' then '---'
 	else Case
			When LeafNode.AgentVersion > '' Then 'Unprotected'
			Else 'Uninstalled Agent'
			End 
	end	
	, '' as RuleDescription
   	, ReportFullPathNodeID.NodeName AS NodeName
	, cast(ReportFullPathNodeID.FullPathShortName as varchar(255)) as FullNodePath
   	, LeafNode.AgentVersion
   	, Case
		When AVIView_Software.SoftwareName > '' then AVIView_Software.SoftwareName
		else	Case
			When LeafNode.AgentVersion > '' Then @Unprotected 
			Else @NoAgent
			End 
		End as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion 
     		ELSE '---'
     		END
	, '' as EngineVer
--   	, EngineVer =
--    		CASE  
--     		WHEN ProductProperties.EngineVer > '' and ProductProperties.DATVer > '' 
--			THEN ProductProperties.EngineVer + ' | ' + ProductProperties.DATVer + ' | '
--     		WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer + ' | '
--     		WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer + ' | '
--     		ELSE '---'
--     		END
  	 , DATVer =
    		CASE  
     		WHEN ProductSettings.Value > '' THEN ProductSettings.Value
     		WHEN ProductSettings.Value = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, '' as ExtraDATNames
	,    ProductFamily =
    		CASE 
     		WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     		WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     		ELSE  AVIView_Software.ProductFamily 
     		END
	, ComputerProperties.DomainName
--	postepo3 - make sure leafnode.nodename used for computername if computerprop entry not existong (NoAgent)
--	epo3.5 - Due to Netware multiple computername issue, always use LN.nodename for computername
	, LeafNode.NodeName as ComputerName
--	, Case
--		When ComputerProperties.ComputerName > '' then ComputerProperties.ComputerName
--		else	LeafNode.NodeName
--		End as ComputerName
--	, ComputerProperties.ComputerName  -- Use leafnode nodename for noagent since they usually dont have computer props
	, ComputerProperties.IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, ComputerProperties.UserName
--    	, CAST('' As varchar(255)) As FileName
  	, '' as FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
   	, RuleNumber = 
		CASE 
		when ProductSettings.Value >=  dbo.tmpDERules.DAT1 then 0
		when ProductSettings.Value >=  dbo.tmpDERules.DAT2 then 1
		when ProductSettings.Value >=  dbo.tmpDERules.DAT3 then 2
--		when ProductSettings.Value >=  dbo.tmpDERules.DAT4 then 3
--		when ProductSettings.Value >=  dbo.tmpDERules.DAT5 then 4
		when ProductSettings.Value <  dbo.tmpDERules.DAT3   then 13
  	   	when ProductSettings.Value = 'N/A' then 6
 		else Case
			When LeafNode.AgentVersion > '' Then 7
			Else 8
			End 
		end	
--	, 1 as RuleNumber
	, LeafNode.LastUpdate as LastContact
     	, cast((ComputerProperties.OSType  + ' ' + ComputerProperties.OSServicePackVer
		+ ' ' + ComputerProperties.OSPlatform) 
        	as varchar(50)) as OSVersion
   	,  LeafNode.AutoID as NodeID
	, Servicepack
	, Hotfix
    	, AVIView_Software.ProductCode
	, '' as Language
		,case 
			when ComputerProperties.OSPlatform = 'Server' then @Server
			when ComputerProperties.OSPlatform = 'Workstation' then @Workstation
			when ComputerProperties.OSPlatform = 'Professional' then @Professional
			else ComputerProperties.OSPlatform
			end 
			as OSPlatform
	, ComputerProperties.OSType



 FROM 
	(
		LeafNode Join ReportFullPathNodeID on(LeafNode.ParentID = ReportFullPathNodeID.LowestNodeID
		  and (LeafNode.LastUpdate  >=  @YYYYMMDD or LeafNode.LastUpdate = '' or LeafNode.LastUpdate is null)
		   AND LeafNode.Type !=24  )    /* Uninstalled */ 
		Join ComputerProperties on(leafnode.autoid = ComputerProperties.parentid)
--		Join ReportFullPathNode on (BranchNode.AutoID = ReportFullPathNode.LowestNodeID)
	   	Join ProductProperties on ( leafnode.autoid = productproperties.parentid )
		Join dbo.tmpBFProdCodes on ( ProductProperties.ProductCode = dbo.tmpBFProdCodes.ProductCode )
		left outer Join AVIView_Software on (ProductProperties.ProductCode = AVIView_Software.ProductCode
		   AND ProductFamily = 'TVD')	
		left outer Join ProductSettings on (ProductProperties.autoid = ProductSettings.parentid
					and SectionName = 'General' 
					and SettingName in ('szBufferOverflowDAT'))
		Join dbo.tmpDERules on (dbo.tmpDERules.ProductFamily = AVIView_Software.ProductFamily
			  		AND dbo.tmpDERules.Rulename = @szReportID  
					and dbo.tmpDERules.DAT1 > '')
	)

 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where BranchNodeEnum.StartAutoID = @FilterID)
   )
and @szReportID = 'BFDAT'
  
Drop Table dbo.tmpBFProdCodes

  end


  set @ret = @@rowcount

--  Drop Table #tmpDATRules
--  Drop Table #tmpEngRules
  Drop Table dbo.tmpDERules


 RETURN @ret
END

GO





/**********  epo3.0 new outbreak recognition procedure *********/

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


CREATE PROCEDURE dbo.AVISP_FilterOutbreakEvents
(
	@iNameSpaceName		VARCHAR(20)
	, @iNameSpaceNode		VARCHAR(20)
    	, @szEpoUserName          	VARCHAR(100)
	, @szNameSpaceName		VARCHAR(100)
	, @szNameSpaceNode		VARCHAR(500)
	, @szMinMachineCount		VARCHAR(20)= '5'
	, @szMinFilenameCount		VARCHAR(20)= '5'
	, @dtStartDate			VARCHAR(50)
	, @szHourRange		VARCHAR(20)='1'
	, @szOptionalReportParms 	 VARCHAR(500) = ''
	, @InfectAfterRule 		varchar(30) = ''

--	, @SaveOutbreakDefn		int=0
--	, @EnableBatchJob		int=0	-- 1 = enable, 2 = disable
--	, @RunasBatchJob		int=0
--	, @UpdateEmailNotification	varchar(100)=''
)
AS
BEGIN
 	/* Copyright + 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

	/* This procedure can run as a report or as a batch job in looking for outbreaks */

 	/* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
	Declare @UsersTopNodeID int
	Declare @FilterNodeID int
	Declare @DayofWeek int
	Declare @iMinMachineCount int		
	Declare @iMinFilenameCount int		
	Declare @iHourRange int	

	-- dont use this as an input parm for now
	Declare @RunasBatchJob int
	IF @szOptionalReportParms = 'BatchModeUpdateTableOnly'
		Set @RunasBatchJob =1
	else
		Set @RunasBatchJob =0

	-- epo3.5 if bad values entered convert to defaults
	if ISNUMERIC(@szMinMachineCount) = 0 or @szMinMachineCount <= '0' 
		set @szMinMachineCount = '5'
	if ISNUMERIC(@szMinFilenameCount) = 0 or @szMinFilenameCount <= '0' 
		set @szMinFilenameCount = '5'
	if ISNUMERIC(@szHourRange) = 0 or @szHourRange <= '0' 
		set @szHourRange = '1'


	select @UsersTopNodeID = convert(int, @iNameSpaceName)
	select @FilterNodeID = convert(int, @iNameSpaceNode)
	select @iMinMachineCount = convert(int, @szMinMachineCount)
	select @iMinFilenameCount = convert(int, @szMinFilenameCount)
	select @iHourRange = convert(int, @szHourRange)

	Declare @FilterID int
	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT
  
	Declare @ret int

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


	-- Fetch Infect After date variables
	Declare @YYYYMMDD datetime
	execute dbo.AVISP_GetDateConversion @dtStartDate, @InfectAfterRule, @YYYYMMDD output


-----------------
-- postepo3 cleanup temp dbs
	IF EXISTS (select * from sysobjects where name = 'tmpOutbreakGroup' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOutbreakGroup

	IF EXISTS (select * from sysobjects where name = 'tmpOutbreakVirus' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOutbreakVirus

	IF EXISTS (select * from sysobjects where name = 'tmpOutbreakStats' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOutbreakStats



	/*************************************************************************************************/
	-- Report Mode - save outbreak definition for Batch Mode processing -- canceled for epo3
/*
	if @SaveOutbreakDefn = 1
	begin
		if exists (select ParmName from ReportInputParametersSaved where ReportID = 'REPORTOUTBREAK' and ParmName = '@iMinMachineCount')
			update ReportInputParametersSaved set ParmValue = @iMinMachineCount where  ReportID = 'REPORTOUTBREAK' and ParmName = '@iMinMachineCount'
		else
			insert ReportInputParametersSaved values( 'REPORTOUTBREAK', '@iMinMachineCount', @iMinMachineCount)

		if exists (select ParmName from ReportInputParametersSaved where ReportID = 'REPORTOUTBREAK' and ParmName = '@iMinFilenameCount')
			update ReportInputParametersSaved set ParmValue = @iMinFilenameCount where  ReportID = 'REPORTOUTBREAK' and ParmName = '@iMinFilenameCount'
		else
			insert ReportInputParametersSaved values( 'REPORTOUTBREAK', '@iMinFilenameCount', @iMinFilenameCount)

		if exists (select ParmName from ReportInputParametersSaved where ReportID = 'REPORTOUTBREAK' and ParmName = '@iHourRange')
			update ReportInputParametersSaved set ParmValue = @iHourRange where  ReportID = 'REPORTOUTBREAK' and ParmName = '@iHourRange'
		else
			insert ReportInputParametersSaved values( 'REPORTOUTBREAK', '@iHourRange', @iHourRange)
	end

	-- Update epo outbreak operator's email address, cancelled for epo3
	if @UpdateEmailNotification > ''
		execute msdb..sp_update_operator
			@name = 'epo_outbreak'
			--,@enabled = 1
			,@email_address = @UpdateEmailNotification
*/
	
	/* Batch Mode - Read input parms from database, override stored procedure inputs */
	if @RunasBatchJob = 1
	begin
		if exists (select ParmName from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szMinMachineCount')
			select @iMinMachineCount=ParmValue from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szMinMachineCount'

		if exists (select ParmName from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szMinFilenameCount')
			select @iMinFilenameCount=ParmValue from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szMinFilenameCount'

		if exists (select ParmName from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szHourRange')
			select @iHourRange=ParmValue from ReportInputParameters where ReportID = 'REPORTOUTBREAK' and ParmName = '@szHourRange'


		-- Set @dtStartDate = detdate - 2* @iHourRange
--		declare @interval int
--		set @interval = ( -1 * @iHourRange * 2 )
--		select @YYYYMMDD = dateadd(hour,  @interval, getdate() ) 

	end

-- debug
--select @iHourRange, @iMinFilenameCount, @iMinMachineCount, @szLang, @YYYYMMDD

	/*********************************************************************************************/
	/* recognize outbreaks by searching for min events over the hour range */

	select 
		Virusname,
		min(Virustype) as VirusType,
		datepart(year, eventdatetime) as dtyear,
		( (24*(datepart(dayofyear, eventdatetime)-1)) + (datepart(hour, eventdatetime)+1)  ) / @iHourRange as HourRangeNumber,
		count(*) as 'TotalEvents',
		count(distinct (hostname + filename)) as 'MachineFileCnt',
		count(distinct hostname) as 'MachinesCnt',
		count(distinct filename) as 'FilesCnt',

		(CASE @szTime
			WHEN 'GMT' 
			THEN 
			cast(min(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			ELSE 	
			cast(min(convert(char(19),eventlocaldatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			END) 
			as 'OutbreakStart',
		(CASE @szTime
			WHEN 'GMT' 
			THEN 
			cast(max(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			ELSE 	
			cast(max(convert(char(19),eventlocaldatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			END) 
			as 'OutbreakEnd'
--		cast(min(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) as 'OutbreakStart',
--		cast(max(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) as 'OutbreakEnd'

	into dbo.tmpOutbreakGroup 
	from Events
	where
 
		virusname > '' and HostName > ''
		AND Virusname not like 'Eicar%'
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
		AND ( TVDEventID < 8500 or TVDEventID > 8999 )

/* todo: setup some action code condiditons */
		AND eventdatetime > @YYYYMMDD
        		AND Events.ProductName != 'ePO Agent' 

	group by
		virusname
--		,Virustype
		,datepart(year, eventdatetime)
		,( (24*(datepart(dayofyear, eventdatetime)-1)) + (datepart(hour, eventdatetime)+1)  ) / @iHourRange
	having 
		count(distinct filename) > @iMinFilenameCount
		or
		count(distinct hostname) > @iMinMachineCount
	order by 
		virusname, HourRangeNumber


/* debug */
--select * from dbo.tmpOutbreakGroup order by  virusname


	/* get outbreak viruses and summary stats */

	select 
		virusname

		,virustype
		,count(*) NumberofOutbreakPeriods
		,min( dbo.tmpOutbreakGroup.OutbreakStart ) as FirstOutbreakEvent 
		,max( dbo.tmpOutbreakGroup.OutbreakEnd ) as LastOutbreakEvent
		,sum(dbo.tmpOutbreakGroup.TotalEvents) as 'TotalEvents'
		,sum(dbo.tmpOutbreakGroup.MachineFileCnt) as 'MachineFileCnt'
		,sum(dbo.tmpOutbreakGroup.MachinesCnt) as 'MachinesCnt'
		,sum(dbo.tmpOutbreakGroup.FilesCnt) as 'FilesCnt'
	into dbo.tmpOutbreakVirus 
	from dbo.tmpOutbreakGroup
	Group by
		virusname, virustype

/* 
--select * from dbo.tmpOutbreakVirus
*/

	/* get outbreak stats starting from the starting scan date */ 

	select 
		Events.Virusname as 'OutbreakVirus'
		,dbo.tmpOutbreakVirus.virustype as 'VirusType'
--   		, case 
--			when VirusType.VirusType > ''  then	VirusType.VirusType
--			else (case Events.VirusType when '' then '---' else Events.VirusType end)
--			end as VirusType

		-- epo3.5 fetch virustype from events.virustype writeback field, use time based on time parm
		,(CASE @szTime
			WHEN 'GMT' 
			THEN 
			cast(min(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100))
			ELSE 	
			cast(min(convert(char(19),eventlocaldatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100))	
			END) 
			as 'OutbreakStart'
		,(CASE @szTime
			WHEN 'GMT' 
			THEN 
			cast(max(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			ELSE 	
			cast(max(convert(char(19),eventlocaldatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) 
			END) 
			as 'OutbreakEnd'
--		,cast(min(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) as 'OutbreakStart'
--		,cast(max(convert(char(19),eventdatetime,120)+ ' ' + HostName + ' ' + ProductName) as varchar(100)) as 'OutbreakEnd'

		,dbo.tmpOutbreakVirus.NumberofOutbreakPeriods as NumberofOutbreakPeriods
		,dbo.tmpOutbreakVirus.FirstOutbreakEvent as FirstOutbreakEvent 
		,dbo.tmpOutbreakVirus.LastOutbreakEvent as LastOutbreakEvent
		,count(*) as 'TotalEvents'
		,count(distinct hostname) as 'MachinesCnt'
		,count(distinct filename) as 'FilesCnt'
		,count(distinct (hostname + filename)) as 'MachineFileCnt'

	into dbo.tmpOutbreakStats
	from 
	Events Join dbo.tmpOutbreakVirus on (Events.Virusname = dbo.tmpOutbreakVirus.Virusname)
	-- epo3.5 remove join to virustype table since data is now written back into events table
--	Left Outer Join VirusType on (events.VirusName = VirusType.VirusName)
	where

		Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
		AND ( TVDEventID < 8500 or TVDEventID > 8999 )
		and eventdatetime > @YYYYMMDD
        		AND Events.ProductName != 'ePO Agent' 

	group by
		Events.virusname
		,dbo.tmpOutbreakVirus.virustype
		,dbo.tmpOutbreakVirus.NumberofOutbreakPeriods
		,dbo.tmpOutbreakVirus.FirstOutbreakEvent 
		,dbo.tmpOutbreakVirus.LastOutbreakEvent
		,events.VirusType
--		,VirusType.VirusType

/*
--select * from dbo.tmpOutbreakStats
*/

/*
 Output select listing details of each occurrence 
*/
/*
*/
	/* Batch Mode - call RAISERROR if an outbreaks exists */
	if @RunasBatchJob = 1
	begin
		declare @numOutbreaks int
--		declare @Virus varchar(64)
		declare @numMachines int
		declare @numFiles int
		declare @datetime varchar(64)


		-- Report Outbreak events in summary table
--		Truncate Table ReportOutbreakEvents
--		output the outbreak summary not the details
		INSERT INTO ReportOutbreakEvents
   	              SELECT
		 dbo.tmpOutbreakStats.OutbreakVirus as 'OutbreakVirus'
		, dbo.tmpOutbreakStats.VirusType as 'VirusType'
		,dbo.tmpOutbreakStats.OutbreakStart as 'OutbreakStart'
		,dbo.tmpOutbreakStats.OutbreakEnd as 'OutbreakEnd'
		,dbo.tmpOutbreakStats.NumberofOutbreakPeriods as NumberofOutbreakPeriods
		,dbo.tmpOutbreakStats.FirstOutbreakEvent as FirstOutbreakEvent 
		,dbo.tmpOutbreakStats.LastOutbreakEvent as LastOutbreakEvent
		,dbo.tmpOutbreakStats.TotalEvents as 'TotalEvents'
		,dbo.tmpOutbreakStats.MachinesCnt as 'MachinesCnt'
		,dbo.tmpOutbreakStats.FilesCnt as 'FilesCnt'
		,dbo.tmpOutbreakStats.MachineFileCnt as 'MachineFileCnt'
		,CAST('' as varchar(100)) AS NodeName
		,CAST('' as varchar(100)) As HostName
		,CAST('' as varchar(100)) AS HostIPAddress
		,dbo.tmpOutbreakStats.OutbreakVirus as VirusName
		,CAST('' as varchar(100)) As FileName
		,CAST('' as varchar(100)) as EngineVersion
		,CAST('' as varchar(100)) as DATVersion
   		,CAST('' as varchar(100)) as ActionTaken
		,CAST('' as varchar(100)) as username
		,CAST('' as varchar(100)) as productname
		,CAST('' as varchar(100)) as productversion
		,CAST('' as varchar(100)) as EventDateTime
		,CAST('' as varchar(100)) as NodeID
		, @iMinMachineCount as RuleMachineCnt
		, @iMinFilenameCount as RuleFileCnt
		, @iHourRange as RuleHourCnt
	     	FROM dbo.tmpOutbreakStats
--select @iHourRange, @iMinFilenameCount, @iMinMachineCount, @szLang, @YYYYMMDD

/*
		INSERT INTO ReportOutbreakEvents
   	              SELECT
		 Events.Virusname as 'OutbreakVirus'
		,Events.VirusType as 'VirusType'
		,dbo.tmpOutbreakStats.OutbreakStart as 'OutbreakStart'
		,dbo.tmpOutbreakStats.OutbreakEnd as 'OutbreakEnd'
		,dbo.tmpOutbreakStats.NumberofOutbreakPeriods as NumberofOutbreakPeriods
		,dbo.tmpOutbreakStats.FirstOutbreakEvent as FirstOutbreakEvent 
		,dbo.tmpOutbreakStats.LastOutbreakEvent as LastOutbreakEvent
		,dbo.tmpOutbreakStats.TotalEvents as 'TotalEvents'
		,dbo.tmpOutbreakStats.MachinesCnt as 'MachinesCnt'
		,dbo.tmpOutbreakStats.FilesCnt as 'FilesCnt'
		,dbo.tmpOutbreakStats.MachineFileCnt as 'MachineFileCnt'
		,CAST('' as varchar(100)) AS NodeName
		,cast(Events.HostName as varchar(50)) As HostName
		,Events.HostIPAddress
		,Events.VirusName
		,cast(Events.FileName as varchar(200)) As FileName
		,Events.EngineVersion
		,Events.DATVersion
   		,ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END
		,Events.username
		,Events.productname
		,Events.productversion
		,Events.EventDateTime
		,Events.NodeID
	     	FROM Events, dbo.tmpOutbreakStats, ReportActionDesc
	     	WHERE
	 		Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
			AND Events.Virusname = dbo.tmpOutbreakStats.OutbreakVirus
	  		AND Events.ActionTaken = ReportActionDesc.ActionIntID
		   	AND ReportActionDesc.LanguageSuffix = @szLang
			and eventdatetime > @YYYYMMDD
        			AND Events.ProductName != 'ePO Agent' 
--			AND ActionTaken in ('51','53','55','58','62','64','66')		-- all virus events
*/

	 	-- summarize result and raise an error - removed for now
/*
		select
			@numOutbreaks = count(*)	
			, @Virus = max(OutbreakVirus)	
			, @numMachines = sum(MachinesCnt)
			, @numFiles = sum(FilesCnt)
		from dbo.tmpOutbreakStats

		select @dateTime = convert(char, GetDate(), 120)

		if @numOutbreaks > 0
			RAISERROR ( 58376, 16, 1
				, @numOutbreaks
				, @dateTime
				, @Virus
				, @numMachines
				, @numFiles )
				 with LOG 
*/
	end 
	else
	begin
	       /* Report Mode - fetch all events from the outbreaks */
	       select 
		Events.Virusname as 'OutbreakVirus'
		,dbo.tmpOutbreakStats.VirusType as 'VirusType'
		,dbo.tmpOutbreakStats.OutbreakStart as 'OutbreakStart'
		,dbo.tmpOutbreakStats.OutbreakEnd as 'OutbreakEnd'
		,dbo.tmpOutbreakStats.NumberofOutbreakPeriods as NumberofOutbreakPeriods
		,dbo.tmpOutbreakStats.FirstOutbreakEvent as FirstOutbreakEvent 
		,dbo.tmpOutbreakStats.LastOutbreakEvent as LastOutbreakEvent
		,dbo.tmpOutbreakStats.TotalEvents as 'TotalEvents'
		,dbo.tmpOutbreakStats.MachinesCnt as 'MachinesCnt'
		,dbo.tmpOutbreakStats.FilesCnt as 'FilesCnt'
		,dbo.tmpOutbreakStats.MachineFileCnt as 'MachineFileCnt'
		,CAST('' as varchar(100)) AS NodeName
		,cast(Events.HostName as varchar(50)) As HostName
		,Events.HostIPAddress
		,Events.VirusName
		,cast(Events.FileName as varchar(200)) As FileName
		,Events.EngineVersion
		,Events.DATVersion
   		,ActionTaken =
	    		CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     		END
		,Events.username
		,Events.productname
		,Events.productversion
--		epo3.5 make timerule work: gmt, local
    		, (CASE @szTime
			WHEN 'GMT' THEN Events.EventDateTime
			ELSE 		Events.EventLocalDateTime
			END) 
			as EventDateTime
		,datepart(year, Events.eventdatetime) as evdtyear
		,datepart(week, Events.eventdatetime) as evdtweek
		,(convert( varchar(5), datepart(year, Events.eventdatetime) )
			+ ' ' +  convert( varchar(5), datepart(quarter, Events.eventdatetime)) + 'Q')
			as evdtquarter

	     from 
		Events Join dbo.tmpOutbreakStats on (Events.Virusname = dbo.tmpOutbreakStats.OutbreakVirus)
		Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
	   		AND ReportActionDesc.LanguageID = @szFullLang)

	     where
  		(	-- check for directory filter
   			@FilterID = 0 OR
    			Events.NodeID in
			( Select LeafNode.autoid from Leafnode where LeafNode.ParentID in 
				(
				select BranchNodeEnum.EndAutoID		/* enum table used to determine list of legal nodes */ 
        			from BranchNodeEnum 
        			where BranchNodeEnum.StartAutoID = @FilterID
				Union
				select @FilterID
				)
			)
  		)
		and
		Events.virusname > '' and Events.HostName > '' and Events.filename > '' and Events.actiontaken > ''
   		AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
		AND ( TVDEventID < 8500 or TVDEventID > 8999 )
		and eventdatetime > @YYYYMMDD
        		AND Events.ProductName != 'ePO Agent' 

	end



/*	
Dont include this order by clause in production - test only

		ORDER BY OutbreakName, EventTime 

*/

	set @ret = @@rowcount


/* cleanup */


	DROP TABLE dbo.tmpOutbreakGroup

	DROP TABLE dbo.tmpOutbreakVirus

	DROP TABLE dbo.tmpOutbreakStats


	/***********************************************************************************/
	/* Update Batch Mode Job and Alert Parameters */

	/* Report Mode - enable Batch Mode job */
	-- canceled for epo3.0
/*
	if @EnableBatchJob = 1
	begin

		execute msdb..sp_update_job
			@job_name = 'epo_outbreak_search'
			,@enabled = 1

		execute msdb..sp_update_jobschedule
			@job_name = 'epo_outbreak_search'
			,@name = 'epo_outbreak'
			,@enabled=1
			--,@freq_type=4 -- daily
			--,@freq_interval=1 -- everyday
			--,@freq_subday_type=8 -- hours
			--,@freq_subday_interval=1 -- 1 hour

		execute msdb..sp_update_operator
			@name = 'epo_outbreak'
			,@enabled = 1
			--,@email_address = ''
	end

	if @EnableBatchJob = 2
	begin

		execute msdb..sp_update_job
			@job_name = 'epo_outbreak_search'
			,@enabled = 0

		execute msdb..sp_update_jobschedule
			@job_name = 'epo_outbreak_search'
			,@name = 'epo_outbreak'
			,@enabled=0
			--,@freq_type=4 -- daily
			--,@freq_interval=1 -- everyday
			--,@freq_subday_type=8 -- hours
			--,@freq_subday_interval=1 -- 1 hour

		execute msdb..sp_update_operator
			@name = 'epo_outbreak'
			,@enabled = 0
			--,@email_address = ''

	end
*/

	/* Set Batch Mode schedule interval */
/*	if @SaveOutbreakDefn = 1
		execute msdb..sp_update_jobschedule
			@job_name = 'epo_outbreak_search'
			,@name = 'epo_outbreak'
			,@freq_type=4 -- daily
			,@freq_interval=1 -- everyday
			,@freq_subday_type=8 -- hours
			,@freq_subday_interval= @iHourRange -- 1 hour
*/


/*
*/

Return @ret
END
GO




-----------------------------------------------------------------
-- Computer and compliance summary routines

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


CREATE PROCEDURE dbo.AVISP_SetComputerSummary
( 
@dtInfectionCheckPoint DateTime
, @dtAsciCheckpoint	DateTime
, @szRuleName varchar(50) = 'default'
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/


	/* Stored procedure to recreate table of nodepaths and node ids */
	/* This table persists and is recreated each time the report runs */

	Execute AVISP_CalculateAllSubNodes 0, 0, '', 'GenerateOutputTable'

-----------------------------
-- postepo3  cleanup temp tables (cant use tempdb anymore)

	IF EXISTS (select * from sysobjects where name = 'tmpUnmanagedProtection' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpUnmanagedProtection

	IF EXISTS (select * from sysobjects where name = 'tmpScanners' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpScanners

----------------------------
-- epo3.5 fix agent productname so they always list OS they are related to
-- Doing this for backward compatibility for already released products
-- All new products must follow the proper naming convention for agents

	update Software 
		set SoftwareName = 'ePO Agent for Netware'
		where ProductFamily = 'epo'
			and Productcode like 'epoagent%nvnw'
			and softwarename != 'ePO Agent for Netware'

	update Software 
		set SoftwareName = 'ePO Agent for Webshield Appliance'
		where ProductFamily = 'epo'
			and Productcode like 'epoagent%lynx'
			and softwarename != 'ePO Agent for Webshield Appliance'
		

---------------------------
	/* Fetch Computer Summary - 1 row for each computer (get all computer related data needed for this report - display and cust data */
	Truncate Table ReportComputerSummary 

	Declare @ret int

	/* Get Computer Properties */
 	INSERT ReportComputerSummary
	  SELECT
		LeafNode.ParentID as BranchNodeID
		, LeafNode.AutoID as NodeID
		, LeafNode.NodeName as NodeNameLeaf
		, BranchNode.NodeName as NodeNameBranch
		, ReportFullPathNodeID.FullPathShortName as FullNodePath
		, '---' as AgentVersion
		, '' as LastAsci
		, 1 as NoAgent
		, NULL as AsciSinceCheckPoint
		, '---' as  ProductName
 		, ' ' as  ProductCode  -- want to default this to a space (when drilldown on policy a null value will make crystal pop a dialog
		, NULL as  ProductFamily
 		, '---' as  ProductVersion
 		, '---' as  EngineVer
 		, '---' as  DATVer
		, NULL as  ExtraDATNames
		, 1 as NoAV
 		, 0 as MultipleScanner
		, NULL as  ScannerLanguage
		, NULL as  ComputerLanguage
		, ComputerProperties.DomainName
--		, NULL as OSVersion
		,    cast((ComputerProperties.OSType 
			+ ' ' + ComputerProperties.OSServicePackVer 
			+ ' ' + ComputerProperties.OSPlatform)
       			as varchar(50)) as OSVersion
--	epo3.5 - Due to Netware multiple computername issue, always use LN.nodename for computername
		, LeafNode.nodename as ComputerName
		, ComputerProperties.IPAddress as IPAdress
		-- ComplianceComparison Changes
		, GetDate() as DateTimeOfRun
		, 0 as VirusCount
		, 0 as UnresolvedVirusCount
		, cast(NULL as varchar(50)) as VirusnameMax
		, cast(NULL as varchar(50)) as UnresolvedVirusnameMax
		, 0 as VirusnameMaxCount
		, 0 as UnresolvedVirusnameMaxCount
		, 0 as DuplicateComputer
		, 0 as DuplicateScannerID
		, 1 as Compliant
        	, '' as Servicepack
		, '' as Hotfix
        	, '' as LicenseStatus
		, '' as ExpirationDate
		, ComputerProperties.OSPlatform as OSPlatform
		, ComputerProperties.OSType as OSType
		,'---' as AgentName
		
	FROM 
	LeafNode Join BranchNode on (LeafNode.ParentID = BranchNode.AutoID)
	Join ReportFullPathNodeID on (BranchNode.AutoID = ReportFullPathNodeID.LowestNodeID)
	Left Outer Join ComputerProperties on (LeafNode.AutoID = ComputerProperties.ParentID)
	WHERE 
		LeafNode.Type=1   
--		AND LeafNode.AutoID *= ComputerProperties.ParentID	-- outer join: finds all leafnodes, event those w/o agents and computer properties
--		AND LeafNode.ParentID = BranchNode.AutoID
--		AND BranchNode.AutoID = ReportFullPathNode.LowestNodeID
/*	Group By 
		BranchNode.AutoID
		, LeafNode.AutoID
*/

	set @ret = @@rowcount

if @szRuleName = 'test'
begin
select 'ReportComputerSummary', * from ReportComputerSummary
select 'ReportFullPathNode', * from ReportFullPathNode
end

	/* Find Duplicate Computers */
	UPDATE	ReportComputerSummary
		SET DuplicateComputer = 1
	FROM
		LeafNode a, LeafNode b, ReportComputerSummary
	WHERE
		a.NodeName = b.NodeName
		and a.AutoID != b.AutoID
		and a.LastUpdate < b.LastUpdate
		and a.LastUpdate is not NULL
		and ReportComputerSummary.NodeID = a.AutoID

if @szRuleName = 'test'
select 'DuplicateComputer', @@rowcount


	/* Get Agent Data */
	-- epo3.5 add agentname to distinquish the various different agent types
	UPDATE	ReportComputerSummary
		SET AgentVersion = ProductProperties.ProductVersion
		    ,AgentName = aviview_software.softwarename
		    , NoAgent = 0
		    , LastAsci = LeafNode.LastUpdate
  		    , AsciSinceCheckPoint = 
				case
				when LeafNode.LastUpdate = '' THEN 0
				when LeafNode.LastUpdate = NULL THEN 0 
				when CONVERT(datetime,
  					(SUBSTRING( LeafNode.LastUpdate,  1 , 4)+'-'+
  					SUBSTRING( LeafNode.LastUpdate,  5 , 2)+'-'+                              
					SUBSTRING( LeafNode.LastUpdate,  7 , 2)+' '+                              
   					SUBSTRING( LeafNode.LastUpdate,  9 , 2)+':'+                              
   					SUBSTRING( LeafNode.LastUpdate,  11 , 2)+':'+                              
   					SUBSTRING( LeafNode.LastUpdate,  13 , 2)                                    
   					), 120 )   
						 > @dtAsciCheckPoint  THEN 1 
				else 0 
			   	end 
			       
		From ProductProperties, LeafNode, aviview_software
		WHERE
			LeafNode.AutoID = ReportComputerSummary.NodeID
			AND ReportComputerSummary.NodeID = ProductProperties.ParentID
			and aviview_software.productcode = ProductProperties.productcode
   			AND ProductProperties.ProductCode LIKE '%Agent%'

if @szRuleName = 'test'
select 'Find agents', @@rowcount

	----------------------------------------------------------------------------------------------
	/* Fetch scanning product data - handles single scanner, multiple scanner, and unmanaged protection cases */

	UPDATE	ReportComputerSummary
		SET 
			ProductName =  AVIView_Software.SoftwareName
			, ProductCode =  ProductProperties.ProductCode
			, ProductVersion = ProductProperties.ProductVersion
			, EngineVer = ProductProperties.EngineVer
			, DATVer = ProductProperties.DATVer
			, ExtraDATNames = 
			    	CASE ProductProperties.ExtraDATNames
			     	WHEN '' THEN '' 
			     	WHEN 'N/A' THEN '' 
			     	ELSE ProductProperties.ExtraDATNames     	
			     	END
			, ScannerLanguage = ProductProperties.Language
			, ProductFamily = AVIView_Software.ProductFamily
			, NoAV = 0
--			, MultipleScanner = count(*)
--			, DuplicateScannerID = MIN( ProductProperties.AutoID )
        		, Servicepack = ProductProperties.Servicepack
			, Hotfix = ProductProperties.Hotfix
        		, LicenseStatus = productproperties.licensestatus
			, ExpirationDate = productproperties.expirationdate
		FROM 	ProductProperties, AVIView_Software
		WHERE
			ReportComputerSummary.NodeID = ProductProperties.ParentID
			and ProductProperties.ProductCode = AVIView_Software.ProductCode
			   and (AVIView_Software.ProductFamily in ('TVD', 'TVD_NC')  
				or AVIView_Software.ProductFamily like 'TVD_NC_%' )


if @szRuleName = 'test'
select 'Find AV data', @@rowcount

	/* Look for duplicate scanner and makesure data for latest and previous is recorded */
	SELECT
			NodeID = LeafNode.AutoID
			, MainScanner = Max( ProductProperties.AutoID )
			, MultipleScanner = count(*)
			, DuplicateScannerID = Min( ProductProperties.AutoID )
	INTO 	dbo.tmpScanners
		FROM 	LeafNode, ProductProperties, AVIView_Software
		WHERE
			LeafNode.AutoID = ProductProperties.ParentID
			and ProductProperties.ProductCode = AVIView_Software.ProductCode
			   and (AVIView_Software.ProductFamily in ('TVD', 'TVD_NC')  
				or AVIView_Software.ProductFamily like 'TVD_NC_%' )
 
		GROUP BY 
			LeafNode.AutoID
			, ProductProperties.AutoID
		HAVING count(*) > 1

	-- Record main scanner in multiple scanner situation
	UPDATE	ReportComputerSummary
		SET 
			ProductName =  AVIView_Software.SoftwareName
			, ProductCode =  ProductProperties.ProductCode
			, ProductVersion = ProductProperties.ProductVersion
			, EngineVer = ProductProperties.EngineVer
			, DATVer = ProductProperties.DATVer
			, ExtraDATNames = 
			    	CASE ProductProperties.ExtraDATNames
			     	WHEN '' THEN '' 
			     	WHEN 'N/A' THEN '' 
			     	ELSE ProductProperties.ExtraDATNames     	
			     	END
			, ScannerLanguage = ProductProperties.Language
			, ProductFamily = AVIView_Software.ProductFamily
			, NoAV = 0
			, MultipleScanner = dbo.tmpScanners.MultipleScanner
        		, Servicepack = ProductProperties.Servicepack
			, Hotfix = ProductProperties.Hotfix
--			, DuplicateScannerID = MIN( ProductProperties.AutoID )
		FROM 	ProductProperties, AVIView_Software, dbo.tmpScanners
		WHERE
			ReportComputerSummary.NodeID = dbo.tmpScanners.NodeID
			and ReportComputerSummary.NodeID = ProductProperties.ParentID
			and ProductProperties.AutoID = dbo.tmpScanners.MainScanner
			and ProductProperties.ProductCode = AVIView_Software.ProductCode
			   and (AVIView_Software.ProductFamily in ('TVD', 'TVD_NC')  
				or AVIView_Software.ProductFamily like 'TVD_NC_%' )
			and dbo.tmpScanners.MultipleScanner > 1

if @szRuleName = 'test'
select 'DuplicateScanner-main', @@rowcount

	-- Record Duplicate scanner
	UPDATE	ReportComputerSummary
		SET 
			 DuplicateScannerID = dbo.tmpScanners.DuplicateScannerID
		FROM 	 dbo.tmpScanners
		WHERE
			ReportComputerSummary.NodeID = dbo.tmpScanners.NodeID
			and dbo.tmpScanners.MultipleScanner > 1

if @szRuleName = 'test'
select 'DuplicateScanner', @@rowcount			

	/* Fetch Nodes with no products: aviinstall=0, but with unmanaged protection (events but no props, groupshield */


	SELECT distinct
   		LeafNode.AutoID as NodeID
   		, ProductName
   		, ProductVersion = 
      			CASE
          			WHEN Max( ProductVersion )  > '' THEN Max( ProductVersion )
 		         	WHEN Max( ProductVersion )  = '' THEN '---'
 		         	ELSE  '---'
		        END
 		  , EngineVer = 
 		    	CASE
		          	WHEN Max(Events.EngineVersion)  > '' THEN Max(Events.EngineVersion)
		          	WHEN Max(Events.EngineVersion)  = '' THEN '---'
		          	ELSE  '---'
 		       END	
 		  , DATVer = 
 		    	CASE
 		         	WHEN Max(Events.DATVersion)  > '' THEN Max(Events.DATVersion)
 		       	  WHEN Max(Events.DATVersion)  = '' THEN '---'
 		         	ELSE  '---'
  		      END
		,ProductFamily = 'TVD'

	 INTO dbo.tmpUnmanagedProtection
	 FROM LeafNode, Events
	 WHERE
 	 	LeafNode.AVInstalls = 0
 		AND LeafNode.Type !=24      
		AND LeafNode.AutoID = Events.NodeID			
   		AND
   		(
      			Events.ProductName like '%GroupShield%'
      			OR (Events.ProductName like '%NetShield%' and ProductVersion < '4.5')
      			OR (Events.ProductName like '%VirusScan%' and ProductVersion < '4.5')
      			OR Events.ProductName like '%WebShield%'
   		)
   	GROUP BY
		LeafNode.AutoID
      		, Events.ProductName

		/* use group by to remove duplicates and return latest version, engine, dats */



/* Merge Unmanaged Protection fields into EventAgentSummary table */


	UPDATE	ReportComputerSummary
	SET
 		ProductName = dbo.tmpUnmanagedProtection.ProductName
 		, ProductVersion = dbo.tmpUnmanagedProtection.ProductVersion
 		, EngineVer = dbo.tmpUnmanagedProtection.EngineVer
 		, DATVer = dbo.tmpUnmanagedProtection.DATVer
		, NoAV = 0
	FROM	dbo.tmpUnmanagedProtection
	WHERE
		ReportComputerSummary.NodeID = dbo.tmpUnmanagedProtection.NodeID
		AND 	(ReportComputerSummary.ProductName = ''
			OR  ReportComputerSummary.ProductName is NULL
			OR  ReportComputerSummary.ProductName = '---')			

if @szRuleName = 'test'
select 'UnmanagedProtection', @@rowcount

drop table dbo.tmpUnmanagedProtection
drop table dbo.tmpScanners




--select * from ReportComputerSummary
--order by duplicatescannerid desc 
--order by duplicatecomputer desc


RETURN @ret
END
GO





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



-- Daily compliance comparison job 
-- fills ReportComplianceComparison and ReportUpdateEvents
-- by comparing ReportComputerSummaryPrevious to ReportComputerSummary
-- Daily compliance comparison job 
-- fills ReportComplianceComparison and ReportUpdateEvents
-- by comparing ReportComputerSummaryPrevious to ReportComputerSummary
CREATE PROCEDURE dbo.AVISP_SetComplianceComparison
(
 @iNameSpaceName  VARCHAR(20)
 , @iNameSpaceNode  VARCHAR(20)
 , @szEpoUserName  VARCHAR(100)
-- , @szNameSpaceName  VARCHAR(100)
-- , @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @dtInfectionCheckPoint DateTime

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      	/* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
 	Declare @UsersTopNodeID int
 	Declare @FilterNodeID int
 	select @UsersTopNodeID = convert(int, @iNameSpaceName)
 	select @FilterNodeID = convert(int, @iNameSpaceNode)


 	Declare @FilterID int
 	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT

	Declare @ret int  
	set @ret = 0

  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


-------------------
-- postepo3   clean up tempdbs

	IF EXISTS (select * from sysobjects where name = 'tmpPreviousNodeIDs' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpPreviousNodeIDs

	IF EXISTS (select * from sysobjects where name = 'tmpNewNodeIDs' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpNewNodeIDs

	IF EXISTS (select * from sysobjects where name = 'tmpOldNodeIDs' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpOldNodeIDs


	----------------------------------------------------------------------
	-- check if this routine was already run today - allow just one run per day 
	Declare @Tabcnt int
	Declare @LastDate char(20)
	select @Tabcnt = count(*), @LastDate = max(DateTimeEnd) from ReportComplianceComparison

	-- If there is already an entry for today, then stop and exit - just do one run a day
     	-- if its a new day then start the comparison

if @szOptionalReportParms = 'test'
select @LastDate, GetDate()

     	if DateDiff( day, @LastDate, GetDate() ) <= 0 and @Tabcnt > 0 and @szOptionalReportParms <> 'test'
     		return

if @szOptionalReportParms = 'test'
select @LastDate, GetDate()



	
	-- temporaray item: need to set this up properly in agent3 install
	-- set agent version correctly if it has not been loaded properly yet
	-- when 3.0 nap file is loaded the leafnode table is not yet updated
	update leafnode
	set agentversion = productproperties.productversion
	from productproperties, leafnode, aviview_software
	where 
	productproperties.parentid = leafnode.autoid
	and productproperties.productcode = aviview_software.productcode
	and aviview_software.productfamily = 'EPO'
	and aviview_software.productcode like 'ePOAgent%'
	and leafnode.agentversion is NULL


	-----------------------------------
	/* Stored procedure to create a table of nodeids, computers, agent versions, and summary event count data */
	/* This table persists and is recreated each time the report runs */
	-- If blank date entered then assume the cutoff should be one day back
	Declare @InfectionCutoff DateTime
	Set @InfectionCutoff = @dtInfectionCheckPoint
	if @InfectionCutoff = '' or @InfectionCutoff is NULL
		Set @InfectionCutoff = DateAdd(day,-1,GetDate());

	Execute AVISP_SetComputerSummary @InfectionCutoff, NULL, @szOptionalReportParms



--select 2, getdate()
	Declare @cnt int
	Declare @Firstrun int
	Set @Firstrun = 0
	-- Save This Computer summary table to ComputerSummaryPrevious if the table is empty (first time run)
	SELECT @cnt = count(*) from ReportComputerSummaryPrevious
	IF @cnt = 0 
	begin
		Set @FirstRun = 1
 		INSERT ReportComputerSummaryPrevious
	  		SELECT * FROM  ReportComputerSummary
--		update ReportComputerSummaryPrevious set LastAsci = ''
	end
	else	-- not first run
	begin
		-- postepo3 fix 34975: Dont run orphan fix if first run (online run)
		-- If have too many orphans it will lock system , wait for batch job to cleanup orphans
		-----------------------------------
		-- Special maintainance procedure to remove orphaned records
		Execute AVIDALSP_RemoveOrphans
	end

if @szOptionalReportParms = 'test'
begin
select * from ReportComputerSummary
select * from ReportComputerSummaryPrevious
end

--select 3, getdate()

	-- Fetch starting datetime	
	Declare @DateTimeStart DateTime
	select @DateTimeStart=max(DateTimeOfRun) from ReportComputerSummaryPrevious

if @szOptionalReportParms = 'test'
select @DateTimeStart, 'from ReportComputerSummaryPrevious'

	-------------------------------------------------------------------------------
	-- Compliance Comparison Changes
	-- 1. Compiles counts to load daily summary table
	-- 2. Writes changes out to update event table
	--	New Computers
	--	Removed Computers
	--	New Product Install
	--	Removed Product Install
	--	New Agent Version
	--	New Product Version
	--	New Engine Version
	--	New DAT Version
	--	New ExtraDAT Version
 	--	DuplicateComputer 
 	--	MultipleScanner 

	-- build temp tables (New, removed, unchanged nodes)
	select ReportComputerSummaryPrevious.NodeID 
		into dbo.tmpPreviousNodeIDs 
		from ReportComputerSummaryPrevious 

if @szOptionalReportParms = 'test'
select 'Prev Nodes', count(*), min(nodeid), max(nodeid) from dbo.tmpPreviousNodeIDs

	select distinct ReportComputerSummary.NodeID 
		into dbo.tmpNewNodeIDs
		from ReportComputerSummary
		where 	ReportComputerSummary.NodeID not in (select NodeID from ReportComputerSummaryPrevious)

if @szOptionalReportParms = 'test'
begin
select 'Prev Nodes',  count(*), min(nodeid), max(nodeid)  from dbo.tmpNewNodeIDs
select * from dbo.tmpNewNodeIDs
end
	select distinct ReportComputerSummaryPrevious.NodeID 
		into dbo.tmpOldNodeIDs
		from ReportComputerSummaryPrevious 
		where 	ReportComputerSummaryPrevious.NodeID not in (select NodeID from ReportComputerSummary)

if @szOptionalReportParms = 'test'
select 'Prev Nodes',  count(*), min(nodeid), max(nodeid)  from dbo.tmpOldNodeIDs

--select 4, getdate()

	-- new, removed computers stuff
	Declare @newcomputers int
	SELECT @newcomputers = count(*) FROM dbo.tmpNewNodeIDs

if @szOptionalReportParms = 'test'
select '@newcomputers',  @newcomputers

--	insert ReportUpdateEvents
--	select 'New Computers', ReportComputerSummary.* from  ReportComputerSummary, dbo.tmpNewNodeIDs where ReportComputerSummary.NodeID =  dbo.tmpNewNodeIDs.NodeID

--select 5, getdate()

	Declare @removedcomputers int
	SELECT @removedcomputers = count(*) FROM dbo.tmpOldNodeIDs

if @szOptionalReportParms = 'test'
select '@removedcomputers',  @removedcomputers

--	insert ReportUpdateEvents
--	select 'Removed Computers', ReportComputerSummaryPrevious.* from  ReportComputerSummaryPrevious, dbo.tmpOldNodeIDs where ReportComputerSummaryPrevious.NodeID =  dbo.tmpOldNodeIDs.NodeID

--select 6, getdate()

	Declare @unchangedcomputers int
	SELECT @unchangedcomputers = count(*) 
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID

if @szOptionalReportParms = 'test'
select '@unchangedcomputers',  @unchangedcomputers

--select 7, getdate()

	-- new, removed product installations
	Declare @newinstalls1 int
	SELECT @newinstalls1 = count(*) 
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID
		and ReportComputerSummary.ProductCode != ReportComputerSummaryPrevious.ProductCode

if @szOptionalReportParms = 'test'
select '@newinstalls1',  @newinstalls1

	Declare @newinstalls2 int
	SELECT @newinstalls2 = count(*) 
	FROM
		ReportComputerSummary
	WHERE
		ReportComputerSummary.NodeID in (select NodeID from dbo.tmpNewNodeIDs)
		and ReportComputerSummary.ProductCode > ''

if @szOptionalReportParms = 'test'
select '@newinstalls2',  @newinstalls2

	Declare @newinstalls int
	set @newinstalls = @newinstalls1 + @newinstalls2

if @szOptionalReportParms = 'test'
select '@newinstalls',  @newinstalls

--	insert ReportUpdateEvents
--	select 'New Product Install', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary, dbo.tmpNewNodeIDs
--	WHERE
--		(ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID
--		and ReportComputerSummary.ProductCode > ReportComputerSummaryPrevious.ProductCode)
		
--	insert ReportUpdateEvents
--	select 'New Product Install', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary, dbo.tmpNewNodeIDs
--	WHERE
--		(ReportComputerSummary.NodeID in (select NodeID from dbo.tmpNewNodeIDs)
--		and ReportComputerSummary.ProductCode > '')

--select 8, getdate()

	Declare @removedinstalls int
	SELECT @removedinstalls = count(*) 
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID
		and ReportComputerSummary.ProductCode < ReportComputerSummaryPrevious.ProductCode

if @szOptionalReportParms = 'test'
select '@removedinstalls',  @removedinstalls

--	insert ReportUpdateEvents
--	select 'Removed Product Install', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		(ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID
--		and ReportComputerSummary.ProductCode < ReportComputerSummaryPrevious.ProductCode)

--select 9, getdate()

	-- computers w/o scanner protection
	Declare @NoScanner int
	SELECT @NoScanner = count(*) FROM ReportComputerSummary WHERE ProductCode in ('', NULL, ' ')

if @szOptionalReportParms = 'test'
select '@NoScanner',  @NoScanner

	-- computers w extradat
	Declare @ExtraDAT int
	SELECT @ExtraDAT = count(*) FROM ReportComputerSummary WHERE ExtraDATNames not in ('', NULL, 'N/A')

if @szOptionalReportParms = 'test'
select '@ExtraDAT',  @ExtraDAT

	-- computers w NoAgents
	Declare @NoAgent int
	SELECT @NoAgent = count(*) FROM ReportComputerSummary WHERE NoAgent > 0

if @szOptionalReportParms = 'test'
select '@NoAgent',  @NoAgent

	-- computers w Unchanges Asci
	Declare @UnchangedAsci int
	Set @UnchangedAsci = 0
	if @Firstrun = 0
	SELECT @UnchangedAsci = count(*) 
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummary.NodeID = ReportComputerSummaryPrevious.NodeID
		and ReportComputerSummary.LastAsci = ReportComputerSummaryPrevious.LastAsci

if @szOptionalReportParms = 'test'
select '@UnchangedAsci',  @UnchangedAsci

	-- DuplicateComputer 
	Declare @DuplicateComputer  int
	SELECT @DuplicateComputer = count(*) FROM ReportComputerSummary WHERE DuplicateComputer > 0

if @szOptionalReportParms = 'test'
select '@DuplicateComputer',  @DuplicateComputer

	-- MultipleScanner 
	Declare @MultipleScanner  int
	SELECT @MultipleScanner = count(*) FROM ReportComputerSummary WHERE MultipleScanner > 1

if @szOptionalReportParms = 'test'
select '@MultipleScanner',  @MultipleScanner

--select 10, getdate()

	-- version changes
	Declare @newagentversion int
	SELECT
		@newagentversion = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.AgentVersion != ReportComputerSummaryPrevious.AgentVersion

if @szOptionalReportParms = 'test'
select '@newagentversion',  @newagentversion

--	insert ReportUpdateEvents
--	select 'New Agent Version', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.AgentVersion != ReportComputerSummaryPrevious.AgentVersion

--select 11, getdate()
		
	Declare @newscannerversion int
	SELECT
		@newscannerversion = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.ProductVersion != ReportComputerSummaryPrevious.ProductVersion

if @szOptionalReportParms = 'test'
select '@newscannerversion',  @newscannerversion

--	insert ReportUpdateEvents
--	select 'New Product Version', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.ProductVersion != ReportComputerSummaryPrevious.ProductVersion

--select 12, getdate()
		
	Declare @newengineversion int
	SELECT
		@newengineversion = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.EngineVer != ReportComputerSummaryPrevious.EngineVer

if @szOptionalReportParms = 'test'
select '@newengineversion',  @newengineversion

--	insert ReportUpdateEvents
--	select 'New Engine Version', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.EngineVer != ReportComputerSummaryPrevious.EngineVer


--select 13, getdate()
		
	Declare @newdatversion int
	SELECT
		@newdatversion = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.DATVer != ReportComputerSummaryPrevious.DATVer

if @szOptionalReportParms = 'test'
select '@newdatversion',  @newdatversion

--	insert ReportUpdateEvents
--	select 'New DAT Version', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.DATVer != ReportComputerSummaryPrevious.DATVer

--select 14, getdate()
		
	Declare @newextradatversion int
	SELECT
		@newextradatversion = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.ExtraDATNames != ReportComputerSummaryPrevious.ExtraDATNames

if @szOptionalReportParms = 'test'
select '@newextradatversion',  @newextradatversion

--	insert ReportUpdateEvents
--	select 'New ExtraDAT Version', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.ExtraDATNames != ReportComputerSummaryPrevious.ExtraDATNames
		
--select 141, getdate()
		
	Declare @newservicepack int
	SELECT
		@newservicepack = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.Servicepack != ReportComputerSummaryPrevious.Servicepack

if @szOptionalReportParms = 'test'
select '@newservicepack',  @newservicepack


--	insert ReportUpdateEvents
--	select 'New Servicepack', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.Servicepack != ReportComputerSummaryPrevious.Servicepack

--select 142, getdate()
		
	Declare @newhotfix int
	SELECT
		@newhotfix = count(*)
	FROM
		ReportComputerSummaryPrevious, ReportComputerSummary
	WHERE
		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
		and ReportComputerSummary.Hotfix != ReportComputerSummaryPrevious.Hotfix

if @szOptionalReportParms = 'test'
select '@newhotfix',  @newhotfix


--	insert ReportUpdateEvents
--	select 'New Hotfix', ReportComputerSummary.* 
--	FROM
--		ReportComputerSummaryPrevious, ReportComputerSummary
--	WHERE
--		ReportComputerSummaryPrevious.NodeID = ReportComputerSummary.NodeID
--		and ReportComputerSummary.Hotfix != ReportComputerSummaryPrevious.Hotfix


--select 15, getdate()


	-------------------------------------------------------------------------------------------------
	-- Load event summary stats

	Declare @VirusCount int
	Declare @UnresolvedVirusCount int
	Declare @MaxVirus varchar(50)
	Declare @MaxUnresolvedVirus varchar(50)
	Declare @MaxVirusCount int
	Declare @MaxUnresolvedVirusCount int
	Declare @MaxEventid int
	Declare @MaxEventidPrevious int
	Declare @ComputersWithVirus int

	-- set previous maxid
	SELECT
		@MaxEventidPrevious = Max(MaxEventid)
	FROM	ReportComplianceComparison
	-- If no previous entries then use current max as default - no events summary data the first time it runs
	if @MaxEventidPrevious is null or @MaxEventidPrevious = 0
	SELECT
		@MaxEventidPrevious = Max(AutoID)
	FROM	Events

	SELECT
		@MaxEventid = Max(AutoID)
	FROM	Events


if @szOptionalReportParms = 'test'
select '@MaxEventid',  @MaxEventid, @MaxEventidPrevious

	SELECT
 		@VirusCount = count(*)
		, @ComputersWithVirus = count( distinct NodeID)
	FROM	Events
	WHERE
		Events.AutoID > @MaxEventidPrevious
		and VirusName > '' 
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        		AND Events.ProductName != 'ePO Agent' 

if @szOptionalReportParms = 'test'
select '@VirusCount',  @VirusCount

--select 16, getdate()

	SELECT
		@UnresolvedVirusCount = count(*)
	FROM	
		Events Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)

	WHERE
		Events.AutoID > @MaxEventidPrevious
		and VirusName > '' 
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        		AND Events.ProductName != 'ePO Agent' 
		and ReportActionDesc.ResolutionID < 0

if @szOptionalReportParms = 'test'
select '@UnresolvedVirusCount',  @UnresolvedVirusCount

--select 17, getdate()

	SELECT
		top 1 @MaxVirus = VirusName
 		,@MaxVirusCount = count(*)
	FROM	Events
	WHERE
		Events.AutoID > @MaxEventidPrevious
		and VirusName > '' 
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        		AND Events.ProductName != 'ePO Agent' 
	GROUP BY
		VirusName
	ORDER BY Count(*) Desc

	if @MaxVirusCount is NULL
		Set @MaxVirusCount = 0
	if @MaxVirus is NULL
		Set @MaxVirus = '---'

if @szOptionalReportParms = 'test'
select '@MaxVirus',  @MaxVirus

--select 18, getdate()

	SELECT
		top 1 @MaxUnresolvedVirus = VirusName
		,@MaxUnresolvedVirusCount = count(*)
	FROM	
		Events Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)
	WHERE
		Events.AutoID > @MaxEventidPrevious
		and VirusName > '' 
	   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   		AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        		AND Events.ProductName != 'ePO Agent' 
		and ReportActionDesc.ResolutionID < 0
	GROUP BY
		VirusName
	ORDER BY Count(*) Desc

if @szOptionalReportParms = 'test'
select '@MaxUnresolvedVirus',  @MaxUnresolvedVirus

	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- Fetch current compliance values (user defined compliance from compliance issues report and dat/engine order using in dat/engine reports
	-- Generate compliance problem counts (functionality of dat/engine and compliance issues reports)


	 -------------------------------------------------------------
	 -- fetch dat engine rules

	-- update top 5 dats and top 3 engines
	EXECUTE @ret= AVISP_ReportParmLoading 
	 @szOptionalReportParms  = '|REPORTDAT|RPTGRPDATENG|'


	IF EXISTS (select * from sysobjects where name = 'tmpDERules' 
   		and xtype = 'U')
 	DROP TABLE dbo.tmpDERules

	create table dbo.tmpDERules
	(
	RuleName nvarchar(50) null
	,ProductFamily nvarchar(50) null
	,DAT1 nvarchar(100) null
	,DAT2 nvarchar(100) null
	,DAT3 nvarchar(100) null
	,DAT4 nvarchar(100) null
	,DAT5 nvarchar(100) null
	,Eng1 nvarchar(100) null
	,Eng2 nvarchar(100) null
	,Eng3 nvarchar(100) null
	,DAT1DE nvarchar(100) null
	,Eng1DE nvarchar(100) null
	)


	-- fetch datengine rules
	insert dbo.tmpDERules
	exec @ret= dbo.AVISP_GetRuleDATEngine
	 @iNameSpaceName  = ''
	 ,@iNameSpaceNode = ''
	 ,@szEpoUserName  = ''
	 ,@szNameSpaceName  = ''
	 ,@szNameSpaceNode  = ''
	 ,@szOptionalReportParms  = ''

if @szOptionalReportParms = 'test'
select 'dbo.tmpDERules',  * from dbo.tmpDERules

	/*************************************************************************/
	-- Fetch compliance rules - Rule Value if given a Rule description (Most Recent, ...)

	Declare @MinAgentVersion nvarchar(50)

	select @MinAgentVersion=ParmValue from ReportInputParameters 
		where
			ReportInputParameters.ReportID = 'COMPLIANCEISSUES' 
			and ReportInputParameters.Parmname = 'ePO Agent' 

if @szOptionalReportParms = 'test'
select '@MinAgentVersion',  @MinAgentVersion


	IF EXISTS (select * from sysobjects where name = 'tmpPFVer' 
   		and xtype = 'U')
 	DROP TABLE dbo.tmpPFVer

	CREATE TABLE [dbo].[tmpPFVer] (
	ProductFamily nvarchar(50)
	 ,[AutoID] [int] NULL 
	 ,[Version] [nvarchar] (100) NULL
	 ,[Rulename] [nvarchar] (100) NULL
	,ParmName nvarchar(100)
	) 

	-- fetch compliance rules
	Insert dbo.tmpPFVer
	Execute dbo.AVISP_GetRuleComplianceIssues
	 @iNameSpaceName  = ''	
	 , @iNameSpaceNode  = ''	
	 , @szEpoUserName  = ''	
	 , @szNameSpaceName  = ''	
	 , @szNameSpaceNode  = ''	
	 , @szOptionalReportParms  = ''	
	 , @Rulename = ''		-- will fetch a particular saved rule name TODO

if @szOptionalReportParms = 'test'
select 'dbo.tmpPFVer',  * from dbo.tmpPFVer

-- debug only
--select * from dbo.tmpDERules
--select @szReportID


	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- determine compliance (assumes everything is compliant, any one of these exceptions means non compliance)
	-- non compliant if product version, dat, or engine not up to compliance rule standards

	Declare @NonComplianceDAT int
	Declare @NonComplianceEngine int
	Declare @NonComplianceProduct int
	Declare @NonComplianceComputer int
	Declare @NonComplianceAgentVersion int

	-- check for product version compliance
	update ReportComputerSummary set Compliant = 0
		from dbo.tmpPFVer
		where
			ReportComputerSummary.ProductName = dbo.tmpPFVer.ParmName
			and ReportComputerSummary.ProductFamily = dbo.tmpPFVer.ProductFamily
			and dbo.tmpPFVer.Rulename = 'ProductVersion'
			and ReportComputerSummary.ProductVersion < dbo.tmpPFVer.Version

	set    @NonComplianceProduct = @@rowcount

if @szOptionalReportParms = 'test'
select '@NonComplianceProduct',  @NonComplianceProduct

	-- check for product dat compliance
	update ReportComputerSummary set Compliant = 0
		from dbo.tmpPFVer
		where
			dbo.tmpPFVer.ParmName = ReportComputerSummary.ProductFamily + '_DATs'
			and dbo.tmpPFVer.Rulename = 'ParmValue'
			and ReportComputerSummary.DATVer < dbo.tmpPFVer.Version

	set    @NonComplianceDAT = @@rowcount

if @szOptionalReportParms = 'test'
select '@NonComplianceDAT',  @NonComplianceDAT


	-- check for product engine compliance
	update ReportComputerSummary set Compliant = 0
		from dbo.tmpPFVer
		where
			dbo.tmpPFVer.ParmName = ReportComputerSummary.ProductFamily + '_Engines'
			and dbo.tmpPFVer.Rulename = 'ParmValue'
			and ReportComputerSummary.EngineVer < dbo.tmpPFVer.Version

	set    @NonComplianceEngine = @@rowcount

if @szOptionalReportParms = 'test'
select '@NonComplianceEngine',  @NonComplianceEngine

	update ReportComputerSummary set Compliant = 0
		where NodeID in (select  NodeID  from ReportComputerSummary where AgentVersion <  @MinAgentVersion and ProductFamily = 'EPO')

	select    @NonComplianceAgentVersion =  @@rowcount

if @szOptionalReportParms = 'test'
select '@NonComplianceAgentVersion',  @NonComplianceAgentVersion

	update ReportComputerSummary set Compliant = 0
		where NodeID in (select  NodeID  from ReportComputerSummary where ProductVersion in ('---', '') )

	select    @NonComplianceComputer = count(*) from ReportComputerSummary where Compliant = 0
	set @ret = @NonComplianceComputer

if @szOptionalReportParms = 'test'
select '@NonComplianceComputer',  @NonComplianceComputer

	Declare @MaxDat varchar(20)
	Declare @MaxEngine varchar(20)
	select    @MaxDat = Max(DatVer) from ReportComputerSummary where DatVer <> '5000'
	select    @MaxEngine = Max(EngineVer) from ReportComputerSummary

if @szOptionalReportParms = 'test'
select '@MaxDat',  @MaxDat, @MaxEngine

	---------------------------------------------------------------------------
	-- determine top dat/engine stats 
	Declare @CountEngine3rdMostRecent int
	Declare @CountEngine2ndMostRecent int
	Declare @CountEngineMostRecent int
	Declare @CountEngineOutOfDate int
	Declare @CountDAT5thMostRecent int
	Declare @CountDAT4thMostRecent int
	Declare @CountDAT3rdMostRecent int
	Declare @CountDAT2ndMostRecent int
	Declare @CountDATMostRecent int
	Declare @CountDATOutOfDate int
	Declare @CountBothUpToDate int
	Declare @CountDATOutOfDateEngineOK int
	Declare @CountEngineOutOfDateDATOK int
	Declare @CountBothOutOfDate int


	select    @CountDATMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer >=  dbo.tmpDERules.DAT1

if @szOptionalReportParms = 'test'
select '@CountDATMostRecent',  @CountDATMostRecent

	select    @CountDAT2ndMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer >=  dbo.tmpDERules.DAT2

if @szOptionalReportParms = 'test'
select '@CountDAT2ndMostRecent',  @CountDAT2ndMostRecent

	select    @CountDAT3rdMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer >=  dbo.tmpDERules.DAT3

if @szOptionalReportParms = 'test'
select '@CountDAT3rdMostRecent',  @CountDAT3rdMostRecent

	select    @CountDAT4thMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer >=  dbo.tmpDERules.DAT4

if @szOptionalReportParms = 'test'
select '@CountDAT4thMostRecent',  @CountDAT4thMostRecent

	select    @CountDAT5thMostRecent = count(*) 
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer >=  dbo.tmpDERules.DAT5

if @szOptionalReportParms = 'test'
select '@CountDAT5thMostRecent',  @CountDAT5thMostRecent

	select    @CountDATOutOfDate = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DAT'
			and DATVer <  dbo.tmpDERules.DAT5

if @szOptionalReportParms = 'test'
select '@CountDATOutOfDate',  @CountDATOutOfDate

	select    @CountEngineMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'ENG'
			and EngineVer >=  dbo.tmpDERules.Eng1

if @szOptionalReportParms = 'test'
select '@CountEngineMostRecent',  @CountEngineMostRecent

	select    @CountEngine2ndMostRecent = count(*) 
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'ENG'
			and EngineVer >=  dbo.tmpDERules.Eng2

if @szOptionalReportParms = 'test'
select '@CountEngine2ndMostRecent',  @CountEngine2ndMostRecent

	select    @CountEngine3rdMostRecent = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'ENG'
			and EngineVer >=  dbo.tmpDERules.Eng3

if @szOptionalReportParms = 'test'
select '@CountEngine3rdMostRecent',  @CountEngine3rdMostRecent

	select    @CountEngineOutOfDate = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'ENG'
			and EngineVer <  dbo.tmpDERules.Eng3

if @szOptionalReportParms = 'test'
select '@CountEngineOutOfDate',  @CountEngineOutOfDate

	set @CountEngine3rdMostRecent = @CountEngine3rdMostRecent - @CountEngine2ndMostRecent
	set @CountEngine2ndMostRecent = @CountEngine2ndMostRecent - @CountEngineMostRecent
	set @CountDAT5thMostRecent = @CountDAT5thMostRecent - @CountDAT4thMostRecent
	set @CountDAT4thMostRecent = @CountDAT4thMostRecent - @CountDAT3rdMostRecent
	set @CountDAT3rdMostRecent = @CountDAT3rdMostRecent - @CountDAT2ndMostRecent
	set @CountDAT2ndMostRecent = @CountDAT2ndMostRecent - @CountDATMostRecent

	select    @CountBothUpToDate = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DATENG'
			and DATVer >=  dbo.tmpDERules.DAT1DE and EngineVer >=  dbo.tmpDERules.Eng1DE

if @szOptionalReportParms = 'test'
select '@CountBothUpToDate',  @CountBothUpToDate

	select    @CountDATOutOfDateEngineOK = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DATENG'
			and DATVer <  dbo.tmpDERules.DAT1DE and EngineVer >=  dbo.tmpDERules.Eng1DE

if @szOptionalReportParms = 'test'
select '@CountDATOutOfDateEngineOK',  @CountDATOutOfDateEngineOK

	select    @CountEngineOutOfDateDATOK = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DATENG'
			and DATVer >=  dbo.tmpDERules.DAT1DE and EngineVer <  dbo.tmpDERules.Eng1DE

if @szOptionalReportParms = 'test'
select '@CountEngineOutOfDateDATOK',  @CountEngineOutOfDateDATOK

	select    @CountBothOutOfDate = count(*)  
		from ReportComputerSummary, dbo.tmpDERules
		 where 	ReportComputerSummary.ProductFamily = dbo.tmpDERules.ProductFamily  and dbo.tmpDERules.RuleName = 'DATENG'
			and DATVer <  dbo.tmpDERules.DAT1DE and EngineVer <  dbo.tmpDERules.Eng1DE

if @szOptionalReportParms = 'test'
select '@CountBothOutOfDate',  @CountBothOutOfDate

	-----------------------------------------------------------------------------------
	-----------------------------------------------------------------------------------
	-- Collect and output all the variables


     -- If there is already an entry for today, then stop and exit - just do one run a day
     -- if its a new day then record the change
     if (DateDiff( day, @LastDate, GetDate() ) > 0 or @Tabcnt = 0) or (@szOptionalReportParms = 'test')
     begin

	insert into ReportComplianceComparison 
	select
	  @newcomputers as NewComputers
	 ,@removedcomputers as  RemovedComputers
	 ,@unchangedcomputers  as UnchangedComputers
	 ,@newinstalls  as NewInstalls
	 ,@removedinstalls  as RemovedInstalls
	 ,@NoScanner  as NoScanner
	 ,@ExtraDAT  as ExtraDAT
	 ,@NoAgent  as NoAgent
	 ,@UnchangedAsci  as UnchangedAsci
	 ,@newagentversion  as NewAgentVersion
	 ,@newscannerversion  as NewScannerVersion
	 ,@newengineversion  as NewEngineVersion
	 ,@newdatversion  as NewDATVersion
	 ,@newextradatversion  as NewExtradatVersion
	 ,@VirusCount  as VirusCount
	 ,@UnresolvedVirusCount  as UnresolvedVirusCount
	 ,@MaxVirus  as MaxVirus
	 ,@MaxUnresolvedVirus  as MaxUnresolvedVirus
	 ,@MaxVirusCount  as MaxVirusCount
	 ,@MaxUnresolvedVirusCount  as MaxUnresolvedVirusCount
	 ,@MaxEventid  as MaxEventid
	 , GetDate() as DateTimeEnd
	, @DateTimeStart as DateTimeStart

	 , @NonComplianceAgentVersion  as NonComplianceAgentVersion
	,  @NonComplianceDAT as NonComplianceDAT
	,  @NonComplianceEngine as NonComplianceEngine
	,  @NonComplianceProduct as NonComplianceProduct
	,  @NonComplianceComputer as NonComplianceComputer

	, @CountDATMostRecent  as CountDATMostRecent
	, @CountDAT2ndMostRecent  as CountDAT2ndMostRecent
	, @CountDAT3rdMostRecent  as CountDAT3rdMostRecent
	, @CountDAT4thMostRecent  as CountDAT4thMostRecent
	, @CountDAT5thMostRecent  as CountDAT5thMostRecent
	, @CountDATOutOfDate as CountDATOutOfDate
	, @CountEngineMostRecent  as CountEngineMostRecent
	, @CountEngine2ndMostRecent  as CountEngine2ndMostRecent
	, @CountEngine3rdMostRecent  as CountEnginee3rdMostRecent
	, @CountEngineOutOfDate as CountEngineOutOfDate
	, @CountBothUpToDate as CountBothUpToDate
	, @CountDATOutOfDateEngineOK as CountDATOutOfDateEngineOK
	, @CountEngineOutOfDateDATOK as CountEngineOutOfDateDATOK
	, @CountBothOutOfDate as CountBothOutOfDate

	,  @MaxDat as MinVersionDAT		-- misnamed, these are actually the max versions
	,  @MaxEngine  as MinVersionEngine
	 , cast( '' as nvarchar(20)) 	  as MinVersionProductMcAfee
	 , cast( '' as nvarchar(20)) 	 	 as MinAgentVersion
	 , cast( '' as nvarchar(20)) 	  as MinVersionProductSymantec

	, cast( '' as nvarchar(20))    as MinVersionDATMostRecent
	, cast( '' as nvarchar(20))    as MinVersionDAT2ndMostRecent
	, cast( '' as nvarchar(20))    as MinVersionDAT3rdMostRecent
	, cast( '' as nvarchar(20))    as MinVersionDAT4thMostRecent
	, cast( '' as nvarchar(20))    as MinVersionDAT5thMostRecent
	, cast( '' as nvarchar(20))    as MinVersionEngineMostRecent
	, cast( '' as nvarchar(20))    as MinVersionEngine2ndMostRecent
	, cast( '' as nvarchar(20))    as MinVersionEngine3rdMostRecent

	, @ComputersWithVirus as ComputersWithVirus
 	, @DuplicateComputer as DuplicateComputer 
 	, @MultipleScanner as MultipleScanner 
 	, @newservicepack as NewServicePack 
 	, @newhotfix as NewHotfix




	----------------------------------------------------------------------------
	-- Save Thus Computer summary table to ComputerSummaryPrevious for the next comparison run.
	TRUNCATE TABLE ReportComputerSummaryPrevious

 	INSERT ReportComputerSummaryPrevious
	  SELECT * FROM  ReportComputerSummary


	---------------------------------------------------------------------------
	-- Daily update of virustype table (determines type from virusname suffix & prefix rules)
	execute dbo.AVISP_FilterVirusType
		@iNameSpaceName		= ''
		,@iNameSpaceNode		= ''
    		,@szEpoUserName          = ''
		,@szNameSpaceName	= ''
		,@szNameSpaceNode	= ''
 		,@szOptionalReportParms   = 'BatchModeUpdateTableOnly'

	---------------------------------------------------------------------------
	-- Daily update of outbreak history table 
	Declare @Outbreakcnt int
	Declare @DateRule varchar(20)
--	postepo3: comment the following out to prevent the whole event table from going through outbreak analysis
--	select @Outbreakcnt = count(*) from ReportOutbreakEvents
--	if @Outbreakcnt = 0 
--		Set @DateRule = 'all'
--	else
		Set @DateRule = 'day1'
		
	execute dbo.AVISP_FilterOutbreakEvents
		@iNameSpaceName		= ''
		, @iNameSpaceNode	= ''
	    	, @szEpoUserName        = ''
		, @szNameSpaceName	= ''
		, @szNameSpaceNode	= ''
		, @szMinMachineCount	= '5'
		, @szMinFilenameCount	= '5'
		, @dtStartDate		= ''
		, @szHourRange		= '1'
		, @szOptionalReportParms = 'BatchModeUpdateTableOnly'
		, @InfectAfterRule 	= @DateRule

     end
     -- new day data added


	---------------------------------------------------------------------------
	-- final cleanup

	drop table  dbo.tmpPreviousNodeIDs
 	drop table  dbo.tmpNewNodeIDs
 	drop table  dbo.tmpOldNodeIDs
 	drop table  dbo.tmpDERules
 	drop table  dbo.tmpPFVer
		
/*
*/


RETURN @ret
END
GO


---------------------------------------------------------------------
---------------------------------------------------------------------
--  AVISP_FilterComplianceSummary


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


CREATE PROCEDURE dbo.AVISP_FilterComplianceSummary
(
 @iNameSpaceName  VARCHAR(20)
 , @iNameSpaceNode  VARCHAR(20)
 , @szEpoUserName  VARCHAR(100)
 , @szNameSpaceName  VARCHAR(100)
 , @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @dtInfectionCheckPoint varchar(64) = ''

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      	/* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
 	Declare @UsersTopNodeID int
 	Declare @FilterNodeID int
 	select @UsersTopNodeID = convert(int, @iNameSpaceName)
 	select @FilterNodeID = convert(int, @iNameSpaceNode)
	Declare @ret int
	set @ret=0

 	Declare @FilterID int
 	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT


     -- set default value
     if len(@dtInfectionCheckPoint) < 6
	Set @dtInfectionCheckPoint = '1/1/2000'
  
  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT


	------------------------------
	-- read in translated terms
   	Declare @Current varchar(30)			
   	Declare @Late varchar(30)			
   	Declare @Agent varchar(30)			
   	Declare @SuperAgentBroadcast varchar(100)	
   	Declare @SuperAgentRepository varchar(100)	
   	Declare @Unprotected varchar(30)		
   	Declare @Unlinked varchar(30)			
   	Declare @NoAgent varchar(30)		
   	Declare @Uncategorized varchar(50)		
	Declare @Critical varchar(50)
	Declare @Major varchar(50)			Declare @Minor varchar(50)
	Declare @Informational varchar(50)		Declare @Warning varchar(50)
	Declare @Blocked varchar(50)
	Declare @BufrOvflDetected varchar(200)
   	Declare @Server varchar(50)			
   	Declare @WorkStation varchar(50)	
	Declare @Professional varchar(50)	

	-- epo3.5 action string translation
	Declare @Cleaned varchar(50)			Declare	@Deleted varchar(50)
	Declare @Moved varchar(50)			Declare	@Excluded varchar(50)
	Declare @ContinueScan varchar(50)		Declare	@TestVirus varchar(50)
	Declare @CleanError varchar(50)			Declare	@DeleteError varchar(50)
	Declare @MoveError varchar(50)			Declare	@ExcludeError varchar(50)
	Declare @HeuristicError varchar(50)		Declare	@AccessDenied varchar(50)
	Declare @ScanTimedOut varchar(50)		Declare	@NotScanned varchar(50)
	Declare @NoCleaner varchar(50)			Declare	@CleanMoveError varchar(50)
	Declare @CleanDeleteError varchar(50)		Declare	@MoveDeleteError varchar(50)
	Declare @DeleteMoveError varchar(50)			
   	Declare @Resolved varchar(30)	
   	Declare @Unresolved varchar(30)	
	-- virustype	
 		Declare @MultiPartite varchar(50) 		Declare @MassMailer varchar(50)
 		Declare @Worm varchar(50) 		Declare @Trojan varchar(50)
 		Declare @Boot varchar(50) 		Declare @FileInfector varchar(50)
 		Declare @Macro varchar(50) 		Declare @Joke varchar(50)
 		Declare @Exploit varchar(50) 		Declare @Script varchar(50)
 		Declare @Test varchar(50)		Declare @Virus varchar(50)
 		Declare @KnownVirus varchar(50) 		
 		Declare @APP varchar(50) 		Declare @Application varchar(50)
 		Declare @app_spyware varchar(50) 		Declare @app_adware varchar(50)
 		Declare @app_remoteadmin varchar(50)
 		Declare @app_dialer varchar(50) 		Declare @app_pwcracker varchar(50)
 		Declare @app_pua varchar(50)
		Declare @Compliant varchar(50)		Declare @Uncompliant varchar(50)



	If @Current = '' or @Current is null				-- if first is not found assume they all are
	Begin
   		Set @Current = 'Current'	Set @Late = 'Late'	Set @Agent = 'Agent'
   		Set @SuperAgentBroadcast = 'Super Agent Broadcast'	Set @SuperAgentRepository = 'Super Agent Repository'
		Set @Unprotected = 'Unprotected'	Set @Unlinked = 'Unlinked'	Set @NoAgent = 'No Agent'
		Set @Critical = 'Critical'	Set @Major = 'Major'	Set @Minor = 'Minor'
		Set @Warning = 'Warning'	Set @Informational = 'Informational'
		Set @Blocked = 'Blocked'
		-- epo3.5 new string translation
   		Set @Server = 'Server'	Set @WorkStation = 'Workstation'	
		Set @Professional = 'Professional'
		-- epo3.5 action string translation
		Set @Cleaned ='Cleaned'				Set @Deleted ='Deleted'
		Set @Moved ='Moved'				Set @Excluded ='Excluded'
		Set @ContinueScan ='ContinuedScan'		Set @TestVirus ='Test Virus'
		Set @CleanError ='Clean Error'			Set @DeleteError ='Delete Error'
		Set @MoveError ='Move Error'			Set @ExcludeError ='Exclude Error'
		Set @HeuristicError ='Heuristic Error'		Set @AccessDenied ='Access Denied'
		Set @ScanTimedOut ='Scan Timed Out'		Set @NotScanned ='Not Scanned'
		Set @NoCleaner ='No Cleaner'			Set @CleanMoveError ='Clean-Move Error'
		Set @CleanDeleteError ='Clean-Delete Error'	Set @MoveDeleteError ='Move-Delete Error'
		Set @DeleteMoveError ='Delete-Move Error'			
	   	Set @Resolved ='Resolved'	
   		Set @Unresolved ='Unresolved'		
		-- epo 3.5 virustype
 		Set @MultiPartite ='MultiPartite' 		Set @MassMailer = 'Mass Mailer'
 		Set @Worm = 'Worm' 		Set @Trojan = 'Trojan'
 		Set @Boot = 'Boot' 		Set @FileInfector = 'File Infector'
 		Set @Macro = 'Macro' 		Set @Joke = 'Joke'
 		Set @Exploit = 'Exploit' 		Set @Script = 'Script'
 		Set @Test = 'Test' 		Set @Virus = 'Virus'
 		Set @KnownVirus = 'Known Virus' 		Set @Uncategorized = 'Uncategorized'
 		Set @APP = 'Application' 		Set @Application = 'Application'
 		Set @app_spyware = 'Spyware' 		Set @app_adware = 'Adware'
 		Set @app_remoteadmin = 'Remote Admin'
 		Set @app_dialer = 'Dialer' 		Set @app_pwcracker = 'Password cracker'
 		Set @app_pua = 'Unwanted program'
 		Set @Compliant = 'Compliant'
 		Set @Uncompliant = 'Uncompliant'
	End

	-- if not english, read in translations
	if @szFullLang <> '0409' 
--		and @szFullLang <> '0411'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0412'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0404'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0804'  -- apac chars dont display in charts, keep this english
	Begin
		Select 	@Current = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Current'
		Select 	@Late = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Late'
		Select 	@Agent =  'Agent'
		Select 	@SuperAgentBroadcast = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentBroadcast'
		Select 	@SuperAgentRepository = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'AgentType' and TextID = 'SuperAgentRepository'
		Select 	@Compliant = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Compliant'
		Select 	@Uncompliant = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Uncompliant'
		Select 	@Unlinked = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unlinked'
		Select 	@Resolved = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Resolved'
		Select 	@UnResolved = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unresolved'
		Select 	@Uncategorized = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Uncategorized'
		Select 	@Critical = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Critical'
		Select 	@Major = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Major'
		Select 	@Minor = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Minor'
		Select 	@Warning = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Warning'
		Select 	@Informational = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Severity' and TextID = 'Informational'
		-- vs7.5
		Select 	@Blocked = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Blocked'

		Select 	@Server = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Server'
		Select 	@WorkStation = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'WorkStation'
		Select 	@Professional = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Professional'
		-- epo3.5 action translations
		-- resolved
		Select 	@Cleaned = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 1
		Select 	@Deleted = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 2
		Select 	@Moved = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 3
		Select 	@Excluded = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 4
		Select 	@ContinueScan = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 5
		Select 	@TestVirus = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = 6
		-- unresolved
		Select 	@CleanError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -1
		Select 	@DeleteError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -2
		Select 	@MoveError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -3
		Select 	@ExcludeError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -4
		Select 	@HeuristicError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -5
		Select 	@AccessDenied = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -6
		Select 	@ScanTimedOut = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -7
		Select 	@NotScanned = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -8
		Select 	@NoCleaner = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -9
		Select 	@CleanMoveError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -10
		Select 	@CleanDeleteError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -11
		Select 	@MoveDeleteError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -12
		Select 	@DeleteMoveError = ActionName from ReportActionDesc 
			Where LanguageID = @szFullLang and ResolutionID = -13
		-- virustype
		Select 	@MultiPartite = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'MultiPartite'
		Select 	@MassMailer = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Mass Mailer'
		Select 	@Worm = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Worm'
		Select 	@Trojan = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Trojan'
		Select 	@Boot = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Boot'
		Select 	@FileInfector = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'FileInfector'
		Select 	@Macro = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Macro'
		Select 	@Joke = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Joke'
		Select 	@Exploit = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Exploit'
		Select 	@Script = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Script'
		Select 	@Test = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Test'
		Select 	@Virus = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Virus'
		Select 	@KnownVirus = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'KnownVirus'
		Select 	@APP = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'App'
		Select 	@Application = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'Application'
		Select 	@app_spyware = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_spyware'
		Select 	@app_adware = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_adware'
		Select 	@app_remoteadmin = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_remoteadmin'
		Select 	@app_dialer = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_dialer'
		Select 	@app_pwcracker = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_pwcracker'
		Select 	@app_pua = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'VirusType' and TextID = 'app_pua'

	End
	
	-- asian chars dont display in x-axis of bar chart, fetch these translations only if non-asian (except japanese)
	if @szFullLang <> '0409' 
		and @szFullLang <> '0412'  -- apac chars dont display in charts, keep this english
		and @szFullLang <> '0404'  -- apac chars dont display in charts, keep this english
		and @szFullLang <> '0804'  -- apac chars dont display in charts, keep this english
	Begin
		Select 	@Unprotected = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'Unprotected'
		Select 	@NoAgent = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'Rulename' and TextID = 'NoAgent'
	End

----------------------------
-- postepo cleanup temp tables

	IF EXISTS (select * from sysobjects where name = 'tmpCompliance' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpCompliance


	/* Stored procedure to create a table of nodeids, computers, agent versions, and summary event count data */
	/* This table persists and is recreated each time the report runs */

	-- No longer used in this routine in an effort to speed things up
--	Execute AVISP_SetComputerSummary @dtInfectionCheckPoint, NULL, NULL


	-- Fetch Infect After date variables
	Declare @InfectYYYYMMDD datetime
	execute dbo.AVISP_GetDateConversion @dtInfectionCheckPoint, '', @InfectYYYYMMDD output




	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- Fetch current compliance values (user defined compliance from compliance issues report and dat/engine order using in dat/engine reports
	-- Generate compliance problem counts (functionality of dat/engine and compliance issues reports)


	/*************************************************************************/
	-- Fetch compliance rules - Rule Value if given a Rule description (Most Recent, ...)

	Declare @MinAgentVersion nvarchar(50)

	select @MinAgentVersion=ParmValue from ReportInputParameters 
		where
			ReportInputParameters.ReportID = 'COMPLIANCEISSUES' 
			and ReportInputParameters.Parmname = 'ePO Agent' 

	IF EXISTS (select * from sysobjects where name = 'tmpPFVer' 
   		and xtype = 'U')
 	DROP TABLE dbo.tmpPFVer

	CREATE TABLE [dbo].[tmpPFVer] (
	ProductFamily nvarchar(50)
	 ,[AutoID] [int] NULL 
	 ,[Version] [nvarchar] (100) NULL
	 ,[Rulename] [nvarchar] (100) NULL
	,ParmName nvarchar(128)
	) 

	-- fetch compliance rules
	Insert dbo.tmpPFVer
	Execute dbo.AVISP_GetRuleComplianceIssues
	 @iNameSpaceName  = ''	
	 , @iNameSpaceNode  = ''	
	 , @szEpoUserName  = ''	
	 , @szNameSpaceName  = ''	
	 , @szNameSpaceNode  = ''	
	 , @szOptionalReportParms  = ''	
	 , @Rulename = ''		-- will fetch a particular saved rule name TODO


-- debug only
--select * from dbo.tmpPFVer
--select @MinAgentVersion

	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- determine compliance (assumes everything is compliant, any one of these exceptions means non compliance)
	-- non compliant if product version, dat, or engine not up to compliance rule standards

-- Enter two entries with a nodename, productname grouping: one for a compliance count, one for a non compliance count


-- fetch all computers - assume all having products are compliant
SELECT
   BranchNode.NodeName
   , Leafnode.Nodename as LNNodename
   , case
	when aviview_software.SoftwareName > '' then  aviview_software.SoftwareName
	else	case
		when Leafnode.AgentVersion > '' then @Unprotected
		else @NoAgent
		end
	end
	as ProductCode
--   , count(*) as 'ComputerCnt'
   , 1 as 'ComputerCnt'
   , case
	when aviview_software.SoftwareName > '' then  cast(@Compliant  as varchar(100)) 
	else	cast(@Uncompliant  as varchar(100)) 
	end
	as Compliant
--   , 'NonCompliant' as Compliant
 INTO dbo.tmpCompliance
  From 
	( Leafnode join Branchnode on (leafnode.parentid = branchnode.autoid) )
	left outer join
	( ProductProperties
	  join aviview_software 
		on (
			ProductProperties.ProductCode = aviview_software.ProductCode
			and ( aviview_software.ProductFamily in ('TVD', 'TVD_NC', 'SECURE')
			or aviview_software.ProductFamily like ('TVD_NC%') )
		)
	) on (ProductProperties.ParentID = LeafNode.AutoID)
 WHERE
   	(
    		@FilterID = 0 OR
     		LeafNode.ParentID = @FilterID OR
    		LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         		from BranchNodeEnum 
         		where  BranchNodeEnum.StartAutoID = @FilterID)
   	)

-- test
--select * from dbo.tmpCompliance
 

Update dbo.tmpCompliance
Set Compliant = cast(@Uncompliant  as varchar(100))
From
dbo.tmpPFVer, ProductProperties, aviview_software, leafnode, branchnode
  where
	dbo.tmpCompliance.LNNodename = Leafnode.Nodename
	and leafnode.parentid = branchnode.autoid
	and ProductProperties.ParentID = LeafNode.AutoID
	and ProductProperties.ProductCode = aviview_software.ProductCode
	and ( aviview_software.ProductFamily in ('TVD', 'TVD_NC', 'SECURE')
		or aviview_software.ProductFamily like ('TVD_NC%') )
	and 
	(
		(
			aviview_software.SoftwareName = dbo.tmpPFVer.ParmName
			and aviview_software.ProductFamily = dbo.tmpPFVer.ProductFamily
			and dbo.tmpPFVer.Rulename = 'ProductVersion'
			and ProductProperties.ProductVersion < dbo.tmpPFVer.Version
		)
		or
		(
			dbo.tmpPFVer.Parmname = aviview_software.ProductFamily + '_DATs'
			and dbo.tmpPFVer.Rulename = 'ParmValue'
			and ProductProperties.DATVer < dbo.tmpPFVer.Version
		)
		or
		(
			dbo.tmpPFVer.Parmname = aviview_software.ProductFamily + '_Engines'
			and dbo.tmpPFVer.Rulename = 'ParmValue'
			and ProductProperties.EngineVer < dbo.tmpPFVer.Version
		)
		or
		(
			LeafNode.AgentVersion < @MinAgentVersion or LeafNode.AgentVersion is NULL
		)	
		or
		(
			LeafNode.AVinstalls <= 0
		)	
	)
-- Group by
--   BranchNode.NodeName
--   , aviview_software.SoftwareName


-- test
--select * from dbo.tmpCompliance


--	select    @ret = sum(ComputerCnt) from dbo.tmpCompliance where Compliant = 'NonCompliant'

-- epo3.5 avoid getting a blank virusname in top 10 virus chart by filling in a default virusname value
-- in the compliance fields having a 0 virus count
Declare @DefaultVirus char(30)
select top 1 @DefaultVirus=virusname from events where virusname > ''

/* fetch product groups */
-- returns product group summaries

SELECT
--   NodeNameBranch as NodeName
   NodeName
   , NULL as AgentVersion
   , ProductCode
   , NULL as ProductVersion 
   , NULL as EngineVer 
   , NULL as DATVer 
   , NULL as ExtraDATNames 
   , NULL as DomainName
   , NULL as ProductFamily 
   , count(*) as 'ComputerCnt'
--  , sum(ComputerCnt) as 'ComputerCnt'
  , @DefaultVirus as VirusName
  , NULL as UserName
  , NULL as FileName
  , NULL as VirusType
   -- postepo3 33749 Remove ... Putting a zero for virus count makes sure that this dosnt get counted
  , cast(@Unresolved as nvarchar(50)) as ActionTaken  -- empty data replaces '...'
--  , '...' as ActionTaken
  , 0 as VirusCount
  , cast(Compliant as varchar(50)) as Compliant

 FROM dbo.tmpCompliance
 Group by
   NodeName
--	, LNNodename
	, ProductCode
	, Compliant


UNION

/* now fetch event data */

SELECT
   BranchNode.NodeName as NodeName
   , NULL as AgentVersion
   -- postepo3 33749 Make event productnames match software table product names
   , ProductCode = 
		CASE 
	     		WHEN  Events.ProductName = 'Netshield 2000' THEN 'NetShield'
	     		WHEN  Events.ProductName = 'Netshield' THEN 'NetShield'
	     		WHEN  Events.ProductName = 'VirusScan Ent' THEN 'VirusScan Enterprise'
	     		WHEN  Events.ProductName = 'VirusScan Ent.' THEN 'VirusScan Enterprise'
	     		ELSE  Events.ProductName
 	    		END
   , NULL as ProductVersion 
   , NULL as EngineVer 
   , NULL as DATVer 
   , NULL as ExtraDATNames 
   , NULL as DomainName
   , NULL as ProductFamily 
   , 0 as 'ComputerCnt'

/* This portion is filled in by unions of event data */
  , VirusName
  , NULL as UserName
  , NULL as FileName
  , NULL as VirusType
   ,ActionTaken =
	 		CASE 
	     		WHEN  ReportActionDesc.Resolution > '' THEN ReportActionDesc.Resolution
	     		ELSE  ''
 	    		END
  , count(*) as VirusCount
   -- postepo3 33749 Remove ... Putting a zero for computer count makes sure that this dosnt get counted
  , cast(@Compliant as varchar(50)) as Compliant	-- fake data computer count=0
--  , '...' as Compliant
 
 FROM 
	Events Join LeafNode on( Events.NodeID = LeafNode.AutoID )
	Join BranchNode on (LeafNode.ParentID = BranchNode.AutoID)
	Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
		and ReportActionDesc.LanguageID = @szFullLang)
 WHERE  
   (
    @FilterID = 0 OR
     LeafNode.ParentID = @FilterID OR
    LeafNode.ParentID in (select BranchNodeEnum.EndAutoID 
         from BranchNodeEnum 
         where  BranchNodeEnum.StartAutoID = @FilterID)
   )
  AND VirusName > '' 
   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   	AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
	AND Events.EventDateTime > @InfectYYYYMMDD

Group by
   BranchNode.NodeName
--   NodeNameBranch
   , Events.ProductName
  , VirusName
   , Events.ActionTaken
  , ReportActionDesc.Resolution


	DROP TABLE dbo.tmpCompliance
	DROP TABLE dbo.tmpPFVer

-- return # cmptrs noncompliant
RETURN @ret
END

GO


--------------------------------------------------------
--------------------------------------------------------
--  AVISP_GetRuleComplianceIssues

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

CREATE PROCEDURE dbo.AVISP_GetRuleComplianceIssues
(
 @iNameSpaceName  nVARCHAR(20)
 , @iNameSpaceNode  nVARCHAR(20)
 , @szEpoUserName  nVARCHAR(100)
 , @szNameSpaceName  nVARCHAR(100)
 , @szNameSpaceNode  nVARCHAR(500)
 , @szOptionalReportParms  nVARCHAR(500) = ''
 , @Rulename nvarchar(50) = ''		-- will fetch a particular saved rule name TODO
-- , @InfectionCheckPoint 		varchar(64)
-- , @AsciCheckPoint 		varchar(64)
--  , @AsciRule 			varchar(64) 
--  , @InfectAfterRule 		varchar(64)
)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      	/* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
 	Declare @UsersTopNodeID int
 	Declare @FilterNodeID int
	Declare @ret int
 	select @UsersTopNodeID = convert(int, @iNameSpaceName)
 	select @FilterNodeID = convert(int, @iNameSpaceNode)


 	Declare @FilterID int
 	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT

  
  /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT





/*************************************************************************/
-- Fetch Rule Value if given a Rule description (Most Recent, ...)

--	Close ProdFams
--	Deallocate ProdFams


	IF EXISTS (select * from sysobjects where name = 'tmpVer' 
   		and xtype = 'U')
  		DROP TABLE dbo.tmpVer

	CREATE TABLE [dbo].[tmpVer] (
	 [AutoID] [int] IDENTITY (1, 1) NOT NULL 
	 ,[Version] [nvarchar] (100) NULL
	 ,[Rulename] [nvarchar] (100) NULL
	) 


	IF EXISTS (select * from sysobjects where name = 'tmpProdFamVer' 
   		and xtype = 'U')
	  	DROP TABLE dbo.tmpProdFamVer

	CREATE TABLE [dbo].[tmpProdFamVer] (
	ProductFamily nvarchar(50)
	 ,[AutoID] [int] NULL 
	 ,[Version] [nvarchar] (100) NULL
	 ,[Rulename] [nvarchar] (100) NULL
	,ParmName nvarchar(100)
	) 

	Declare @ProdFam nvarchar(50)

	Declare ProdFams Cursor Forward_only static for
	select ProductFamily 
	from ProductProperties, AVIView_Software
	where 
	ProductProperties.ProductCode =  AVIView_Software.ProductCode
	and (ProductFamily in ('TVD', 'TVD_NC')
	or ProductFamily like 'TVD_NC%')
	Group By

	AVIView_Software.ProductFamily

	Open ProdFams

	Fetch Next from ProdFams into @ProdFam

	-- create table with all top dat/engine versions for each product family
	While @@Fetch_Status = 0
	begin
		truncate table dbo.tmpVer

		-- get top 3 dats
		insert dbo.tmpVer
		select top 3 DATVer as Version
		from ProductProperties, AVIView_Software
		where 
		ProductProperties.ProductCode =  AVIView_Software.ProductCode
		and ProductFamily = @ProdFam
		and DATVer != '5000'
		group by ProductFamily, DATVer
		order by DATVer Desc

-- remove functionality - not working and no time to fix
--		update dbo.tmpVer set Rulename = '1st Most Recent Version' where autoid = 1
--		update dbo.tmpVer set Rulename = '2nd Most Recent Version' where autoid = 2
--		update dbo.tmpVer set Rulename = '3rd Most Recent Version' where autoid = 3
 
		-- Insert version value for 1st, 2nd, 3rd most recent rulenames
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, dbo.tmpVer.autoid
			, dbo.tmpVer.Version
			, 'ParmValue'
			, @ProdFam + '_DATs'  as ParmName
			from dbo.tmpVer, ReportInputParameters
			where
				ReportInputParameters.ReportID = 'ComplianceIssues'
				and @ProdFam + '_DATs'  = ReportInputParameters.ParmName
				and ReportInputParameters.ParmValue = dbo.tmpVer.Rulename

		-- insert actual parmvalue if compliance setting is an actual dat version
		if @@rowcount = 0
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, 4
			, ParmValue
			, 'ParmValue'
			, @ProdFam + '_DATs'  as ParmName
			from ReportInputParameters 
			where
				ReportInputParameters.ReportID = 'ComplianceIssues'
				and @ProdFam + '_DATs'  = ReportInputParameters.ParmName

		-- get top engines
		truncate table dbo.tmpVer

		insert dbo.tmpVer
		select top 3 EngineVer as Version
		from ProductProperties, AVIView_Software
		where 
		ProductProperties.ProductCode =  AVIView_Software.ProductCode
		and ProductFamily = @ProdFam
		group by ProductFamily, EngineVer
		order by EngineVer Desc

--		update dbo.tmpVer set Rulename = '1st Most Recent Version' where autoid = 1
--		update dbo.tmpVer set Rulename = '2nd Most Recent Version' where autoid = 2
--		update dbo.tmpVer set Rulename = '3rd Most Recent Version' where autoid = 3

		-- Insert version value for 1st, 2nd, 3rd most recent rulenames
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, dbo.tmpVer.autoid
			, dbo.tmpVer.Version
			, 'ParmValue'
			, @ProdFam + '_Engines'  as ParmName
			from dbo.tmpVer, ReportInputParameters
			where
				ReportInputParameters.ReportID = 'ComplianceIssues'
				and @ProdFam + '_Engines'  = ReportInputParameters.ParmName
				and ReportInputParameters.ParmValue = dbo.tmpVer.Rulename

		-- insert actual parmvalue if compliance setting is an actual dat version
		if @@rowcount = 0
		insert dbo.tmpProdFamVer
		select 
			@ProdFam as ProductFamily
			, 4
			, ParmValue
			, 'ParmValue'
			, @ProdFam + '_Engines'  as ParmName
			from ReportInputParameters 
			where
				ReportInputParameters.ReportID = 'ComplianceIssues'
				and @ProdFam + '_Engines'  = ReportInputParameters.ParmName


		-- get next product family
		Fetch Next from ProdFams into @ProdFam

	end

	Close ProdFams
	Deallocate ProdFams


	---------------------------------------------------------------------------------------
	-- add product version rules

	insert dbo.tmpProdFamVer
	select
		ProductFamily
		,1
		,ReportInputParameters.ParmValue as Version
		,'ProductVersion' as Rulename
		, ReportInputParameters.ParmName as ParmName
 	FROM AVIView_Software, ReportInputParameters
	 WHERE  
	ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
	AND  AVIView_Software.SoftwareName = ReportInputParameters.ParmName
	and ( ProductFamily in ('TVD', 'TVD_NC', 'SECURE')
		or (ProductFamily = 'EPO' and ProductCode Like 'EPOAGENT%') 
--	and (ProductFamily in ('TVD', 'TVD_NC', 'SECURE', 'EPO')
	or ProductFamily like 'TVD_NC%')




	----------------------------------------------------
	-- dump results
	select * from dbo.tmpProdFamVer
	set @ret = @@rowcount

	-- cleanup
	Drop Table  dbo.tmpVer
	Drop Table  dbo.tmpProdFamVer


return @ret
end
GO


--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
/* compliance issues */
/* Compliance Issues Report */
if exists (select * from sysobjects where id = object_id(N'[dbo].[AVISP_FilterComplianceIssues]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AVISP_FilterComplianceIssues]
GO

SET QUOTED_IDENTIFIER  ON    SET ANSI_NULLS  ON 
GO


CREATE PROCEDURE dbo.AVISP_FilterComplianceIssues
(
 @iNameSpaceName  VARCHAR(20)
 , @iNameSpaceNode  VARCHAR(20)
 , @szEpoUserName  VARCHAR(100)
 , @szNameSpaceName  VARCHAR(100)
 , @szNameSpaceNode  VARCHAR(500)
 , @szOptionalReportParms  VARCHAR(500) = ''
 , @InfectionCheckPoint 		varchar(64)
 , @AsciCheckPoint 		varchar(64)
  , @AsciRule 			varchar(64) 
  , @InfectAfterRule 		varchar(64)

-- , @iMinMachineCount		int =5		-- outbreak def'n
-- , @iMinFilenameCount		int =5		-- outbreak def'n
-- , @iHourRange			int =24		-- outbreak def'n
-- , @RuleCutoff		int=7

)
AS
BEGIN
 /* Copyright c 1995-2001 Networks Associates Technology, Inc. All Rights Reserved.*/

      	/* Get ID to filter on: Users top node, user selected filter node (< top node), */
	/*    or no filtering (0) if users top node = root node and no filter selected */
 	Declare @UsersTopNodeID int
 	Declare @FilterNodeID int
	Declare @ret int
 	select @UsersTopNodeID = convert(int, @iNameSpaceName)
 	select @FilterNodeID = convert(int, @iNameSpaceNode)


 	Declare @FilterID int
 	EXECUTE AVIDALSP_GetNodeIDFilter @UsersTopNodeID, @FilterNodeID, @FilterID OUTPUT

    /* Fetch Report Parms: LANG, TIME, FILTER: not all of these are used in every proc */
   Declare @szLang VARCHAR(3)
   Declare @szFullLang VARCHAR(5)
   Declare @szDefaultLang VARCHAR(5)
   Declare @szLanguageID VARCHAR(5)
   Declare @szTime VARCHAR(10)
   Declare @szFilter VARCHAR(64)
   Declare @szReportID VARCHAR(64)
   Declare @szRptGroup VARCHAR(64)
   Set @szLanguageID = '0409'   
   Set @szLang = '09'
   Set @szFullLang = '0'
   Set @szTime = 'GMT'
   Set @szReportID = 'ASCI'


   if @szOptionalReportParms > ''
   	Execute AVISP_GetReportParms2 @szOptionalReportParms, 
		@szLang OUTPUT, @szFullLang OUTPUT, @szTime OUTPUT, 
		@szFilter OUTPUT, @szReportID OUTPUT,
		@szRptGroup OUTPUT



	-- Fetch Infect After date variables
	Declare @ConnectYYYYMMDD datetime
	execute dbo.AVISP_GetDateConversion @AsciCheckPoint, @AsciRule, @ConnectYYYYMMDD output

	-- Fetch Infect After date variables
	Declare @InfectYYYYMMDD datetime
	execute dbo.AVISP_GetDateConversion @InfectionCheckPoint, @InfectAfterRule, @InfectYYYYMMDD output

	-- 'all now returns blank value which must be altered for this report
	if @InfectYYYYMMDD = '' or @InfectYYYYMMDD is null
		set @InfectYYYYMMDD = '19900101'
	if @ConnectYYYYMMDD = '' or @ConnectYYYYMMDD is null
		set @ConnectYYYYMMDD = '19900101'

	/* Stored procedure to create a table of nodeids, computers, agent versions, and summary event count data */
	/* This table persists and is recreated each time the report runs */

	Execute AVISP_SetComputerSummary @InfectYYYYMMDD, @ConnectYYYYMMDD, NULL


	------------------------------
	-- read in translated terms
   	Declare @Server varchar(50)			
   	Declare @WorkStation varchar(50)			
	Declare @Professional varchar(50)	
		

	If @Server = '' or @Server is null				-- if first is not found assume they all are
	Begin
   		Set @Server = 'Server'	Set @WorkStation = 'Workstation'	
		Set @Professional = 'Professional'
	End

	-- if not english, read in translations
	if @szFullLang <> '0409' 
--		and @szFullLang <> '0411'  -- jp rpt will use chart labels instead of legends which wont display jp chars
--		and @szFullLang <> '0412'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0404'  -- apac chars dont display in charts, keep this english
--		and @szFullLang <> '0804'  -- apac chars dont display in charts, keep this english
	Begin
		Select 	@Server = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Server'
		Select 	@WorkStation = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'WorkStation'
		Select 	@Professional = TranslatedValue from ReportTranslations 
			Where LanguageID = @szFullLang and Subject = 'General' and TextID = 'Professional'
	End


	------------------------------------------------------------------------------------------
	-- If no data exists in ReportComplianceComparison table then run routine to fill it
	-- Do this so that there is data in the compliance subreports
	Declare @dtInfectionCheckPoint DateTime
	Set @dtInfectionCheckPoint = DateAdd( day, -1, GetDate())
	if not exists ( select * from ReportComplianceComparison )
		Execute dbo.AVISP_SetComplianceComparison
			 @iNameSpaceName  
			 , @iNameSpaceNode  
			 , @szEpoUserName  
--			 , @szNameSpaceName 
--			 , @szNameSpaceNode  
			 , @szOptionalReportParms  
			 , @dtInfectionCheckPoint 


/*************************************************************************/
-- Fetch compliance rules - Rule Value if given a Rule description (Most Recent, ...)

--	Close ProdFams
--	Deallocate ProdFams

	Declare @MinAgentVersion nvarchar(50)

	select @MinAgentVersion=ParmValue from ReportInputParameters 
		where
			ReportInputParameters.ReportID = 'COMPLIANCEISSUES' 
			and ReportInputParameters.Parmname = 'ePO Agent' 


	-- postepo3 Change table name here and in dateng report so it doesnt match the table name
	--	used within the getrule routine (make columns bigger)
	IF EXISTS (select * from sysobjects where name = 'tmpPFVer' 
   		and xtype = 'U')
 	DROP TABLE dbo.tmpPFVer

	CREATE TABLE [dbo].[tmpPFVer] (
	ProductFamily nvarchar(50)
	 ,[AutoID] [int] NULL 
	 ,[Version] [nvarchar] (100) NULL
	 ,[Rulename] [nvarchar] (100) NULL
	,ParmName nvarchar(100)
	) 

	Insert dbo.tmpPFVer
	Execute dbo.AVISP_GetRuleComplianceIssues
	 @iNameSpaceName  = ''	
	 , @iNameSpaceNode  = ''	
	 , @szEpoUserName  = ''	
	 , @szNameSpaceName  = ''	
	 , @szNameSpaceNode  = ''	
	 , @szOptionalReportParms  = ''	
	 , @Rulename = ''		-- will fetch a particular saved rule name TODO




/**************************************************************************/
/* Implement each compliance rule with a union clause */
/* todo - localize rule name and description (get it from text strings table) */

-- Rules listed by priority - RuleCutoff value wont run any lower rules
-- Rule 1 - No Agents: fetch machines with NO Agent 
-- Rule 2 - No AV Protection: fetch machines with NO AV machines and an Agent 
-- Rule 3 - Unresolved Viruses: fetch machines with unresolved virus after InfectionCheckpoint date
-- Rule 4 - Old DAT/Engine: fetch machines with old dat/engines and recent Asci 
-- Rule 5 - Old Products: fetch machines with old Prod versions and recent Asci 
-- Rule 6 - Old Agent: fetch machines with old Agent versions and recent Asci 
-- Rule 7 - Late Asci: fetch machines with LastAsci < AsciCheckpoint date (recent Asci)



-- Rule 1 - fetch machines with NO Agent 
       SELECT
   	'No Agents' as RuleName
	, 'Machines without an ePO agent' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion 
     		ELSE '---'
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
  	 , DATVer =
    		CASE  
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, NodeNameLeaf as ComputerName  -- Use leafnode nodename for noagent since they usually dont have computer props
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
--  	, '' as FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 1 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , '' as Servicepack
	, '' as Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)

  	 )
	AND ReportComputerSummary.NoAgent = 1
--	AND @RuleCutoff > 1

-- Rule 2 - fetch machines with NO AV machines and an Agent 
UNION

       SELECT
   	'No AV Protection' as RuleName
	, 'Machines without anti-virus protection' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 2 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , '' as Servicepack
	, '' as Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.NoAgent = 0
	AND ReportComputerSummary.NoAV = 1
--	AND @RuleCutoff > 2




-- Rule 4 - Old DAT/Engine: fetch machines with old dat/engines and recent Asci 
UNION

       SELECT
   	'Old DAT/Engine' as RuleName
	, 'Machines with outdated DATs or Engines' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	,  ComputerName  
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 4 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        	, Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary, ReportInputParameters, dbo.tmpPFVer 

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.AsciSinceCheckPoint = 1
	and ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
	AND 
	(
		(ReportInputParameters.ParmName = ReportComputerSummary.ProductFamily + '_DATs'
		and ReportInputParameters.ParmName = dbo.tmpPFVer.ParmName
		and  DATVer < dbo.tmpPFVer.Version	
		)		
		OR
		(ReportInputParameters.ParmName = ReportComputerSummary.ProductFamily + '_Engines'
		and ReportInputParameters.ParmName = dbo.tmpPFVer.ParmName
		and  EngineVer < dbo.tmpPFVer.Version
		)		
	)
--	AND @RuleCutoff > 4

-- Rule 5 - Old Products: fetch machines with old Prod versions and recent Asci 
UNION

       SELECT
   	'Old Products' as RuleName
	, 'Machines with outdated anti-virus scanning products' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 5 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary, ReportInputParameters

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.AsciSinceCheckPoint = 1
	and ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
	AND  ReportComputerSummary.ProductName = ReportInputParameters.ParmName
	and ReportComputerSummary.ProductVersion < ReportInputParameters.ParmValue

--	AND @RuleCutoff > 5


-- Rule 6 - Old Agent: fetch machines with old Agent versions and recent Asci 
UNION

       SELECT
   	'Old Agent' as RuleName
	, 'Machines with an outdated ePO agent' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, AgentVersion as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 

     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount

	, 6 as RuleNumber
--	, LastAsci
   	, CONVERT(char(50),
  	 (SUBSTRING( ReportComputerSummary.LastAsci,  1 , 4)+'-'+
   	SUBSTRING( ReportComputerSummary.LastAsci,  5 , 2)+'-'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  7 , 2)+' '+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  9 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  11 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  13 , 2)                                    
  	 ), 120 )   as LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary, ReportInputParameters

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.AsciSinceCheckPoint = 1
	and ReportInputParameters.ReportID = 'COMPLIANCEISSUES'
	AND  ReportComputerSummary.AgentName = ReportInputParameters.ParmName
	and ReportComputerSummary.AgentVersion < ReportInputParameters.ParmValue

--	AND ReportComputerSummary.AsciSinceCheckPoint = 1
--	AND AgentVersion < @MinAgentVersion



-- Rule 7 - Late Asci: fetch machines with LastAsci < AsciCheckpoint date (recent Asci)
UNION

       SELECT
   	'Inactive Agents' as RuleName
	, 'Machines That have not checked-in since ASCI checkpoint cuttoff' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, AgentVersion as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 7 as RuleNumber
--	, LastAsci
   	, CONVERT(char(50),
  	 (SUBSTRING( ReportComputerSummary.LastAsci,  1 , 4)+'-'+
   	SUBSTRING( ReportComputerSummary.LastAsci,  5 , 2)+'-'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  7 , 2)+' '+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  9 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  11 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  13 , 2)                                    
  	 ), 120 )   as LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.AsciSinceCheckPoint = 0
--	AND @RuleCutoff > 7


-- Rule 8 - Duplicate Computers - Machines having duplicate entries in ePO (shows the outdated entry)
UNION

       SELECT
   	'Orphaned Computers' as RuleName
	, 'Machines having duplicate entries in ePO (shows the outdated entry)' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, AgentVersion as AgentVersion
   	, ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE  
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'  
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  ReportComputerSummary.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 8 as RuleNumber
--	, LastAsci
   	, CONVERT(char(50),
  	 (SUBSTRING( ReportComputerSummary.LastAsci,  1 , 4)+'-'+
   	SUBSTRING( ReportComputerSummary.LastAsci,  5 , 2)+'-'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  7 , 2)+' '+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  9 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  11 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  13 , 2)                                    
  	 ), 120 )   as LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.DuplicateComputer > 0
--	AND @RuleCutoff > 7


-- Rule 9 - Duplicate Scanners - Machines having duplicate Scanning Products in ePO (shows the outdated entry)
UNION

       SELECT
   	'Orphaned Scanners' as RuleName
	, 'Machines having duplicate Scanning Products in ePO (shows the outdated entry)' as RuleDescription
   	, NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, AgentVersion as AgentVersion
   	, AVIView_Software.SoftwareName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ProductProperties.ProductVersion > '' THEN ProductProperties.ProductVersion
     		ELSE '---'
     		END
   	, EngineVer =
    		CASE  
     		WHEN ProductProperties.EngineVer > '' THEN ProductProperties.EngineVer 
     		WHEN ProductProperties.EngineVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
  	 , DATVer =
    		CASE 
     		WHEN ProductProperties.DATVer > '' THEN ProductProperties.DATVer 
     		WHEN ProductProperties.DATVer = 'N/A' THEN '---' 
     		ELSE '---'
     		END
   	, ExtraDATNames =
    		CASE ProductProperties.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ProductProperties.ExtraDATNames 
     		END
	, ProductFamily = 
    	CASE 
     	WHEN  AVIView_Software.ProductFamily = 'TVD' THEN 'McAfee'
     	WHEN  AVIView_Software.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
     	ELSE  AVIView_Software.ProductFamily 
     	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, '' as VirusName
  	, '' as UserName
    	, CAST('' As varchar(255)) As FileName
  	, '' as VirusType
  	, '' as ActionTaken
  	, '' as EventDateTime 
--  	, 0 as VirusCount
	, 9 as RuleNumber
--	, LastAsci
   	, CONVERT(char(50),
  	 (SUBSTRING( ReportComputerSummary.LastAsci,  1 , 4)+'-'+
   	SUBSTRING( ReportComputerSummary.LastAsci,  5 , 2)+'-'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  7 , 2)+' '+                              

   	SUBSTRING( ReportComputerSummary.LastAsci,  9 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  11 , 2)+':'+                              
   	SUBSTRING( ReportComputerSummary.LastAsci,  13 , 2)                                    
  	 ), 120 )   as LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , ProductProperties.Servicepack
	, ProductProperties.Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM ReportComputerSummary, ProductProperties, AVIView_Software

	 WHERE  
   	(
   	@FilterID = 0 OR
     	ReportComputerSummary.BranchNodeID = @FilterID OR
    	ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
         	from BranchNodeEnum 
         	where  BranchNodeEnum.StartAutoID = @FilterID)
  	 )
	AND ReportComputerSummary.MultipleScanner > 1
	and ReportComputerSummary.DuplicateScannerID = ProductProperties.AutoID
	and ProductProperties.ProductCode =  AVIView_Software.ProductCode
--	AND @RuleCutoff > 7


/*
-- Rule 10 - Outbreak Infections: Machines affected by an Outbreak
UNION

       SELECT
   	'Outbreak Infections' as RuleName
	, 'Machines affected by an Outbreak' as RuleDescription
   	, ReportComputerSummary.NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ReportComputerSummary.ProductName as ProductName
   	, ProductVersion =
    		CASE ReportComputerSummary.ProductVersion
     		WHEN '' THEN '---' 
     		ELSE ReportComputerSummary.ProductVersion
     		END
   	, EngineVer =
    		CASE ReportComputerSummary.EngineVer 
     		WHEN '' THEN '---' 
     		WHEN 'N/A' THEN '---' 
     		ELSE ReportComputerSummary.EngineVer 
     		END
  	 , DATVer =
    		CASE ReportComputerSummary.DATVer 
     		WHEN '' THEN '---' 
     		WHEN 'N/A' THEN '---' 
     		ELSE ReportComputerSummary.DATVer 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
 	   	CASE 
 	    	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
  	   	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
   	  	ELSE  ReportComputerSummary.ProductFamily 
    	 	END
	, DomainName
	, ComputerName
	, IPAddress

--	   , count(*) as 'ComputerCnt'

	-- This portion is filled in by unions of event data 
  	, VirusName
  	, UserName
    	, CAST(FileName As varchar(255)) As FileName
  	, VirusType
  	, ActionTaken = ReportOutbreakEvents.ActionTaken
--	    	CASE 
-- 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
--	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
--	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
--	     	END
  	, EventDateTime  
--		= (CASE @szTime
--			WHEN 'GMT' THEN MAX(EventDateTime)
--			ELSE 		MAX(EventLocalDateTime)
--		END) 

 -- 	, count(*) as VirusCount
	, 10 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , ReportComputerSummary.Servicepack
	, ReportComputerSummary.Hotfix
	, ReportComputerSummary.ProductCode as ProductCode


 	FROM ReportComputerSummary, ReportOutbreakEvents

	 WHERE  
   	(
   	 @FilterID = 0 OR
	     ReportComputerSummary.BranchNodeID = @FilterID OR
	    ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
  	       from BranchNodeEnum 
  	       where  BranchNodeEnum.StartAutoID = @FilterID)
   	)
  	AND ReportOutbreakEvents.NodeID = ReportComputerSummary.NodeID	
	AND VirusName > '' 
	AND ReportOutbreakEvents.EventDateTime > @InfectionCheckPoint
--	AND ActionTaken in ('51','53','55','58','62','64','66')
--	AND @RuleCutoff > 3
	Group by
--   		RuleName
--		, RuleDescription
--   		, 
		ReportComputerSummary.NodeNameBranch
		, FullNodePath
		   , AgentVersion
		   , ReportComputerSummary.ProductName
		   , ReportComputerSummary.ProductVersion
		   , EngineVer
		   , DATVer
		   , ExtraDATNames

		   , DomainName
		   , ProductFamily
		, DomainName
		, ComputerName
		, IPAddress
		, OSVersion
		, LastAsci
		  , VirusName
		  , UserName
		  , FileName
		  , VirusType
		  ,   ActionTaken
--			CASE 
--			WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
--			WHEN  ReportActionDesc.ActionName = '' THEN '---'
--			ELSE  CAST(Events.ActionTaken AS varchar(16))
--		     	END
		, EventDateTime
		, LastAsci
		, ReportComputerSummary.NodeID
        , ReportComputerSummary.Servicepack
	, ReportComputerSummary.Hotfix
	, ReportComputerSummary.ProductCode 

*/

-- Rule 3 - Unresolved Viruses: fetch machines with unresolved virus after InfectionCheckpoint date
UNION

       SELECT
   	'Unresolved Viruses' as RuleName
	, 'Machines with an unresolved virus' as RuleDescription
   	, ReportComputerSummary.NodeNameBranch as NodeName
	, cast( FullNodePath as varchar(255) ) as FullNodePath
   	, '' as AgentVersion
   	, ReportComputerSummary.ProductName as ProductName
   	, ProductVersion =
    		CASE 
     		WHEN ReportComputerSummary.ProductVersion > '' THEN ReportComputerSummary.ProductVersion
     		ELSE '---' 
     		END
   	, EngineVer =
    		CASE 
     		WHEN ReportComputerSummary.EngineVer > '' THEN ReportComputerSummary.EngineVer 
     		WHEN ReportComputerSummary.EngineVer = 'N/A' THEN ReportComputerSummary.EngineVer 
     		ELSE '---' 
     		END
  	 , DATVer =
    		CASE 
     		WHEN ReportComputerSummary.DATVer > '' THEN ReportComputerSummary.DATVer 
     		WHEN ReportComputerSummary.DATVer = 'N/A' THEN '---' 
     		ELSE '---' 
     		END
   	, ExtraDATNames =
    		CASE ReportComputerSummary.ExtraDATNames 
     		WHEN 'N/A' THEN '' 
     		ELSE ReportComputerSummary.ExtraDATNames 
     		END
	, ProductFamily = 
 	   	CASE 
 	    	WHEN  ReportComputerSummary.ProductFamily = 'TVD' THEN 'McAfee'
  	   	WHEN  ReportComputerSummary.ProductFamily = 'TVD_NC' THEN 'NonMcAfee'
   	  	ELSE  ReportComputerSummary.ProductFamily 
    	 	END
	, DomainName
	, ComputerName
	, IPAddress
--	   , count(*) as 'ComputerCnt'

	/* This portion is filled in by unions of event data */
  	, VirusName
  	, UserName
    	, CAST(FileName As varchar(255)) As FileName
  	, VirusType
  	, ActionTaken =
	    	CASE 
 	    		WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
	     		WHEN  ReportActionDesc.ActionName = '' THEN '---'
	     		ELSE  CAST(Events.ActionTaken AS varchar(16))
	     	END
  	, EventDateTime = 
		(CASE @szTime
			WHEN 'GMT' THEN MAX(EventDateTime)
			ELSE 		MAX(EventLocalDateTime)
		END) 

 -- 	, count(*) as VirusCount
	, 3 as RuleNumber
	, LastAsci
	, OSVersion
	, ReportComputerSummary.NodeID
        , Servicepack
	, Hotfix
	, ReportComputerSummary.ProductCode as ProductCode
	, ReportComputerSummary.ScannerLanguage as Language
		,case 
			when ReportComputerSummary.OSPlatform = 'Server' then @Server
			when ReportComputerSummary.OSPlatform = 'Workstation' then @Workstation
			when ReportComputerSummary.OSPlatform = 'Professional' then @Professional
			else ReportComputerSummary.OSPlatform
			end 
			as OSPlatform
	, ReportComputerSummary.OSType

 	FROM 
		Events Join ReportComputerSummary on(Events.NodeID = ReportComputerSummary.NodeID)
		Left Outer Join ReportActionDesc on (Events.ActionTaken = ReportActionDesc.ActionIntID
			and ReportActionDesc.LanguageID = @szFullLang)

	 WHERE  
   	(
   	 @FilterID = 0 OR
	     ReportComputerSummary.BranchNodeID = @FilterID OR
	    ReportComputerSummary.BranchNodeID in (select BranchNodeEnum.EndAutoID 
  	       from BranchNodeEnum 
  	       where  BranchNodeEnum.StartAutoID = @FilterID)
   	)
	AND VirusName > '' 
   	AND TVDEventID not in (1202, 1203, 1506, 4600, 4650, 4651)  -- webshield\spam killer events, scan on/off
   	AND (  TVDEventID < 8500 or TVDEventID > 8999  )
        	AND Events.ProductName != 'ePO Agent' 
	AND Events.EventDateTime > @InfectYYYYMMDD




	Group by
--   		RuleName
--		, RuleDescription
--   		, 
		ReportComputerSummary.NodeNameBranch
		, FullNodePath
		   , AgentVersion
		   , ReportComputerSummary.ProductName
		   , ReportComputerSummary.ProductVersion
		   , EngineVer
		   , DATVer
		   , ExtraDATNames
		   , DomainName
		   , ProductFamily
		, DomainName
		, ComputerName
		, IPAddress
		, OSVersion
		, LastAsci
		  , VirusName
		  , UserName
		  , FileName
		  , VirusType
--		  , Events.ProductID
		, ReportActionDesc.ActionName
		, Events.ActionTaken
--		  ,    CASE 
--			WHEN  ReportActionDesc.ActionName > '' THEN ReportActionDesc.ActionName
--			WHEN  ReportActionDesc.ActionName = '' THEN '---'
--			ELSE  CAST(Events.ActionTaken AS varchar(16))
--		     	END
		, LastAsci
		, ReportComputerSummary.NodeID
        	, Servicepack
		, Hotfix
	, ReportComputerSummary.ProductCode
	, ReportComputerSummary.ScannerLanguage 
	, ReportComputerSummary.OSPlatform
	, ReportComputerSummary.OSType

	set @ret = @@rowcount

	Drop Table dbo.tmpPFVer

RETURN @ret
END
GO

------



