# a modified attachment_image() in application_odt_psuedoformatter.py
# to allow inclusion of attachments sourced from other pages
# modified by IanRiley 2012.01.02

    def attachment_image(self, url, *args, **kargs): 
        # prevent hacking (filenames like "../../../../etc/passwd")
        # attachbasename = wikiutil.taintfilename( url )

        # The above prevents including attachments from other wiki pages,
        # resulting in an untrapped error at line 151 in RenderAsOpenDocument.py.
        # An alternative (remember to import os above):

        pagename, filename = AttachFile.absoluteName(url, self.pagename)
        fname = wikiutil.taintfilename(filename)
        fpath = AttachFile.getFilename(self.request, pagename, fname)
        if os.path.exists(fpath):
            attachbasename = fname
        else:
            attachbasename = None

        # accept only the most popular web image types
        (mimetype, extension) = self.getMimetype( attachbasename )
        if not mimetype.startswith( "image/" ): return ""
        
        # get real path in filesystem
        # use pagename from AttachFile.absoluteName not self.pagename
        attachfilename = AttachFile.getFilename(self.request, pagename, attachbasename)

        # create internal name and store filename->internal name mapping, but only once
        if attachfilename in self.attachments:
            internalName = self.attachments[ attachfilename ]
        else:
            if self.isIncluded:
                # Will be replaced by calling formatter
                includeId = '<<INCLUDE_ID>>'
            else:
                includeId = ''
                
            internalName = str( self.getNextAttachmentCounter() )
            internalName = "Pictures/" + includeId + (12 - len(internalName) ) * "0" + internalName + "." + extension
            self.attachments[ attachfilename ] = internalName

        # embed image
        self.open( 'draw:frame' )
        imageNode = self.open( 'draw:image' )
        imageNode.setAttribute( 'xlink:href', self.attachments[attachfilename] )
        imageNode.setAttribute( 'xlink:type', 'simple' )
        imageNode.setAttribute( 'xlink:show', 'embed' )
        imageNode.setAttribute( 'xlink:actuate', 'onLoad' )
        self.close( 'draw:image' )
        self.close( 'draw:frame' )
        return ""
    
    

