'#Reference {A3B5C45B-F842-44fc-A5E5-50CED69BA86E}#2.0#0#C:\Program Files\Mindjet\MindManager 6\Mm5WebExport.dll#Mm5webexport 2.0 Type Library
'#Uses "GlobalParameterNames.mmbas"
'#Uses "GlobalTypes.mmbas"

Option Explicit

Public Sub ProcessString(webex As WebExport, s As String)
    ' Processes all Include, Expand and Run commands and
    ' does all parameter replacements
    Dim processedMacro As Boolean
    Dim filename As String
    Dim originalCommand As String

    ' Do all our processing until we're done.
    '
    ' Each time we run a macro, we have to go through the loop again
    ' to make sure we don't miss any processing of the updated string.
    Do
        processedMacro = False

        ' Process all Include commands
        webex.Trace("Before ProcessIncludeCommands(s)", 4)
        webex.ProcessIncludeCommands(s)

        ' Process each Expand command individually (since we have to run the macro)
        While webex.IsSuccessful And webex.GetExpandCommand(s, originalCommand, filename)

            ' Run the macro (which will push a string on the stack as its return value)
            webex.Trace("Before Expand MacroRun(" + filename + ")", 4)
            MacroRun(filename)

            ' Update our string with the result
            webex.Trace("Before ProcessExpandCommand", 4)
            webex.ProcessExpandCommand(s, originalCommand)

            ' Remember that we ran a macro
            processedMacro = True
        Wend

        ' Do all parameter replacements
        webex.Trace("Before ReplaceParameters", 4)
        webex.ReplaceParameters(s)

        ' Process each Run command individually (since we have to run the macro)
        While webex.IsSuccessful And webex.GetRunCommand(s, originalCommand, filename)

            ' Push our string on the stack for processing
            webex.PushString(s)

            ' Run the macro (which will pop our string,
            ' process it and then push it back on the stack)
            webex.Trace("Before Run MacroRun(" + filename + ")", 4)
            MacroRun(filename)

            ' Get our transformed string back
            s = webex.PopString()

            ' Mark this command as "Processed"
            webex.Trace("Before ProcessRunCommand", 4)
            webex.ProcessRunCommand(s, originalCommand)

            ' Remember that we ran a macro
            processedMacro = True
        Wend

    Loop While webex.IsSuccessful And processedMacro
End Sub

Public Sub ProcessFile(webex As WebExport, filename As String)
    ' Reads a file from a template, processes it, then writes it out to the export
    Dim s As String
    s = webex.ReadFile(filename)
    ProcessString webex, s
    webex.WriteFile(filename, s)
End Sub

Public Sub ProcessResourceFile(webex As WebExport, relativeResourceFilename As String)
    Dim Path As String
    Dim fullPath As String
    Path = webex.GetParameter(TdFolderResources) + "\" + relativeResourceFilename
    fullPath = webex.FullExportFilename(Path)
    If webex.ShouldWriteFile(fullPath) Then
        ' Process the file
        ProcessFile webex, Path
    End If
End Sub

Public Sub ProcessError(webex As WebExport)
    ' Only save a new error if there isn't one already pending
    ' (because WeErrorNumber may have already been set by a routine above us)
    If webex.IsSuccessful Then
        MsgBox("Error " + CStr(Err.Number) + ": " + Err.Description)
        webex.SetParameter(WeErrorNumber, Err.Number)
        webex.SetParameter(WeErrorDescription, Err.Description)
    End If
End Sub

' Accepts a topic and checks if its topic text is empty. If it is empty the function will
' return whatever string the user chose to use for "untitled topics"
Public Function NonEmptyTopicText(webex As WebExport, aTopic As Topic) As String
   ' Returns topic text or substitute string if empty
   ' (so the returned text is guaranteed not to be empty)

   NonEmptyTopicText = aTopic.Text
   
   If NonEmptyTopicText = "" Then
      NonEmptyTopicText = webex.GetParameter(WeEmptyTopicText)
   End If
End Function

