Example #1
0
File: page.py Project: happytk/moin
    def highlight(self, text, mime=None, syntax=None, line_no=0):
        """Colorize the source code."""

        if pygments is None:
            yield werkzeug.html.pre(werkzeug.html(text))
            return

        formatter = pygments.formatters.HtmlFormatter()
        formatter.line_no = line_no

        def wrapper(source, unused_outfile):
            """Wrap each line of formatted output."""

            yield 0, '<div class="highlight"><pre>'
            for lineno, line in source:
                yield (lineno,
                       werkzeug.html.span(line, id_="line_%d" %
                                         formatter.line_no))
                formatter.line_no += 1
            yield 0, '</pre></div>'

        formatter.wrap = wrapper
        try:
            if mime:
                lexer = pygments.lexers.get_lexer_for_mimetype(mime)
            elif syntax:
                lexer = pygments.lexers.get_lexer_by_name(syntax)
            else:
                lexer = pygments.lexers.guess_lexer(text)
        except pygments.util.ClassNotFoundErr:
            yield werkzeug.html.pre(werkzeug.html(text))
            return
        html = pygments.highlight(text, lexer, formatter)
        yield html
Example #2
0
    def highlight(self, text, mime=None, syntax=None, line_no=0):
        """Colorize the source code."""

        if pygments is None:
            yield werkzeug.html.pre(werkzeug.html(text))
            return

        formatter = pygments.formatters.HtmlFormatter()
        formatter.line_no = line_no

        def wrapper(source, unused_outfile):
            """Wrap each line of formatted output."""

            yield 0, '<div class="highlight"><pre>'
            for lineno, line in source:
                yield (lineno,
                       werkzeug.html.span(line,
                                          id_="line_%d" % formatter.line_no))
                formatter.line_no += 1
            yield 0, '</pre></div>'

        formatter.wrap = wrapper
        try:
            if mime:
                lexer = pygments.lexers.get_lexer_for_mimetype(mime)
            elif syntax:
                lexer = pygments.lexers.get_lexer_by_name(syntax)
            else:
                lexer = pygments.lexers.guess_lexer(text)
        except pygments.util.ClassNotFoundErr:
            yield werkzeug.html.pre(werkzeug.html(text))
            return
        html = pygments.highlight(text, lexer, formatter)
        yield html
Example #3
0
def diff(title, from_rev, to_rev):
    """Show the differences between specified revisions."""

    _ = current_app.gettext

    p = page.get_page(request, title)
    build = current_app.get_url
    from_url = build(view='revision', title=title, rev=from_rev)
    to_url = build(view='revision', title=title, rev=to_rev)
    a = werkzeug.html.a
    links = {
        'link1': a(str(from_rev), href=from_url),
        'link2': a(str(to_rev), href=to_url),
        'link': a(werkzeug.html(title), href=current_app.get_url(title)),
    }
    message = werkzeug.html(_(
        'Differences between revisions %(link1)s and %(link2)s '
        'of page %(link)s.')) % links
    diff_content = getattr(p, 'diff_content', None)
    if diff_content:
        from_text = current_app.storage.revision_text(p.title, from_rev)
        to_text = current_app.storage.revision_text(p.title, to_rev)
        content = diff_content(from_text, to_text, message)
    else:
        content = [werkzeug.html.p(werkzeug.html(
            _("Diff not available for this kind of pages.")))]
    special_title = _('Diff for "%(title)s"') % {'title': title}
    html = p.template('page_special.html', content=content,
                        special_title=special_title)
    resp = response.WikiResponse(html, content_type='text/html')
    return resp
