<%

'*****************************************************************************
' Microsoft Content Management Server
'
' File: SDReportInitialize.INC
'
' Purpose:
'   ASP server-side include file that performs initialization for any Site
'	Deployment report. This file is one of the first files included by the
'	main report ASP file, and takes care of creating global objects and 
'	parsing the report XML.
'
' GLOBAL DEPENDENCIES:
'	pReportXMLTag [out] - the root XML tag of the report XML.
'	pGrammarParser [out] - instance of grammar parser for manipulating XML
'
'*****************************************************************************

	'*************************************************************************
	' CONSTANTS
	'*************************************************************************
	
	' CONSTANTS FOR THE VARIOUS STYLES USED IN THE Export OBJECTS
	' TREE - THESE CONSTANTS MUST MATCH THE STYLE NAMES IN THE 
	' SITE DEPLOYMENT REPORTS STYLE SHEET
	
	' declare a constant that indicates what the ID of any container
	' nodes are in the tree. This helps us search for the most 
	' immediately parent container tag when one of a container's 
	' children is clicked on
	const ID_CONTAINER = "ObjectContainer"
	
	' declare a constant that represents the style of a node in the
	' tree that represents a non-container Export object
	const ID_ITEM = "ObjectItem"
	
	' declare a constant that represents the style of a list when 
	' used in the Export objects tree to list the children of a 
	' node in the tree
	const ID_LIST_OBJECTS = "ObjectList"
	
	' declare a constant that represents the style of a list when 
	' used to display child Export objects in the Export objects 
	' tree
	const ID_LIST_CHILD_OBJECTS = "ObjectChildren"
	
	' define a set of style names that indicate how to treat the various
	' columns in the tables that are used to spit out objects in 
	' the reports
	'
	' NOTE: THESE STYLE NAMES MUST MATCH THOSE DEFINED IN THE SITE 
	' DEPLOYMENT REPORTS STYLE SHEET
	
	' IMPORT Styles
	const ID_COLUMN_SOURCE = "SourceColumn"
	const ID_COLUMN_LOCATIONACTION = "LocationActionColumn"
	const ID_COLUMN_DESTINATION = "DestinationColumn"
	
	' EXPORT Styles
	const ID_COLUMN_APPROVEDEXISTS = "ApprovedExistsColumn"
	const ID_COLUMN_STATUS = "StatusColumn"
	const ID_COLUMN_LASTMODIFIED = "LastModifiedColumn"
	
	' constants used in the XML to describe various types of export
	' and import objects. There is basically one entry here for every
	' type of node in the Resolution system
	const strOBJECT_TYPE_RESGAL = "ResourceGallery"
	const strOBJECT_TYPE_RESGALITEM = "Resource"
	const strOBJECT_TYPE_TEMPGAL = "TemplateGallery"
	const strOBJECT_TYPE_TEMPLATE = "Template"
	const strOBJECT_TYPE_FOLDER = "Folder"
	const strOBJECT_TYPE_PAGE = "Page"
	const strOBJECT_TYPE_CHANNEL = "Channel"
	const strOBJECT_TYPE_POSTING = "Posting"
	const strOBJECT_TYPE_URG = "RightsGroup"
	const strOBJECT_TYPE_USER = "User"

	' HOTFIX #8110 - following constant introduced:
	' constant for Locale ID for English (United States)
	const lLCID_ENGLISH_US = 1033
	
	' NOTE: the use of classes in VBScript requires VBSCRIPT 5.0 or later

	' declare a global class that will be used throughout this
	' script to maintain state information about the type of Export
	' object being dumped out
	class CObjectTypeInfo
	
		' the XML tag that points to the collection of Export objects
		' to be dumped out
		private m_pObjectTypeXMLTag
		
		' the type of container that we expect in the XML for this 
		' collection of Export objects - type integer
		private m_nObjectContainerType
		
		' the type of item that we expect in the XML for this collection
		' of Export objects - type integer
		private m_nObjectItemType

		' initialization method that sets all of the member variables
		' with known values
		public sub Initialize( pXMLTag, varContainerType, varItemType )
		
			set m_pObjectTypeXMLTag = pXMLTag

			' we expect client to initialize us with a string object type
			' so we need to convert them b4 we store them in memvars

			if IsNumeric(varContainerType) then
				m_nObjectContainerType = CInt(varContainerType)
			else
				m_nObjectContainerType = MapStringToSDType(varContainerType)
			end if

			if IsNumeric(varItemType) then
				m_nObjectItemType = CInt(varItemType)
			else
				m_nObjectItemType = MapStringToSDType(varItemType)
			end if
			
		end sub
		
		' PROPERTY DEFINITIONS (corresponding to member variables above)
		
		property get XMLTag
			set XMLTag = m_pObjectTypeXMLTag
		end property
		
		' The member variable is of type Integer.  
		' Note that the Property should be compared against numeric type.
		'	E.g. if CInt(pExportedObject.ObjectType) = m_pObjectTypeInfo.ContainerType then...
		' This is because the XML tag/attribute values are normally retrieved as string.		
		
		property get ContainerType
			' just for safety even though we defined m_nObjectContainerType as CInt 
			' at the start
			ContainerType = CInt(m_nObjectContainerType)
		end property
		
		' The member variable is of type Integer.  
		' Note that the Property should be compared against numeric type.
		'	E.g. if CInt(pExportedObject.ObjectType) = m_pObjectTypeInfo.ItemType then...
		' This is because the XML tag/attribute values are normally retrieved as string.		

		property get ItemType
			' just for safety even though we defined m_nObjectItemType as CInt 
			' at the start
			ItemType = CInt(m_nObjectItemType)
		end property
		
		property get ItemTypeForDisplay
			' just for safety even though we defined m_nObjectItemType as CInt 
			' at the start
			if m_nObjectItemType = NR_OP_OBJECT_TYPE_POSTING then
				ItemTypeForDisplay = NR_OP_OBJECT_TYPE_PAGE
			else				
				ItemTypeForDisplay = CInt(m_nObjectItemType)
			end if
		end property
		
		' TODO: Put in member functions to return the PLURAL of a 
		' container and item name

	end class


	'*************************************************************************
	' Subroutines/Functions
	'*************************************************************************

	' private function to work out a timeout estimate based on the report file
	' size.
	function estimateTimeOutByReportSize( strFilePath )
		
		
		estimateTimeOutByReportSize = 0
		
		' NOTE: customizing the script timeout is necessary as report ASP
		'		timeouts may occur to large XML files.
		'
		'		we won't set a timeout of more than 15 minutes.  if anyone
		' 		still times out on 15 minutes, we learn something new.
		' 		revise if necessary.
		'       the following heristics is purely ARBITRARY due to lack of
		'		sampling, update if necessary.
		
		const lTIMEOUT_90_SECONDS = 90	' 90 secs, IIS's default
		const lTIMEOUT_5_MINUTE  = 300	' 5 minute
		const lTIMEOUT_15_MINUTE = 900	' 15 minute

		' Fixes bug 6939: The report file that is being accessed is stored in 
		' the resource cache directory. With version 4.1, the permissions
		' on this directory have been changed such that directory listing
		' priviliges are disabled on the folder. For some unknown reason,
		' calling f.Size on a file in a folder that does not have list
		' permissions will fail. As a result, we cannot make a good 
		' estimate of the timeout period. As a temporary fix, we will use
		' the largest timeout value. In the future, we should revisit this
		' problem and make a better estimate using some other means (e.g.
		' number of objects in the report). The code below is left in 
		' a commented out capacity as it will need to be revisited.
		
		Dim lTimeOutVal		' in seconds
		lTimeOutVal = lTIMEOUT_15_MINUTE
		
