Esempio n. 1
0
    def macro(self, content, arguments, page_url, alternative):
        """
        Invocation: <<MailTo(user AT example DOT org, write me)>>
        where 2nd parameter is optional.
        """
        if arguments:
            arguments = arguments[0].split(',')
        try:
            assert len(arguments) > 0 and len(arguments) < 3
            email = arguments[0]
            assert len(email) >= 5
        except (AttributeError, AssertionError):
            raise ValueError(
                _("MailTo: invalid format, try: <<MailTo(user AT example DOT org, write me)>>"
                  ))

        try:
            text = arguments[1]
        except IndexError:
            text = u''

        if flaskg.user.valid:
            # decode address and generate mailto: link
            email = decodeSpamSafeEmail(email)
            result = moin_page.a(
                attrib={xlink.href: u'mailto:{0}'.format(email)},
                children=[text or email])
        else:
            # unknown user, maybe even a spambot, so just return text as given in macro args
            if text:
                text += " "
            result = moin_page.code(children=[text, "<{0}>".format(email)])

        return result
Esempio n. 2
0
 def inline_link_repl(self,
                      stack,
                      link,
                      link_url=None,
                      link_item=None,
                      link_text=None,
                      link_interwiki_site=None,
                      link_interwiki_item=None):
     """Handle all kinds of links."""
     if link_interwiki_site:
         if is_known_wiki(link_interwiki_site):
             link = Iri(scheme='wiki',
                        authority=link_interwiki_site,
                        path='/' + link_interwiki_item)
             element = moin_page.a(attrib={xlink.href: link})
             stack.push(element)
             if link_text:
                 self.parse_inline(link_text, stack, self.inlinedesc_re)
             else:
                 stack.top_append(link_interwiki_item)
             stack.pop()
             return
         else:
             # assume local language uses ":" inside of words, set link_item and continue
             link_item = '{0}:{1}'.format(link_interwiki_site,
                                          link_interwiki_item)
     if link_item is not None:
         att = 'attachment:'  # moin 1.9 needed this for an attached file
         if link_item.startswith(att):
             link_item = '/' + link_item[len(att):]  # now we have a subitem
         # we have Anchor macro, so we support anchor links despite lack of docs in Creole spec
         if '#' in link_item:
             path, fragment = link_item.rsplit('#', 1)
         else:
             path, fragment = link_item, None
         target = Iri(scheme='wiki.local', path=path, fragment=fragment)
         text = link_item
     else:
         target = Iri(link_url)
         text = link_url
     element = moin_page.a(attrib={xlink.href: target})
     stack.push(element)
     if link_text:
         self.parse_inline(link_text, stack, self.inlinedesc_re)
     else:
         stack.top_append(text)
     stack.pop()
Esempio n. 3
0
 def __call__(self, rev, contenttype=None, arguments=None):
     item_name = rev.item.fqname.fullname
     attrib = {
         xlink.href: Iri(scheme='wiki', authority='', path='/' + item_name, query='do=modify'),
     }
     a = moin_page.a(attrib=attrib, children=[_("%(item_name)s does not exist. Create it?", item_name=item_name)])
     body = moin_page.body(children=(a, ))
     return moin_page.page(children=(body, ))
Esempio n. 4
0
 def __call__(self, rev, contenttype=None, arguments=None):
     item_name = rev.item.name or rev.meta['name'][0]
     attrib = {
         xlink.href: Iri(scheme='wiki', authority='', path='/' + item_name,
                         query='do=get&rev={0}'.format(rev.revid)),
     }
     a = moin_page.a(attrib=attrib, children=[u"Download {0}.".format(item_name)])
     body = moin_page.body(children=(a, ))
     return moin_page.page(children=(body, ))
Esempio n. 5
0
 def process_name(self, member_name):
     attrib = {
         xlink.href:
         Iri(scheme='wiki',
             authority='',
             path='/' + self.item_name,
             query='do=get&member={0}'.format(member_name)),
     }
     return moin_page.a(attrib=attrib, children=[
         member_name,
     ])
