Exemplo n.º 1
0
 def _render_wiki_page(self, path_info):
     req = MockRequest(self.env, path_info=path_info, method='GET')
     mod = WikiModule(self.env)
     self.assertTrue(mod.match_request(req))
     resp = mod.process_request(req)
     self.assertEqual(2, len(resp))
     return self._render_template(req, resp[0], resp[1])
Exemplo n.º 2
0
    def test_delete_page(self):
        page = WikiPage(self.env)
        page.name = 'SandBox'
        page.text = 'Contents for SandBox'
        page.save('trac', 'create page')

        mod = WikiModule(self.env)
        req = MockRequest(self.env,
                          path_info='/wiki/SandBox',
                          method='GET',
                          args={
                              'action': 'delete',
                              'version': '1'
                          })
        self.assertTrue(mod.match_request(req))
        resp = mod.process_request(req)
        self.assertEqual(2, len(resp))
        self.assertIn('Are you sure you want to completely delete this page?',
                      self._render_template(req, resp[0], resp[1]))

        req = MockRequest(self.env,
                          path_info='/wiki/SandBox',
                          method='POST',
                          args={'action': 'delete'})
        self.assertTrue(mod.match_request(req))
        self.assertRaises(RequestDone, mod.process_request, req)
        self.assertIn('The page SandBox has been deleted.',
                      req.chrome.get('notices'))
        self.assertEqual(False, WikiPage(self.env, 'SandBox').exists)
Exemplo n.º 3
0
    def test_edit_action_with_empty_verion(self):
        """Universal edit button requires request with parameters string
        ?action=edit&version= and ?action=view&version= (#12937)
        """
        req = MockRequest(self.env,
                          path_info='/wiki/NewPage',
                          method='GET',
                          args={
                              'action': 'view',
                              'version': '',
                              'page': 'NewPage'
                          })

        resp = WikiModule(self.env).process_request(req)

        self.assertEqual('wiki_view.html', resp[0])
        self.assertIsNone(resp[1]['version'])
        self.assertEqual('NewPage', resp[1]['page'].name)

        req = MockRequest(self.env,
                          path_info='/wiki/NewPage',
                          method='GET',
                          args={
                              'action': 'edit',
                              'version': '',
                              'page': 'NewPage'
                          })

        resp = WikiModule(self.env).process_request(req)

        self.assertEqual('wiki_edit.html', resp[0])
        self.assertNotIn('version', resp[1])
        self.assertEqual('NewPage', resp[1]['page'].name)
Exemplo n.º 4
0
    def process_request(self, req):
        self.log.debug('TinyMceWiki:process_request')
        #for tynimce
        if req.args.get('editor') == 'tinymce':
            req.hdf['wiki.editor'] = 'tinymce' 
            req.hdf['wiki.hoge'] = 'TinyMceWiki' 

        WikiModule.process_request(self, req)
        return 'tinymcewiki.cs',None
Exemplo n.º 5
0
 def _dispatch_request(self, req):
     module = WikiModule(self.env)
     self.assertTrue(module.match_request(req))
     try:
         params = module.process_request(req)
     except RequestDone:
         return []
     else:
         return params
Exemplo n.º 6
0
    def process_request(self, req):
        self.log.debug('TinyMceWiki:process_request')
        #for tynimce
        if req.args.get('editor') == 'tinymce':
            req.hdf['wiki.editor'] = 'tinymce'
            req.hdf['wiki.hoge'] = 'TinyMceWiki'

        WikiModule.process_request(self, req)
        return 'tinymcewiki.cs', None
Exemplo n.º 7
0
 def _render_wiki_page(self, path_info):
     req = MockRequest(self.env, path_info=path_info, method='GET')
     mod = WikiModule(self.env)
     self.assertTrue(mod.match_request(req))
     resp = mod.process_request(req)
     self.assertEqual(2, len(resp))
     content = Chrome(self.env).render_template(req, resp[0], resp[1], {
         'iterable': False,
         'fragment': False
     })
     return content.decode('utf-8')
Exemplo n.º 8
0
    def test_invalid_get_request_raises_exception(self):
        req = MockRequest(self.env, method='GET', action=None,
                          args=dict(version='a', old_version='1'))

        with self.assertRaises(HTTPBadRequest):
            WikiModule(self.env).process_request(req)

        req = MockRequest(self.env, method='GET', action=None,
                          args=dict(version='2', old_version='a'))

        with self.assertRaises(HTTPBadRequest):
            WikiModule(self.env).process_request(req)
Exemplo n.º 9
0
    def process_request(self, req):
        from tractags.api import TagEngine
        from trac.web.chrome import add_stylesheet

        add_stylesheet(req, 'tags/css/tractags.css')

        pagename = req.args.get('page', 'WikiStart')
        action = req.args.get('action', 'view')

        engine = TagEngine(self.env)
        wikitags = engine.tagspace.wiki
        tags = list(wikitags.get_tags([pagename]))
        tags.sort()

        if action == 'edit':
            req.hdf['tags'] = req.args.get('tags', ', '.join(tags))
        elif action == 'view':
            hdf_tags = []
            for tag in tags:
                href, title = engine.get_tag_link(tag)
                hdf_tags.append({'name': tag,
                                 'href': href,
                                 'title': title})
            req.hdf['tags'] = hdf_tags
        result = WikiModule.process_request(self, req)
        if result is None:
            return None
        if result[0] == 'wiki.cs':
            return 'tagswiki.cs', None
        return result