' Accepts a topic and checks if its topic text is empty. If it is empty the function will
' return whatever string the user chose to use for "untitled topics"
' The returned string is guaranteed to be on a single line and encoded for use in HTML.
Public Function VerifyTopicText(webex As WebExport, aTopic As Topic) As String
    ' Returns topic text or substitute string if empty
    ' (so the returned text is guaranteed not to be empty)

    VerifyTopicText = NonEmptyTopicText(webex, aTopic)
    webex.SingleLineStringWithLimit(VerifyTopicText)
    VerifyTopicText = webex.EncodeTextForHtml(VerifyTopicText)

End Function

' Accepts a string and checks if it is empty. If it is empty the function will
' return whatever string the user chose to use for "untitled topics"
Public Function VerifyText(webex As WebExport, aString As String) As String

   If aString = "" Then
      aString = webex.GetParameter(WeEmptyTopicText)
   End If

   VerifyText = webex.EncodeTextForHtml(aString)
   
End Function

' Accepts a path name as a string and returns the file name contained in the path
Public Function GetFileNameFromPath(FullPath As String) As String
   GetFileNameFromPath = Right$(FullPath, Len(FullPath) - InStrRev(FullPath, "\"))
End Function

' Accepts a topic and then determines if it has relationships and hyperlinks associated
' with it that qualify to be exported in the "related section" of the exported page
Public Function DoExportRelatedSection_Links (oneTopic As Topic, webex As WebExport) As Boolean

    Dim oneCalloutCollection As Topics
    Dim oneRelationshipCollection As Relationships
    Dim oneRelationship As Relationship
    Dim oneCallout As Topic
    Dim oneBoundary As Boundary
    Dim MMCalloutType As String

    ' Assume there is no related info to export
    DoExportRelatedSection_Links = False

    ' Check for hyperlink
    If oneTopic.HasHyperlink = True Then
       DoExportRelatedSection_Links = True
       Exit Function
    End If

    ' Check for attachments
    If oneTopic.Attachments.Count > 0 Then
		DoExportRelatedSection_Links = True
    End If

    ' Check relationships for topic / callout
    If oneTopic.Relationships(False).Count > 0 Then
       Set oneRelationshipCollection = oneTopic.Relationships(False)
            For Each oneRelationship In oneRelationshipCollection
                If DoExportRelationshipSettings(oneRelationship, webex) = True Then
                    DoExportRelatedSection_Links = True
                    Exit Function
                End If
            Next
    End If
    ' Check relationships for boundary (if topic)
    If oneTopic.IsCentralTopic = False Then
       If oneTopic.IsCalloutTopic = False And oneTopic.IsSummaryTopic = False Then
         If oneTopic.HasBoundary = True Then
           Set oneBoundary = oneTopic.Boundary
           If oneBoundary.IsValid Then
                If oneBoundary.Relationships(False).Count > 0 Then
                   DoExportRelatedSection_Links = True
                   Exit Function
                End If
              End If
          End If
       End If
    End If

End Function

' Accepts a topic and then determines if it has callouts associated
' with it that qualify to be exported in the "related section" of the exported page
Public Function DoExportRelatedSection_Callouts (oneTopic As Topic, webex As WebExport) As Boolean

    Dim oneCalloutCollection As Topics
    Dim oneCallout As Topic
    Dim oneBoundary As Boundary
    Dim MMCalloutType As Variant

    ' Assume there is no related info to export
    DoExportRelatedSection_Callouts = False

    ' Check callouts
    If oneTopic.IsCentralTopic = False Then
      If oneTopic.CalloutTopics(False).Count > 0 Then
        Set oneCalloutCollection = oneTopic.CalloutTopics(False)
            For Each oneCallout In oneCalloutCollection
                MMCalloutType = webex.CalloutType (oneCallout)
                If MMCalloutType = weLinkCallout Then
                  DoExportRelatedSection_Callouts = True
                  Exit Function
                End If
            Next
       End If
    End If
    
    ' Check summary
    If oneTopic.IsCentralTopic = False Then
      If oneTopic.HasBoundary Then
		If oneTopic.Boundary.HasSummaryTopic Then
			Set oneCallout = oneTopic.Boundary.SummaryTopic
            MMCalloutType = webex.CalloutType (oneCallout)
            If MMCalloutType = weLinkCallout Then
                DoExportRelatedSection_Callouts = True
                Exit Function
            End If
		End If     
      End If
    End If

End Function

' Accepts a relationship object for a topic or boundary. Will then
' determine if the relationship is to be exported as a link or if it should be ignored.
' Use the Select Case block to change what relationships are exported and not
Public Function DoExportRelationshipSettings (oneRelationship As Relationship, webex As WebExport) As Boolean

    Dim linkingObject As Object
    Dim relationshipSource As Object
    Dim relationshipTarget As Object
    Dim ArrowType As Variant
    Dim IsSourceItem As Boolean
    Dim linkText As String
    Dim linkUrl As String

' In case we encounter an unexpected runtime error (for example when trying to find
' the export page of an invalid object, ignore the error and abort the export of that
' particular relationship)
On Error GoTo InvalidObject

    Set relationshipSource = oneRelationship.ConnectedObject1
    Set relationshipTarget = oneRelationship.ConnectedObject2

    ' Ignore relationships involving floating topics
    If relationshipSource.Type = mmDocumentObjectTypeTopic Then
       If relationshipSource.IsFloatingTopic = True Then
          DoExportRelationshipSettings = False
          Exit Function
       End If
    End If
    If relationshipTarget.Type = mmDocumentObjectTypeTopic Then
       If relationshipTarget.IsFloatingTopic = True Then
          DoExportRelationshipSettings = False
          Exit Function
       End If
    End If

    ' If relationship involves boundary adjust object to point to parent topic
    If relationshipSource.Type = mmDocumentObjectTypeBoundary Then
       Set relationshipSource = relationshipSource.Topic
    End If
    If relationshipTarget.Type = mmDocumentObjectTypeBoundary Then
       Set relationshipTarget = relationshipTarget.Topic
    End If

    ' Determine if topic is the source or target item for the relationship
    If relationshipSource Is webex.ActiveTopic Then
        ' current topic is source for relationship
        IsSourceItem = True
        Set linkingObject = relationshipTarget
    Else
        ' current topic is not source for relationship
        IsSourceItem = False
        Set linkingObject = relationshipSource
    End If

    ' Determine arrow type for the object pointed to
    If IsSourceItem Then
        ArrowType = oneRelationship.Shape2
    Else
        ArrowType = oneRelationship.Shape1
    End If

   
    ' Determine if we need to insert a link to the linked object,
    ' modify this logic to insert more or less links in web pages
    ' DoExportRelationshipSettings = True means the relationship
    ' type is exported to HTML
    DoExportRelationshipSettings = webex.IsLinkToShape(ArrowType)

    ' Prevent export of "links to self" (can happen if topic
    ' links to boundary surrounding the same topic)
    If relationshipSource Is relationshipTarget Then
       ' current topic is source for relationship
       DoExportRelationshipSettings = False
    End If

    ' Adjust export parameters depending on whether we want to export the link or not
    webex.SetParameter(TcpHyperlinkTarget, "")  ' Target for URL always empty

    If DoExportRelationshipSettings Then
    
       ' Get non-empty link text
       linkText = linkingObject.Text
       If linkText = "" Then
           linkText = webex.GetParameter(WeEmptyTopicText)
       End If
       
       linkUrl = webex.PathToUrl(webex.Pages.FindPage(linkingObject).Filename)
       
       webex.SetParameter(TcpHyperlinkName, linkText)
       webex.SetParameter(TcpHyperlinkURL, linkUrl)
    Else
       webex.SetParameter(TcpHyperlinkName, "")
       webex.SetParameter(TcpHyperlinkURL, "")
    End If

Exit Function

' See comment on top of function
InvalidObject:
    DoExportRelationshipSettings = False
    Err.Clear

End Function

' Function used to clean strings for the dynamic outline navigation section
Public Function CleanString (AString As String, webex As WebExport, DoTruncate As Boolean) As String

    Dim CleanedString As String
    Dim MaxLength As Variant

    If DoTruncate = True Then

        MaxLength = webex.GetParameter("Strings.Miscellaneous.DynamicOutlineWidth")

        If Len(AString) > MaxLength Then
            CleanString = Left(AString,MaxLength) + "... "
        Else
            CleanString = AString
        End If

    Else
        CleanString = AString
    End If

    CleanedString = Replace(CleanString, vbCr," ",1,-1)
    CleanedString = Replace(CleanedString, vbLf," ",1,-1)
    CleanedString = Replace(CleanedString, vbCrLf," ",1,-1)
    CleanedString = Replace(CleanedString, vbNullChar," ",1,-1)
    CleanedString = Replace(CleanedString, vbBack," ",1,-1)
    CleanedString = Replace(CleanedString, vbFormFeed," ",1,-1)
    CleanedString = Replace(CleanedString, vbTab," ",1,-1)
    CleanedString = Replace(CleanedString, vbVerticalTab," ",1,-1)
    ' replace slash first!
    CleanedString = Replace(CleanedString, "\" , "\\" ,1,-1)
    CleanedString = Replace(CleanedString, Chr(34),"\" + Chr(34) ,1,-1)
    CleanedString = Replace(CleanedString, "'","\'",1,-1)
    CleanedString = Replace(CleanedString, "," , "\," ,1,-1)
    CleanString = CleanedString

End Function


' Function used to clean strings for the static outline navigation section
Public Function CleanStringStaticOutline (AString As String, webex As WebExport, DoTruncate As Boolean) As String

    Dim Str As String
    Dim CleanedString As String
    Dim MaxLength As Variant

    If DoTruncate = True Then

        MaxLength = webex.GetParameter("Strings.Miscellaneous.DynamicOutlineWidth")

        If Len(AString) > MaxLength Then
            Str = Left(AString,MaxLength) + "... "
        Else
            Str = AString
        End If

    Else
        Str = AString
    End If

    CleanedString = Replace(Str, vbCr," ",1,-1)
    CleanedString = Replace(CleanedString, vbLf," ",1,-1)
    CleanedString = Replace(CleanedString, vbCrLf," ",1,-1)
    CleanedString = Replace(CleanedString, vbNullChar," ",1,-1)
    CleanedString = Replace(CleanedString, vbBack," ",1,-1)
    CleanedString = Replace(CleanedString, vbFormFeed," ",1,-1)
    CleanedString = Replace(CleanedString, vbTab," ",1,-1)
    CleanedString = Replace(CleanedString, vbVerticalTab," ",1,-1)

    CleanStringStaticOutline = CleanedString

End Function

' Function used to escape restricted characters in strings used for the
' dynamic outline navigation section. Restricted characters are ' \ and ,
Public Function CleanFileName (AString As String) As String
Dim CleanedString As String

    CleanedString = Trim(AString)
    CleanedString = Replace(CleanedString, "\" , "\\", 1, -1) ' do not replace \ characters after this
    CleanedString = Replace(CleanedString, vbCr, " ", 1, -1)
    CleanedString = Replace(CleanedString, "'", "\'", 1, -1)
    CleanedString = Replace(CleanedString, ",", "\,", 1, -1)


    CleanFileName = CleanedString

End Function

' Returns the relative map marker path from the base map marker name (without extension)
Public Function RelativeMapMarkerPath(webex As WebExport, baseIconName As String) As String

    RelativeMapMarkerPath = webex.GetParameter(TdFolderMapMarkers) + "/" + baseIconName + ".gif"
    
End Function

' Returns the hyperlink URL, text and target for this topic 
' (which may be a hyperlink-only topic, in which case, the hyperlink 
' for the topic is returned)
Public Function TopicHyperlink(webex As WebExport, aTopic As Topic) As HyperlinkData

    If webex.IsHyperlinkOnlyTopic(aTopic) Then
        webex.UrlFromHyperlink(aTopic.Hyperlink, TopicHyperlink.Url, TopicHyperlink.Label, TopicHyperlink.Target)
    Else
        ' Get the filename and bookmark for this topic
        Dim filename As String
        Dim bookmark As String
        webex.FilenameAndBookmarkFromTopic(aTopic, filename, bookmark)
        
        ' Convert it to a URL
        TopicHyperlink.Url = webex.PathToUrl(filename) + "#" + webex.PathToUrl(bookmark)
        
        ' Use the topic text for the hyperlink text
        TopicHyperlink.Label = VerifyTopicText(webex, aTopic)
        
        ' No special target
        TopicHyperlink.Target = ""
    End If
    
End Function

' Returns the URL for the page that contains this topic
Public Function TopicPageUrl(webex As WebExport, aTopic As Topic) As String
    
    TopicPageUrl = webex.PathToUrl(webex.Pages.FindPage(aTopic).Filename)
    
End Function

' Returns the exported Notes string (optionally with special characters encoded)
Public Function GlobalExportNotes(webex As WebExport, aTopic As Topic) As String

    Dim absoluteImageFolder As String
    Dim relativeImageFolder As String
    Dim topicId As String

    topicId = webex.TopicIdForExport(aTopic)
    relativeImageFolder = webex.GetParameter(TdFolderNotesImages)
    absoluteImageFolder = webex.FullExportFilename(relativeImageFolder)

    GlobalExportNotes = aTopic.Notes.ExportToValidatedXhtml(topicId, absoluteImageFolder, relativeImageFolder)
    webex.RemoveOuterNotesTags(GlobalExportNotes)
    
    If webex.GetParameter(WeEncodeSpecialStrings) Then
        webex.EncodeSpecialStrings(GlobalExportNotes)
    End If

End Function

' Returns the map marker label (if any) for a given icon
Function IconLabel(anIcon As Icon, doc As Document) As String

	Dim aMapMarkerGroup As MapMarkerGroup
	Dim aMapMarker As MapMarker

	For Each aMapMarkerGroup In doc.MapMarkerGroups
		For Each aMapMarker In aMapMarkerGroup
		    Select Case aMapMarker.Type
		        ' all cases with icons
				Case mmMapMarkerGroupTypePriority, _
				     mmMapMarkerGroupTypePercentageComplete, _
				     mmMapMarkerGroupTypeSingleIcon, _
					 mmMapMarkerGroupTypeIcon
					If anIcon.Name = aMapMarker.Icon.Name Then
						IconLabel = aMapMarker.Label
						Exit Function
					End If
			End Select
		Next
	Next

End Function

' Converts a long decimal value to a hexidecimal color string
' suitable for use in HTML tags
'
' e.g. HexColorString(127) returns "00007F"
Function HexColorString(value As Long)

	' convert the value to a hex string
	HexColorString = Hex(value)

	' pad the string with leading zeros as needed
	While Len(HexColorString) < 6
		HexColorString = "0" + HexColorString
	Wend

End Function

' Converts a long decimal value to an RGB color string
' suitable for use in a CSS style sheet
'
' e.g. CssRgbColorString(127) returns "rgb(0,0,127)"
Function CssRgbColorString(value As Long)

    Dim r As Integer
    Dim g As Integer
    Dim b As Integer
    
    b = value Mod 256
    value = Int(value / 256)
    g = value Mod 256
    value = Int(value / 256)
    r = value Mod 256

	CssRgbColorString = "rgb(" + CStr(r) + "," + CStr(g) + "," + CStr(b) + ")"

End Function

Public Function TargetAttribute(ByRef aHyperlink As HyperlinkData)

    ' Returns the attribute string for a hyperlink target, 
    ' empty string if no target is defined

    If Len(aHyperlink.Target) > 0 Then
        TargetAttribute = " target=""" + aHyperlink.Target + """"
    End If
    
End Function
