
    def validateHTML(self,closingtags):
        ''' validate the current response data using Web Design Group's HTML validator
        available at http://www.htmlhelp.com/tools/validator/

        Make sure you install the offline validator (called "validate") which can be called
        from the command-line.  The "validate" script must be in your path.

        Add this method to your SitePage (the servlet from which all your servlets inherit),
        override Page.writeBodyParts() in your SitePage like so:
            def writeBodyParts(self):
                Page.writeBodyParts()
                self.validateHTML('</body></html>')
        
        The "closingtags" param is a string which is appended to the page before validation.  
        Typically, it would be the string "</body></html>".  At the point this method is 
        called (e.g. from writeBodyParts() the page is not yet 100% complete, so we have 
        to fake it.
        '''

        # don't bother validating if the servlet has redirected
        status = self.response().header('status',None)
        if status and status.find('Redirect') != -1:
            return

        response = self.response().rawResponse()

        # add the closing tags so that the page is a complete html document
        contents = response['contents'] + closingtags
        input, output = os.popen4('validate')
        input.write(contents)
        input.close()
        out = output.readlines() 
        output.close()

        errlines = {}
        for line in out:
            if line[0:5] == 'Line ':
                i = line.find(',')
                if i != -1:
                    linenum = int(line[5:i])
                    errlines[linenum] = line

        # Be quiet if all's well
        if not errlines:
            return
            
        self.writeln('<table style="background-color: #ffffff"><tr><td colspan="2">')
        self.write("<pre>%s</pre>" % "".join(out) )
        self.writeln('</td></tr>')

        colors = ['#d0d0d0','#e0e0e0','#ffd0d0']
        from WebUtils.Funcs import htmlEncode
        lines = contents.splitlines(1)
        i = 1
        for line in lines:
            if errlines.has_key(i):
                self.writeln('<tr style="background-color: %s"><td rowspan="2">%d</td><td>%s</td></tr>' % (colors[2],i,htmlEncode(errlines[i])))
                self.writeln('<tr style="background-color: %s"><td>%s</td></tr>' % (colors[2],htmlEncode(line)))
            else:
                color = colors[i % 2]
                self.writeln('<tr style="background-color: %s"><td>%d</td><td>%s</td></tr>' % (color,i,htmlEncode(line)))
            i += 1
        self.writeln('</table>')