Exemplo n.º 10
0
    def process_request(self, req):
        from tractags.api import TagEngine
        from trac.web.chrome import add_stylesheet

        add_stylesheet(req, 'tags/css/tractags.css')

        pagename = req.args.get('page', 'WikiStart')
        action = req.args.get('action', 'view')

        engine = TagEngine(self.env)
        wikitags = engine.tagspace.wiki
        tags = list(wikitags.get_tags([pagename]))
        tags.sort()

        if action == 'edit':
            req.hdf['tags'] = req.args.get('tags', ', '.join(tags))
        elif action == 'view':
            hdf_tags = []
            for tag in tags:
                href, title = engine.get_tag_link(tag)
                hdf_tags.append({'name': tag, 'href': href, 'title': title})
            req.hdf['tags'] = hdf_tags
        result = WikiModule.process_request(self, req)
        if result is None:
            return None
        if result[0] == 'wiki.cs':
            return 'tagswiki.cs', None
        return result
Exemplo n.º 11
0
    def test_wiki_template_absolute_path(self):
        self._insert_templates()
        req = MockRequest(self.env, path_info='/wiki/NewPage', method='GET',
                          args={'action': 'edit', 'page': 'NewPage',
                                'template': '/TheTemplate'})

        resp = WikiModule(self.env).process_request(req)

        self.assertEqual('The template below /', resp[1]['page'].text)
Exemplo n.º 12
0
    def test_invalid_get_request_raises_exception(self):
        req = MockRequest(self.env,
                          method='GET',
                          action=None,
                          args=dict(version='a', old_version='1'))

        with self.assertRaises(HTTPBadRequest) as cm:
            WikiModule(self.env).process_request(req)
        self.assertEqual(
            "400 Bad Request (Invalid value for request argument "
            "<em>version</em>.)", unicode(cm.exception))

        req = MockRequest(self.env,
                          method='GET',
                          action=None,
                          args=dict(version='2', old_version='a'))

        with self.assertRaises(HTTPBadRequest) as cm:
            WikiModule(self.env).process_request(req)
        self.assertEqual(
            "400 Bad Request (Invalid value for request argument "
            "<em>old_version</em>.)", unicode(cm.exception))
Exemplo n.º 13
0
    def pre_process_request(self, req, handler):
        """Check if request of for new page creation from a template. If that's true,
        check if template has parameters, then redirect to our own page creation form."""
        if handler == WikiModule(self.env):
            template = req.args.get('template', '')
            page = req.args.get('page', 'WikiStart')
            action = req.args.get('action', '')

            if action == 'edit' and page and template:
                template_page = WikiPage(
                    self.env, WikiModule.PAGE_TEMPLATES_PREFIX + template)
                if len(self._find_fields(template_page.text)) > 0:
                    req.redirect(
                        req.href.newpage(page.strip('/'), template=template))
        return handler
Exemplo n.º 14
0
 def _get_search_filters(self, req):
     filters = []
     if TicketModule(self.env).get_search_filters(req) is not None:
         filters.extend([{
             'name': ticket.name,
             'label': ticket.name,
             'active': True
         } for ticket in Type.select(self.env)])
     wikifilters = WikiModule(self.env).get_search_filters(req)
     if wikifilters:
         filters.extend([{
             'name': f[0],
             'label': f[1],
             'active': True
         } for f in wikifilters])
     return filters
Exemplo n.º 15
0
    def _do_save(self, req, db, page):
        # This method is overridden so the user doesn't get "Page not modified"
        # exceptions when updating tags but not wiki content.
        from tractags.api import TagEngine
        if 'tags' in req.args:
            newtags = set([t.strip() for t in
                          _tag_split.split(req.args.get('tags')) if t.strip()])
            wikitags = TagEngine(self.env).tagspace.wiki
            oldtags = wikitags.get_tags([page.name])

            if oldtags != newtags:
                wikitags.replace_tags(req, page.name, newtags)
                # No changes, just redirect
                if req.args.get('text') == page.text:
                    req.redirect(self.env.href.wiki(page.name))
                    return
        return WikiModule._do_save(self, req, db, page)
Exemplo n.º 16
0
    def _do_save(self, req, db, page):
        # This method is overridden so the user doesn't get "Page not modified"
        # exceptions when updating tags but not wiki content.
        from tractags.api import TagEngine
        if 'tags' in req.args:
            newtags = set([t.strip() for t in
                          _tag_split.split(req.args.get('tags')) if t.strip()])
            wikitags = TagEngine(self.env).tagspace.wiki
            oldtags = wikitags.get_tags([page.name])

            if oldtags != newtags:
                wikitags.replace_tags(req, page.name, newtags)
                # No changes, just redirect
                if req.args.get('text') == page.text:
                    req.redirect(self.env.href.wiki(page.name))
                    return
        return WikiModule._do_save(self, req, db, page)
