' Verbindung aufbauen
Dim oServer : Set oServer = CreateObject("OxSvrSpt.Server") 'nur fuer VB Script
Dim oSession : Set oSession = oServer.Login("osservice", "optimal", "localhost", "4000", pwNotEncrypted)	'BENUTZERDATEN EINGEBEN
Dim bTest : bTest = true 'true bedeutet, dass im Testmodus keine Daten geschrieben verndert werden. 


'WICHTIG: VOR DER AUSFUEHRUNG DES SKRIPTS SOLLTE DIE ZEILE 

'myControlledDocuments.CheckTrainingStructure lObjectID,lObjectType,lActionID

'im KernelAfterJob::IndexDataChanged-Event auskommentiert werden.


log2file "  __  __ _                 _   _                _____      _           _                                  _   "
log2file " |  \/  (_)               | | (_)              / ____|    | |         | |                                | |  "
log2file " | \  / |_  __ _ _ __ __ _| |_ _  ___  _ __   | (___   ___| |__  _   _| |_   _ _ __   __ _ ___  __ _ _ __| |_ "
log2file " | |\/| | |/ _` | '__/ _` | __| |/ _ \| '_ \   \___ \ / __| '_ \| | | | | | | | '_ \ / _` / __|/ _` | '__| __|"
log2file " | |  | | | (_| | | | (_| | |_| | (_) | | | |  ____) | (__| | | | |_| | | |_| | | | | (_| \__ \ (_| | |  | |_ "
log2file " |_|  |_|_|\__, |_|  \__,_|\__|_|\___/|_| |_| |_____/ \___|_| |_|\__,_|_|\__,_|_| |_|\__, |___/\__,_|_|   \__|"
log2file "            __/ |                                                                     __/ |                   "
log2file "           |___/                                                                     |___/                    "


createBackups	'create backups of all distribution register first
migrateTrainingTypeOnDistributionRegister

Set oJob = Nothing
oSession.Logout
Set oServer = Nothing

'**********************************************************
' createBackups
' @description: creates backups of all distribution register
' @param: -
' @return: the folder path
'**********************************************************
Function createBackups

	log2file "================"
	log2file "STARTE SICHERUNG"
	log2file "Anmerkung: Es werden alle Verteiler gesichert (auch von ggfs. ungueltigen Versionen)"
	log2file "================"

	Dim sBackupFolder : sBackupFolder = createBackupFolder
	
	Dim bFinished : bFinished = False
    Dim lOffset : lOffset = 0
    Dim lCounter : lCounter = 0
    Dim lSuccessCounter : lSuccessCounter = 0

    do while bFinished = False        
        Dim oJob : Set oJob = oSession.NewJob("dms.GetResultList")
        ' Parameter hinzufuegen
        sXML = "<DMSQuery request_type='HOL'>" & vbcrlf
        sXML = sXML & "<Archive internal_name='" & "m_cd_folder" & "'>" & vbcrlf
        sXML = sXML & "	<ObjectType internal_name='" & "m_cd_distributionregister" & "' >" & vbcrlf 
        sXML = sXML & "		<Fields field_schema='ALL'>" & vbcrlf
        sXML = sXML & "		</Fields>" & vbcrlf
        sXML = sXML & "	</ObjectType>" & vbcrlf
        sXML = sXML & "</Archive>" & vbcrlf
        sXML = sXML & "</DMSQuery>" & vbcrlf

        oJob.InputParameters.AddNewIntegerParameter "Flags", 16
        oJob.InputParameters.AddNewIntegerParameter "PageSize", 1
        oJob.InputParameters.AddNewIntegerParameter "Offset", lOffset
        Dim oParameter : Set oParameter = oJob.InputParameters.AddNewXMLParameter("XML",sXML)

        ' Job ausfuehren
        oJob.Execute

        ' XML aus dem XML-Fileparameter auslesen
        Dim strXML 
        strXML = oJob.OutputFileParameters(1).XML
        TotalHits = oJob.OutputParameters("TotalHits")

        Dim objDOM : Set objDOM = CreateObject("MSXML.DOMDocument")
        objDOM.loadXML(strXML)
		
		Dim myObject : Set myObject = objDOM.selectSingleNode("//Object")
		If Not myObject Is Nothing Then
			sDistributionRegisterObjectID = objDOM.selectSingleNode("//Object").attributes.GetNamedItem("id").text
			log2file "Sichere Verteiler mit der ID: " & sDistributionRegisterObjectID
			objDOM.save sBackupFolder & "\" & sDistributionRegisterObjectID & ".xml"
			lCounter = lCounter + 1
		Else
			bFinished = true
		End If

        lOffset = lOffset + 1
    loop

    Set objDOM = Nothing
	
	log2file "================"
	log2file "SICHERUNG ABGESCHLOSSEN: " & lCounter & " von " & TotalHits & " Verteilern gesichert"
	log2file "================"
	