Esempio n. 6
0
    def inline_url_repl(self, stack, url, url_target, escaped_url=None):
        """Handle raw urls in text."""

        if not escaped_url:
            # this url is NOT escaped
            attrib = {xlink.href: url_target}
            element = moin_page.a(attrib=attrib, children=(url_target, ))
            stack.top_append(element)
        else:
            # this url is escaped, we render it as text
            stack.top_append(url_target)
Esempio n. 7
0
    def create_pagelink_list(self, pagenames, ordered=False, display="FullPath"):
        """ Creates an ET with a list of pagelinks from a list of pagenames.

            Parameters:

              pagenames: a list of pages, each being like a flask request.path[1:]

              ordered: Should the list be ordered or unordered list (<ol> or <ul>)?

                  Options:
                      False : Display list as an unordered list.  (default)
                      True  : Display list as an ordered list.

              display: How should the link be displayed?

                  Options:
                      FullPath  : The full page path (default)
                      ChildPath : The last component of the FullPath, including the '/'
                      ChildName : ChildPath, but minus the leading '/'
                      UnCameled : ChildName, but with a space ' ' character between
                                  blocks of lowercase characters or numbers and an
                                  uppercase character.
                      skiptag   : skip items with this tag
                      ItemTitle : Use the title from the first header in the linked page *not implemented
            """

        page_list = moin_page.list(attrib={moin_page.item_label_generate: ordered and 'ordered' or 'unordered'})
        for pagename in pagenames:
            # This link can never reach pagelinks
            url = str(iri.Iri(scheme='wiki', authority='', path='/' + pagename))

            if display == "FullPath":
                linkname = pagename
            elif display == "ChildPath":
                index = pagename.rfind('/')
                linkname = pagename[index:]
            elif display == "ChildName":
                index = pagename.rfind('/')
                linkname = pagename[(index + 1):]
            elif display == "UnCameled":
                index = pagename.rfind('/')
                tempname = re.sub("([a-z0-9])([A-Z])", r"\g<1> \g<2>", pagename[(index + 1):])  # space before a cap char
                linkname = re.sub("([a-zA-Z])([0-9])", r"\g<1> \g<2>", tempname)
            elif display == "ItemTitle":
                raise NotImplementedError(_('"ItemTitle" is not implemented yet.'))
            else:
                raise KeyError(_('Unrecognized display value "%s".' % display))

            pagelink = moin_page.a(attrib={xlink.href: url}, children=[linkname])
            item_body = moin_page.list_item_body(children=[pagelink])
            item = moin_page.list_item(children=[item_body])
            page_list.append(item)
        return page_list
Esempio n. 8
0
 def create_number_pagelink_list(self, num_pagenames, ordered=False):
     """ creates an ET with a list of pagelinks from a list of pagenames """
     num_page_list = moin_page.list(attrib={moin_page.item_label_generate: ordered and 'ordered' or 'unordered'})
     for num, pagename in num_pagenames:
         num_code = moin_page.code(children=["{0:6d} ".format(num)])
         # This link can never reach pagelinks
         url = str(iri.Iri(scheme='wiki', authority='', path='/' + pagename))
         pagelink = moin_page.a(attrib={xlink.href: url}, children=[pagename])
         item_body = moin_page.list_item_body(children=[num_code, pagelink])
         item = moin_page.list_item(children=[item_body])
         num_page_list.append(item)
     return num_page_list