Example #4
0
    def diff(self, request, title, from_rev, to_rev):
        """Show the differences between specified revisions."""

        _ = self.gettext
        page = self.get_page(request, title)
        build = request.adapter.build
        from_url = build(self.revision, {'title': title, 'rev': from_rev})
        to_url = build(self.revision, {'title': title, 'rev': to_rev})
        a = werkzeug.html.a
        links = {
            'link1': a(str(from_rev), href=from_url),
            'link2': a(str(to_rev), href=to_url),
            'link': a(werkzeug.html(title), href=request.get_url(title)),
        }
        message = werkzeug.html(_(
            u'Differences between revisions %(link1)s and %(link2)s '
            u'of page %(link)s.')) % links
        diff_content = getattr(page, 'diff_content', None)
        if diff_content:
            from_text = self.storage.revision_text(page.title, from_rev)
            to_text = self.storage.revision_text(page.title, to_rev)
            content = page.diff_content(from_text, to_text, message)
        else:
            content = [werkzeug.html.p(werkzeug.html(
                _(u"Diff not available for this kind of pages.")))]
        special_title = _(u'Diff for "%(title)s"') % {'title': title}
        html = page.template('page_special.html', content=content,
                            special_title=special_title)
        response = WikiResponse(html, mimetype='text/html')
        return response
Example #5
0
 def _block_conflict(self, block):
     for self.line_no, part in block:
         yield u'<div class="conflict">'
         local = u"\n".join(self.lines_until(self.conflict_sep_re))
         yield werkzeug.html.pre(werkzeug.html(local),
                                 class_="local",
                                 id="line_%d" % self.line_no)
         other = u"\n".join(self.lines_until(self.conflict_close_re))
         yield werkzeug.html.pre(werkzeug.html(other),
                                 class_="other",
                                 id="line_%d" % self.line_no)
         yield u'</div>'
Example #6
0
 def _block_conflict(self, block):
     for self.line_no, part in block:
         yield u'<div class="conflict">'
         local = u"\n".join(self.lines_until(self.conflict_sep_re))
         yield werkzeug.html.pre(werkzeug.html(local),
                                 class_="local",
                                 id="line_%d" % self.line_no)
         other = u"\n".join(self.lines_until(self.conflict_close_re))
         yield werkzeug.html.pre(werkzeug.html(other),
                                 class_="other",
                                 id="line_%d" % self.line_no)
         yield u'</div>'
Example #7
0
 def footer(self, special_title, edit_url):
     for part in super(WikiPageWiki, self).footer(special_title, edit_url):
         yield part
     yield werkzeug.html.a(werkzeug.html(_('Slides')),
         href=self.get_url(self.title, self.wiki.slides),
         class_='slides')
     yield u'\n'
Example #8
0
 def footer(self, special_title, edit_url):
     for part in super(WikiPageWiki, self).footer(special_title, edit_url):
         yield part
     yield werkzeug.html.a(werkzeug.html(_('Slides')),
                           href=self.get_url(self.title, self.wiki.slides),
                           class_='slides')
     yield u'\n'
Example #9
0
 def wiki_image(self, addr, alt, class_='wiki', lineno=0):
     addr = addr.strip()
     chunk = ''
     if hatta.parser.external_link(addr):
         return html.img(src=werkzeug.url_fix(addr),
                         class_="external",
                         alt=alt)
     if '#' in addr:
         addr, chunk = addr.split('#', 1)
     if addr == '':
         return html.a(name=chunk)
     elif addr.startswith(':'):
         if chunk:
             chunk = '#' + chunk
         alias = self._link_alias(addr[1:])
         href = werkzeug.url_fix(alias + chunk)
         return html.img(src=href, class_="external alias", alt=alt)
     elif addr in self.wiki.storage:
         mime = page_mime(addr)
         if mime.startswith('image/'):
             return html.img(src=self.get_ref_path(addr),
                             class_=class_,
                             alt=alt)
         else:
             return html.img(href=self.get_ref_path(addr), alt=alt)
     else:
         return html.a(html(alt), href=self.get_ref_path(addr))
