예제 #1
0
 def test_nonexistent_page_noedit(self):
     self.app.get(h.urlquote('/wiki/tést/'),
                  extra_environ=dict(username=str('*anonymous')),
                  status=404)
     self.app.get(h.urlquote('/wiki/tést/'),
                  extra_environ=dict(username=str('test-user')),
                  status=404)
예제 #2
0
    def test_file_raw(self):
        self._setup_weird_chars_repo()
        ci = self._get_ci(repo='/p/test/weird-chars/')
        url = ci + 'tree/' + h.urlquote('привіт.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in('Привіт!\nWhich means Hello!', resp.text)
        assert_equal(
            six.ensure_text(resp.headers.get('Content-Disposition')),
            'attachment;filename="%D0%BF%D1%80%D0%B8%D0%B2%D1%96%D1%82.txt"')

        url = ci + 'tree/' + h.urlquote('with space.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in('with space', resp.text)
        assert_equal(six.ensure_text(resp.headers.get('Content-Disposition')),
                     'attachment;filename="with%20space.txt"')

        url = ci + 'tree/' + h.urlquote(
            'with%2Furlquote-literal.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in('%2F means /', resp.body.decode('utf-8'))
        assert_equal(
            resp.headers.get('Content-Disposition').decode('utf-8'),
            'attachment;filename="with%252Furlquote-literal.txt"')

        url = ci + 'tree/' + h.urlquote('with"&:specials.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in('"&: encodes as %22%26%3A', resp.body.decode('utf-8'))
        assert_equal(
            resp.headers.get('Content-Disposition').decode('utf-8'),
            'attachment;filename="with%22%26%3Aspecials.txt"')
예제 #3
0
 def test_page_get_markdown(self):
     self.app.post(h.urlquote('/wiki/tést/update'),
                   params={
                       'title': 'tést'.encode('utf-8'),
                       'text': '- [ ] checkbox',
                       'labels': '',
                   })
     response = self.app.get(h.urlquote('/wiki/tést/get_markdown'))
     assert '- [ ] checkbox' in response
예제 #4
0
 def url(self):
     if self.post_id:
         return self.post.url() + 'attachment/' + h.urlquote(self.filename)
     elif self.thread_id:
         return self.thread.url() + 'attachment/' + h.urlquote(
             self.filename)
     else:
         return self.discussion.url() + 'attachment/' + h.urlquote(
             self.filename)
예제 #5
0
 def test_page_update(self, spam_checker):
     self.app.get(h.urlquote('/wiki/tést/'))
     response = self.app.post(h.urlquote('/wiki/tést/update'),
                              params={
                                  'title': 'tést'.encode('utf-8'),
                                  'text': 'sometext',
                                  'labels': '',
                              })
     assert_equal(spam_checker.check.call_args[0][0], 'tést\nsometext')
     assert_equal(response.location, 'http://localhost/wiki/t%C3%A9st/')
예제 #6
0
파일: test_rest.py 프로젝트: 00mjk/allura
 def test_create_page(self):
     data = {
         'text': 'Embrace the Dark Side',
         'labels': 'head hunting,dark side'
     }
     r = self.api_post(h.urlquote('/rest/p/test/wiki/tést/'), **data)
     assert_equal(r.status_int, 200)
     r = self.api_get(h.urlquote('/rest/p/test/wiki/tést/'))
     assert_equal(r.json['text'], data['text'])
     assert_equal(r.json['labels'], data['labels'].split(','))
예제 #7
0
파일: discuss.py 프로젝트: brondsem/allura
 def url(self):
     if self.post_id:
         return (self.post.url() + 'attachment/' +
                 h.urlquote(self.filename))
     elif self.thread_id:
         return (self.thread.url() + 'attachment/' +
                 h.urlquote(self.filename))
     else:
         return (self.discussion.url() + 'attachment/' +
                 h.urlquote(self.filename))
예제 #8
0
 def test_unicode(self):
     self.app.post(h.urlquote('/wiki/tést/update'),
                   params={
                       'title': 'tést'.encode('utf-8'),
                       'text': 'sometext',
                       'labels': '',
                   })
     r = self.api_get(h.urlquote('/rest/p/test/wiki/tést/'))
     assert r.status_int == 200
     assert r.json['title'] == 'tést', r.json
예제 #9
0
 def test_subpage_attempt(self):
     self.app.get(h.urlquote('/wiki/tést/'))
     self.app.post(
         h.urlquote('/wiki/tést/update'),
         params={
             'title': 'tést'.encode('utf-8'),
             'text': 'text1',
             'labels': '',
             })
     assert '/p/test/wiki/Home/' in self.app.get(h.urlquote('/wiki/tést/Home/'))
     self.app.get(h.urlquote('/wiki/tést/notthere/'), status=404)
예제 #10
0
 def test_page_revert_no_text(self):
     self.app.post(
         h.urlquote('/wiki/tést/update'),
         params={
             'title': 'tést'.encode('utf-8'),
             'text': '',
             'labels': '',
             })
     response = self.app.post(h.urlquote('/wiki/tést/revert'), params=dict(version='1'))
     assert '.' in response.json['location']
     response = self.app.get(h.urlquote('/wiki/tést/'))
     assert 'tést' in response
예제 #11
0
 def test_new_attachment(self):
     self.app.post(h.urlquote('/wiki/tést/update'),
                   params={
                       'title': 'tést'.encode('utf-8'),
                       'text': 'sometext',
                       'labels': '',
                   })
     content = open(__file__, 'rb').read()
     self.app.post(h.urlquote('/wiki/tést/attach'),
                   upload_files=[('file_info', 'test_root.py', content)])
     response = self.app.get(h.urlquote('/wiki/tést/'))
     assert 'test_root.py' in response
예제 #12
0
 def test_post_feeds(self):
     self._post()
     d = self._blog_date()
     response = self.app.get(h.urlquote('/blog/%s/my-pôst/feed.rss' % d))
     assert 'Nothing to see' in response
     response = self.app.get(h.urlquote('/blog/%s/my-pôst/feed.atom' % d))
     assert 'Nothing to see' in response
     self._post(title='test', text='*sometext*')
     response = self.app.get('/blog/feed')
     assert_in(
         '<div class="markdown_content"><p><em>sometext</em></p></div>',
         response)
예제 #13
0
    def test_file_raw(self):
        self._setup_weird_chars_repo()
        ci = self._get_ci(repo='/p/test/weird-chars/')
        url = ci + 'tree/' + h.urlquote(u'привіт.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in(u'Привіт!\nWhich means Hello!', resp.body.decode('utf-8'))
        assert_equal(resp.headers.get('Content-Disposition').decode('utf-8'),
                     u'attachment;filename="привіт.txt"')

        url = ci + 'tree/' + h.urlquote(u'with space.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in(u'with space', resp.body.decode('utf-8'))
        assert_equal(resp.headers.get('Content-Disposition').decode('utf-8'),
                     u'attachment;filename="with space.txt"')
예제 #14
0
    def test_file_raw(self):
        self._setup_weird_chars_repo()
        ci = self._get_ci(repo='/p/test/weird-chars/')
        url = ci + 'tree/' + h.urlquote(u'привіт.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in(u'Привіт!\nWhich means Hello!', resp.body.decode('utf-8'))
        assert_equal(resp.headers.get('Content-Disposition').decode('utf-8'),
                     u'attachment;filename="привіт.txt"')

        url = ci + 'tree/' + h.urlquote(u'with space.txt') + '?format=raw'
        resp = self.app.get(url)
        assert_in(u'with space', resp.body.decode('utf-8'))
        assert_equal(resp.headers.get('Content-Disposition').decode('utf-8'),
                     u'attachment;filename="with space.txt"')
예제 #15
0
 def test_new_text_attachment_content(self):
     self.app.post(h.urlquote('/wiki/tést/update'),
                   params={
                       'title': 'tést'.encode('utf-8'),
                       'text': 'sometext',
                       'labels': '',
                   })
     file_name = 'test_root.py'
     file_data = open(__file__, 'rb').read()
     upload = ('file_info', file_name, file_data)
     self.app.post(h.urlquote('/wiki/tést/attach'), upload_files=[upload])
     page_editor = self.app.get(h.urlquote('/wiki/tést/edit'))
     download = page_editor.click(description=file_name)
     assert_true(download.body == file_data)
예제 #16
0
 def index(self, version=None, page=0, limit=25, **kw):
     if not self.page:
         redirect(c.app.url+h.urlquote(self.title)+'/edit')
     c.thread = W.thread
     c.attachment_list = W.attachment_list
     c.subscribe_form = W.page_subscribe_form
     post_count = self.page.discussion_thread.post_count
     limit, pagenum = h.paging_sanitizer(limit, page, post_count)
     page = self.get_version(version)
     if page is None:
         if version: redirect('.?version=%d' % (version-1))
         else: redirect('.')
     elif 'all' not in page.viewable_by and c.user.username not in page.viewable_by:
         raise exc.HTTPForbidden(detail="You may not view this page.")
     cur = page.version
     if cur > 1: prev = cur-1
     else: prev = None
     next = cur+1
     hide_left_bar = not (c.app.show_left_bar)
     return dict(
         page=page,
         cur=cur, prev=prev, next=next,
         subscribed=M.Mailbox.subscribed(artifact=self.page),
         hide_left_bar=hide_left_bar, show_meta=c.app.show_right_bar,
         pagenum=pagenum, limit=limit, count=post_count)
예제 #17
0
 def test_root_suffix_with_url_value(self):
     response = self.app.get('/admin/link/options', validate_chunk=True)
     response.form['url'] = 'http://www.google.de/search?q='
     response.form.submit()
     redir = self.app.get(h.urlquote('/link/helpåß'), status=302)
     assert_equal(redir.location,
                  'http://www.google.de/search?q=help%C3%A5%C3%9F')
예제 #18
0
 def test_page_label_unlabel(self):
     self.app.get(h.urlquote('/wiki/tést/'))
     response = self.app.post(h.urlquote('/wiki/tést/update'),
                              params={
                                  'title': 'tést'.encode('utf-8'),
                                  'text': 'sometext',
                                  'labels': 'yellow,green',
                              })
     assert_equal(response.location, 'http://localhost/wiki/t%C3%A9st/')
     response = self.app.post(h.urlquote('/wiki/tést/update'),
                              params={
                                  'title': 'tést'.encode('utf-8'),
                                  'text': 'sometext',
                                  'labels': 'yellow',
                              })
     assert_equal(response.location, 'http://localhost/wiki/t%C3%A9st/')
예제 #19
0
파일: discuss.py 프로젝트: pombreda/allura
    def url_paginated(self):
        '''Return link to the thread with a #target that poins to this comment.

        Also handle pagination properly.
        '''
        if not self.thread:  # pragma no cover
            return None
        limit, p, s = g.handle_paging(None, 0)  # get paging limit
        if self.query.find(dict(thread_id=self.thread._id)).count() <= limit:
            # all posts in a single page
            page = 0
        else:
            posts = self.thread.find_posts()
            posts = self.thread.create_post_threads(posts)

            def find_i(posts):
                '''Find the index number of this post in the display order'''
                q = []
                def traverse(posts):
                    for p in posts:
                        if p['post']._id == self._id:
                            return True  # found
                        q.append(p)
                        if traverse(p['children']):
                            return True
                traverse(posts)
                return len(q)

            page = find_i(posts) / limit

        slug = h.urlquote(self.slug)
        url = self.thread.url()
        if page == 0:
            return '%s?limit=%s#%s' % (url, limit, slug)
        return '%s?limit=%s&page=%s#%s' % (url, limit, page, slug)
예제 #20
0
파일: utils.py 프로젝트: xmonader/allura
def serve_file(fp, filename, content_type, last_modified=None,
               cache_expires=None, size=None, embed=True, etag=None):
    '''Sets the response headers and serves as a wsgi iter'''
    if not etag and filename and last_modified:
        etag = '{0}?{1}'.format(filename, last_modified).encode('utf-8')
    if etag:
        etag_cache(etag)
    tg.response.headers['Content-Type'] = str('')
    tg.response.content_type = str(content_type)
    tg.response.cache_expires = cache_expires or asint(
        tg.config.get('files_expires_header_secs', 60 * 60))
    tg.response.last_modified = last_modified
    if size:
        tg.response.content_length = size
    if 'Pragma' in tg.response.headers:
        del tg.response.headers['Pragma']
    if 'Cache-Control' in tg.response.headers:
        del tg.response.headers['Cache-Control']
    if not embed:
        from allura.lib import helpers as h
        tg.response.headers.add(
            str('Content-Disposition'),
            str('attachment;filename="%s"' % h.urlquote(filename)))
    # http://code.google.com/p/modwsgi/wiki/FileWrapperExtension
    block_size = 4096
    if 'wsgi.file_wrapper' in tg.request.environ:
        return tg.request.environ['wsgi.file_wrapper'](fp, block_size)
    else:
        return iter(lambda: fp.read(block_size), b'')
예제 #21
0
 def sidebar_menu(self):
     try:
         l = []
         moderate_link = None
         forum_links = []
         forums = DM.Forum.query.find(
             dict(app_config_id=c.app.config._id,
                  parent_id=None,
                  deleted=False))
         for f in forums:
             if has_access(f, 'read')():
                 if f.url() in request.url and h.has_access(f,
                                                            'moderate')():
                     moderate_link = SitemapEntry(
                         'Moderate',
                         "%smoderate/" % f.url(),
                         ui_icon=g.icons['pencil'],
                         small=DM.ForumPost.query.find({
                             'discussion_id': f._id,
                             'status': {
                                 '$ne': 'ok'
                             }
                         }).count())
                 forum_links.append(
                     SitemapEntry(f.name, f.url(), small=f.num_topics))
         url = c.app.url + 'create_topic/'
         url = h.urlquote(url + c.forum.shortname
                          if getattr(c, 'forum', None) and c.forum else url)
         l.append(SitemapEntry('Create Topic', url,
                               ui_icon=g.icons['plus']))
         if has_access(c.app, 'configure')():
             l.append(
                 SitemapEntry('Add Forum',
                              c.app.url + 'new_forum',
                              ui_icon=g.icons['conversation']))
             l.append(
                 SitemapEntry('Admin Forums',
                              c.project.url() + 'admin/' +
                              self.config.options.mount_point + '/forums',
                              ui_icon=g.icons['pencil']))
         if moderate_link:
             l.append(moderate_link)
         # if we are in a thread and not anonymous, provide placeholder links to use in js
         if '/thread/' in request.url and c.user not in (
                 None, M.User.anonymous()):
             l.append(
                 SitemapEntry('Mark as Spam',
                              'flag_as_spam',
                              ui_icon=g.icons['flag'],
                              className='sidebar_thread_spam'))
         if forum_links:
             l.append(SitemapEntry('Forums'))
             l = l + forum_links
         l.append(SitemapEntry('Help'))
         l.append(
             SitemapEntry('Formatting Help', c.app.url + 'markdown_syntax'))
         return l
     except:  # pragma no cover
         log.exception('sidebar_menu')
         return []
예제 #22
0
    def url_paginated(self):
        '''Return link to the thread with a #target that poins to this comment.

        Also handle pagination properly.
        '''
        if not self.thread:  # pragma no cover
            return None
        limit, p, s = g.handle_paging(None, 0)  # get paging limit
        if self.query.find(dict(thread_id=self.thread._id)).count() <= limit:
            # all posts in a single page
            page = 0
        else:
            posts = self.thread.find_posts()
            posts = self.thread.create_post_threads(posts)

            def find_i(posts):
                '''Find the index number of this post in the display order'''
                q = []
                def traverse(posts):
                    for p in posts:
                        if p['post']._id == self._id:
                            return True  # found
                        q.append(p)
                        if traverse(p['children']):
                            return True
                traverse(posts)
                return len(q)

            page = find_i(posts) / limit

        slug = h.urlquote(self.slug)
        url = self.thread.url()
        if page == 0:
            return '%s?limit=%s#%s' % (url, limit, slug)
        return '%s?limit=%s&page=%s#%s' % (url, limit, page, slug)
예제 #23
0
 def test_page_update_markdown(self):
     self.app.post(h.urlquote('/wiki/tést/update'),
                   params={
                       'title': 'tést'.encode('utf-8'),
                       'text': '- [ ] checkbox',
                       'labels': '',
                   })
     response = self.app.post(h.urlquote('/wiki/tést/update_markdown'),
                              params={'text': '- [x] checkbox'})
     print(response)
     assert response.json['status'] == 'success'
     # anon users can't edit markdown
     response = self.app.post(
         h.urlquote('/wiki/tést/update_markdown'),
         params={'text': '- [x] checkbox'},
         extra_environ=dict(username=str('*anonymous')))
     assert response.json['status'] == 'no_permission'
예제 #24
0
 def test_show_metadata(self):
     self.app.post(h.urlquote('/wiki/tést/update'), params={
         'title': 'tést'.encode('utf-8'),
         'text': 'sometext',
         'labels': '',
         })
     wiki_page = self.app.get(h.urlquote('/wiki/tést/'))
     assert wiki_page.html.find('div', {'class': 'editbox'})
     options_admin = self.app.get(
         '/admin/wiki/options', validate_chunk=True)
     assert options_admin.form['show_right_bar'].checked
     options_admin.form['show_right_bar'].checked = False
     options_admin.form.submit()
     options_admin2 = self.app.get(
         '/admin/wiki/options', validate_chunk=True)
     assert not options_admin2.form['show_right_bar'].checked
     wiki_page2 = self.app.get(h.urlquote('/wiki/tést/'))
     assert not wiki_page2.html.find('div', {'class': 'editbox'})
예제 #25
0
파일: test_root.py 프로젝트: apache/allura
 def test_root_index(self):
     page_url = h.urlquote(u'/wiki/tést/')
     r = self.app.get(page_url).follow()
     assert u'tést' in r
     assert 'Create Page' in r
     # No 'Create Page' button if user doesn't have 'create' perm
     r = self.app.get('/wiki/Home',
                      extra_environ=dict(username='******'))
     assert 'Create Page' not in r, r
예제 #26
0
파일: test_root.py 프로젝트: lym/allura-git
 def test_root_index(self):
     page_url = h.urlquote(u'/wiki/tést/')
     r = self.app.get(page_url).follow()
     assert u'tést' in r
     assert 'Create Page' in r
     # No 'Create Page' button if user doesn't have 'create' perm
     r = self.app.get(page_url,
                      extra_environ=dict(username='******')).follow()
     assert 'Create Page' not in r
예제 #27
0
 def test_create_topic_unicode(self):
     r = self.app.get('/admin/discussion/forums')
     form = r.forms['add-forum']
     form['add_forum.shortname'] = 'téstforum'.encode('utf-8')
     form['add_forum.name'] = 'Tést Forum'.encode('utf-8')
     form.submit()
     r = self.app.get('/admin/discussion/forums')
     assert 'téstforum'.encode('utf-8') in r
     r = self.app.get(h.urlquote('/p/test/discussion/create_topic/téstforum/'))
     assert '<option value="téstforum" selected>Tést Forum</option>' in r
예제 #28
0
 def sidebar_menu(self):
     if not self.repo or self.repo.status != "ready":
         return []
     links = [SitemapEntry("Browse Commits", c.app.url + "commit_browser", ui_icon=g.icons["folder"])]
     if self.forkable and self.repo.status == "ready":
         links.append(SitemapEntry("Fork", c.app.url + "fork", ui_icon=g.icons["fork"]))
     merge_request_count = self.repo.merge_requests_by_statuses("open").count()
     if merge_request_count:
         links += [SitemapEntry("Merge Requests", c.app.url + "merge-requests/", small=merge_request_count)]
     if self.repo.forks:
         links += [SitemapEntry("Forks", c.app.url + "forks/", small=len(self.repo.forks))]
     if self.repo.upstream_repo.name:
         repo_path_parts = self.repo.upstream_repo.name.strip("/").split("/")
         links += [
             SitemapEntry("Clone of"),
             SitemapEntry("%s / %s" % (repo_path_parts[1], repo_path_parts[-1]), self.repo.upstream_repo.name),
         ]
         if not c.app.repo.is_empty() and has_access(c.app.repo, "admin"):
             merge_url = c.app.url + "request_merge"
             if getattr(c, "revision", None):
                 merge_url = merge_url + "?branch=" + h.urlquote(c.revision)
             links.append(SitemapEntry("Request Merge", merge_url, ui_icon=g.icons["merge"]))
         pending_upstream_merges = self.repo.pending_upstream_merges()
         if pending_upstream_merges:
             links.append(
                 SitemapEntry(
                     "Pending Merges",
                     self.repo.upstream_repo.name + "merge-requests/",
                     small=pending_upstream_merges,
                 )
             )
     ref_url = self.repo.url_for_commit(self.default_branch_name, url_type="ref")
     branches = self.repo.get_branches()
     if branches:
         links.append(SitemapEntry("Branches"))
         for branch in branches:
             if branch.name == self.default_branch_name:
                 branches.remove(branch)
                 branches.insert(0, branch)
                 break
         max_branches = 10
         for branch in branches[:max_branches]:
             links.append(SitemapEntry(branch.name, quote(self.repo.url_for_commit(branch.name) + "tree/")))
         if len(branches) > max_branches:
             links.append(SitemapEntry("More Branches", ref_url + "branches/"))
     tags = self.repo.get_tags()
     if tags:
         links.append(SitemapEntry("Tags"))
         max_tags = 10
         for b in tags[:max_tags]:
             links.append(SitemapEntry(b.name, quote(self.repo.url_for_commit(b.name) + "tree/")))
         if len(tags) > max_tags:
             links.append(SitemapEntry("More Tags", ref_url + "tags/"))
     return links
예제 #29
0
 def tarball(self, **kw):
     path = request.params.get('path')
     if not asbool(tg.config.get('scm.repos.tarball.enable', False)):
         raise exc.HTTPNotFound()
     rev = self._commit.url().split('/')[-2]
     status = c.app.repo.get_tarball_status(rev, path)
     if not status and request.method == 'POST':
         allura.tasks.repo_tasks.tarball.post(rev, path)
         redirect(
             'tarball?path={0}'.format(h.urlquote(path) if path else ''))
     return dict(commit=self._commit, revision=rev, status=status)
예제 #30
0
파일: main.py 프로젝트: 99Kies/allura
 def save(self, **kw):
     require_access(c.app, 'write')
     self.rate_limit(BM.BlogPost, 'Create/edit', c.app.config.url())
     attachment = kw.pop('attachment', None)
     post = BM.BlogPost.new(**kw)
     g.spam_checker.check(kw['title'] + '\n' + kw['text'], artifact=post,
                          user=c.user, content_type='blog-post')
     if attachment is not None:
         post.add_multiple_attachments(attachment)
     notification_tasks.send_usermentions_notification.post(post.index_id(), kw['text'])
     redirect(h.urlquote(h.really_unicode(post.url())))
예제 #31
0
 def test_change_home_page(self):
     self.app.post(h.urlquote('/wiki/tést/update'), params={
         'title': 'our_néw_home'.encode('utf-8'),
         'text': 'sometext',
         'labels': '',
         })
     homepage_admin = self.app.get('/admin/wiki/home', validate_chunk=True)
     assert_equal(homepage_admin.form['new_home'].value, 'Home')
     homepage_admin.form['new_home'].value = 'our_néw_home'
     homepage_admin.form.submit()
     root_path = self.app.get('/wiki/', status=302)
     assert root_path.location.endswith('/wiki/our_n%C3%A9w_home/'), root_path.location
예제 #32
0
 def test_show_left_bar(self):
     self.app.post(h.urlquote('/wiki/tést/update'), params={
         'title': 'tést'.encode('utf-8'),
         'text': 'sometext',
         'labels': '',
         })
     wiki_page = self.app.get(h.urlquote('/wiki/tést/'))
     assert wiki_page.html.find('ul', {'class': 'sidebarmenu'})
     options_admin = self.app.get(
         '/admin/wiki/options', validate_chunk=True)
     assert options_admin.form['show_left_bar'].checked
     options_admin.form['show_left_bar'].checked = False
     options_admin.form.submit()
     options_admin2 = self.app.get(
         '/admin/wiki/options', validate_chunk=True)
     assert not options_admin2.form['show_left_bar'].checked
     wiki_page2 = self.app.get(
         h.urlquote('/wiki/tést/'), extra_environ=dict(username=str('*anonymous')))
     assert not wiki_page2.html.find('ul', {'class': 'sidebarmenu'})
     wiki_page3 = self.app.get(h.urlquote('/wiki/tést/'))
     assert not wiki_page3.html.find('ul', {'class': 'sidebarmenu'})
예제 #33
0
    def test_page_history(self):
        self.app.get(h.urlquote('/wiki/tést/'))
        self.app.post(h.urlquote('/wiki/tést/update'),
                      params={
                          'title': 'tést'.encode('utf-8'),
                          'text': 'text1',
                          'labels': '',
                      })
        self.app.post(h.urlquote('/wiki/tést/update'),
                      params={
                          'title': 'tést'.encode('utf-8'),
                          'text': 'text2',
                          'labels': '',
                      })
        response = self.app.get(h.urlquote('/wiki/tést/history'))
        assert 'tést' in response
        # two revisions are shown
        assert '<tr data-version="2" data-username="******">' in response
        assert '<tr data-version="1" data-username="******">' in response
        # you can revert to an old revison, but not the current one
        assert response.html.find('a', {'data-dialog-id': '1'}), response.html
        assert not response.html.find('a', {'data-dialog-id': '2'})
        response = self.app.get(h.urlquote('/wiki/tést/history'),
                                extra_environ=dict(username=str('*anonymous')))
        # two revisions are shown
        assert '<tr data-version="2" data-username="******">' in response
        assert '<tr data-version="1" data-username="******">' in response
        # you cannot revert to any revision
        assert not response.html.find('a', {'data-dialog-id': '1'})
        assert not response.html.find('a', {'data-dialog-id': '2'})

        # view an older version
        response = self.app.get(h.urlquote('/wiki/tést/') + '?version=1')
        response.mustcontain('text1')
        response.mustcontain(no='text2')
예제 #34
0
 def raw(self, **kw):
     content_type = self._blob.content_type
     filename = self._blob.name
     response.headers['Content-Type'] = str('')
     response.content_type = str(content_type)
     if self._blob.content_encoding is not None:
         content_encoding = self._blob.content_encoding
         response.headers['Content-Encoding'] = str('')
         response.content_encoding = str(content_encoding)
     response.headers.add(
         str('Content-Disposition'),
         str('attachment;filename="%s"') % h.urlquote(filename))
     return iter(self._blob)
예제 #35
0
 def sidebar_menu(self):
     try:
         l = []
         moderate_link = None
         forum_links = []
         forums = DM.Forum.query.find(dict(
             app_config_id=c.app.config._id,
             parent_id=None, deleted=False))
         for f in forums:
             if has_access(f, 'read')():
                 if f.url() in request.url and h.has_access(f, 'moderate')():
                     num_moderate = DM.ForumPost.query.find({
                         'discussion_id': f._id,
                         'status': {'$ne': 'ok'},
                         'deleted': False,
                     }).count()
                     moderate_link = SitemapEntry(
                         'Moderate', "%smoderate/" % f.url(), ui_icon=g.icons['moderate'],
                         small=num_moderate)
                 forum_links.append(
                     SitemapEntry(f.name, f.url(), small=f.num_topics))
         url = c.app.url + 'create_topic/'
         url = h.urlquote(
             url + c.forum.shortname if getattr(c, 'forum', None) and c.forum else url)
         l.append(
             SitemapEntry('Create Topic', url, ui_icon=g.icons['add']))
         if has_access(c.app, 'configure')():
             l.append(SitemapEntry('Add Forum', c.app.url +
                      'new_forum', ui_icon=g.icons['conversation']))
             l.append(SitemapEntry('Admin Forums', c.project.url() + 'admin/' +
                      self.config.options.mount_point + '/forums', ui_icon=g.icons['admin']))
         if moderate_link:
             l.append(moderate_link)
         # if we are in a thread and not anonymous, provide placeholder
         # links to use in js
         if '/thread/' in request.url and c.user not in (None, M.User.anonymous()):
             l.append(SitemapEntry(
                 'Mark as Spam', 'flag_as_spam',
                 ui_icon=g.icons['flag'], className='sidebar_thread_spam'))
         l.append(SitemapEntry('Stats Graph', c.app.url +
                  'stats', ui_icon=g.icons['stats']))
         if forum_links:
             l.append(SitemapEntry('Forums'))
             l = l + forum_links
         l.append(SitemapEntry('Help'))
         l.append(
             SitemapEntry('Formatting Help', c.app.url + 'markdown_syntax'))
         return l
     except:  # pragma no cover
         log.exception('sidebar_menu')
         return []
예제 #36
0
 def _setUp(self):
     self.app.get('/wiki/')
     self.app.get('/bugs/')
     self.app.post(
         '/bugs/save_ticket',
         params=variable_encode(
             dict(ticket_form=dict(ticket_num='',
                                   labels='',
                                   assigned_to='',
                                   milestone='',
                                   summary='This is a ticket',
                                   status='open',
                                   description='This is a description'))),
         status=302)
     title = 'Descri\xe7\xe3o e Arquitetura'
     self.app.post(h.urlquote('/wiki/%s/update' % title),
                   params=dict(
                       title=title.encode('utf-8'),
                       text="Nothing much",
                       labels='',
                   ),
                   status=302)
     self.app.get(h.urlquote('/wiki/%s/' % title))
예제 #37
0
파일: auth.py 프로젝트: apache/allura
    def send_verification_link(self):
        self.set_nonce_hash()
        log.info('Sending verification link to %s', self.email)
        text = '''
To verify the email address %s belongs to the user %s,
please visit the following URL:

%s
''' % (self.email,
       self.claimed_by_user(include_pending=True).username,
       h.absurl('/auth/verify_addr?a={}'.format(h.urlquote(self.nonce))),
       )
        log.info('Verification email:\n%s', text)
        allura.tasks.mail_tasks.sendsimplemail.post(
            fromaddr=g.noreply,
            reply_to=g.noreply,
            toaddr=self.email,
            subject=u'%s - Email address verification' % config['site_name'],
            message_id=h.gen_message_id(),
            text=text)
예제 #38
0
 def url(self):
     slug = str(self.granted_to_project.shortname).replace('/','_')
     return h.urlquote(slug)
예제 #39
0
파일: test_root.py 프로젝트: apache/allura
 def test_root_new_search(self):
     self.app.get(h.urlquote(u'/wiki/tést/'))
     response = self.app.get('/wiki/search/?q=' + h.urlquote(u'tést'))
     assert u'Search wiki: tést' in response
예제 #40
0
파일: test_root.py 프로젝트: apache/allura
 def test_root_new_page(self):
     response = self.app.get('/wiki/new_page?title=' + h.urlquote(u'tést'))
     assert u'tést' in response
예제 #41
0
파일: test_root.py 프로젝트: apache/allura
 def test_nonexistent_page_edit(self):
     resp = self.app.get('/wiki/tést/')
     assert resp.location.endswith(h.urlquote(u'/wiki/tést/edit')), resp.location
     resp = resp.follow()
     assert 'tést' in resp
예제 #42
0
파일: discuss.py 프로젝트: brondsem/allura
 def url(self):
     if self.thread:
         return self.thread.url() + h.urlquote(self.slug) + '/'
     else:  # pragma no cover
         return None
예제 #43
0
파일: forum.py 프로젝트: apache/allura
 def url(self):
     return h.urlquote(self.app.url + self.shortname + '/')
예제 #44
0
    def _make_notification(cls, artifact, topic, **kwargs):
        '''
        Create a Notification instance based on an artifact.  Special handling
        for comments when topic=='message'
        '''

        from allura.model import Project
        idx = artifact.index() if artifact else None
        subject_prefix = '[%s:%s] ' % (
            c.project.shortname, c.app.config.options.mount_point)
        post = ''
        if topic == 'message':
            post = kwargs.pop('post')
            text = kwargs.get('text') or post.text
            file_info = kwargs.pop('file_info', None)
            if file_info is not None:
                text = "%s\n\n\nAttachments:\n" % text
                if not isinstance(file_info, list):
                    file_info = [file_info]
                for attach in file_info:
                    attach.file.seek(0, 2)
                    bytecount = attach.file.tell()
                    attach.file.seek(0)
                    url = h.absurl('{}attachment/{}'.format(
                        post.url(), h.urlquote(attach.filename)))
                    text = "%s\n- [%s](%s) (%s; %s)" % (
                        text, attach.filename, url,
                        h.do_filesizeformat(bytecount), attach.type)

            subject = post.subject or ''
            if post.parent_id and not subject.lower().startswith('re:'):
                subject = 'Re: ' + subject
            author = post.author()
            msg_id = kwargs.get('message_id') or artifact.url() + post._id
            parent_msg_id = artifact.url() + \
                post.parent_id if post.parent_id else artifact.message_id()
            d = dict(
                _id=msg_id,
                from_address=str(
                    author._id) if author != User.anonymous() else None,
                reply_to_address='"%s" <%s>' % (
                    subject_prefix, getattr(
                        artifact, 'email_address', g.noreply)),
                subject=subject_prefix + subject,
                text=text,
                in_reply_to=parent_msg_id,
                references=cls._references(artifact, post),
                author_id=author._id,
                pubdate=datetime.utcnow())
        elif topic == 'flash':
            n = cls(topic=topic,
                    text=kwargs['text'],
                    subject=kwargs.pop('subject', ''))
            return n
        else:
            subject = kwargs.pop('subject', '%s modified by %s' % (
                h.get_first(idx, 'title'), c.user.get_pref('display_name')))
            reply_to = '"%s" <%s>' % (
                h.get_first(idx, 'title'),
                getattr(artifact, 'email_address', g.noreply))
            d = dict(
                from_address=reply_to,
                reply_to_address=reply_to,
                subject=subject_prefix + subject,
                text=kwargs.pop('text', subject),
                author_id=c.user._id,
                pubdate=datetime.utcnow())
            if kwargs.get('message_id'):
                d['_id'] = kwargs['message_id']
            if c.user.get_pref('email_address'):
                d['from_address'] = '"%s" <%s>' % (
                    c.user.get_pref('display_name'),
                    c.user.get_pref('email_address'))
            elif c.user.email_addresses:
                d['from_address'] = '"%s" <%s>' % (
                    c.user.get_pref('display_name'),
                    c.user.email_addresses[0])
        if not d.get('text'):
            d['text'] = ''
        try:
            ''' Add addional text to the notification e-mail based on the artifact type '''
            template = cls.view.get_template(
                'mail/' + artifact.type_s + '.txt')
            d['text'] += template.render(dict(c=c, g=g,
                                         config=config, data=artifact, post=post, h=h))
        except jinja2.TemplateNotFound:
            pass
        except:
            ''' Catch any errors loading or rendering the template,
            but the notification still gets sent if there is an error
            '''
            log.warn('Could not render notification template %s' %
                     artifact.type_s, exc_info=True)

        assert d['reply_to_address'] is not None
        project = c.project
        if d.get('project_id', c.project._id) != c.project._id:
            project = Project.query.get(_id=d['project_id'])
        if project.notifications_disabled:
            log.debug(
                'Notifications disabled for project %s, not sending %s(%r)',
                project.shortname, topic, artifact)
            return None
        n = cls(ref_id=artifact.index_id(),
                topic=topic,
                link=kwargs.pop('link', artifact.url()),
                **d)
        return n
예제 #45
0
 def longurl(self):
     slug = str(self.granted_to_project.shortname).replace('/','_')
     slug = self.award.longurl() + '/' + slug
     return h.urlquote(slug)
예제 #46
0
 def longurl(self):
     slug = str(self.granted_to_project.shortname).replace("/", "_")
     slug = self.award.longurl() + "/" + slug
     return h.urlquote(slug)
예제 #47
0
def test_urlquote_unicode():
    # No exceptions please
    h.urlquote(u'\u0410')
    h.urlquoteplus(u'\u0410')
예제 #48
0
파일: repository.py 프로젝트: apache/allura
    def sidebar_menu(self):
        if not self.repo or self.repo.status != 'ready':
            return []
        links = [SitemapEntry('Browse Commits', c.app.url +
                              'commit_browser', ui_icon=g.icons['browse_commits'])]
        if self.forkable and self.repo.status == 'ready' and not self.repo.is_empty():
            links.append(
                SitemapEntry('Fork', c.app.url + 'fork', ui_icon=g.icons['fork']))
        merge_request_count = self.repo.merge_requests_by_statuses(
            'open').count()
        if self.forkable:
            links += [
                SitemapEntry(
                    'Merge Requests', c.app.url + 'merge-requests/',
                    small=merge_request_count)]
        if self.repo.forks:
            links += [
                SitemapEntry('Forks', c.app.url + 'forks/',
                             small=len(self.repo.forks))
            ]

        has_upstream_repo = False
        if self.repo.upstream_repo.name:
            try:
                self.repo.push_upstream_context()
            except Exception:
                log.warn('Could not get upstream repo (perhaps it is gone) for: %s %s',
                         self.repo, self.repo.upstream_repo.name, exc_info=True)
            else:
                has_upstream_repo = True

        if has_upstream_repo:
            repo_path_parts = self.repo.upstream_repo.name.strip(
                '/').split('/')
            links += [
                SitemapEntry('Clone of'),
                SitemapEntry('%s / %s' %
                             (repo_path_parts[1], repo_path_parts[-1]),
                             self.repo.upstream_repo.name)
            ]
            if not c.app.repo.is_empty() and has_access(c.app.repo, 'admin'):
                merge_url = c.app.url + 'request_merge'
                if getattr(c, 'revision', None):
                    merge_url = merge_url + '?branch=' + h.urlquote(c.revision)
                links.append(SitemapEntry('Request Merge', merge_url,
                             ui_icon=g.icons['merge'],
                                          ))
            pending_upstream_merges = self.repo.pending_upstream_merges()
            if pending_upstream_merges:
                links.append(SitemapEntry(
                    'Pending Merges',
                    self.repo.upstream_repo.name + 'merge-requests/',
                    small=pending_upstream_merges))
        ref_url = self.repo.url_for_commit(
            self.default_branch_name, url_type='ref')
        branches = self.repo.get_branches()
        if branches:
            links.append(SitemapEntry('Branches'))
            for branch in branches:
                if branch.name == self.default_branch_name:
                    branches.remove(branch)
                    branches.insert(0, branch)
                    break
            max_branches = 10
            for branch in branches[:max_branches]:
                links.append(SitemapEntry(
                    branch.name,
                    quote(self.repo.url_for_commit(branch.name) + 'tree/')))
            if len(branches) > max_branches:
                links.append(
                    SitemapEntry(
                        'More Branches',
                        ref_url + 'branches/',
                    ))
        tags = self.repo.get_tags()
        if tags:
            links.append(SitemapEntry('Tags'))
            max_tags = 10
            for b in tags[:max_tags]:
                links.append(SitemapEntry(
                    b.name,
                    quote(self.repo.url_for_commit(b.name) + 'tree/')))
            if len(tags) > max_tags:
                links.append(
                    SitemapEntry(
                        'More Tags',
                        ref_url + 'tags/',
                    ))
        return links
예제 #49
0
 def url(self):
     s = self.app_config.url() + \
         h.urlquote(self.title.encode('utf-8')) + '/'
     if self.deleted:
         s += '?deleted=True'
     return s
예제 #50
0
 def url(self):
     return self.artifact.url() + 'attachment/' + h.urlquote(self.filename)