Ejemplo n.º 1
0
    def testMemorySafety(self):
        # This is meant to be run with ASAN and checks that
        # certain use-after-frees are not present.
        cgi = neo_cgi.CGI()
        hdf = cgi.hdf
        del cgi
        hdf.getValue("x", "y")
        del hdf

        cgi = neo_cgi.CGI()
        cs = cgi.cs()
        del cgi
        cs.parseStr("x")
        del cs

        hdf = neo_util.HDF()
        hdf.setValue("y.z", "1")
        child = hdf.getChild("y")
        del hdf
        child.getValue("x", "y")
        del child

        hdf = neo_util.HDF()
        cs = neo_cs.CS(hdf)
        del hdf
        cs.parseStr("x")
        del cs
Ejemplo n.º 2
0
def execute(macro, args):
    request = macro.request
    content = []
    page_name = macro.formatter.page.page_name

    # get args
    include_page_name = ''
    if args is not None:
        (include_page_name, _, hdf_text) = args.partition(',')

    include_page_name = wikiutil.AbsPageName(page_name, include_page_name)

    include_page = Page(request, include_page_name)

    if include_page is None:
        return ''
    if not request.user.may.read(include_page_name):
        return ''

    cstemplate = include_page.getPageText()

    pagename = macro.formatter.page.page_name

    hdf = neo_util.HDF()
    hdf.readString(hdf_text)

    hdf.setValue("Config.WhiteSpaceStrip ", "0")

    cs = neo_cs.CS(hdf)
    cs.parseStr(cstemplate)

    body = cs.render()

    body = wikiutil.renderText(request, WikiParser, body)
    return body
Ejemplo n.º 3
0
def _render(f, template_file, environ, start_response, *args, **kwds):

    # call our original function with original args
    try:
        results = f(environ, start_response)

        template_name, ext = template_file.split(".")
        contenttype = "text/html"
        if len(ext) > 1 and (ext[1] in extensions):
            contenttype = extensions[ext[1]]

        hdf = neo_util.HDF()
        _set(hdf, '', results)
        hdf.setValue('style', stylesheet_uri)

        # shove the results into the template
        clearsilver = neo_cs.CS(hdf)
        clearsilver.parseFile(os.path.join('templates', template_name + '.cs'))

        # XXX where is our error handling?
        start_response("200 OK", [('Content-Type', contenttype)])
        return [clearsilver.render()]
    except DataNotFound:
        start_response("404 Not Found", [('Content-Type', 'text/plain')])
        return ['404 Error, Content not found']
    except HTTP303, e:
        url = str(e.value)
        if not url.startswith(('http', '/')):
            url = request_uri(environ) + url
        start_response("302 Found", [('Location', url)])
        return ['Redirect to url']
Ejemplo n.º 4
0
    def error(self, ecode, reason=None):
        import httpResponses
        message = httpResponses.gHTTPResponses[ecode]

        template = httpResponses.errorMessage_Default
        if ecode == 404:
            template = httpResponses.errorMessage_404

        hdf = neo_util.HDF()
        hdf.setValue("code", str(ecode))
        if message: hdf.setValue("message", message)
        if reason: hdf.setValue("reason", reason)

        for key, val in self.context.environ.items():
            hdf.setValue("environ." + key, str(val))

        self.context.stdout.write("Content-Type: text/html\r\n")
        self.context.setStatus(None, ecode)
        self.context.stdout.write("Status: %s\r\n" % ecode)
        self.context.stdout.write("\r\n")

        cs = neo_cs.CS(hdf)
        cs.parseStr(template)
        page = cs.render()

        self.context.stdout.write(page)

        warn("Error", message, reason)
Ejemplo n.º 5
0
def eval_cs(hdf,a_cs_string):
    cs = neo_cs.CS(hdf)
    try:
      cs.parseStr(a_cs_string)
      return cs.render()
    except:
      return "Error in CS tags: %s" % neo_cgi.htmlEscape(repr(a_cs_string))
Ejemplo n.º 6
0
    def render(self, template, form_token=None):
        """Render the HDF using the given template.

        The template parameter can be either an already parse neo_cs.CS
        object, or a string. In the latter case it is interpreted as name of the
        template file.
        """
        if isinstance(template, basestring):
            filename = template
            try:
                import neo_cs
            except ImportError:
                raise TracError("You're using a plugin which requires "
                                "the Clearsilver template engine and "
                                "Clearsilver is not installed. "
                                "Either disable that plugin or install "
                                "Clearsilver.")
            template = neo_cs.CS(self.hdf)
            template.parseFile(filename)

        if form_token:
            from cStringIO import StringIO
            out = StringIO()
            injector = FormTokenInjector(form_token, out)
            injector.feed(template.render())
            return out.getvalue()
        else:
            return template.render()