End Function


'**********************************************************
' createBackupFolder
' @description: creates a folder for backup files
' @param: -
' @return: the folder path
'**********************************************************
Function createBackupFolder
	Dim FSO_FOLDER
	Dim Folder

	Set FSO_FOLDER = CreateObject("Scripting.FileSystemObject")
	newFolderPath = FSO_FOLDER.GetParentFolderName(WScript.ScriptFullName) & "\" & "Backup Verteiler_" & Replace(Replace(Now,".","_"),":","-")
	
	If Not FSO_FOLDER.FolderExists(newFolderPath) Then
		Set newFolder = FSO_FOLDER.CreateFolder(newFolderPath)
		createBackupFolder = newFolderPath
	End If

	Set FSO_FOLDER = Nothing
End Function

'**********************************************************
' log2file
' @description: logs values to file
' @param: sMsg - the message which should be logged
' @return: 
'**********************************************************
Function log2file (sMsg)
	
	WScript.Echo sMsg
	Set fso = CreateObject("Scripting.FileSystemObject")
	sPath = fso.GetParentFolderName(WScript.ScriptFullName)
	Set File = fso.OpenTextFile(sPath & "\MigrateTrainingType_debug.txt", 8, True)
	File.Write Now & vbTab & sMsg & vbCrLf
	File.Close
	Set fso = Nothing
	Set File = Nothing


End Function