Esempio n. 9
0
    def visit_reference(self, node):
        refuri = node.get('refuri', '')
        if refuri.startswith('<<') and refuri.endswith('>>'):  # moin macro
            macro_name = refuri[2:-2].split('(')[0]
            if macro_name == "TableOfContents":
                arguments = refuri[2:-2].split('(')[1][:-1].split(',')
                node = moin_page.table_of_content()
                self.open_moin_page_node(node)
                if arguments and arguments[0]:
                    node.set(moin_page.outline_level, arguments[0])
                return
            if macro_name == "Include":
                # include macros are expanded by include.py similar to transclusions
                # rst include handles only wiki pages and does not support additional arguments like moinwiki
                arguments = refuri[2:-2].split('(')[1][:-1].split(',')
                link = Iri(scheme='wiki.local', path=arguments)
                node = xinclude.include(
                    attrib={
                        xinclude.href: link,
                        moin_page.alt: refuri,
                        moin_page.content_type: 'x-moin/macro;name=' +
                        macro_name,
                    })
                self.open_moin_page_node(node)
                return
            try:
                arguments = refuri[2:-2].split('(')[1][:-1]
            except IndexError:
                arguments = ''  # <<DateTime>>

            self.open_moin_page_node(
                moin_page.inline_part(
                    attrib={
                        moin_page.content_type:
                        "x-moin/macro;name={0}".format(macro_name)
                    }))
            if arguments:
                self.open_moin_page_node(moin_page.arguments())
                self.open_moin_page_node(arguments)
                self.close_moin_page_node()
                self.close_moin_page_node()
            return

        if not allowed_uri_scheme(refuri):
            self.visit_error(node)
            return
        if refuri == '':
            # build a link to a heading or an explicitly defined anchor
            refuri = Iri(scheme='wiki.local',
                         fragment=node.attributes['name'].replace(' ', '_'))
        self.open_moin_page_node(moin_page.a(attrib={xlink.href: refuri}))
Esempio n. 10
0
def build_dom_calendar_table(rows, head=None, caption=None, cls=None):
    """
    Build a DOM table with data from <rows>.
    """
    table = moin_page.table()
    if cls is not None:
        table.attrib[moin_page('class')] = cls

    if caption is not None:
        table_caption = moin_page.caption()
        table_caption.append(caption)
        table.append(table_caption)

    if head is not None:
        table_head = moin_page.table_header()
        table_row = moin_page.table_row()
        for _idx, cell_tuple in enumerate(head):
            (cell, cell_class) = cell_tuple
            table_cell = moin_page.table_cell(children=[cell])
            table_cell.attrib[moin_page('class')] = cell_class
            table_row.append(table_cell)
        table_head.append(table_row)
        table.append(table_head)
    table_body = moin_page.table_body()

    for row in rows:
        table_row = moin_page.table_row()
        for cell_tuple in row:

            # - cell content
            # - href for <a> tag
            # - CSS class for <td> tag
            (cell, cell_addr, cell_class) = cell_tuple

            # empty cell
            if not cell_addr:
                table_cell = moin_page.table_cell(children=[cell])
                table_cell.attrib[moin_page('class')] = cell_class

            # cell with link to calendar
            else:
                table_a = moin_page.a(attrib={xlink.href: Iri(cell_addr)},
                                      children=[cell])
                table_cell = moin_page.table_cell(children=[table_a])
                table_cell.attrib[moin_page('class')] = cell_class
            table_row.append(table_cell)
        table_body.append(table_row)
    table.append(table_body)
    return table
Esempio n. 11
0
 def create_pagelink_list(self, pagenames, ordered=False):
     """ creates an ET with a list of pagelinks from a list of pagenames """
     page_list = moin_page.list(attrib={
         moin_page.item_label_generate:
         ordered and 'ordered' or 'unordered'
     })
     for pagename in pagenames:
         # This link can never reach pagelinks
         url = unicode(
             iri.Iri(scheme=u'wiki', authority=u'', path=u'/' + pagename))
         pagelink = moin_page.a(attrib={xlink.href: url},
                                children=[pagename])
         item_body = moin_page.list_item_body(children=[pagelink])
         item = moin_page.list_item(children=[item_body])
         page_list.append(item)
     return page_list