Ejemplo n.º 7
0
    def redirectUri(self, redirectTo):
        ncgi = self.ncgi
        if ncgi.hdf.getIntValue("Cookie.debug", 0) == 1:
            ncgi.hdf.setValue("CGI.REDIRECT_TO", redirectTo)
            #            ncgi.display("dbg/redirect.cs")

            cs = neo_cs.CS(ncgi.hdf)
            self['Content-Type'] = "text/html"
            template = """
Redirect
<br><br>
<a href="<?cs var:CGI.REDIRECT_TO ?>"><?cs var:CGI.REDIRECT_TO ?></a>
"""
            cs.parseStr(template)
            page = cs.render()

            self.push(page)

            self.push("<PRE>\n")
            self.push(neo_cgi.htmlEscape(ncgi.hdf.dump()) + "\n")
            self.push("</PRE>\n")
            raise DisplayDone()

        self.context.setStatus(self, 302)
        self.ncgi.redirectUri(redirectTo)
        raise Redirected("redirected To: %s" % redirectTo)
Ejemplo n.º 8
0
    def GenreateCode(self):
        items = urllib2.unquote(request.params['hdf']).split(';')
        # .split(';')
        hdf = neo_util.HDF()
        print items
        for item in items:
            print item
            v = item.split('=')
            if (len(v) == 2):
                hdf.setValue(v[0], v[1])

        cs = neo_cs.CS(hdf)
        cs.parseFile("./feedtpladmin/public/feed-java-code.cs"
                     )  # parse a file from disk
        gen_code = cs.render()

        url_path = '/FeedBuilder_' + request.params[
            'stype'] + '_' + request.params['version'] + '.java'

        f = open("./feedtpladmin/public" + url_path, "w")

        f.write(gen_code)
        f.close()

        return url_path
Ejemplo n.º 9
0
    def format(self, formatter):
        # print "format"
        # format is also called for each !# command. its called after __init__
        # is called. this is where parsers do most of their work.
        # they write their results into the Httprequest object
        # which is usually stored from __init__ in self.request.

        # print "formatter",dir(formatter)
        # formatter is a special object in MoinMoin that
        # is supposed to help people who write extensions to have
        # sort of a uniform looking thing going on.
        # see http://moinmoin.wikiwikiweb.de/ApplyingFormatters?highlight=%28formatter%29

        # but formatter is not documented well. you have to look at
        # moinmoin/formatter/base.py. And if you do, you will see that half of
        # the methods raise a 'not implemented' error.
        # formatter is also being refactored alot so dont get used to it.
        # if all else fails just use formatter.rawHTML which will
        # screw up XML output but at least it will work.

        page_name = formatter.page.page_name
        cs_template_page = wikiutil.AbsPageName(page_name,
                                                self.kw["format_args"])
        cs_template = Page(self.request, cs_template_page).getPageText()

        hdf = neo_util.HDF()
        hdf.readString(self.raw)
        hdf.setValue("Config.WhiteSpaceStrip", "0")

        cs = neo_cs.CS(hdf)
        cs.parseStr(cs_template)
        body = cs.render()
        body = wikiutil.renderText(self.request, WikiParser, body)
        self.request.write(formatter.rawHTML(body))
Ejemplo n.º 10
0
 def testCsRenderStrip(self):
     hdf = neo_util.HDF()
     cs = neo_cs.CS(hdf)
     hdf.setValue("Foo.Bar", "1")
     cs.parseStr("This is my         file   <?cs var:Foo.Bar ?>   ")
     assert cs.render() == 'This is my         file   1   '
     hdf.setValue("ClearSilver.WhiteSpaceStrip", "1")
     assert cs.render() == 'This is my file 1 '
Ejemplo n.º 11
0
 def parse(self, string):
     """Parse the given string as template text, and returns a neo_cs.CS
     object.
     """
     import neo_cs
     cs = neo_cs.CS(self.hdf)
     cs.parseStr(string)
     return cs
Ejemplo n.º 12
0
 def __init__(self, env, msg_template):
     self.env = env
     self.db = env.get_db_cnx()
     self.hdf = neo_util.HDF()
     core.populate_hdf(self.hdf, env, self.db, None)
     tmpl = os.path.join(env.get_config('general', 'templates_dir'),
                         msg_template)
     self.cs = neo_cs.CS(self.hdf)
     self.cs.parseFile(tmpl)
Ejemplo n.º 13
0
 def ValidateTemplate(self):
     tpl = request.params['tpl']
     hdf = neo_util.HDF()  # create an HDF dataset
     cs = neo_cs.CS(hdf)
     try:
         cs.parseStr(urllib2.unquote(str(tpl)))
         cs.render()
     except neo_util.ParseError, e:
         return "错误:", str(e)
Ejemplo n.º 14
0
 def render():
     hdf = neo_util.HDF()
     hdf.setValue('hdf.loadpaths.0', dirname)
     hdf.setValue('title', escape('Just a test'))
     hdf.setValue('user', escape('joe'))
     for num in range(1, 15):
         hdf.setValue('items.%d' % (num - 1), escape('Number %d' % num))
     cs = neo_cs.CS(hdf)
     cs.parseFile('template.cs')
     return cs.render()