'		Dim fso, f
		
'	   	Set fso = CreateObject( "Scripting.FileSystemObject" )
'	  	Set f = fso.GetFile( strFilePath )

		' NOTE: the following is arbitrary.  revise if necessary.
		' scheme for timeout value VS file size
		
'		if f.size > 8000000 then
		
			' File size > 8 MB
'			lTimeOutVal = lTIMEOUT_15_MINUTE
		
'		elseif f.size > 4000000 then
		
			' File size > 4 MB
'			lTimeOutVal = lTIMEOUT_5_MINUTE
'		else			
		
			' default case: use IIS's default
'			lTimeOutVal = lTIMEOUT_90_SECONDS
			
'		end if	' switch on file size
		
		estimateTimeOutByReportSize = lTimeOutVal
		
	end function	' estimateTimeOutByReportSize
	
	
	'*************************************************************************
	' GLOBAL VARIABLES (used throughout other include files as well)
	'*************************************************************************
	
	dim bError
	dim bReportSuppressed
	dim pGrammarParser
	dim pReportXMLTag
	
	' enhanced mode
	const bTRACETIMEOUT = false
 	
	' Attempt to keep the request from timing out
	' when we are exporting large .rop's.
	Dim g_lOriginalScriptTimeOutVal 
	
%>


<!-- #include file="SDReportErrorCodes.INC" -->
<!-- #include file="SDReportUtility.INC" -->
<!-- #include file="SDReportImages.INC" -->

