php.py :  » Project-Management » Trac » Trac-0.11.7 » trac » mimeview » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Project Management » Trac 
Trac » Trac 0.11.7 » trac » mimeview » php.py
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2005 Christian Boos <cboos@bct-technology.com>
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Christian Boos <cboos@bct-technology.com>
#         Christopher Lenz <cmlenz@gmx.de>

import os
import re

from genshi.core import Markup

from trac.core import *
from trac.config import Option
from trac.mimeview.api import IHTMLPreviewRenderer,content_to_unicode
from trac.util import NaivePopen
from trac.util.html import Deuglifier

__all__ = ['PHPRenderer']

php_types = ('text/x-php', 'application/x-httpd-php',
             'application/x-httpd-php4', 'application/x-httpd-php1')


class PhpDeuglifier(Deuglifier):

    def format(self, indata):
        # The PHP highlighter produces the end-span tags on the next line
        # instead of the line they actually apply to, which causes
        # Trac to produce lots of (useless) open-and-immediately-close
        # spans beginning each line.  This tries to curtail by bubbling
        # the first span after a set of 1+ "<br />" to before them.
        r_fixeol = re.compile(r"((?:<br />)+)(</(?:font|span)>)")
        indata = r_fixeol.sub(lambda m: m.group(2) + m.group(1), indata)
        
        # Now call superclass implementation that handles the dirty work
        # of applying css classes.
        return Deuglifier.format(self, indata)

    def rules(cls):
        colors = dict(comment='FF8000', lang='0000BB', keyword='007700',
                      string='DD0000')
        # rules check for <font> for PHP 4 or <span> for PHP 5
        color_rules = [
            r'(?P<%s><(?:font color="|span style="color: )#%s">)' % c
            for c in colors.items()
            ]
        return color_rules + [ r'(?P<font><font.*?>)', r'(?P<endfont></font>)' ]
    rules = classmethod(rules)


class PHPRenderer(Component):
    """Syntax highlighting using the PHP executable if available.
    """

    implements(IHTMLPreviewRenderer)

    path = Option('mimeviewer', 'php_path', 'php',
        """Path to the PHP executable (''since 0.9'').""")

    returns_source = True

    # IHTMLPreviewRenderer methods

    def get_quality_ratio(self, mimetype):
        if mimetype in php_types:
            return 5
        return 0

    def render(self, context, mimetype, content, filename=None, rev=None):
        if not getattr(self, '_deprecation_shown', False):
            self.log.warning('The PHP highlighter is deprecated and will be '
                             'disabled by default in 0.12')
            self._deprecation_shown = True
        
        # -n to ignore php.ini so we're using default colors
        cmdline = '%s -sn' % self.path
        self.env.log.debug("PHP command line: %s" % cmdline)

        content = content_to_unicode(self.env, content, mimetype)
        content = content.encode('utf-8')
        np = NaivePopen(cmdline, content, capturestderr=1)
        if (os.name != 'nt' and np.errorlevel) or np.err:
            msg = 'Running (%s) failed: %s, %s.' % (cmdline,
                                                    np.errorlevel,
                                                    np.err)
            raise Exception(msg)

        odata = ''.join(np.out.splitlines()[1:-1])
        if odata.startswith('X-Powered-By:') or \
                odata.startswith('Content-type:'):
            raise TracError(_('You appear to be using the PHP CGI '
                              'binary. Trac requires the CLI version '
                              'for syntax highlighting.'))

        epilogues = ["</span>", "</font>"]
        for e in epilogues:
            if odata.endswith(e):
                odata = odata[:-len(e)]
                break

        html = PhpDeuglifier().format(odata.decode('utf-8'))

        # PHP generates _way_ too many non-breaking spaces...
        # We don't need them anyway, so replace them by normal spaces
        return [Markup(line.replace('&nbsp;', ' '))
                for line in html.split('<br />')]
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.