Ejemplo n.º 15
0
 def render():
     hdf = neo_util.HDF()
     hdf.setValue("hdf.loadpaths.0", dirname)
     hdf.setValue("title", escape("Just a test"))
     hdf.setValue("user", escape("joe"))
     for num in range(1, 15):
         hdf.setValue("items.%d" % (num - 1), escape("Number %d" % num))
     cs = neo_cs.CS(hdf)
     cs.parseFile("template.cs")
     return cs.render()
Ejemplo n.º 16
0
 def ValidateTemplate(self):
     stype = int(request.params['stype'])
     tpl = request.params['tpl']
     if stype <= 0 or not tpl:
         return '请求参数错误'
     hdf = neo_util.HDF()  # create an HDF dataset
     cs = neo_cs.CS(hdf)
     try:
         cs.parseStr(urllib2.unquote(str(tpl)))
         cs.render()
     except neo_util.ParseError, e:
         return "错误:", str(e)
Ejemplo n.º 17
0
    def render(self, template):
        """Render the HDF using the given template.

        The template parameter can be either an already parse neo_cs.CS
        object, or a string. In the latter case it is interpreted as name of the
        template file.
        """
        if isinstance(template, (str, unicode)):
            filename = template
            import neo_cs
            template = neo_cs.CS(self.hdf)
            template.parseFile(filename)
        return template.render()
Ejemplo n.º 18
0
    def test_clearsilver():
        """ClearSilver"""
        hdf = neo_util.HDF()
        for i, row in enumerate(table):
            for j, c in enumerate(row.values()):
                hdf.setValue("rows.%d.cell.%d" % (i, j), cgi.escape(str(c)))

        cs = neo_cs.CS(hdf)
        cs.parseStr("""
<table><?cs
  each:row=rows
?><tr><?cs each:c=row.cell
  ?><td><?cs var:c ?></td><?cs /each
?></tr><?cs /each?>
</table>""")
        cs.render()
Ejemplo n.º 19
0
def execute(macro, args):
    request = macro.request
    content = []
    page_name = macro.formatter.page.page_name

    # get args
    include_page_name = ''
    if args is not None:
        include_page_name = args

    include_page_name = wikiutil.AbsPageName(page_name, include_page_name)

    include_page = Page(request, include_page_name)

    if include_page is None:
        return ''
    if not request.user.may.read(include_page_name):
        return ''

    cstemplate = include_page.getPageText()

    pagename = macro.formatter.page.page_name
    kv_page = Page(request, pagename)
    kv_body = kv_page.get_body()

    hdf = neo_util.HDF()
    for line in kv_body.split("\n"):
        if line.startswith("##"):
            line = line[2:].strip()
            parts = line.split("=", 1)
            if len(parts) == 2:
                val = parts[1].strip()
                #val = parts[1].strip().encode('utf-8')  # swh
                hdf.setValue(parts[0].strip(), val)

    hdf.setValue("Config.WhiteSpaceStrip ", "0")

    cs = neo_cs.CS(hdf)
    cs.parseStr(cstemplate)

    body = cs.render()

    body = wikiutil.renderText(request, WikiParser, body)

    open("/tmp/out.html", "w").write(body)

    return body
Ejemplo n.º 20
0
    def render(self, template, form_token=None):
        """Render the HDF using the given template.

        The template parameter can be either an already parse neo_cs.CS
        object, or a string. In the latter case it is interpreted as name of the
        template file.
        """
        if isinstance(template, basestring):
            filename = template
            import neo_cs
            template = neo_cs.CS(self.hdf)
            template.parseFile(filename)

        if form_token:
            from cStringIO import StringIO
            out = StringIO()
            injector = FormTokenInjector(form_token, out)
            injector.feed(template.render())
            return out.getvalue()
        else:
            return template.render()
Ejemplo n.º 21
0
 def display(self, cs, content_type='text/html', response=200):
     import neo_cgi
     # The following line is needed so that ClearSilver can be loaded when
     # we are being run in multiple interpreters under mod_python
     neo_cgi.update()
     import neo_cs
     import neo_util
     if type(cs) == type(''):
         filename = cs
         cs = neo_cs.CS(self.hdf)
         cs.parseFile(filename)
     data = cs.render()
     self.send_response(response)
     self.send_header('Cache-control', 'no-cache')
     self.send_header('Expires', 'Fri, 01 Jan 1999 00:00:00 GMT')
     self.send_header('Content-Type', content_type + ';charset=utf-8')
     self.send_header('Content-Length', len(data))
     cookies = self.outcookie.output(header='')
     for cookie in cookies.splitlines():
         self.send_header('Set-Cookie', cookie.strip())
     self.end_headers()
     if self.command != 'HEAD':
         self.write(data)
Ejemplo n.º 22
0
import neo_cgi
import neo_util
import neo_cs

hdf = neo_util.HDF()
hdf.setValue("hdf.loadpaths.0", ".")
hdf.readFile("units.hdf")
hdf.readFile("slots.hdf")

cs = neo_cs.CS(hdf)
cs.parseFile("dhcpd.conf.cst")

print cs.render()
Ejemplo n.º 23
0
 def display(self):
     cs = neo_cs.CS(self.req.hdf)
     cs.parseStr(self.about_cs)
     self.req.display(cs)