'**********************************************************
' migrateTrainingTypeOnDistributionRegister
' @description: old distribution registers don't have values for the training type in the table column Schulungsart
'				this function fills the values according to the selected training type at the document
' @param: 
' @return: 
'**********************************************************
Function migrateTrainingTypeOnDistributionRegister
    Dim bFinished : bFinished = False
    Dim lOffset : lOffset = 0
	Dim lPageSize : lPageSize = 1
    Dim lCounter : lCounter = 0
    Dim lSuccessCounter : lSuccessCounter = 0
	Dim lUpdateCounter : lUpdateCounter = 0

    do while bFinished = False        
        Dim oJob : Set oJob = oSession.NewJob("dms.GetResultList")
        ' Parameter hinzufuegen
        sXML = "<DMSQuery request_type='HOL'>" & vbcrlf
        sXML = sXML & "<Archive internal_name='" & "m_cd_folder" & "'>" & vbcrlf
        sXML = sXML & "	<ObjectType internal_name='" & "m_cd_document" & "' >" & vbcrlf 
        sXML = sXML & "		<Fields field_schema='DEF'>" & vbcrlf
        sXML = sXML & "			<Field internal_name='m_doc_title'/>" & vbcrlf
		sXML = sXML & "			<Field internal_name='m_doc_number'/>" & vbcrlf
		sXML = sXML & "			<Field internal_name='m_doc_version'/>" & vbcrlf
		sXML = sXML & "			<Field internal_name='m_doc_training_type'/>" & vbcrlf
        sXML = sXML & "		</Fields>" & vbcrlf
        sXML = sXML & "		<Conditions>" & vbcrlf
        sXML = sXML & "			<ConditionObject internal_name ='" & "m_cd_document" & "' type='DOCUMENT'>" & vbcrlf
		sxml = sxml & "			    <FieldGroup operator='AND'>" & vbCrLf
		sxml = sxml & "			    	<FieldGroup operator='OR'>" & vbCrLf
		sXML = sXML & "				    	<FieldCondition internal_name='" & "m_doc_training_mandatory" & "' operator='='>" & vbcrlf
        sXML = sXML & "				    		<Value>" & "nein / no" & "</Value>" & vbcrlf
        sXML = sXML & "				    	</FieldCondition>"	& vbcrlf		
		sXML = sXML & "				    	<FieldCondition internal_name='" & "m_doc_training_mandatory" & "' operator='='>" & vbcrlf
        sXML = sXML & "				    		<Value>" & "" & "</Value>" & vbcrlf
        sXML = sXML & "				    	</FieldCondition>"	& vbcrlf				
		sxml = sxml & "					</FieldGroup>" & vbCrLf		
		sxml = sxml & "				</FieldGroup>" & vbCrLf		
        sxml = sxml & "			    <FieldGroup operator='OR'>" & vbCrLf
        sXML = sXML & "				    <FieldCondition internal_name='" & "m_doc_status" & "' operator='='>" & vbcrlf
        sXML = sXML & "				    	<Value>" & "1" & "</Value>" & vbcrlf
        sXML = sXML & "				    </FieldCondition>"	& vbcrlf
        sXML = sXML & "				    <FieldCondition internal_name='" & "m_doc_status" & "' operator='='>" & vbcrlf
        sXML = sXML & "				    	<Value>" & "2" & "</Value>" & vbcrlf
        sXML = sXML & "				    </FieldCondition>"	& vbcrlf  
        sxml = sxml & "				</FieldGroup>" & vbCrLf
        sxml = sxml & "			    <FieldGroup operator='AND'>" & vbCrLf
        sXML = sXML & "				    <FieldCondition internal_name='" & "m_doc_training_type" & "' operator='='>" & vbcrlf
        sXML = sXML & "				    	<Value>" & "" & "</Value>" & vbcrlf
        sXML = sXML & "				    </FieldCondition>"	& vbcrlf
        sxml = sxml & "				</FieldGroup>" & vbCrLf		
		sxml = sxml & "				<TableCondition internal_name='m_doc_responsible'>" & vbcrlf
		sxml = sxml & "					<TableColumn internal_name='Guid' operator='='>" & vbcrlf
		sxml = sxml & "						<Value>" & "*" & "</Value>" & vbcrlf
		sxml = sxml & "					</TableColumn>"	& vbcrlf
		sxml = sxml & "				</TableCondition>"	& vbcrlf		        
        sXML = sXML & "			</ConditionObject>" & vbcrlf
        sXML = sXML & "		</Conditions>" & vbcrlf        
		sXML = sXML & "		<ParentObjects>" & vbCrLf
		sXML = sXML & "			<ParentObjectType internal_name='m_cd_register'>" & vbCrLf
		sXML = sXML & "				<Fields field_schema='MIN'>" & vbcrlf
		sXML = sXML & "				</Fields>" & vbcrlf
		sXML = sXML & "			</ParentObjectType>" & vbCrLf
		sXML = sXML & "		</ParentObjects>" & vbCrLf		
        sXML = sXML & "	</ObjectType>" & vbcrlf
        sXML = sXML & "</Archive>" & vbcrlf
        sXML = sXML & "</DMSQuery>" & vbcrlf

        oJob.InputParameters.AddNewIntegerParameter "Flags", 16
        Dim oParameter : Set oParameter = oJob.InputParameters.AddNewXMLParameter("XML",sXML)

        ' Job ausfuehren
        oJob.Execute

        ' XML aus dem XML-Fileparameter auslesen
        Dim strXML 
        strXML = oJob.OutputFileParameters(1).XML
        TotalHits = oJob.OutputParameters("TotalHits")
        log2file TotalHits & " Dokumente gefunden"
        Dim objDOM : Set objDOM = CreateObject("MSXML.DOMDocument")
        objDOM.loadXML(strXML)

        Set oDocuments = objDOM.selectNodes("//ObjectType[@internal_name='m_cd_document']/ObjectList/Object")
        
		
		
		If oDocuments.length > 0 Then
			sDocumentType = objDOM.selectSingleNode("//ObjectType[@internal_name='m_cd_document']").attributes.GetNamedItem("id").text
		else
			bFinished = true
		end if
		
        ' if TotalHits > 0 Then
			' sDocumentType = objDOM.selectSingleNode("//ObjectType[@internal_name='m_cd_document']").attributes.GetNamedItem("id").text
		' end if
        
        For Each oDocument in oDocuments
            Dim sDocumentID : sDocumentID = oDocument.Attributes.GetNamedItem("id").text
            'log2file lCounter & " von " & TotalHits & " (Objekt-ID: " & sDocumentID & ", " & sDocumentType & ")"
			log2file "Ueberpruefe Dokument " & lCounter & " von " & TotalHits
            Dim sDocTitle : sDocTitle = oDocument.selectSingleNode("./Fields/Field[@internal_name='m_doc_title']").text
			Dim sDocNumber : sDocNumber = oDocument.selectSingleNode("./Fields/Field[@internal_name='m_doc_number']").text
			Dim sDocVersion : sDocVersion = oDocument.selectSingleNode("./Fields/Field[@internal_name='m_doc_version']").text		
			
			log2file "Das Dokument '" & sDocTitle & "' (" & sDocNumber & " V-" & sDocVersion & "ID : " & sDocumentID & " ) muss aktualisiert werden."
			lUpdateCounter = lUpdateCounter + 1
			'now get distribution objects and update them with the training type
			Dim sVersionObjectTypeID : sVersionObjectTypeID = oDocument.selectSingleNode("../../../../../../@id").text

			Dim sVersionObjectID : sVersionObjectID = oDocument.selectSingleNode("../../../../@id").text

			
			lUpdateResult = updateDistributionObjects (sVersionObjectID, sVersionObjectTypeID, "")
			if lUpdateResult = 0 Then 'everything OK
				lSuccessCounter = lSuccessCounter + 1
			End If
				
            lCounter = lCounter + 1

        Next

		bFinished = true
		' if TotalHits <= lPageSize Then
			' bFinished = true
		' end if

        ' if lOffset >= TotalHits Then
            ' bFinished = true
        ' End If

        lOffset = lOffset + lPageSize
    loop
    log2file lUpdateCounter & " von " & lCounter & " Dokumenten sollten aktualisiert werden."

    log2file lSuccessCounter & " von " & lCounter & " Dokumente aktualisiert"

    Set objDOM = Nothing  

