Esempio n. 1
0
 def _do_account(self, req):
     assert(req.authname and req.authname != 'anonymous')
     action = req.args.get('action')
     delete_enabled = self.acctmgr.supports('delete_user') and \
                          self.acctmgr.allow_delete_account
     data = {'delete_enabled': delete_enabled,
             'delete_msg_confirm': _(
                 "Are you sure you want to delete your account?"),
            }
     force_change_password = req.session.get('force_change_passwd', False)
     if req.method == 'POST':
         if action == 'save':
             data.update(self._do_change_password(req))
             if force_change_password:
                 del(req.session['force_change_passwd'])
                 req.session.save()
                 chrome.add_notice(req, Markup(tag.span(tag_(
                     "Thank you for taking the time to update your password."
                 ))))
                 force_change_password = False
         elif action == 'delete' and delete_enabled:
             data.update(self._do_delete(req))
         else:
             data.update({'error': 'Invalid action'})
     if force_change_password:
         chrome.add_warning(req, Markup(tag.span(_(
             "You are required to change password because of a recent "
             "password change request. "),
             tag.b(_("Please change your password now.")))))
     return data
Esempio n. 2
0
    def test_verify_conf_changes(self):
        """Registration challenges with EmailVerificationModule enabled."""
        self.env = EnvironmentStub(
            enable=['trac.*', 'acct_mgr.admin.*', 'acct_mgr.register.*'])
        self.env.path = tempfile.mkdtemp()
        set_user_attribute(self.env, 'admin', 'email', '*****@*****.**')

        check = EmailCheck(self.env)
        req = self.req

        # Inspector provides the email text input field.
        old_email_input = '*****@*****.**'
        acct = dict(username='******', email=old_email_input, name='User')
        req.args.update(acct)
        field_res = check.render_registration_fields(req, acct)
        self.assertEqual(len(field_res), 2)
        self.assertTrue(Markup(field_res[0]).startswith('<label>Email:'))
        # Ensure, that old input is restored on failure.
        self.assertTrue(old_email_input in Markup(field_res[0]))
        # Ensure, that template data dict is passed unchanged.
        self.assertEqual(field_res[1], acct)
        req.args.update(dict(email=''))

        # 1st: Initially try with account verification disabled by setting.
        self.env.config.set('account-manager', 'verify_email', False)
        self.assertEqual(check.validate_registration(req), None)
        # 2nd: Again no email, but now with account verification enabled.
        self.env.config.set('account-manager', 'verify_email', True)
        self.assertRaises(RegistrationError, check.validate_registration, req)
        # 3th attempt: Valid email, but already registered with a username.
        req.args['email'] = '*****@*****.**'
        self.assertRaises(RegistrationError, check.validate_registration, req)
        # 4th attempt: Finally some valid input.
        req.args['email'] = '*****@*****.**'
        self.assertEqual(check.validate_registration(req), None)
Esempio n. 3
0
 def process_request(self, req):
     if req.authname != 'anonymous':
         req.redirect(req.href.prefs('account'))
     action = req.args.get('action')
     data = {
         'acctmgr': {
             'username': None,
             'name': None,
             'email': None,
         },
         '_dgettext': dgettext,
     }
     data['verify_account_enabled'] = is_enabled(
         self.env, EmailVerificationModule) and self.acctmgr.verify_email
     if req.method == 'POST' and action == 'create':
         try:
             _create_user(req, self.env)
         except TracError, e:
             data['registration_error'] = e.message
             data['acctmgr'] = getattr(e, 'acctmgr', '')
         else:
             chrome.add_notice(
                 req,
                 Markup(
                     tag.span(
                         Markup(
                             _("""Registration has been finished successfully.
                  You may login as user %(user)s now.""",
                               user=tag.b(req.args.get('username')))))))
             req.redirect(req.href.login())