Example #10
0
 def content_iter(self, lines=None):
     import csv
     _ = self.wiki.gettext
     # XXX Add preview support
     csv_file = self.storage.open_page(self.title)
     reader = csv.reader(csv_file)
     html_title = werkzeug.escape(self.title, quote=True)
     yield '<table id="%s" class="csvfile">' % html_title
     try:
         for row in reader:
             yield '<tr>%s</tr>' % (''.join('<td>%s</td>' % cell
                                            for cell in row))
     except csv.Error as e:
         yield '</table>'
         yield werkzeug.html.p(
             werkzeug.html(
                 _('Error parsing CSV file %{file}s on '
                   'line %{line}d: %{error}s') % {
                       'file': html_title,
                       'line': reader.line_num,
                       'error': e
                   }))
     finally:
         csv_file.close()
     yield '</table>'
Example #11
0
 def _block_indent(self, block):
     parts = []
     first_line = None
     for self.line_no, part in block:
         if first_line is None:
             first_line = self.line_no
         parts.append(part.rstrip())
     text = u"\n".join(parts)
     yield werkzeug.html.pre(werkzeug.html(text), id="line_%d" % first_line)
Example #12
0
 def _block_indent(self, block):
     parts = []
     first_line = None
     for self.line_no, part in block:
         if first_line is None:
             first_line = self.line_no
         parts.append(part.rstrip())
     text = u"\n".join(parts)
     yield werkzeug.html.pre(werkzeug.html(text), id="line_%d" % first_line)
Example #13
0
 def revision(self, request, title, rev):
     _ = self.gettext
     text = self.storage.revision_text(title, rev)
     link = werkzeug.html.a(werkzeug.html(title),
                            href=request.get_url(title))
     content = [
         werkzeug.html.p(
             werkzeug.html(
                 _(u'Content of revision %(rev)d of page %(title)s:'))
             % {'rev': rev, 'title': link}),
         werkzeug.html.pre(werkzeug.html(text)),
     ]
     special_title = _(u'Revision of "%(title)s"') % {'title': title}
     page = self.get_page(request, title)
     html = page.template('page_special.html', content=content,
                          special_title=special_title)
     response = self.response(request, title, html, rev=rev, etag='/old')
     return response
Example #14
0
 def _block_syntax(self, block):
     for self.line_no, part in block:
         syntax = part.lstrip('{#!').strip()
         inside = u"\n".join(self.lines_until(self.code_close_re))
         if self.wiki_syntax:
             return self.wiki_syntax(inside, syntax=syntax,
                                     line_no=self.line_no)
         else:
             return [werkzeug.html.div(werkzeug.html.pre(
                 werkzeug.html(inside), id="line_%d" % self.line_no),
                 class_="highlight")]
Example #15
0
File: page.py Project: happytk/moin
 def content_iter(self, lines):
     last_lines = []
     in_header = False
     in_bug = False
     attributes = {}
     title = None
     for line_no, line in enumerate(lines):
         if last_lines and line.startswith('----'):
             title = ''.join(last_lines)
             last_lines = []
             in_header = True
             attributes = {}
         elif in_header and ':' in line:
             attribute, value = line.split(':', 1)
             attributes[attribute.strip()] = value.strip()
         else:
             if in_header:
                 if in_bug:
                     yield '</div>'
                 #tags = [tag.strip() for tag in
                 #        attributes.get('tags', '').split()
                 #        if tag.strip()]
                 yield '<div id="line_%d">' % (line_no)
                 in_bug = True
                 if title:
                     yield werkzeug.html.h2(werkzeug.html(title))
                 if attributes:
                     yield '<dl>'
                     for attribute, value in attributes.iteritems():
                         yield werkzeug.html.dt(werkzeug.html(attribute))
                         yield werkzeug.html.dd(werkzeug.html(value))
                     yield '</dl>'
                 in_header = False
             if not line.strip():
                 if last_lines:
                     if last_lines[0][0] in ' \t':
                         yield werkzeug.html.pre(werkzeug.html(
                                         ''.join(last_lines)))
                     else:
                         yield werkzeug.html.p(werkzeug.html(
                                         ''.join(last_lines)))
                     last_lines = []
             else:
                 last_lines.append(line)
     if last_lines:
         if last_lines[0][0] in ' \t':
             yield werkzeug.html.pre(werkzeug.html(
                             ''.join(last_lines)))
         else:
             yield werkzeug.html.p(werkzeug.html(
                             ''.join(last_lines)))
     if in_bug:
         yield '</div>'