End Function

'**********************************************************
' updateDistributionObjects
' @description: updates the distribution register
' @param: sVersionObjectID - the id of the version register, sVersionObjectTypeID - the object type of the version register, sDocTrainingType - the training type value (either 0 or 1)
' @return: 
'**********************************************************
Function updateDistributionObjects(sVersionObjectID, sVersionObjectTypeID, sDocTrainingType)
    Dim oJobSearchDistObjects : Set oJobSearchDistObjects = oSession.NewJob("dms.GetResultList")
	Dim bError : bError = false
	

   ' Parameter hinzufuegen
	sXML = "<DMSQuery request_type='HOL'>" & vbcrlf
	sXML = sXML & "<Archive internal_name='" & "m_cd_folder" & "'>" & vbcrlf
	sXML = sXML & "	<ObjectType internal_name='" & "m_cd_register" & "' >" & vbcrlf 
	sXML = sXML & "		<Fields field_schema='DEF'>" & vbcrlf
	sXML = sXML & "			<Field internal_name='m_doc_title'/>" & vbcrlf
	sXML = sXML & "			<Field internal_name='m_doc_number'/>" & vbcrlf
	sXML = sXML & "			<Field internal_name='m_doc_version'/>" & vbcrlf
	sXML = sXML & "		</Fields>" & vbcrlf
	sXML = sXML & "		<Conditions>" & vbcrlf
	sXML = sXML & "			<ObjectID>" & sVersionObjectID & "</ObjectID>" & vbcrlf
	sXML = sXML & "		</Conditions>" & vbcrlf
	sXML = sXML & "		<ChildObjects child_schema='REG' export_depth='1'>" & vbCrLf
	sXML = sXML & "			<ChildObjectType internal_name='m_cd_distributionregister'>" & vbCrLf
	sXML = sXML & "				<Fields field_schema='DEF'>" & vbcrlf
	sXML = sXML & "					<Field internal_name='m_r_participants'/>" & vbcrlf	
	sXML = sXML & "				</Fields>" & vbcrlf
	sXML = sXML & "			</ChildObjectType>" & vbCrLf
	sXML = sXML & "		</ChildObjects>" & vbCrLf		
	sXML = sXML & "	</ObjectType>" & vbcrlf
	sXML = sXML & "</Archive>" & vbcrlf
	sXML = sXML & "</DMSQuery>" & vbcrlf
	
	oJobSearchDistObjects.InputParameters.AddNewIntegerParameter "Flags", 16
	Dim oParameter : Set oParameter = oJobSearchDistObjects.InputParameters.AddNewXMLParameter("XML",sXML)

	' Job ausfuehren
	oJobSearchDistObjects.Execute

	' XML aus dem XML-Fileparameter auslesen
	Dim strDistObjectsXML 
	strDistObjectsXML = oJobSearchDistObjects.OutputFileParameters(1).XML
	TotalHits = oJobSearchDistObjects.OutputParameters("TotalHits")
	Dim objDOM_DistObjects : Set objDOM_DistObjects = CreateObject("MSXML.DOMDocument")
	objDOM_DistObjects.loadXML(strDistObjectsXML)
	'log2file objDOM_DistObjects.xml
	Dim oDistributionObjects : Set oDistributionObjects = objDOM_DistObjects.selectNodes("//ObjectType[@internal_name='m_cd_distributionregister']/ObjectList/Object")
	log2file vbTab & "Gefundene Verteiler: " & oDistributionObjects.length
	
	
	For Each oDistributionObject in oDistributionObjects
		sRowUpdate = ""
		Dim sDistributionObjectId : sDistributionObjectId = oDistributionObject.Attributes.GetNamedItem("id").text
	
		log2file vbTab & "Verteiler-ID: " & sDistributionObjectId
		'log2file oDistributionObject.xml
		
		Dim oParticipantsTable : Set oParticipantsTable = oDistributionObject.selectSingleNode("./TableFields/TableField[@internal_name='m_r_participants']")

		Dim oRows : Set oRows = oParticipantsTable.selectNodes("./Row")

		For Each oRow in oRows 
			Dim oValues : Set oValues = oRow.selectNodes("./Value")
			sGUID = oValues.Item(0).text
			sName = oValues.Item(1).text
			sTraining = oValues.Item(2).text
			sTrainer = oValues.Item(3).text
			sTrainerLogin = oValues.Item(4).text
			
			If sTraining = "" Then
				Select Case sDocTrainingType
					Case "0"
						sTrainingType = "Prsenzschulung / Classroom training"
					Case "1"
						sTrainingType = "Leseschulung / Read and understood"
					Case ""
						sTrainingType = "Leseschulung / Read and understood"	'special case: the training was initiated for a document with "training mandatory = no" or "training mandatory = ''"
				End Select
			Else 
				sTrainingType = sTraining
			End If
			
			sRowUpdate = sRowUpdate & "<Row>" &_
			"<Field internal_name='" & "Guid" & "'>" & convertToValidXML(sGUID) & "</Field>" &_
			"<Field internal_name='" & "Name" & "'>" & convertToValidXML(sName) & "</Field>"	&_
			"<Field internal_name='" & "Training" & "'>" & convertToValidXML(sTrainingType) & "</Field>"	&_
			"<Field internal_name='" & "Trainer" & "'>" & convertToValidXML(sTrainer) & "</Field>"	&_
			"<Field internal_name='" & "TrainerLogin" & "'>" & convertToValidXML(sTrainerLogin) & "</Field>"	&_
			"</Row>"
        Next		
		

		log2file vbTab & vbTab & "Aktualisiere Verteiler mit der ID " & sDistributionObjectId
		'update distribution object
		
		if bTest = True Then
				log2file vbTab & vbTab & "TEST-MODUS: Update wurde nicht durchgefhrt."
			Else
				lReturn = UpdateDistributionObjectTable (sDistributionObjectId, sRowUpdate)
				If lReturn = 0 Then
					lSuccessCounter = lSuccessCounter + 1
					log2file vbTab & vbTab & "Aktualisierung erfolgreich..."
				Else
					log2file vbTab & vbTab & "Aktualisierung fehlgeschlagen..."
					bError = true
				End If     	
		End If

	Next
	
	if bError = false Then
		updateDistributionObjects = 0
	Else
		updateDistributionObjects = -1
	End If
	