Esempio n. 4
0
 def test_check(self):
     check = BasicCheck(self.env)
     req = self.req
     # Inspector doesn't provide additional fields.
     field_res = check.render_registration_fields(req, {})
     self.assertEqual(len(field_res), 2)
     self.assertEqual((Markup(field_res[0]), field_res[1]),
                      (Markup(''), {}))
     # 1st attempt: No input.
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 2nd attempt: Illegal character.
     req.args['username'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 3rd attempt: All upper-case word.
     req.args['username'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 4th attempt: Reserved word.
     req.args['username'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 5th attempt: Existing user.
     req.args['username'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 6th attempt: Valid username, but no password.
     req.args['username'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 7th attempt: Valid username, no matching passwords.
     req.args['password'] = '******'
     self.assertRaises(RegistrationError, check.validate_registration, req)
     # 8th attempt: Finally some valid input.
     req.args['password_confirm'] = 'password'
     self.assertEqual(check.validate_registration(req), None)
Esempio n. 5
0
    def test_check(self):
        check = BotTrapCheck(self.env)
        req = self.req

        # Inspector provides the email text input field.
        wrong_input = "Hey, I'm a bot."
        data = dict(basic_token=wrong_input)
        req.args.update(data)
        field_res = check.render_registration_fields(req, data)
        self.assertEqual(len(field_res), 2)
        self.assertTrue(Markup(field_res[0]).startswith('<label>Parole:'))

        # 1st attempt: Wrong input.
        self.assertRaises(RegistrationError, check.validate_registration, req)
        # Ensure, that old input is restored on failure.
        self.assertTrue(wrong_input in Markup(field_res[0]))
        # Ensure, that template data dict is passed unchanged.
        self.assertEqual(field_res[1], data)

        # 2nd attempt: No input.
        req.args['basic_token'] = ''
        self.assertRaises(RegistrationError, check.validate_registration, req)
        # 3th attempt: Finally valid input.
        req.args['basic_token'] = self.basic_token
        self.assertEqual(check.validate_registration(req), None)
        # 4rd attempt: Fill the hidden field too.
        req.args['sentinel'] = "Humans can't see this? Crap - I'm superior!"
        self.assertRaises(RegistrationError, check.validate_registration, req)
Esempio n. 6
0
 def test_markup_escape(self):
     from genshi.core import Markup
     m = Markup('See %s') % tag.a('genshi',
                                  href='http://genshi.edgwall.org')
     self.assertEqual(
         m, Markup('See <a href="http://genshi.edgwall.org">'
                   'genshi</a>'))
Esempio n. 7
0
    def post_process_request(self, req, template, data, content_type):
        if not req.session.authenticated:
            # Don't start the email verification precedure on anonymous users.
            return template, data, content_type

        email = req.session.get('email')
        # Only send verification if the user entered an email address.
        acctmgr = AccountManager(self.env)
        if acctmgr.verify_email and self.email_enabled is True and email and \
                email != req.session.get('email_verification_sent_to') and \
                not req.perm.has_permission('ACCTMGR_ADMIN'):
            req.session['email_verification_token'] = self._gen_token()
            req.session['email_verification_sent_to'] = email
            acctmgr._notify('email_verification_requested', req.authname,
                            req.session['email_verification_token'])
            # TRANSLATOR: An email has been sent to %(email)s
            # with a token to ... (the link label for following message)
            link = tag.a(_("verify your new email address"),
                         href=req.href.verify_email())
            # TRANSLATOR: ... verify your new email address
            chrome.add_notice(
                req,
                Markup(
                    tag.span(
                        Markup(
                            _("""An email has been sent to %(email)s with a token to
                %(link)s.""",
                              email=email,
                              link=link)))))
        return template, data, content_type
Esempio n. 8
0
 def __call__(self):
     resources = fanstatic.get_needed()
     stream = self.tmpl.generate(resources=Markup(resources.render()),
                                 title=self.context.title,
                                 launcher=Markup(self.launcher()))
     self.request.response.mimetype = 'text/html'
     self.request.response.write(stream.render('html', doctype='html'))
Esempio n. 9
0
 def expand_macro(self, formatter, name, content, args=None):
     style_args = {'fg': 'color', 'bg': 'background-color',
                   'size': 'font-size'}
     style_values = {'color': '', 'background-color': '', 'font-size': ''}
     space_start = ''
     space_end = ''
     if args:
         text = content
         for k in args.keys():
             style = style_args[k] if k in style_args else k
             style_values[style] = args.get(k)
         html = format_to_html(self.env, formatter.context, text)
     else:
         args = content.split(',')
         text = ','.join(args[:-1])
         args = args[-1].split('/') + ['']*3
         style_values['color'] = args.pop(0).strip()
         # background color is optional
         arg = args.pop(0).strip()
         if len(arg) > 0 and arg[0].isdigit():
             style_values['font-size'] = arg
         else:
             style_values['background-color'] = arg
             style_values['font-size'] = args.pop(0).strip()
         html = format_to_oneliner(self.env, formatter.context, text)
         if text.startswith(u' '):
             space_start = Markup('&nbsp')
         if text.endswith(u' '):
             space_end = Markup('&nbsp')
     if style_values['font-size'].isdigit():
         style_values['font-size'] += '%'
     style = ';'.join('%s:%s' % (k, v) for (k, v) in
                      style_values.iteritems() if v)
     return tag.span(space_start, html, space_end, style=style)
Esempio n. 10
0
 def save(self, req):
     if req.args and req.args.has_key('action') \
     and req.args['action'] == 'save':
         for key in SESSION_KEYS.values():
             if req.args.has_key(key):
                 if key == 'wiki.href':
                     wiki_href = req.args[key]
                     if wiki_href == '':
                         req.session[key] = ''
                         continue
                     validated = WikiSystem(self.env).has_page(wiki_href)
                     if validated:
                         req.session[key] = req.args[key]
                     else:
                         add_warning(req, Markup(tag.span(Markup(_(
                             "%(page)s is not a valid Wiki page",
                             page=tag.b(wiki_href)
                             )))))
                 elif key == 'tickets.href':
                     ticket_href = req.args[key]
                     if ticket_href == '':
                         req.session[key] = ''
                         continue
                     reports = self.get_report_list()
                     self.log.info('reports: %s' % reports)
                     if ticket_href in ('report', 'query') \
                     or as_int(ticket_href, 0) in reports:
                         req.session[key] = req.args[key]
                     else:
                         add_warning(req, Markup(tag.span(Markup(_(
                             "%(report)s is not a valid report",
                             report=tag.b(ticket_href)
                             )))))
                 else:
                     req.session[key] = req.args[key]
Esempio n. 11
0
def flatten(el, result):
  attrs = ''
  for key in el.attrib:
    attrs += ' %s="%s"' % (key, el.attrib[key])
  result.append(Markup("<%s%s>" % (el.tag, attrs)))
  flatten_children(el, result)
  result.append(Markup("</%s>" % el.tag))
Esempio n. 12
0
    def post_process_request(self, req, template, data, content_type):
        if not req.session.authenticated:
            # Don't start the email verification procedure on anonymous users.
            return template, data, content_type

        email = req.session.get('email')
        # Only send verification if the user entered an email address.
        if self.verify_email and self.email_enabled is True and email and \
                email != req.session.get('email_verification_sent_to') and \
                not req.perm.has_permission('ACCTMGR_ADMIN'):
            req.session['email_verification_token'] = self._gen_token()
            req.session['email_verification_sent_to'] = email
            try:
                AccountManager(self.env)._notify(
                    'email_verification_requested', 
                    req.authname, 
                    req.session['email_verification_token']
                )
            except NotificationError, e:
                chrome.add_warning(req, _(
                    "Error raised while sending a change notification."
                    ) + _("You should report that issue to a Trac admin."))
                self.log.error('Unable to send registration notification: %s',
                               exception_to_unicode(e, traceback=True))
            else:
                # TRANSLATOR: An email has been sent to <%(email)s>
                # with a token to ... (the link label for following message)
                link = tag.a(_("verify your new email address"),
                             href=req.href.verify_email())
                # TRANSLATOR: ... verify your new email address
                chrome.add_notice(req, Markup(tag.span(Markup(_(
                    "An email has been sent to <%(email)s> with a token to "
                    "%(link)s.", email=tag(email), link=link))))
                )
Esempio n. 13
0
 def test_format_cjk_name(self):
     self.assertEqual(
         Markup(
             u'Wiki'
             u'<a class="wiki" href="/wiki/%E3%81%82%E3%81%84%E3%81%86Name">あいうName</a>'
             u'ABC'
             u'<a class="wiki" href="/wiki/Name%E3%81%82%E3%81%84%E3%81%86">Nameあいう</a>'
             u'A'
             u'<a class="wiki" href="/wiki/%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93">かきくけこ</a>'
             u'abc'
         ),
         self.format_to_oneliner(
             u'WikiあいうNameABCNameあいうAかきくけこabc'))
     self.assertEqual(
         Markup(
             u'<a class="wiki" href="/wiki/%E3%81%82%E3%81%84%E3%81%86Name">あいうName</a>'
             u'<a class="wiki" href="/wiki/%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93">かきくけこ</a>'
         ),
         self.format_to_oneliner(
             u'あいうNameかきくけこ'))
     self.assertEqual(
         Markup(
             u'<a class="wiki" href="/wiki/%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93">かきくけこ</a>'
             u'<a class="wiki" href="/wiki/%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93">かきくけこ</a>'
         ),
         self.format_to_oneliner(
             u'かきくけこかきくけこ'))
Esempio n. 14
0
    def produce_html(self, context, url, kwargs={}):
        attr = dict()
        attr['data'] = context.href.chrome('mindmap', 'visorFreemind.swf')
        attr['width'] = kwargs.pop('width', self.default_width)
        attr['height'] = kwargs.pop('height', self.default_height)
        try:
            int(attr['height'])
        except:
            pass
        else:
            attr['height'] += "px"
        try:
            int(attr['width'])
        except:
            pass
        else:
            attr['width'] += "px"

        flashvars = dict(
            [[k.strip(), v.strip()]
             for k, v in [kv.split('=') for kv in self.default_flashvars]])
        try:
            flashvars.update([[k.strip(), v.strip()] for k, v in [
                kv.split('=')
                for kv in kwargs['flashvars'].strip("\"'").split('|')
            ]])
        except:
            pass
        flashvars['initLoadFile'] = url

        css = ''
        if 'border' in kwargs:
            border = kwargs['border'].strip("\"'").replace(';', '')
            if border == "1":
                border = "solid"
            elif border == "0":
                border = "none"
            css = 'border: ' + border

        if self.resizable and (
            ('resizable' not in kwargs and self.default_resizable)
                or kwargs.get('resizable', 'false').lower() == "true"):
            class_ = "resizablemindmap mindmap"
        else:
            class_ = "mindmap"

        return tag.div(
            tag.object(tag.param(name="quality", value="high"),
                       tag.param(name="bgcolor", value="#ffffff"),
                       tag.param(name="flashvars",
                                 value=Markup("&".join([
                                     "=".join([k, unicode(v)])
                                     for k, v in flashvars.iteritems()
                                 ]))),
                       type="application/x-shockwave-flash",
                       **attr),
            class_=class_,
            style=Markup(css),
        )
Esempio n. 15
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:

            if kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [' ', attr]
                    elif ':' in attr:
                        if attr == 'xml:lang' and u'lang' not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != 'xmlns':
                        buf += [' ', attr, '="', escape(value), '"']
                buf.append('>')
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append('</%s>' % tag)
                yield Markup(u''.join(buf))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield Markup('</%s>' % data)
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield data
                else:
                    yield escape(data, quotes=False)

            elif kind is COMMENT:
                yield Markup('<!--%s-->' % data)

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(u''.join(buf)) % filter(None, data)
                have_doctype = True

            elif kind is PI:
                yield Markup('<?%s %s?>' % data)
Esempio n. 16
0
 def _get_adds(self, req):
     """Find all links to add."""
     for adder in self.ctxtnav_adders:
         if adder.match_ctxtnav_add(req):
             for add in adder.get_ctxtnav_adds(req):
                 if isinstance(add, Markup):
                     yield Markup(add.replace("'", "\\'"))
                 else:
                     yield tag.a(add[1], href=Markup(add[0]))
Esempio n. 17
0
class EmailVerificationModule(CommonTemplateProvider):
    """Performs email verification on every new or changed address.

    A working email sender for Trac (!TracNotification or !TracAnnouncer)
    is strictly required to enable this module's functionality.

    Anonymous users should register and perms should be tweaked, so that
    anonymous users can't edit wiki pages and change or create tickets.
    So this email verification code won't be used on them. 
    """

    implements(IRequestFilter, IRequestHandler)

    def __init__(self, *args, **kwargs):
        self.email_enabled = True
        if self.config.getbool('announcer', 'email_enabled') != True and \
                self.config.getbool('notification', 'smtp_enabled') != True:
            self.email_enabled = False
            if is_enabled(self.env, self.__class__) == True:
                self.env.log.warn(' '.join([
                    self.__class__.__name__,
                    "can't work because of missing email setup."
                ]))

    # IRequestFilter methods

    def pre_process_request(self, req, handler):
        if not req.session.authenticated:
            # Permissions for anonymous users remain unchanged.
            return handler
        elif req.path_info == '/prefs' and req.method == 'POST' and \
                not 'restore' in req.args:
            try:
                EmailCheck(self.env).validate_registration(req)
                # Check passed without error: New email address seems good.
            except RegistrationError, e:
                # Attempt to change email to an empty or invalid
                # address detected, resetting to previously stored value.
                chrome.add_warning(req, Markup(gettext(e.message)))
                req.redirect(req.href.prefs(None))
        if AccountManager(self.env).verify_email and handler is not self and \
                'email_verification_token' in req.session and \
                not req.perm.has_permission('ACCTMGR_ADMIN'):
            # TRANSLATOR: Your permissions have been limited until you ...
            link = tag.a(_("verify your email address"),
                         href=req.href.verify_email())
            # TRANSLATOR: ... verify your email address
            chrome.add_warning(
                req,
                Markup(
                    tag.span(
                        Markup(
                            _("Your permissions have been limited until you %(link)s.",
                              link=link)))))
            req.perm = perm.PermissionCache(self.env, 'anonymous')
        return handler
Esempio n. 18
0
    def __call__(self,
                 stream,
                 ctxt=None,
                 space=XML_NAMESPACE['space'],
                 trim_trailing_space=re.compile('[ \t]+(?=\n)').sub,
                 collapse_lines=re.compile('\n{2,}').sub):
        mjoin = Markup('').join
        preserve_elems = self.preserve
        preserve = 0
        noescape_elems = self.noescape
        noescape = False

        textbuf = []
        push_text = textbuf.append
        pop_text = textbuf.pop
        for kind, data, pos in chain(stream, [(None, None, None)]):

            if kind is TEXT:
                if noescape:
                    data = Markup(data)
                push_text(data)
            else:
                if textbuf:
                    if len(textbuf) > 1:
                        text = mjoin(textbuf, escape_quotes=False)
                        del textbuf[:]
                    else:
                        text = escape(pop_text(), quotes=False)
                    if not preserve:
                        text = collapse_lines('\n',
                                              trim_trailing_space('', text))
                    yield TEXT, Markup(text), pos

                if kind is START:
                    tag, attrs = data
                    if preserve or (tag in preserve_elems
                                    or attrs.get(space) == 'preserve'):
                        preserve += 1
                    if not noescape and tag in noescape_elems:
                        noescape = True

                elif kind is END:
                    noescape = False
                    if preserve:
                        preserve -= 1

                elif kind is START_CDATA:
                    noescape = True

                elif kind is END_CDATA:
                    noescape = False

                if kind:
                    yield kind, data, pos
Esempio n. 19
0
    def __init__(
        self,
        txt,
        target_id_parent,
        target_id,
        left,
        top,
        width,
        height,
        lb_left,
        lb_top,
        lb_width,
        lb_height,
        zoomed_img_left,
        zoomed_img_top,
        img_src,
        ordinal=None,
        zoom_factor=1.5,
        pre_data=None,
        post_data=None,
    ):
        self.txt = txt
        self.target_id_parent = target_id_parent
        self.target_id = target_id

        # coordinates for click target
        self.top = top
        self.left = left
        self.height = height
        self.width = width

        # lb_ refers to lightbox image
        self.lb_top = lb_top
        self.lb_left = lb_left
        self.lb_width = lb_width
        self.lb_height = lb_height

        # zoomed_img_ referes to position on zoomed image relative to lightbox
        self.zoomed_img_top = zoomed_img_top
        self.zoomed_img_left = zoomed_img_left

        self.ordinal = ordinal
        self.zoom_factor = zoom_factor
        self.img_src = img_src
        # text/etc to display
        if post_data:
            self.post_data = Markup(post_data)
        else:
            self.post_data = ""
        if pre_data:
            self.pre_data = Markup(pre_data)
        else:
            self.pre_data = ""
Esempio n. 20
0
    def _gen_ticket_entry(self, t, a_class=''):
        id = str(t.get('id'))
        status = t.get('status')
        summary = to_unicode(t.get('summary'))
        owner = to_unicode(t.get('owner'))
        description = to_unicode(t.get('description')[:1024])
        url = t.get('href')

        if status == 'closed':
            a_class = a_class + 'closed'
        else:
            a_class = a_class + 'open'
        markup = format_to_html(self.env, self.ref.context, description)
        # Escape, if requested
        if self.sanitize is True:
            try:
                description = HTMLParser(StringIO(markup)
                                           ).parse() | HTMLSanitizer()
            except ParseError:
                description = escape(markup)
        else:
            description = markup

        # Replace tags that destruct tooltips too much
        desc = self.end_RE.sub(']', Markup(description))
        desc = self.del_RE.sub('', desc)
        # need 2nd run after purging newline in table cells in 1st run
        desc = self.del_RE.sub('', desc)
        desc = self.item_RE.sub('X', desc)
        desc = self.tab_RE.sub('[|||]', desc)
        description = self.open_RE.sub('[', desc)

        tip = tag.span(Markup(description))
        ticket = '#' + id
        ticket = tag.a(ticket, href=url)
        ticket(tip, class_='tip', target='_blank')
        ticket = tag.div(ticket)
        ticket(class_=a_class, align='left')
        # fix stripping of regular leading space in IE
        blank = '&nbsp;'
        ticket(Markup(blank), summary, ' (', owner, ')')

        summary = tag(summary, ' (', owner, ')')
        ticket_short = '#' + id
        ticket_short = tag.a(ticket_short, href=url)
        ticket_short(target='_blank', title_=summary)
        ticket_short = tag.span(ticket_short)
        ticket_short(class_=a_class)

        return ticket,ticket_short
Esempio n. 21
0
 def process_request(self, req):
     acctmgr = self.acctmgr
     if req.authname != 'anonymous':
         req.redirect(req.href.prefs('account'))
     action = req.args.get('action')
     name = req.args.get('name', '').strip()
     username = acctmgr.handle_username_casing(
         req.args.get('username', '').strip())
     data = {
         '_dgettext': dgettext,
         'acctmgr': dict(name=name, username=username),
         'ignore_auth_case': self.config.getbool('trac', 'ignore_auth_case')
     }
     verify_enabled = is_enabled(self.env, EmailVerificationModule) and \
                      acctmgr.verify_email
     data['verify_account_enabled'] = verify_enabled
     if req.method == 'POST' and action == 'create':
         try:
             # Check request and prime account on success.
             acctmgr.validate_registration(req)
         except RegistrationError, e:
             # Attempt deferred translation.
             message = gettext(e.message)
             # Check for (matching number of) message arguments before
             #   attempting string substitution.
             if e.msg_args and \
                     len(e.msg_args) == len(re.findall('%s', message)):
                 message = message % e.msg_args
             chrome.add_warning(req, Markup(message))
         else:
             if verify_enabled:
                 chrome.add_notice(
                     req,
                     Markup(
                         tag.span(
                             Markup(
                                 _("""Your username has been successfully registered but
                     your account still requires activation. Please login
                     as user %(user)s, and follow the instructions.""",
                                   user=tag.b(username))))))
                 req.redirect(req.href.login())
             chrome.add_notice(
                 req,
                 Markup(
                     tag.span(
                         Markup(
                             _("""Registration has been finished successfully.
                  You may log in as user %(user)s now.""",
                               user=tag.b(username))))))
             req.redirect(req.href.login())
Esempio n. 22
0
 def test_insert_markup(self):
     from genshi.core import Markup
     self.env.db_transaction(
             "INSERT INTO system (name,value) VALUES (%s,%s)",
             ('test-markup', Markup(u'<em>märkup</em>')))
     self.assertEqual([(u'<em>märkup</em>',)], self.env.db_query(
         "SELECT value FROM system WHERE name='test-markup'"))
Esempio n. 23
0
    def render(self, context, mimetype, content, filename=None, rev=None):
        # -n to ignore php.ini so we're using default colors
        cmdline = '%s -sn' % self.path
        self.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 />')
        ]
Esempio n. 24
0
 def type(self, el):
   M = Markup
   if el.tag == 'typename':
     name = el.text
     if name.startswith("tart.core."): name = name[10:]
     if 'hlink' in self.options and el.attrib['type'] != 'primitive':
       uri = self.index.makeUri(el.text)
       return self.a(name, uri, 'type-name-link')
     else:
       return self.span(name, 'type-name')
   elif el.tag == 'type-variable':
     name = el.attrib['name']
     if 'tsig' in self.options: return self.concat('%', self.span(name, 'type-variable-name'))
     else: return self.span(name, 'type-name')
   elif el.tag == 'array':
     return self.concat(self.typeContent(el), "[]")
   elif el.tag == 'variadic':
     return self.concat(self.typeContent(el), "...")
   elif el.tag == 'address':
     return self.concat('Address[', self.typeContent(el), ']')
   elif el.tag == 'tuple':
     return self.concat('(', self.typeList(el.findall("*")), ')')
   elif el.tag == 'union':
     return Markup(" or ").join(self.type(ty) for ty in el.findall("*"))
   elif el.tag == 'template-instance':
     return self.concat(
         self.typeContent(el),
         self.typeParamList(el.findall("template-arg/*")))
   else:
     return self.concat(el.tag, "??")
Esempio n. 25
0
 def test_pickle(self):
     markup = Markup('foo')
     buf = BytesIO()
     pickle.dump(markup, buf, 2)
     buf.seek(0)
     expected_foo = "u'foo'" if IS_PYTHON2 else "'foo'"
     self.assertEqual("<Markup %s>" % expected_foo, repr(pickle.load(buf)))
Esempio n. 26
0
 def process_request(self, req):
     if not req.session.authenticated:
         chrome.add_warning(
             req,
             Markup(
                 tag.span(
                     tag_(
                         "Please log in to finish email verification procedure."
                     ))))
         req.redirect(req.href.login())
     if 'email_verification_token' not in req.session:
         chrome.add_notice(req, _("Your email is already verified."))
     elif req.method == 'POST' and 'resend' in req.args:
         AccountManager(self.env)._notify(
             'email_verification_requested', req.authname,
             req.session['email_verification_token'])
         chrome.add_notice(
             req, _("A notification email has been resent to <%s>."),
             req.session.get('email'))
     elif 'verify' in req.args:
         # allow via POST or GET (the latter for email links)
         if req.args['token'] == req.session['email_verification_token']:
             del req.session['email_verification_token']
             chrome.add_notice(
                 req, _("Thank you for verifying your email address."))
             req.redirect(req.href.prefs())
         else:
             chrome.add_warning(req, _("Invalid verification token"))
     data = {'_dgettext': dgettext}
     if 'token' in req.args:
         data['token'] = req.args['token']
     if 'email_verification_token' not in req.session:
         data['button_state'] = {'disabled': 'disabled'}
     return 'verify_email.html', data, None
Esempio n. 27
0
    def test_bad_check(self):
        class BadRegistrationInspector(GenericRegistrationInspector):
            """Child class, that is left as a copy of its base.

            Bad check class example, because check method is not implemented.
            """

        check = BadRegistrationInspector(self.env)
        # Default (empty) response for providing additional fields is safe.
        field_res = check.render_registration_fields(self.req, {})
        self.assertEqual(len(field_res), 2)
        self.assertEqual((Markup(field_res[0]), field_res[1]),
                         (Markup(''), {}))
        # Check class without 'validate_registration' implementation fails.
        self.assertRaises(NotImplementedError, check.validate_registration,
                          self.req)
Esempio n. 28
0
def html(macro, environ, data, *args, **kwargs):
    """Displays raw HTML content.

    This macro allows you to display raw HTML with any **safe** content.

    **NB:** Any elements considered unsafe are automatically stripped.
    
    **Arguments:** //No Arguments//

    **Example(s):**
    {{{
    <<html>>
    <h1>Hello World!</h1>
    <</html>>
    }}}

    <<html>>
    <h1>Hello World!</h1>
    <</html>>
    """

    if not macro.body:
        return None

    return Markup("".join(serializer(sanitizer(HTML(macro.body)))))
Esempio n. 29
0
    def __init__(self, db_name, result, q):
        """Generate information for display in a search result. 

        """
        self.rank = result.rank + 1
        data = json.loads(result.data['_bamboo_doc'][0])
        text = []
        self.caption = ''

        for field in data:
            if field[0] == 'title' and not self.caption:  # HACK
                self.caption = field[1]
            elif field[0] == 'text':
                text.append(field[1])

        text = ' '.join(text)

        # generate a summary
        if q:
            hl = highlight.Highlighter()
            qterms = [(x, ) for x in q.split()]
            self.sample = Markup(
                hl.makeSample(text, qterms, 400, hl=('<b>', '</b>')))
        elif len(text) > 400:
            self.sample = text[:400] + '...'
        else:
            self.sample = text

        docurl = '/dbs/%s/docs/%s' % (urllib.quote_plus(db_name),
                                      urllib.quote_plus(result.docid))

        self.view_href = docurl
        self.edit_href = docurl + '/edit'
        self.similar_href = docurl + '/similar'
Esempio n. 30
0
def process_dir(dirpath, filenames, projects):
    '''
    Process a directory
    '''
    translations = GNUTranslations(
        open(os.path.join(options.podir, options.lang + '.mo')))
    loader = TemplateLoader(['.'],
                            callback=lambda template: template.filters.insert(
                                0, Translator(translations.ugettext)))
    for fn in filenames:
        if fn.endswith('~') or fn.endswith('.swp'):
            continue
        src_file = os.path.join(dirpath, fn)
        dest_file = os.path.join(
            options.output,
            src_file[len(options.input):]) + '.' + options.lang  # Hideous
        curpage = src_file[len(options.input):].rstrip('.html')
        relpath = '../' * (dest_file.count('/') - 1)
        relpath = relpath.rstrip('/')
        if relpath == '': relpath = '.'
        if not os.path.exists(os.path.dirname(dest_file)):
            os.makedirs(os.path.dirname(dest_file))
        template = loader.load(src_file)
        # Variables made availble to all templates
        page = template.generate(
            _=lambda text: Markup(translations.ugettext(text)),
            lang=options.lang,
            path=options.basepath,
            relpath=relpath,
            curpage=curpage,
            projects=projects).render(method='html', doctype='html')
        output = open(dest_file, 'w')
        output.write(page)
        output.close()