<%	

	'*************************************************************************
	' INITIALIZATION LOGIC
	'*************************************************************************
	
	' turn on buffering for efficiency
	' NOTE: This line causes a Response object error where it complains that no HTTP 
	' 		header modification should be made after writing page content
	' Response.Buffer = true
	
	' by default, the report indicates a success case
	bError = false
	bReportSuppressed = false
	
	if AutoSession.UserCanAuthor = false then
		Response.End
	end if
	
	' create an instance of the grammar parser object that will parse
	' the report XML file
	set pGrammarParser = Server.CreateObject( "GrammarParserC.AEGrammarParser" )

	if pGrammarParser is nothing then	
		call Err.Raise( nERROR_FAILED_TO_CREATE_GRAMMAR_PARSER, "SDReportInitialize", strERROR_FAILED_TO_CREATE_GRAMMAR_PARSER )
	end if

	' retrieve the filename of the XML representing the report from the 
	' URL query string
	dim strReportFilename
	strReportFilename = Request.QueryString( "ReportXML" )
	
	Dim regEx
	Set regEx = New RegExp
	regEx.Pattern = "[^a-zA-Z0-9.\-]"
	regEx.Global = true
	strReportFilename = regEx.Replace(strReportFilename, "")
	
	' instantiate the server session object so we can get at the BLOB Manager
	' to ultimately get the path to the resource cache on the server. For some 
	' reason we can't use Server.CreateObject here - it returns an error 
	' loading the type library/DLL. Also, make sure the version on the end of 
	' the ProgID is present, or problems occur.
	'
	' ALSO, if problems occur creating the session object from within this
	' script, it may be due to IIS set to run scripts in the report virtual 
	' directory in a separate memory space. Try deselecting this option from
	' the MMC by selecting properties on the reports virtual directory.

	dim pSession
	set pSession = CreateObject( "AESession.AESession.1" )
	
	if pSession is nothing then	
		call Err.Raise( nERROR_FAILED_TO_CREATE_SESSION, "SDReportInitialize", strnERROR_FAILED_TO_CREATE_SESSION )
	end if

    Dim pASPUtils
    Set pASPUtils = GetInitializedASPUtils()

	dim pBLOBManager
	set pBLOBManager = pSession.CreateBlobManager()
	
	if pBLOBManager is nothing then	
		call Err.Raise( nERROR_FAILED_TO_CREATE_BLOB_MANAGER, "SDReportInitialize", strERROR_FAILED_TO_CREATE_BLOB_MANAGER )
	end if

	' grab the path to the resource cache on the server
	dim strResourceCachePath
	strResourceCachePath = pBLOBManager.GetPhysicalPathPrefix()
	
	' make sure that there is a trailing backslash on the end of the filename
	' so that the path passed to estimateTimeOutByReportSize() is valid
	if Right( strResourceCachePath, 1 ) <> "\" then
		strResourceCachePath = strResourceCachePath & "\"
	end if  'if last character is NOT a backslash
	
	' done with the BLOB manager, so get rid of it
	set pBLOBManager = nothing
	
	' now with the file path, we can look up the size of the report
	' XML file to estimate how to customize the timeout for this script.
	g_lOriginalScriptTimeOutVal = Server.ScriptTimeOut 
	Server.ScriptTimeOut = estimateTimeOutByReportSize( strResourceCachePath & strReportFilename )

	if bTRACETIMEOUT then
		response.write (vbcrlf & "*** Server.ScriptTimeOut = " & cstr(Server.ScriptTimeOut) & " ***")
	end if

			' parse the report XML - the file that is parsed is the one passed
	' in as the ReportXML query string parameter.
	
	' IMPORTANT: For the parse to work with the file sitting in the resource cache
	' directory, the script must be running as the Resolution administrator 
	' account, which is the only account that has access to this directory. If
	' the script is not running as an administrator, the grammar parser will
	' puke with an access denied message
	
	' ENABLE ONE OF THESE FOR DEBUGGING: 
	
	' Sample Import Report
	' set pReportXMLTag = pGrammarParser.ParseTagFromFile( "P:\NRNoBuild\Debugging Tools\SiteDeployment\Reports\TestData\PostImportReportSample.XML" )
	
	' Sample Import Report (One Posting)
	' set pReportXMLTag = pGrammarParser.ParseTagFromFile( "P:\NRNoBuild\Debugging Tools\SiteDeployment\Reports\TestData\PostImportReportOnePosting.XML" )
	
	' Sample Import Report (Error)
	' set pReportXMLTag = pGrammarParser.ParseTagFromFile( "P:\NRNoBuild\Debugging Tools\SiteDeployment\Reports\TestData\ImportReportErrorSample.XML" )
	
	' Sample Export Report
	' set pReportXMLTag = pGrammarParser.ParseTagFromFile( "P:\NRNoBuild\Debugging Tools\SiteDeployment\Reports\TestData\PostExportReportSample.XML" )
	
	' Sample Export Report (Error)
	' set pReportXMLTag = pGrammarParser.ParseTagFromFile( "P:\NRNoBuild\Debugging Tools\SiteDeployment\Reports\TestData\ExportReportErrorSample.XML" )
	
	' Release build parse statement
	set pReportXMLTag = pGrammarParser.ParseTagFromFile( strResourceCachePath & strReportFilename )

	' determine if this report represents an error case. If so, set the
	' flag indicating this event so that the rest of the reporting
	' modules are aware
	bError = pReportXMLTag.ErrorInfo.Error
	
	bReportSuppressed = pReportXMLTag.ErrorInfo.ReportSuppressed
		
%>