Example #16
0
 def _block_syntax(self, block):
     for self.line_no, part in block:
         syntax = part.lstrip('{#!').strip()
         inside = u"\n".join(self.lines_until(self.code_close_re))
         if self.wiki_syntax:
             return self.wiki_syntax(inside,
                                     syntax=syntax,
                                     line_no=self.line_no)
         else:
             return [
                 werkzeug.html.div(werkzeug.html.pre(werkzeug.html(inside),
                                                     id="line_%d" %
                                                     self.line_no),
                                   class_="highlight")
             ]
Example #17
0
 def content_iter(self, lines):
     last_lines = []
     in_header = False
     in_bug = False
     attributes = {}
     title = None
     for line_no, line in enumerate(lines):
         if last_lines and line.startswith('----'):
             title = ''.join(last_lines)
             last_lines = []
             in_header = True
             attributes = {}
         elif in_header and ':' in line:
             attribute, value = line.split(':', 1)
             attributes[attribute.strip()] = value.strip()
         else:
             if in_header:
                 if in_bug:
                     yield '</div>'
                 #tags = [tag.strip() for tag in
                 #        attributes.get('tags', '').split()
                 #        if tag.strip()]
                 yield '<div id="line_%d">' % (line_no)
                 in_bug = True
                 if title:
                     yield werkzeug.html.h2(werkzeug.html(title))
                 if attributes:
                     yield '<dl>'
                     for attribute, value in attributes.items():
                         yield werkzeug.html.dt(werkzeug.html(attribute))
                         yield werkzeug.html.dd(werkzeug.html(value))
                     yield '</dl>'
                 in_header = False
             if not line.strip():
                 if last_lines:
                     if last_lines[0][0] in ' \t':
                         yield werkzeug.html.pre(
                             werkzeug.html(''.join(last_lines)))
                     else:
                         yield werkzeug.html.p(
                             werkzeug.html(''.join(last_lines)))
                     last_lines = []
             else:
                 last_lines.append(line)
     if last_lines:
         if last_lines[0][0] in ' \t':
             yield werkzeug.html.pre(werkzeug.html(''.join(last_lines)))
         else:
             yield werkzeug.html.p(werkzeug.html(''.join(last_lines)))
     if in_bug:
         yield '</div>'
Example #18
0
File: page.py Project: happytk/moin
 def content_iter(self, lines=None):
     import csv
     _ = self.wiki.gettext
     # XXX Add preview support
     csv_file = self.storage.open_page(self.title)
     reader = csv.reader(csv_file)
     html_title = werkzeug.escape(self.title, quote=True)
     yield u'<table id="%s" class="csvfile">' % html_title
     try:
         for row in reader:
             yield u'<tr>%s</tr>' % (u''.join(u'<td>%s</td>' % cell
                                              for cell in row))
     except csv.Error, e:
         yield u'</table>'
         yield werkzeug.html.p(werkzeug.html(
             _(u'Error parsing CSV file %{file}s on '
               u'line %{line}d: %{error}s') %
             {'file': html_title, 'line': reader.line_num, 'error': e}))