Exemplo n.º 17
0
    def test_invalid_post_request_raises_exception(self):
        req = MockRequest(self.env, method='POST', action=None)

        self.assertRaises(HTTPBadRequest,
                          WikiModule(self.env).process_request, req)
Exemplo n.º 18
0
 def __init__(self):
     WikiModule.__init__(self, self.compmgr)
Exemplo n.º 19
0
    def expand_macro(self, formatter, name, content):

        args, kw = parse_args(content)
        req = formatter.req
        context = formatter.context

        # Prevent multiple inclusions - store a temp in req
        if hasattr(req, 'addcommentmacro'):
            raise TracError('\'AddComment\' macro cannot be included twice.')
        req.addcommentmacro = True

        # Prevent it being used outside of wiki page context
        resource = context.resource
        if not resource.realm == 'wiki':
            raise TracError(
                '\'AddComment\' macro can only be used in Wiki pages.')

        # Setup info and defaults
        authname = req.authname
        page = WikiPage(self.env, resource)
        page_url = req.href.wiki(resource.id)
        wikipreview = req.args.get("preview", "")

        # Can this user add a comment to this page?
        appendonly = ('appendonly' in args)
        cancomment = False
        if page.readonly:
            if 'WIKI_ADMIN' in req.perm(resource):
                cancomment = True
        elif 'WIKI_MODIFY' in req.perm(resource):
            cancomment = True
        elif appendonly and 'WIKI_VIEW' in req.perm(resource):
            cancomment = True
        else:
            self.log.debug(
                'Insufficient privileges for %s to AddComment to %s',
                req.authname, resource.id)

        # Get the data from the POST
        comment = req.args.get("addcomment", "")
        preview = req.args.get("previewaddcomment", "")
        cancel = req.args.get("canceladdcomment", "")
        submit = req.args.get("submitaddcomment", "")
        if not cancel and req.authname == 'anonymous':
            authname = req.args.get("authoraddcomment", authname)

        # Ensure [[AddComment]] is not present in comment, so that infinite
        # recursion does not occur.
        comment = to_unicode(
            re.sub('(^|[^!])(\[\[AddComment)', '\\1!\\2', comment))

        the_preview = the_message = the_form = tag()

        # If we are submitting or previewing, inject comment as it should look
        if cancomment and comment and (preview or submit):
            heading = tag.h4("Comment by ",
                             authname,
                             " on ",
                             to_unicode(time.strftime('%c', time.localtime())),
                             id="commentpreview")
            if preview:
                the_preview = tag.div(heading,
                                      format_to_html(self.env, context,
                                                     comment),
                                      class_="wikipage",
                                      id="preview")

        # Check the form_token
        form_ok = True
        if submit and req.args.get('__FORM_TOKEN', '') != req.form_token:
            form_ok = False
            the_message = tag.div(tag.strong("ERROR: "),
                                  "AddComment received incorrect form token. "
                                  "Do you have cookies enabled?",
                                  class_="system-message")

        # When submitting, inject comment before macro
        if comment and submit and cancomment and form_ok:
            submitted = False
            newtext = ""
            for line in page.text.splitlines():
                if line.find('[[AddComment') == 0:
                    newtext += "==== Comment by %s on %s ====\n%s\n\n" % (
                        authname,
                        to_unicode(time.strftime('%c',
                                                 time.localtime())), comment)
                    submitted = True
                newtext += line + "\n"
            if submitted:
                page.text = newtext

                # Let the wiki page manipulators have a look at the
                # submission.
                valid = True
                req.args.setdefault('comment', 'Comment added.')
                try:
                    for manipulator in WikiModule(self.env).page_manipulators:
                        for field, message in manipulator.validate_wiki_page(
                                req, page):
                            valid = False
                            if field:
                                the_message += tag.div(tag.strong(
                                    "invalid field '%s': " % field),
                                                       message,
                                                       class_="system-message")
                            else:
                                the_message += tag.div(tag.strong("invalid: "),
                                                       message,
                                                       class_="system-message")

                # The TracSpamfilterPlugin does not generate messages,
                # but throws RejectContent.
                except TracError, s:
                    valid = False
                    the_message += tag.div(tag.strong("ERROR: "),
                                           s,
                                           class_="system-message")

                if valid:
                    page.save(authname, req.args['comment'],
                              req.environ['REMOTE_ADDR'])
                    # We can't redirect from macro as it will raise RequestDone
                    # which like other macro errors gets swallowed in the Formatter.
                    # We need to re-raise it in a post_process_request instead.
                    try:
                        self.env.log.debug(
                            "AddComment saved - redirecting to: %s" % page_url)
                        req._outheaders = []
                        req.redirect(page_url)
                    except RequestDone:
                        req.addcomment_raise = True
            else:
                the_message = tag.div(
                    tag.strong("ERROR: "), "[[AddComment]] "
                    "macro call must be the only content on its line. "
                    "Could not add comment.",
                    class_="system-message")