Esempio n. 12
0
    def inline_freelink_repl(self,
                             stack,
                             freelink,
                             freelink_bang=None,
                             freelink_interwiki_page=None,
                             freelink_interwiki_ref=None,
                             freelink_page=None,
                             freelink_email=None):
        if freelink_bang:
            stack.top_append(freelink)
            return

        attrib = {}

        if freelink_page:
            page = freelink_page.encode('utf-8')
            if '#' in page:
                path, fragment = page.rsplit('#', 1)
            else:
                path, fragment = page, None
            link = Iri(scheme='wiki.local', path=path, fragment=fragment)
            text = freelink_page

        elif freelink_email:
            link = 'mailto:' + freelink_email
            text = freelink_email

        else:
            if not is_known_wiki(freelink_interwiki_ref):
                stack.top_append(freelink)
                return

            link = Iri(scheme='wiki',
                       authority=freelink_interwiki_ref,
                       path='/' + freelink_interwiki_page)
            text = freelink_interwiki_page

        attrib[xlink.href] = link

        element = moin_page.a(attrib, children=[text])
        stack.top_append(element)
Esempio n. 13
0
    def macro(self, content, arguments, page_url, alternative):
        if arguments:
            item_count = int(arguments[0])
        else:
            item_count = 1

        all_item_names = self.get_item_names()

        # Now select random item from the full list, and if it exists and
        # we can read it, save.
        random_item_names = []
        found = 0
        while found < item_count and all_item_names:
            # Take one random item from the list
            item_name = random.choice(all_item_names)
            all_item_names.remove(item_name)

            # Filter out items the user may not read.
            try:
                item = Item.create(item_name)
                random_item_names.append(item_name)
                found += 1
            except AccessDenied:
                pass

        if not random_item_names:
            return

        random_item_names.sort()

        result = moin_page.span()
        for name in random_item_names:
            link = unicode(Iri(scheme=u'wiki', authority=u'',
                               path=u'/' + name))
            result.append(
                moin_page.a(attrib={xlink.href: link}, children=[name]))
            result.append(", ")

        del result[-1]  # kill last comma
        return result
Esempio n. 14
0
 def __call__(self, rev, contenttype=None, arguments=None):
     try:
         item_name = rev.item.name or rev.meta['name'][0]
     except IndexError:
         # item is deleted
         message = _(
             'This deleted item must be restored before it can be viewed or downloaded, ItemID = {itemid}'
         ).format(itemid=rev.item.itemid)
         admonition = moin_page.div(
             attrib={moin_page.class_: 'error'},
             children=[moin_page.p(children=[message])])
         body = moin_page.body(children=(admonition, ))
         return moin_page.page(children=(body, ))
     attrib = {
         xlink.href:
         Iri(scheme='wiki',
             authority='',
             path='/' + item_name,
             query='do=get&rev={0}'.format(rev.revid)),
     }
     a = moin_page.a(attrib=attrib,
                     children=["Download {0}.".format(item_name)])
     body = moin_page.body(children=(a, ))
     return moin_page.page(children=(body, ))
Esempio n. 15
0
 def inline_url_repl(self, stack, url, url_target):
     url = Iri(url_target)
     attrib = {xlink.href: url}
     element = moin_page.a(attrib=attrib, children=[url_target])
     stack.top_append(element)