Example #19
0
File: page.py Project: happytk/moin
    def render_editor(self, preview=None, captcha_error=None):
        """Generate the HTML for the editor."""

        _ = self.wiki.gettext
        author = self.request.get_author()
        lines = []
        try:
            lines = self.storage.page_text(self.title).splitlines(True)
            (rev, old_date, old_author,
                old_comment) = self.storage.page_meta(self.title)
            comment = _(u'modified')
            if old_author == author:
                comment = old_comment
        except hatta.error.NotFoundErr:
            comment = _(u'created')
            rev = -1
        except hatta.error.ForbiddenErr, e:
            return werkzeug.html.p(werkzeug.html(unicode(e)))
Example #20
0
    def render_editor(self, preview=None, captcha_error=None):
        """Generate the HTML for the editor."""

        _ = self.wiki.gettext
        author = self.request.get_author()
        lines = []
        try:
            page_file = self.storage.open_page(self.title)
            lines = self.storage.page_lines(page_file)
            (rev, old_date, old_author,
             old_comment) = self.storage.page_meta(self.title)
            comment = _(u'modified')
            if old_author == author:
                comment = old_comment
        except error.NotFoundErr:
            comment = _(u'created')
            rev = -1
        except error.ForbiddenErr, e:
            return werkzeug.html.p(werkzeug.html(unicode(e)))
Example #21
0
    def render_editor(self, preview=None, captcha_error=None):
        """Generate the HTML for the editor."""

        _ = self.wiki.gettext
        author = self.request.get_author()
        lines = []
        try:
            lines = self.storage.page_text(self.title).splitlines(True)
            (rev, old_date, old_author,
             old_comment) = self.storage.page_meta(self.title)
            comment = _('modified')
            if old_author == author:
                comment = old_comment
        except error.NotFoundErr:
            comment = _('created')
            rev = -1
        except error.ForbiddenErr as e:
            return werkzeug.html.p(werkzeug.html(str(e)))
        if preview:
            lines = preview
            comment = self.request.form.get('comment', comment)
        if captcha and self.wiki.recaptcha_public_key:
            recaptcha_html = captcha.displayhtml(
                self.wiki.recaptcha_public_key, error=captcha_error)
        else:
            recaptcha_html = None
        context = {
            'comment': comment,
            'preview': preview,
            'recaptcha_html': recaptcha_html,
            'help': self.get_edit_help(),
            'author': author,
            'parent': rev,
            'lines': lines,
        }
        return self.template('edit_text.html', **context)
Example #22
0
def save(title):
    _ = current_app.gettext

    page.check_lock(current_app, title)
    url = current_app.get_url(title)
    if request.form.get('cancel'):
        if title not in current_app.storage:
            url = current_app.get_url(current_app.front_page)
    if request.form.get('preview'):
        text = request.form.get("text")
        if text is not None:
            lines = text.split('\n')
        else:
            lines = [werkzeug.html.p(werkzeug.html(
                _('No preview for binaries.')))]
        return edit(title, preview=lines)
    elif request.form.get('save'):
        if captcha and current_app.recaptcha_private_key:
            resp = captcha.submit(
                request.form.get('recaptcha_challenge_field', ''),
                request.form.get('recaptcha_response_field', ''),
                current_app.recaptcha_private_key, request.remote_addr)
            if not resp.is_valid:
                text = request.form.get("text", '')
                return edit(request, title, preview=text.split('\n'),
                                 captcha_error=response.error_code)
        comment = request.form.get("comment", "")
        if 'href="' in comment or 'http:' in comment:
            raise error.ForbiddenErr()
        author = request.get_author()
        text = request.form.get("text")
        try:
            parent = int(request.form.get("parent"))
        except (ValueError, TypeError):
            parent = None
        p = page.get_page(request, title)
        if text is not None:
            if title == current_app.locked_page:
                for link, label in p.extract_links(text):
                    if title == link:
                        raise error.ForbiddenErr(
                            _("This page is locked."))
            if text.strip() == '':
                current_app.storage.delete_page(title, author, comment)
                url = current_app.get_url(current_app.front_page)
            else:
                current_app.storage.save_text(title, text, author, comment,
                                       parent)
        else:
            text = ''
            upload = request.files.get('data')
            if upload and upload.stream and upload.filename:
                f = upload.stream
                current_app.storage.save_data(title, f.read(), author,
                                       comment, parent)
            else:
                current_app.storage.delete_page(title, author, comment)
                url = current_app.get_url(current_app.front_page)
        current_app.index.update(current_app)
    resp = response.redirect(url, code=303)
    resp.set_cookie('author',
                        werkzeug.url_quote(request.get_author()),
                        max_age=604800)
    return resp