End Function

'**********************************************************
' UpdateDistributionObjectTable
' @description: updates the distribution register
' @param: lObjectID - the id of the distribution register, sRowUpdate - the content of the table which should be updated
' @return: 
'**********************************************************
Function UpdateDistributionObjectTable(lObjectID, sRowUpdate)
	
	' Job erstellen
	Dim oParameter 
	Dim strXML 
	Dim fso, File

	Dim oUpdateJob : Set oUpdateJob = oSession.NewJob("dms.XMLUpdate")

	' Parameter hinzufuegen
	sXML = "<DMSData>" 	& vbcrlf
	sXML = sXML & "<Archive internal_name='" & "m_cd_folder" & "'>" 	& vbcrlf
	sXML = sXML & "	<ObjectType internal_name='" & "m_cd_distributionregister" & "' type='REGISTER'>" 	& vbcrlf
	sXML = sXML & "		<Object object_id='" & lObjectID & "'>"	& vbcrlf
	sXML = sXML & "			<TableFields>"	& vbcrlf
	sXML = sXML & "				<TableField internal_name='m_r_participants'>" & sRowUpdate & "</TableField>"	& vbcrlf
	sXML = sXML & "			</TableFields>"	& vbcrlf
	sXML = sXML & "		</Object>"	& vbcrlf
	sXML = sXML & "	</ObjectType>"	& vbcrlf
	sXML = sXML & "</Archive>"	& vbcrlf
	sXML = sXML & "</DMSData>"	& vbcrlf

	oUpdateJob.InputParameters.AddNewIntegerParameter "Flags", 16
	oUpdateJob.InputParameters.AddNewStringParameter "Options", "REPLACETABLEFIELDS=1;CHECKREADONLY=0;TRUNCATEVALUES=1;CHECKCATALOGUE=0;CHECKOBLIGATION=0"
	oUpdateJob.InputParameters.AddNewXMLParameter "XML",sXML
	' Job ausfuehren
	iRet = oUpdateJob.Execute
    UpdateDistributionObjectTable = iRet
	
	Set oUpdateJob = Nothing	
End Function


'**********************************************************
' convertToValidXML
' @description: converts a string value to a valid xml value
' @param: sInput - string
'
' @return: the valid xml string
'**********************************************************
Const C_XMLOK="yxcvbnmasdfghjklqwertzuiopYXCVBNMASDFGHJKLQWERTZUIOP1234567890() ."
Function convertToValidXML(sInput)
	sDest=""
	sSource=sInput
	sChar=""
	For jj = 0 To Len(sInput)-1
		sChar = Left(sSource,1)
		sSource = Right(sSource, Len(sSource)-1)
		If InStr(1, C_XMLOK, sChar) = 0 Then sChar="&#"&Asc(sChar)&";"
		sDest = sDest & sChar	
	Next
	convertToValidXML=sDest
End Function