Esempio n. 16
0
    def inline_link_repl(self,
                         stack,
                         link,
                         link_url=None,
                         link_item=None,
                         link_text=None,
                         link_args=None,
                         link_interwiki_site=None,
                         link_interwiki_item=None):
        """Handle all kinds of links."""
        if link_interwiki_site:
            if is_known_wiki(link_interwiki_site):
                link = Iri(scheme='wiki',
                           authority=link_interwiki_site,
                           path='/' + link_interwiki_item)
                element = moin_page.a(attrib={xlink.href: link})
                stack.push(element)
                if link_text:
                    self.parse_inline(link_text, stack, self.inlinedesc_re)
                else:
                    stack.top_append(link_interwiki_item)
                stack.pop()
                return
            else:
                # assume local language uses ":" inside of words, set link_item and continue
                link_item = '{0}:{1}'.format(link_interwiki_site,
                                             link_interwiki_item)

        attribs = {}
        query = []
        if link_args:
            link_args = parse_arguments(
                link_args)  # XXX needs different parsing
            for key in link_args.keys():
                if key in ('target', 'title', 'download', 'class',
                           'accesskey'):
                    attribs[html(key)] = link_args[key]
                if key[0] == '&':
                    query.append('{0}={1}'.format(key[1:], link_args[key]))
        if link_item is not None:
            att = 'attachment:'  # moin 1.9 needed this for an attached file
            if link_item.startswith(att):
                link_item = '/' + link_item[len(att):]  # now we have a subitem
            if '#' in link_item:
                if link_item.startswith('#') and '/+convert/' in request.url:
                    # avoid traceback in link.py when converting moinwiki item to reST | HTML | Docbook
                    link_item = request.url.split('+convert/')[-1] + link_item
                link_item, fragment = link_item.rsplit('#', 1)
            else:
                link_item, fragment = link_item, None
            if '?' in link_item:
                path, link_query = link_item.rsplit('?', 1)
                query.insert(0, link_query)
            else:
                path, link_query = link_item, None
            if query:
                query = '&' + '&'.join(query)
            else:
                query = None
            target = Iri(scheme='wiki.local',
                         path=path,
                         query=query,
                         fragment=fragment)
            text = link_item
        else:
            target = Iri(link_url)
            text = link_url
        attribs[xlink.href] = target
        element = moin_page.a(attrib=attribs)
        stack.push(element)
        if link_text:
            self.parse_inline(link_text, stack, self.inlinedesc_re)
        else:
            stack.top_append(text)
        stack.pop()
Esempio n. 17
0
    def inline_link_repl(self,
                         stack,
                         link,
                         link_url=None,
                         link_item=None,
                         link_args=u'',
                         external_link_url=None,
                         alt_text=u''):
        """Handle all kinds of links."""
        link_text = ''
        link_args_list = []
        # Remove the first pipe/space, example of link_args : |arg1|arg2 or " arg1 arg2"
        parsed_args = self.parse_args(link_args[1:])
        query = None
        if parsed_args.keyword:
            query = url_encode(parsed_args.keyword,
                               charset=CHARSET,
                               encode_keys=True,
                               sort=True)
        # Take the last of positional parameters as link_text(caption)
        if parsed_args.positional:
            link_text = parsed_args.positional.pop()
        if link_item is not None:
            if '#' in link_item:
                path, fragment = link_item.rsplit('#', 1)
            else:
                path, fragment = link_item, None
            target = Iri(scheme='wiki.local',
                         path=path,
                         query=query,
                         fragment=fragment)
            text = link_item
        else:
            if link_url and len(link_url.split(':')) > 0 and link_url.split(
                    ':')[0] == 'File':
                object_item = ':'.join(link_url.split(':')[1:])
                args = parsed_args.keyword
                if object_item is not None:
                    if 'do' not in args:
                        # by default, we want the item's get url for transclusion of raw data:
                        args['do'] = 'get'
                    query = url_encode(args,
                                       charset=CHARSET,
                                       encode_keys=True,
                                       sort=True)
                    target = Iri(scheme='wiki.local',
                                 path=object_item,
                                 query=query,
                                 fragment=None)
                    text = object_item
                else:
                    target = Iri(scheme='wiki.local', path=link_url)
                    text = link_url

                if not link_text:
                    link_text = text
                attrib = {xlink.href: target}
                attrib[moin_page.alt] = link_text

                element = moin_page.object(attrib)
                stack.push(element)
                if link_text:
                    self.preprocessor.push()
                    self.parse_inline(link_text, stack, self.inlinedesc_re)
                    self.preprocessor.pop()
                else:
                    stack.top_append(text)
                stack.pop()
                return
            target = Iri(scheme='wiki.local', path=link_url)
            text = link_url
        if external_link_url:
            target = Iri(external_link_url)
            text = alt_text
        element = moin_page.a(attrib={xlink.href: target})
        stack.push(element)
        if link_text:
            self.preprocessor.push()
            self.parse_inline(link_text, stack, self.inlinedesc_re)
            self.preprocessor.pop()
        else:
            stack.top_append(text)
        stack.pop()