Example #23
0
 def _block_code(self, block):
     for self.line_no, part in block:
         inside = u"\n".join(self.lines_until(self.code_close_re))
         yield werkzeug.html.pre(werkzeug.html(inside), class_="code",
                                 id="line_%d" % self.line_no)
Example #24
0
 def _block_code(self, block):
     for self.line_no, part in block:
         inside = u"\n".join(self.lines_until(self.code_close_re))
         yield werkzeug.html.pre(werkzeug.html(inside),
                                 class_="code",
                                 id="line_%d" % self.line_no)
Example #25
0
 def save(self, request, title):
     _ = self.gettext
     self._check_lock(title)
     url = request.get_url(title)
     if request.form.get('cancel'):
         if title not in self.storage:
             url = request.get_url(self.front_page)
     if request.form.get('preview'):
         text = request.form.get("text")
         if text is not None:
             lines = text.split('\n')
         else:
             lines = [werkzeug.html.p(werkzeug.html(
                 _(u'No preview for binaries.')))]
         return self.edit(request, title, preview=lines)
     elif request.form.get('save'):
         if captcha and self.recaptcha_private_key:
             response = captcha.submit(
                 request.form.get('recaptcha_challenge_field', ''),
                 request.form.get('recaptcha_response_field', ''),
                 self.recaptcha_private_key, request.remote_addr)
             if not response.is_valid:
                 text = request.form.get("text", '')
                 return self.edit(request, title, preview=text.split('\n'),
                                  captcha_error=response.error_code)
         comment = request.form.get("comment", "")
         author = request.get_author()
         text = request.form.get("text")
         try:
             parent = int(request.form.get("parent"))
         except (ValueError, TypeError):
             parent = None
         self.storage.reopen()
         self.index.update(self)
         page = self.get_page(request, title)
         if text is not None:
             if title == self.locked_page:
                 for link, label in page.extract_links(text):
                     if title == link:
                         raise error.ForbiddenErr(
                             _(u"This page is locked."))
             if u'href="' in comment or u'http:' in comment:
                 raise error.ForbiddenErr()
             if text.strip() == '':
                 self.storage.delete_page(title, author, comment)
                 url = request.get_url(self.front_page)
             else:
                 self.storage.save_text(title, text, author, comment,
                                        parent)
         else:
             text = u''
             upload = request.files['data']
             f = upload.stream
             if f is not None and upload.filename is not None:
                 try:
                     self.storage.save_file(title, f.tmpname, author,
                                            comment, parent)
                 except AttributeError:
                     self.storage.save_data(title, f.read(), author,
                                            comment, parent)
             else:
                 self.storage.delete_page(title, author, comment)
                 url = request.get_url(self.front_page)
         self.index.update_page(page, title, text=text)
     response = werkzeug.routing.redirect(url, code=303)
     response.set_cookie('author',
                         werkzeug.url_quote(request.get_author()),
                         max_age=604800)
     return response
Example #26
0
File: page.py Project: happytk/moin
 def content_iter(self, lines):
     yield '<pre>'
     for line in lines:
         yield werkzeug.html(line)
     yield '</pre>'
Example #27
0
 def content_iter(self, lines):
     yield '<pre>'
     for line in lines:
         yield werkzeug.html(line)
     yield '</pre>'