Exemple #1
0
    def addTrail(self, pagename):
        """
        Add page to trail.
        
        @param pagename: the page name to add to the trail
        """
        if self.valid and (self.show_page_trail or self.remember_last_visit):
            # load trail if not known
            self.getTrail()      
            
            # don't append tail to trail ;)
            if self._trail and self._trail[-1] == pagename: return

            # Add only existing pages that the user may read
            if self._request:
                from MoinMoin.Page import Page
                page = Page(self._request, pagename)
                if not (page.exists() and
                        self._request.user.may.read(page.page_name)):
                    return

            # append new page, limiting the length
            self._trail = filter(lambda p, pn=pagename: p != pn, self._trail)
            self._trail = self._trail[-(self._cfg.trail_size-1):]
            self._trail.append(pagename)

            # save new trail
            trailfile = codecs.open(self.__filename() + ".trail", "w", config.charset)
            for t in self._trail:
                trailfile.write('%s\n' % t)
            trailfile.close()
            try:
                os.chmod(self.__filename() + ".trail", 0666 & config.umask)
            except OSError:
                pass
Exemple #2
0
    def do_replaceunderlay(self, filename, pagename):
        """
        Overwrites underlay pages. Implementational detail: This needs to be
        kept in sync with the page class.

        @param filename: name of the file in the package
        @param pagename: page to be overwritten
        """
        page = Page(self.request, pagename)

        pagedir = page.getPagePath(use_underlay=1, check_create=1)

        revdir = os.path.join(pagedir, 'revisions')
        cfn = os.path.join(pagedir, 'current')

        revstr = '%08d' % 1
        if not os.path.exists(revdir):
            os.mkdir(revdir)

        currentf = open(cfn, 'w')
        currentf.write(revstr + "\n")
        currentf.close()

        pagefile = os.path.join(revdir, revstr)
        self._extractToFile(filename, pagefile)

        # Clear caches
        try:
            del self.request.cfg.DICTS_DATA
        except AttributeError:
            pass
        self.request.pages = {}
        caching.CacheEntry(self.request, 'wikidicts', 'dicts_groups', scope='wiki').remove()
        page.clean_acl_cache()
Exemple #3
0
    def save(self, editor, newtext, rev, **kw):
        request = self.request
        username = request.user.name
        pagename = editor.page_name

        if grouppage_autocreate and username == pagename:
            # create group pages when a user saves his own homepage
            for page in grouppages:
                grouppagename = "%s/%s" % (username, page)
                grouppage = Page(request, grouppagename)
                if not grouppage.exists():
                    text = """\
#acl %(username)s:read,write,delete,revert
 * %(username)s
""" % locals()
                    editor = PageEditor(request, grouppagename)
                    editor._write_file(text)

        parts = pagename.split('/')
        if len(parts) == 2:
            subpage = parts[1]
            if subpage in grouppages and not self.admin(pagename):
                return False

        # No problem to save if my base class agrees
        return Permissions.save(self, editor, newtext, rev, **kw)
Exemple #4
0
def getAttachDir(request, pagename, create=0):
    """ Get directory where attachments for page `pagename` are stored. """
    if request.page and pagename == request.page.page_name:
        page = request.page # reusing existing page obj is faster
    else:
        page = Page(request, pagename)
    return page.getPagePath("attachments", check_create=create)
Exemple #5
0
    def _do_queued_updates(self, request, amount=5):
        """ Assumes that the write lock is acquired """
        self.touch()
        writer = xapidx.Index(self.dir, True)
        writer.configure(self.prefixMap, self.indexValueMap)

        # do all page updates
        pages = self.update_queue.pages()[:amount]
        for name in pages:
            p = Page(request, name)
            if request.cfg.xapian_index_history:
                for rev in p.getRevList():
                    self._index_page(writer, Page(request, name, rev=rev), mode='update')
            else:
                self._index_page(writer, p, mode='update')
            self.update_queue.remove([name])

        # do page/attachment removals
        items = self.remove_queue.pages()[:amount]
        for item in items:
            _item = item.split('//')
            p = Page(request, _item[0])
            self._remove_item(writer, p, _item[1])
            self.remove_queue.remove([item])

        writer.close()
Exemple #6
0
    def do_replaceunderlay(self, filename, pagename):
        """
        Overwrites underlay pages. Implementational detail: This needs to be
        kept in sync with the page class.

        @param filename: name of the file in the package
        @param pagename: page to be overwritten
        """
        page = Page(self.request, pagename)

        pagedir = page.getPagePath(use_underlay=1, check_create=1)

        revdir = os.path.join(pagedir, 'revisions')
        cfn = os.path.join(pagedir, 'current')

        revstr = '%08d' % 1
        if not os.path.exists(revdir):
            os.mkdir(revdir)

        currentf = open(cfn, 'w')
        currentf.write(revstr + "\n")
        currentf.close()

        pagefile = os.path.join(revdir, revstr)
        self._extractToFile(filename, pagefile)
    def copypage(self, request, rootdir, pagename):
        """ quick and dirty! """
        pagedir = os.path.join(rootdir, 'pages', wikiutil.quoteWikinameFS(pagename))
        os.makedirs(pagedir)

        # write a "current" file with content "00000001"
        revstr = '%08d' % 1
        cf = os.path.join(pagedir, 'current')
        file(cf, 'w').write(revstr+'\n')

        # create a single revision 00000001
        revdir = os.path.join(pagedir, 'revisions')
        os.makedirs(revdir)
        tf = os.path.join(revdir, revstr)
        p = Page(request, pagename)
        text = p.get_raw_body().replace("\n", "\r\n")
        codecs.open(tf, 'wb', config.charset).write(text)

        source_dir = AttachFile.getAttachDir(request, pagename)
        if os.path.exists(source_dir):
            dest_dir = os.path.join(pagedir, "attachments")
            os.makedirs(dest_dir)
            for filename in os.listdir(source_dir):
                source_file = os.path.join(source_dir, filename)
                dest_file = os.path.join(dest_dir, filename)
                shutil.copyfile(source_file, dest_file)
Exemple #8
0
def execute(pagename, request):
    _ = request.getText
    sub_page_name = request.cfg.supplementation_page_name
    sub_page_template = request.cfg.supplementation_page_template
    newpagename = "%s/%s" % (pagename, sub_page_name)
    errormsg = _("You are not allowed to create the supplementation page.")

    if pagename.endswith(sub_page_name): # sub_sub_page redirects to sub_page
        query = {}
        url = Page(request, pagename).url(request, query)
        request.http_redirect(url)
    elif request.user.may.read(newpagename):
        query = {}
        url = Page(request, newpagename).url(request, query)
        test = Page(request, newpagename)
        if test.exists(): # page is defined -> redirect
            request.http_redirect(url)
        elif request.user.may.write(newpagename):  # page will be created from template
            query = {'action': 'edit', 'backto': newpagename, 'template': quoteWikinameURL(sub_page_template)}
            url = Page(request, newpagename).url(request, query)
            request.http_redirect(url)
        else:
            request.theme.add_msg(errormsg, "error")
    else:
        request.theme.add_msg(errormsg, "error")
    def trail(self, d):
        """ Assemble page trail

        @param d: parameter dictionary
        @rtype: unicode
        @return: trail html
        """
        request = self.request
        user = request.user
        html = ''
        if not user.valid or user.show_page_trail:
            trail = user.getTrail()
            if trail:
                items = []
                for pagename in trail:
                    try:
                        interwiki, page = wikiutil.split_interwiki(pagename)
                        if interwiki != request.cfg.interwikiname and interwiki != 'Self':
                            link = (self.request.formatter.interwikilink(True, interwiki, page) +
                                    self.shortenPagename(page) +
                                    self.request.formatter.interwikilink(False, interwiki, page))
                            items.append(link)
                            continue
                        else:
                            pagename = page

                    except ValueError:
                        pass
                    page = Page(request, pagename)
                    title = page.split_title()
                    title = self.shortenPagename(title)
                    link = page.link_to(request, title)
                    items.append(link)
                html = u'<div id="pagetrail">%s</div>' % u'<span class="sep"> &raquo; </span>'.join(items)
        return html
 def username(self, d):
     """ Assemble the username / userprefs link
     
     @param d: parameter dictionary
     @rtype: string
     @return: username html
     """
     from MoinMoin.Page import Page
     request = self.request
     _ = request.getText
     
     userlinks = []
     # Add username/homepage link for registered users. We don't care
     # if it exists, the user can create it.
     if request.user.valid:
         homepage = Page(request, request.user.name)
         title = homepage.split_title(request)
         homelink = homepage.link_to(request, text=title)
         userlinks.append(homelink)
     
         # Set pref page to localized Preferences page
         prefpage = wikiutil.getSysPage(request, 'UserPreferences')
         title = prefpage.split_title(request)
         userlinks.append(prefpage.link_to(request, text=title))
     else:
         # Add prefpage links with title: Login
         prefpage = wikiutil.getSysPage(request, 'UserPreferences')
         userlinks.append(prefpage.link_to(request, text=_("Login")))
         
     html = '<ul id="username"><li>%s</li></ul>' % '</li>\n<li>'.join(userlinks)
     return html
Exemple #11
0
def _getPages(request, pagename):
    """ Return a (filtered) list of pages names.
    """
    page = Page(request, pagename)
    #links = page.parsePageLinks(request)
    links = page.getPageLinks(request)
    return links
Exemple #12
0
def getAcl(request, pagename):
    pg = Page(request, pagename)
    pi = pg.get_pi()
    ret = pi["acl"].getString()
    if ret == '':
        ret = "not defined"
    return ret
Exemple #13
0
def handle_file_attached(event):
    """Sends an email to super users that have subscribed to this event type"""

    names = set()
    from_address = event.request.cfg.mail_from
    request = event.request
    page = Page(request, event.pagename)

    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, False)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getBaseURL() + getAttachUrl(event.pagename, event.filename, request)
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers:
        emails = []
        _ = lambda text: request.getText(text, lang=lang)

        links = _("Attachment link: %(attach)s\n" \
                  "Page link: %(page)s\n") % {'attach': attachlink, 'page': pagelink}

        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
        data['text'] = data['text'] + links

        emails = [usr.email for usr in subscribers[lang]]

        if send_notification(request, from_address, emails, data):
            names.update(recipients)

    return notification.Success(names)
def parse(story):
    """
    The main workhorse that does nothing but call MoinMoin to do its dirty
    laundry

    @param story: A text for conversion
    @type story: string
    @returns: formatted string
    @rtype: string
    """
    s = StringIO()
    oldstdout = sys.stdout
    form = None
    page = Page(None)
    page.hilite_re = None
    request = Request()
    request.user = User()
    formatter = Formatter(request)
    formatter.setPage(page)
    sys.stdout = s
    Parser(story, request).format(formatter, form)
    sys.stdout = oldstdout
    result = s.getvalue()
    s.close()
    return result
Exemple #15
0
    def make_iconlink(self, which, d):
        """
        Make a link with an icon

        @param which: icon id (dictionary key)
        @param d: parameter dictionary
        @rtype: string
        @return: html link tag
        """
        page_name, querystr, title, icon = self.button_table[which]
        d['title'] = title % d
        d['i18ntitle'] = self.request.getText(d['title'], formatted=False)
        img_src = self.make_icon(icon, d)
        attrs = {'rel': 'nofollow', 'title': d['i18ntitle'], }
        if page_name:
            page = Page(self.request, page_name % d)
        else:
            page = d['page']
        if self.is_moin_1_5:  # Moin 1.5.x
            url = wikiutil.quoteWikinameURL(page.page_name)
            querystr = wikiutil.makeQueryString(querystr)
            if querystr:
                url = '%s?%s' % (url, querystr)
            html = wikiutil.link_tag(self.request, url, img_src, title="%(i18ntitle)s" % d)
        else:  # Moin 1.6
            rev = d['rev']
            if rev and which in ['raw', 'print', ]:
                querystr['rev'] = str(rev)
            html = page.link_to_raw(self.request, text=img_src, querystr=querystr, **attrs)
        return html
Exemple #16
0
    def include(self, name, arguments, options, content, lineno,
                content_offset, block_text, state, state_machine):
        # content contains the included file name

        _ = self.request.getText

        # Limit the number of documents that can be included
        if self.num_includes < self.max_includes:
            self.num_includes += 1
        else:
            lines = [_("**Maximum number of allowed includes exceeded**")]
            state_machine.insert_input(lines, 'MoinDirectives')
            return

        if len(content):
            pagename = content[0]
            page = Page(page_name=pagename, request=self.request)
            if not self.request.user.may.read(pagename):
                lines = [_("**You are not allowed to read the page: %s**") % (pagename, )]
            else:
                if page.exists():
                    text = page.get_raw_body()
                    lines = text.split('\n')
                    # Remove the "#format rst" line
                    if lines[0].startswith("#format"):
                        del lines[0]
                else:
                    lines = [_("**Could not find the referenced page: %s**") % (pagename, )]
            # Insert the text from the included document and then continue parsing
            state_machine.insert_input(lines, 'MoinDirectives')
        return
Exemple #17
0
    def render(self):
        """ Redirect to the new page, using edit action and template """
        
        error = self.checkAndCombineArguments() or self.checkPermissions()
        if error:
            # Send back to the page you came from, with an error msg
            page = Page(self.request, self.referrer)
            page.send_page(self.request, msg=error)
        else:
            # Redirect to new page using edit action. No error checking
            # is needed because it is done later in new request.
            pagename = self.pagename
            query = {'action': 'edit', 'backto': self.referrer}

            template = self.request.form.get('template', [''])[0]
            if template:
                from MoinMoin.wikiutil import quoteWikinameURL
                query['template'] = quoteWikinameURL(template)

            parent = self.request.form.get('parent', [''])[0]
            if parent:
                pagename = "%s/%s" % (parent, pagename)

            url = Page(self.request, pagename).url(self.request, query, 0)
            self.request.http_redirect(url)
            raise MoinMoinNoFooter

        return ''
 def retrain(self, request):
     self.close_spamdb()
     if os.path.exists(self.spam_db):
         os.unlink(self.spam_db)
     self.open_spamdb(request)
     nham = nspam = 0
     for url in Group(request, "HamPages").members():
         scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
         rev = 0
         for pair in query.split("&"):
             key, val = pair.split("=")
             if key == "rev":
                 raw = int(val)
                 break
         pg = Page(request, path[1:], rev=rev)
         self.sbayes.train_ham(pg.get_raw_body())
         nham += 1
     for url in Group(request, "SpamPages").members():
         scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
         rev = 0
         for pair in query.split("&"):
             key, val = pair.split("=")
             if key == "rev":
                 raw = int(val)
                 break
         pg = Page(request, path[1:], rev=rev)
         self.sbayes.train_spam(pg.get_raw_body())
         nspam += 1
     self.close_spamdb()
     return (nham, nspam)
Exemple #19
0
def move_file(request, pagename, new_pagename, attachment, new_attachment):
    _ = request.getText

    newpage = Page(request, new_pagename)
    if newpage.exists(includeDeleted=1) and request.user.may.write(new_pagename) and request.user.may.delete(pagename):
        new_attachment_path = os.path.join(getAttachDir(request, new_pagename,
                              create=1), new_attachment).encode(config.charset)
        attachment_path = os.path.join(getAttachDir(request, pagename),
                          attachment).encode(config.charset)

        if os.path.exists(new_attachment_path):
            upload_form(pagename, request,
                msg=_("Attachment '%(new_pagename)s/%(new_filename)s' already exists.") % {
                    'new_pagename': new_pagename,
                    'new_filename': new_attachment})
            return

        if new_attachment_path != attachment_path:
            # move file
            filesys.rename(attachment_path, new_attachment_path)
            _addLogEntry(request, 'ATTDEL', pagename, attachment)
            _addLogEntry(request, 'ATTNEW', new_pagename, new_attachment)
            upload_form(pagename, request,
                        msg=_("Attachment '%(pagename)s/%(filename)s' moved to '%(new_pagename)s/%(new_filename)s'.") % {
                            'pagename': pagename,
                            'filename': attachment,
                            'new_pagename': new_pagename,
                            'new_filename': new_attachment})
        else:
            upload_form(pagename, request, msg=_("Nothing changed"))
    else:
        upload_form(pagename, request, msg=_("Page '%(new_pagename)s' does not exist or you don't have enough rights.") % {
            'new_pagename': new_pagename})
Exemple #20
0
def linkto(pagename, request, params=''):
    _ = request.getText

    if not request.cfg.chart_options:
        return (request.formatter.sysmsg(1) +
                request.formatter.text(_('Charts are not available!')) +
                request.formatter.sysmsg(0))

    if _debug:
        return draw(pagename, request)

    page = Page(request, pagename)

    # Create escaped query string from dict and params
    querystr = {'action': 'chart', 'type': 'pagesize'}
    querystr = wikiutil.makeQueryString(querystr)
    querystr = wikiutil.escape(querystr)
    if params:
        querystr += '&amp;' + params

    data = {'url': page.url(request, querystr)}
    data.update(request.cfg.chart_options)
    result = ('<img src="%(url)s" width="%(width)d" height="%(height)d"'
              ' alt="pagesize chart">') % data
    return result
Exemple #21
0
def macro_RandomQuote(macro, pagename=u'FortuneCookies'):
    _ = macro.request.getText

    if macro.request.user.may.read(pagename):
        page = Page(macro.request, pagename)
        raw = page.get_raw_body()
    else:
        raw = ""

    # this selects lines looking like a list item
    # !!! TODO: make multi-line quotes possible (optionally split by "----" or something)
    quotes = raw.splitlines()
    quotes = [quote.strip() for quote in quotes]
    quotes = [quote[2:] for quote in quotes if quote.startswith('* ')]

    if not quotes:
        return (macro.formatter.highlight(1) +
                _('No quotes on %(pagename)s.') % {'pagename': pagename} +
                macro.formatter.highlight(0))

    quote = random.choice(quotes)
    page.set_raw_body(quote, 1)
    quote = macro.request.redirectedOutput(page.send_page,
        content_only=1, content_id="RandomQuote")

    return quote
Exemple #22
0
class PackagePages:
    def __init__(self, pagename, request):
        self.request = request
        self.pagename = pagename
        self.page = Page(request, pagename)

    def allowed(self):
        """ Check if user is allowed to do this. """
        return not self.__class__.__name__ in self.request.cfg.actions_excluded

    def render(self):
        """ Render action

        This action returns a wiki page with optional message, or
        redirects to new page.
        """
        _ = self.request.getText

        if 'cancel' in self.request.values:
            # User canceled
            return self.page.send_page()

        try:
            if not self.allowed():
                self.request.theme.add_msg(_('You are not allowed to edit this page.'), "error")
                raise ActionError
            elif not self.page.exists():
                self.request.theme.add_msg(_('This page is already deleted or was never created!'))
                raise ActionError

            self.package()
        except ActionError, e:
            return self.page.send_page()
def parse(body):
    """Parse body and return html
    
    Create a page with body, then parse it and format using html formatter
    """
    assert body is not None

    request.reset()

    pg = Page(request, 'ThisPageDoesNotExistsAndWillNeverBeReally')
    pg.set_raw_body(body)

    from MoinMoin.formatter.text_html import Formatter
    pg.formatter = Formatter(request)
    request.formatter = pg.formatter
    pg.formatter.setPage(pg)
    pg.hilite_re = None

    output = []
    
    # Temporarily replace request.write with custom write function that 
    # write into our output object.
    def write_output(text, o=output):
        o.append(text)
    saved_write = request.write
    request.write = write_output
    try:
        Parser(body, request).format(pg.formatter)
    finally:
        request.write = saved_write

    return ''.join(output)
Exemple #24
0
def linkto(pagename, request, params=''):
    _ = request.getText

    if not request.cfg.chart_options:
        request.formatter = Formatter(request)
        return text(pagename, request, params)

    if _debug:
        return draw(pagename, request)

    page = Page(request, pagename)

    # Create escaped query string from dict and params
    querystr = {'action': 'chart', 'type': 'hitcounts'}
    querystr = wikiutil.makeQueryString(querystr)
    querystr = wikiutil.escape(querystr)
    if params:
        querystr += '&amp;' + params
    
    # TODO: remove escape=0 in 2.0
    data = {'url': page.url(request, querystr, escape=0)}
    data.update(request.cfg.chart_options)
    result = ('<img src="%(url)s" width="%(width)d" height="%(height)d"'
              ' alt="hitcounts chart">') % data

    return result
Exemple #25
0
    def _retrieve_members(self, group_name):
        """
        MoinMoin.formatter.groups is used to extract group members from a page.
        """
        formatter = Formatter(self.request)
        page = Page(self.request, group_name, formatter=formatter)

        request_page = getattr(self.request, "page", None)
        self.request.page = page
        # send_special is set to True because acl of the page should
        # not be processed to avoid infinite recursion in the
        # following case.
        #
        # Consider page UserGroup content:
        #
        # #acl UserGroup:read,write,admin All:read
        #
        #  * ExampleUser
        #  * TestGroup
        #
        page.send_page(content_only=True, send_special=True)

        if request_page:
            self.request.page = request_page
        else:
            del self.request.page

        return formatter.members
Exemple #26
0
 def pagelink(self, on, pagename="", page=None, **kw):
     FormatterBase.pagelink(self, on, pagename, page, **kw)
     if page is None:
         page = Page(self.request, pagename, formatter=self)
     link_text = page.link_to(self.request, on=on, **kw)
     self._curr.xml_append(tree.text(U(link_text)))
     return ""
Exemple #27
0
    def breadcrumbs(self, d, is_footer=False):
        request = self.request
        _ = request.getText
        user = request.user

        if not user.valid:
            return ""

        items = []

        if user.show_page_trail:
            trail = user.getTrail()
            if trail:
                for pagename in trail[::-1]:
                    try:
                        interwiki, page = wikiutil.split_interwiki(pagename)
                        if interwiki != request.cfg.interwikiname and interwiki != 'Self':
                            link = (
                                self.request.formatter.interwikilink(
                                    True, interwiki, page) +
                                self.shortenPagename(page) +
                                self.request.formatter.interwikilink(
                                    False, interwiki, page))
                            items.append(link)
                            continue
                        else:
                            pagename = page
                    except ValueError:
                        pass
                    page = Page(request, pagename)
                    title = page.split_title()
                    title = self.shortenPagename(title)
                    link = page.link_to(request, title)
                    items.append(link)

        val = """  <div class="navbar breadcrumb">
    <ul class="breadcrumb navbar-left">"""
        for i, item in enumerate(items):
            if i == 0:
                val += '\n      <li class="active">%s</li>' % item
            else:
                val += '\n      <li>%s</li>' % item

        val += '\n    </ul>\n    <ul class="breadcrumb navbar-right">'
        actions = getattr(request.cfg, 'bootstrap_actions',
                          self.BREADCRUMB_ACTIONS)
        for i, act in enumerate(actions):
            if act[0].isupper() and not act in self.available_actions:
                continue
            val += '\n      <li><a href="?action=%s%s">%s</a></li>' % (act, self.rev, self._actiontitle(act))

        val += u"""
      <li class="toggleCommentsButton" style="display:none;">
          <a href="#" class="nbcomment" onClick="toggleComments(); return false;">%s</a>
      </li>
        %s
    </ul>
  </div>""" % (_('Comments'), self.actionsmenu(d, is_footer))

        return val
Exemple #28
0
    def render(self):
        """ Redirect to the new page, using edit action and template """
        error = self.checkAndCombineArguments() or self.checkPermissions()
        if error:
            # Send back to the page you came from, with an error msg
            page = Page(self.request, self.referrer)
            self.request.theme.add_msg(error, "error")
            page.send_page()
        else:
            # Redirect to new page using edit action. No error checking
            # is needed because it is done later in new request.
            pagename = self.pagename
            query = {'action': 'edit', 'backto': self.referrer}

            template = self.request.form.get('template', [''])[0]
            if template:
                query['template'] = template

            parent = self.request.form.get('parent', [''])[0]
            if parent:
                pagename = "%s/%s" % (parent, pagename)

            url = Page(self.request, pagename).url(self.request, query)
            self.request.http_redirect(url)

        return ''
Exemple #29
0
    def _load_group(self):
        request = self.request
        group_name = self.name

        page = Page(request, group_name)
        if page.exists():
            arena = 'pagegroups'
            key = wikiutil.quoteWikinameFS(group_name)
            cache = caching.CacheEntry(request, arena, key, scope='wiki', use_pickle=True)
            try:
                cache_mtime = cache.mtime()
                page_mtime = wikiutil.version2timestamp(page.mtime_usecs())
                # TODO: fix up-to-date check mtime granularity problems.
                #
                # cache_mtime is float while page_mtime is integer
                # The comparision needs to be done on the lowest type of both
                if int(cache_mtime) > int(page_mtime):
                    # cache is uptodate
                    return cache.content()
                else:
                    raise caching.CacheError
            except caching.CacheError:
                # either cache does not exist, is erroneous or not uptodate: recreate it
                members, member_groups = super(WikiGroup, self)._load_group()
                cache.update((members, member_groups))
                return members, member_groups
        else:
            raise GroupDoesNotExistError(group_name)
    def trail(self, d):
        """ Assemble page trail
        
        @param d: parameter dictionary
        @rtype: unicode
        @return: trail html
        """
        request = self.request
        user = request.user
        if user.valid and user.show_page_trail:
            trail = user.getTrail()
            if trail:
                items = []
                # Show all items except the last one which is this page.
                for pagename in trail[:-1]:
                    page = Page(request, pagename)
                    title = page.split_title(request)
                    title = self.shortenPagename(title)
                    link = page.link_to(request, title)
                    items.append('<li>%s</li>' % link)
                html = '''
<ul id="pagetrail">
%s
</ul>''' % '\n'.join(items)
            return html
        return ''
Exemple #31
0
def handle_file_changed(event):
    """Sends an email to users that have subscribed to this event type"""

    names = set()
    from_address = event.request.cfg.mail_from
    request = event.request
    page = Page(request, event.pagename)

    if isinstance(event, ev.FileAttachedEvent):
        notification_fn = notification.attachment_added
    elif isinstance(event, ev.FileRemovedEvent):
        notification_fn = notification.attachment_removed

    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, False)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getQualifiedURL(
        getAttachUrl(event.pagename, event.filename, request))
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers:
        _ = lambda text: request.getText(text, lang=lang)

        links = _("Attachment link: %(attach)s\n" \
                  "Page link: %(page)s\n") % {'attach': attachlink, 'page': pagelink}

        data = notification_fn(request, _, event.pagename, event.filename,
                               event.size)
        data['text'] = data['text'] + links

        emails = [usr.email for usr in subscribers[lang]]

        if send_notification(request, from_address, emails, data):
            names.update(recipients)

    return notification.Success(names)
Exemple #32
0
    def _index_page_rev(self,
                        request,
                        connection,
                        pagename,
                        revno,
                        mode='update'):
        """ Index a page revision.

        @param request: request suitable for indexing
        @param connection: the Indexer connection object
        @param pagename: the page name
        @param revno: page revision number (int)
        @param mode: 'add' = just add, no checks
                     'update' = check if already in index and update if needed (mtime)
        """
        page = Page(request, pagename, rev=revno)
        request.page = page  # XXX for what is this needed?

        wikiname = request.cfg.interwikiname or u"Self"
        revision = str(page.get_real_rev())
        itemid = "%s:%s:%s" % (wikiname, pagename, revision)
        mtime = page.mtime_usecs()

        doc = self._get_document(connection, itemid, mtime, mode)
        logging.debug("%r %s %r" % (pagename, revision, doc))
        if doc:
            mimetype = 'text/%s' % page.pi['format']  # XXX improve this

            fields = {}
            fields['wikiname'] = wikiname
            fields['pagename'] = pagename
            fields['attachment'] = ''  # this is a real page, not an attachment
            fields['mtime'] = str(mtime)
            fields['revision'] = revision
            fields['title'] = pagename
            fields['content'] = page.get_raw_body()
            fields['lang'], fields['stem_lang'] = self._get_languages(page)
            fields['author'] = page.edit_info().get('editor', '?')

            multivalued_fields = {}
            multivalued_fields['mimetype'] = [
                mt for mt in [mimetype] + mimetype.split('/')
            ]
            multivalued_fields['domain'] = self._get_domains(page)
            multivalued_fields['linkto'] = page.getPageLinks(request)
            multivalued_fields['category'] = self._get_categories(page)

            self._add_fields_to_document(request, doc, fields,
                                         multivalued_fields)

            try:
                connection.replace(doc)
            except xappy.IndexerError, err:
                logging.warning("IndexerError at %r %r %r (%s)" %
                                (wikiname, pagename, revision, str(err)))
Exemple #33
0
    def formatPage(self, pagename, formatter):
        """Parse a page. Should not raise an exception if the API of the
        formatter is correct.
        """

        self.request.reset()
        page = Page(self.request, pagename, formatter=formatter)
        self.request.formatter = page.formatter = formatter(self.request)
        self.request.page = page
        #page.formatter.setPage(page)
        #page.hilite_re = None

        return self.request.redirectedOutput(page.send_page, content_only=1)
Exemple #34
0
 def check_condition(self):
     """ checks valid page and rev """
     _ = self._
     if not self.request.rev or Page(
             self.request, self.pagename).current_rev() == self.request.rev:
         # same string as in PageEditor...
         note = _(
             'You were viewing the current revision of this page when you called the revert action. '
             'If you want to revert to an older revision, first view that older revision and '
             'then call revert to this (older) revision again.')
         return note
     else:
         return None
Exemple #35
0
 def member_url(self, member):
     """ return URL for accessing container member
         (we use same URL for get (GET) and put (POST))
     """
     url = Page(self.request, self.pagename).url(
         self.request,
         {
             'action': 'AttachFile',
             'do': 'box',  # shorter to type than 'container'
             'target': self.containername,
             #'member': member,
         })
     return url + '&member=%s' % member
Exemple #36
0
def execute(macro, args):
    request = macro.request

    if args:
        page = Page(request, args)
    else:
        page = request.page

    pagelist, metakeys = get_revisions(request, page)

    return "".join(
        construct_table(request, dict(), pagelist, metakeys,
                        'Meta by Revision'))
Exemple #37
0
    def trail(self, d):
        """
		Assemble page trail

		@param d: parameter dictionary
		@rtype: unicode
		@return: trail html
		"""
        request = self.request
        user = request.user
        html = ''
        if not user.valid or user.show_page_trail:
            trail = user.getTrail()
            if trail:
                items = []
                for pagename in trail:
                    try:
                        interwiki, page = wikiutil.split_interwiki(pagename)
                        if interwiki != request.cfg.interwikiname and interwiki != 'Self':
                            link = (self.request.formatter.interwikilink(
                                True, interwiki, page) +
                                    self.shortenPagename(page) +
                                    self.request.formatter.interwikilink(
                                        False, interwiki, page))
                            items.append(link)
                            continue
                        else:
                            pagename = page

                    except ValueError:
                        pass
                    page = Page(request, pagename)
                    title = page.split_title()
                    title = self.shortenPagename(title)
                    link = page.link_to(request, title)
                    items.append(link)
                html = u'<div id="pagetrail">%s</div>' % u'<span class="sep"> &raquo; </span>'.join(
                    items)
        return html
Exemple #38
0
    def testSaveAbort(self):
        """Test if saveText() is interrupted if PagePreSave event handler returns Abort"""
        def handler(event):
            from MoinMoin.events import Abort
            return Abort("This is just a test")

        pagename = u'AutoCreatedMoinMoinTemporaryTestPageFortestSave'
        testtext = u'ThisIsSomeStupidTestPageText!'

        self.request.cfg.event_handlers = [handler]

        page = Page(self.request, pagename)
        if page.exists():
            deleter = PageEditor(self.request, pagename)
            deleter.deletePage()

        editor = PageEditor(self.request, pagename)
        editor.saveText(testtext, 0)

        print "PageEditor can't save a page if Abort is returned from PreSave event handlers"
        page = Page(self.request, pagename)
        assert page.body != testtext
Exemple #39
0
 def write_homepage(self, account, homepage_text):
     # writes the homepage
     if account.exists() and not account.disabled and not Page(self.request, account.name).exists():
         userhomepage = PageEditor(self.request, account.name)
         try:
             userhomepage.saveText(homepage_text, 0)
             print "INFO homepage for %s created." % account.name
         except userhomepage.Unchanged:
             print "You did not change the page content, not saved!"
         except userhomepage.NoAdmin:
             print "You don't have enough rights to create the %s page" % account.name
     else:
         print "INFO homepage for %s already exists or account is disabled or user does not exist." % account.name
    def sidebar(self, d, **keywords):
        """ Display page called SideBar as an additional element on every page
        content_id has been changed from the original

        @param d: parameter dictionary
        @rtype: string
        @return: sidebar html
        """

        # Check which page to display, return nothing if doesn't exist.
        sidebar = self.request.getPragma('sidebar', u'SideBar')
        page = Page(self.request, sidebar)
        if not page.exists():
            return u""
        # Capture the page's generated HTML in a buffer.
        buffer = StringIO.StringIO()
        self.request.redirect(buffer)
        try:
            page.send_page(content_only=1, content_id="sidebar-content")
        finally:
            self.request.redirect()
        return u'<div class="sidebar clearfix">%s</div>' % buffer.getvalue()
Exemple #41
0
def execute(pagename, request):
    """ Handle refresh action """
    # Without arguments, refresh action will refresh the page text_html cache.
    arena = request.values.get('arena', 'Page.py')
    if arena == 'Page.py':
        arena = Page(request, pagename)
    key = request.values.get('key', 'text_html')

    # Remove cache entry (if exists), and send the page
    from MoinMoin import caching
    caching.CacheEntry(request, arena, key, scope='item').remove()
    caching.CacheEntry(request, arena, "pagelinks", scope='item').remove()
    request.page.send_page()
Exemple #42
0
    def do_addattachment(self,
                         zipname,
                         filename,
                         pagename,
                         author=u"Scripting Subsystem",
                         comment=u""):
        """
        Installs an attachment

        @param pagename: Page where the file is attached. Or in 2.0, the file itself.
        @param zipname: Filename of the attachment from the zip file
        @param filename: Filename of the attachment (just applicable for MoinMoin < 2.0)
        """
        if self.request.user.may.write(pagename):
            _ = self.request.getText

            attachments = Page(self.request,
                               pagename).getPagePath("attachments",
                                                     check_create=1)
            filename = wikiutil.taintfilename(filename)
            zipname = wikiutil.taintfilename(zipname)
            target = os.path.join(attachments, filename)
            page = PageEditor(self.request,
                              pagename,
                              do_editor_backup=0,
                              uid_override=author)
            rev = page.current_rev()
            path = page.getPagePath(check_create=0)
            if not os.path.exists(target):
                self._extractToFile(zipname, target)
                if os.path.exists(target):
                    filesys.chmod(target, 0666 & config.umask)
                    action = 'ATTNEW'
                    edit_logfile_append(self,
                                        pagename,
                                        path,
                                        rev,
                                        action,
                                        logname='edit-log',
                                        comment=u'%(filename)s' %
                                        {"filename": filename},
                                        author=author)
                self.msg += u"%(filename)s attached \n" % {
                    "filename": filename
                }
            else:
                self.msg += u"%(filename)s not attached \n" % {
                    "filename": filename
                }
        else:
            self.msg += u"action add attachment: not enough rights - nothing done \n"
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]
    if not args:
        args = pagename

    handle = form.get('handle', [None])[0]
    if handle:
        handle = str(handle)

    getvalues = form.get('getvalues', [None])[0]
    if getvalues:
        args = "%s=/.+/" % getvalues

    inc_get_metas = wikiutil.importPlugin(request.cfg, "xmlrpc", "IncGetMeta",
                                          "inc_get_metas")
    out = inc_get_metas(request, args, handle)

    if getvalues:
        changed = out[2][1]
        filtered = dict()
        for page, metas in changed.items():
            for key, vals in metas.items():
                if key == getvalues:
                    filtered[page] = {key: vals}

        out[2] = (out[2][0], filtered)
    
    if form.get('formatted', [None])[0]:
        formatted = dict()

        for page, metas in out[2][1].items():
            vals = list()
            for key, values in metas.items():
                vals.append(key)
                vals.extend(values[1])
           
            request.page = Page(request, page)

            for val in vals:
                f = format_wikitext(request, val)
                if val != f:
                    formatted[val] = f

        out.append(formatted)


    json.dump(out, request, indent=2)
Exemple #44
0
def execute(pagename, request):
    _ = request.getText
    start, end, matches = findMatches(pagename, request)

    # Error?
    if isinstance(matches, (str, unicode)):
        request.theme.add_msg(wikiutil.escape(matches), "info")
        Page(request, pagename).send_page()
        return

    # No matches
    if not matches:
        request.theme.add_msg(_('No pages like "%s"!') % (wikiutil.escape(pagename), ), "error")
        Page(request, pagename).send_page()
        return

    # One match - display it
    if len(matches) == 1:
        request.theme.add_msg(_('Exactly one page like "%s" found, redirecting to page.') % (wikiutil.escape(pagename), ), "info")
        Page(request, matches.keys()[0]).send_page()
        return

    # more than one match, list 'em
    # This action generate data using the user language
    request.setContentLanguage(request.lang)

    request.theme.send_title(_('Pages like "%s"') % (pagename), pagename=pagename)

    # Start content - IMPORTANT - without content div, there is no
    # direction support!
    request.write(request.formatter.startContent("content"))

    showMatches(pagename, request, start, end, matches)

    # End content and send footer
    request.write(request.formatter.endContent())
    request.theme.send_footer(pagename)
    request.theme.send_closing_html()
Exemple #45
0
def invite_user_to_page(request,
                        page,
                        email,
                        new_template=None,
                        old_template=None,
                        **custom_vars):
    check_inviting_enabled(request)
    if not user_may_invite(request.user, page):
        raise InviteException("No permissions to invite from '%s'." % page)

    page_url = Page(request, page).url(request, relative=False)
    page_url = request.getQualifiedURL(page_url)
    return _invite(request, page_url, email, new_template, old_template,
                   **custom_vars)
Exemple #46
0
def linkto(pagename, request, params=''):
    _ = request.getText

    if not request.cfg.chart_options:
        return text(pagename, request)
    if _debug:
        return draw(pagename, request)

    page = Page(request, pagename)

    # Create escaped query string from dict and params
    querystr = {'action': 'chart', 'type': 'useragents'}
    querystr = wikiutil.makeQueryString(querystr)
    querystr = wikiutil.escape(querystr)
    if params:
        querystr += '&amp;' + params

    data = {'url': page.url(request, querystr)}
    data.update(request.cfg.chart_options)
    result = ('<img src="%(url)s" width="%(width)d" height="%(height)d"'
              ' alt="useragents chart">') % data

    return result
Exemple #47
0
def wiki2html(s):
    """
    INPUT:
         s -- a string formatted using wiki markup
    OUTPUT:
         string -- formatted as HTML
    """
    request = Request()
    request.form = ''
    request.rootpage = Page()
    request.cfg = Cfg()
    request.cfg.siteid = ''
    request.cfg.data_underlay_dir = ''
    request._page_headings = ''
Exemple #48
0
def do_show(pagename,
            request,
            content_only=0,
            count_hit=1,
            cacheable=1,
            print_mode=0,
            mimetype=u'text/html'):
    """ show a page, either current revision or the revision given by "rev=" value.
        if count_hit is non-zero, we count the request for statistics.
    """
    # We must check if the current page has different ACLs.
    if not request.user.may.read(pagename):
        Page(request, pagename).send_page()
    else:
        mimetype = request.values.get('mimetype', mimetype)
        rev = request.rev or 0
        if rev == 0:
            request.cacheable = cacheable
        Page(request, pagename, rev=rev, formatter=mimetype).send_page(
            count_hit=count_hit,
            print_mode=print_mode,
            content_only=content_only,
        )
Exemple #49
0
class LogoutHandler:
    def __init__(self, pagename, request):
        self.request = request
        self._ = request.getText
        self.page = Page(request, pagename)

    def handle(self):
        _ = self._
        # if the user really was logged out say so,
        # but if the user manually added ?action=logout
        # and that isn't really supported, then don't
        if not self.request.user.valid:
            self.request.theme.add_msg(_("You are now logged out."), "info")
        return self.page.send_page()
Exemple #50
0
    def include(self, name, arguments, options, content, lineno,
                content_offset, block_text, state, state_machine):
        # content contains the included file name

        _ = self.request.getText

        # Limit the number of documents that can be included
        if self.num_includes < self.max_includes:
            self.num_includes += 1
        else:
            lines = [_("**Maximum number of allowed includes exceeded**")]
            state_machine.insert_input(lines, 'MoinDirectives')
            return []

        if len(content):
            pagename = content[0]
            page = Page(page_name=pagename, request=self.request)
            if not self.request.user.may.read(pagename):
                lines = [
                    _("**You are not allowed to read the page: %s**") %
                    (pagename, )
                ]
            else:
                if page.exists():
                    text = page.get_raw_body()
                    lines = text.split('\n')
                    # Remove the "#format rst" line
                    if lines[0].startswith("#format"):
                        del lines[0]
                else:
                    lines = [
                        _("**Could not find the referenced page: %s**") %
                        (pagename, )
                    ]
            # Insert the text from the included document and then continue parsing
            state_machine.insert_input(lines, 'MoinDirectives')
        return []
Exemple #51
0
def handle_file_attached(event):
    """Handles event sent when a file is attached to a page"""

    names = set()
    request = event.request
    page = Page(request, event.pagename)
    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, True)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getQualifiedURL(
        getAttachUrl(event.pagename, event.filename, request))
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers.keys():
        _ = lambda text: request.getText(text, lang=lang)
        data = notification.attachment_added(request, _, event.pagename,
                                             event.filename, event.size)
        links = [{
            'url': attachlink,
            'description': _("Attachment link")
        }, {
            'url': pagelink,
            'description': _("Page link")
        }]

        jids = [usr.jid for usr in subscribers[lang]]
        data['url_list'] = links
        data['action'] = "file_attached"

        if send_notification(request, jids, data):
            names.update(recipients)

    return notification.Success(names)
Exemple #52
0
def newday (Wiki, ParentPage, TemplatePage, NewPage, Editor, UidName, GidName):

    from os import seteuid,setegid
    from pwd import getpwnam
    from grp import getgrnam

    uid = getpwnam(UidName).pw_uid
    gid = getgrnam(GidName).gr_gid

    setegid(gid)
    seteuid(uid)

    from MoinMoin.PageEditor import PageEditor
    from MoinMoin.Page import Page
    from MoinMoin.user import getUserId, User
    from MoinMoin.web.contexts import ScriptContext

    PageName = "%s/%s" % (ParentPage,NewPage)

    RequestPage = ScriptContext(Wiki, PageName)
    UserId = getUserId(RequestPage, Editor)
    RequestPage.user = User(RequestPage, UserId)

    Editor = PageEditor(RequestPage, PageName)
    Dummy, Revision, Exists = Editor.get_rev()

    if not Exists:

        RequestTemplate = ScriptContext(Wiki, TemplatePage)
        Viewer = Page(RequestTemplate, TemplatePage)

        Text = Viewer.getPageText().replace("@PAGE@", NewPage)
        Header = Viewer.getPageHeader()

        Text=Header+Text

        return Editor.saveText(Text, Revision)
Exemple #53
0
def execute(pagename, request):
    found = False
    for auth in request.cfg.auth:
        if isinstance(auth, MoinAuth):
            found = True
            break

    if not found:
        # we will not have linked, so forbid access
        request.makeForbidden403()
        return

    page = Page(request, pagename)
    _ = request.getText
    form = request.form
    if not request.user.isSuperUser():
        request.theme.add_msg(_('You are not allowed to use this action.'),
                              "error")
        return page.send_page()

    submitted = form.has_key('create')

    if submitted:  # user pressed create button
        request.theme.add_msg(_create_user(request), "dialog")
        return page.send_page()
    else:  # show create form
        request.theme.send_title(_("Create Account"), pagename=pagename)

        request.write(request.formatter.startContent("content"))

        # THIS IS A BIG HACK. IT NEEDS TO BE CLEANED UP
        request.write(_create_form(request))

        request.write(request.formatter.endContent())

        request.theme.send_footer(pagename)
        request.theme.send_closing_html()
Exemple #54
0
    def do_siblings(self, parentPage, root=None):
        """ Navigate from a subpage to its siblings.
        """
        _ = self._

        # iterate over children, adding links to all of them
        result = []
        children = _getPages(self.macro.request, parentPage)
        for child, linktext in children:
            # display short page name, leaving out the parent path
            # (and make sure the name doesn't get wrapped)
            if child.startswith("Category"): continue
            shortname = child
            if child.startswith(parentPage):
                shortname = child[len(parentPage):]

            parts = string.split(child, "/")

            if linktext:
                shortname = linktext
            else:
                shortname = parts[-1]

            if not shortname: continue

            if child == self.pagename:
                # do not link to focus
                result.append(self.macro.formatter.text(shortname))
            else:
                # link to sibling / child
                result.append(
                    Page(self.macro.request, child).link_to(self.macro.request,
                                                            text=shortname))

        if len(result) >= 2:
            str = self.macro.formatter.strong(
                1) + self.macro.formatter.emphasis(1) + result[
                    0] + self.macro.formatter.strong(0) + ": " + ' | '.join(
                        result[1:]) + self.macro.formatter.emphasis(0)
        else:
            str = ' | '.join(result)

        # wrap up the nav menu in a span so it's easier for rosmanual to find
        if len(str) > 0:
            str = self.macro.formatter.span(
                1, css_class="macro-nav-menu"
            ) + str + self.macro.formatter.span(0) + "\n"

        return str
Exemple #55
0
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request
    _ = request.getText

    if not cairo_found:
        return formatter.text(_(\
            "ERROR: Cairo Python extensions not installed. " +\
            "Not performing layout.")) + formatter.linebreak()

    urlargs, macro_args = radarchart_args(args)

    pagename = request.page.page_name
    # The first page mentioned will be the page of the chart
    for arg in macro_args.split(','):
        page = Page(request, arg)
        if page.exists():
            pagename = arg
            break

    return u'<div class="metaradarchart">' + \
           u'<img src="%s">' % url_construct(request, urlargs, pagename) + \
           u'</div>'
Exemple #56
0
def wiki_url(macro,
             page,
             shorten=None,
             querystr=None,
             relative=False,
             raw=False):
    """
    Create link to ROS wiki page
    @param raw: Return a raw html link instead of a wiki link. (This will avoid moin moin link checking.)
    """
    if not shorten or len(page) < shorten:
        page_text = page
    else:
        page_text = page[:shorten] + '...'
    if raw:
        ret = '<a href="'
        ret += Page(macro.request, page).url(macro.request,
                                             querystr=querystr,
                                             relative=relative)
        ret += '">%s</a>' % page_text
        return ret
    return Page(macro.request, page).link_to(macro.request,
                                             text=page_text,
                                             querystr=querystr)
Exemple #57
0
def execute(pagename, request):
    """ Unsubscribe the user from pagename """
    _ = request.getText
    if not request.user.valid:
        actname = __name__.split('.')[-1]
        request.theme.add_msg(
            _("You must login to use this action: %(action)s.") %
            {"action": actname}, "error")
        return Page(request, pagename).send_page()

    if request.user.isSubscribedTo([pagename]):
        # Try to unsubscribe
        if request.user.unsubscribe(pagename):
            request.theme.add_msg(
                _('Your subscription to this page has been removed.'), "info")
        else:
            msg = _("Can't remove regular expression subscription!") + u' ' + \
                  _("Edit the subscription regular expressions in your settings.")
            request.theme.add_msg(msg, "error")
    else:
        # The user is not subscribed
        request.theme.add_msg(_('You need to be subscribed to unsubscribe.'),
                              "info")
    Page(request, pagename).send_page()
Exemple #58
0
def execute(pagename, request):
    """ Subscribe the user to pagename """
    _ = request.getText
    if not request.user.valid:
        actname = __name__.split('.')[-1]
        request.theme.add_msg(_("You must login to use this action: %(action)s.") % {"action": actname}, "error")
        return Page(request, pagename).send_page()

    cfg = request.cfg

    if not request.user.may.read(pagename):
        request.theme.add_msg(_("You are not allowed to subscribe to a page you can't read."), "error")

    # Check if mail is enabled
    elif not cfg.mail_enabled and not cfg.jabber_enabled:
        request.theme.add_msg(_("This wiki is not enabled for mail/Jabber processing."), "error")

    # Suggest visitors to login
    elif not request.user.valid:
        request.theme.add_msg(_("You must log in to use subscriptions."), "error")

    # Suggest users without email to add their email address
    elif not request.user.email and not request.user.jid:
        request.theme.add_msg(_("Add your email address or Jabber ID in your user settings to use subscriptions."),
                              "error")

    elif request.user.isSubscribedTo([pagename]):
        request.theme.add_msg(_('You are already subscribed to this page.'))
    else:
        # Try to subscribe
        if request.user.subscribe(pagename):
            request.theme.add_msg(_('You have been subscribed to this page.'), "info")
        else: # should not happen
            request.theme.add_msg(_('You could not get subscribed to this page.'), "error")

    Page(request, pagename).send_page()
Exemple #59
0
def execute(pagename, request):
    """ Add the current wiki page to the user quicklinks """
    _ = request.getText

    if not request.user.valid:
        request.theme.add_msg(_("You must login to add a quicklink."), "error")
    elif not request.user.isQuickLinkedTo([pagename]):
        if request.user.addQuicklink(pagename):
            request.theme.add_msg(_('A quicklink to this page has been added for you.'), "info")
        else: # should not happen
            request.theme.add_msg(_('A quicklink to this page could not be added for you.'), "error")
    else:
        request.theme.add_msg(_('You already have a quicklink to this page.'))

    Page(request, pagename).send_page()
Exemple #60
0
    def do_action_finish(self, success):
        if success:
            pg = Page(self.request, self.newpagename)

            ngowikiutil = NgoWikiUtil(self.request)
            ngowikiutil.open_database()
            try:
                pageinfo = ngowikiutil.parse_page(pg)
                pagerecord = ngowikiutil.select_page_by_path(self.pagename)
                page_uuid = None
                if pagerecord == None:
                    page_uuid = ngowikiutil.insert_page(pg)["id"]
                else:
                    page_uuid = pagerecord["id"]
                    ngowikiutil.update_page(page_uuid, pg)
                pageinfo["id"] = page_uuid
                ngowikiutil.update_page_meta(pageinfo)
            finally:
                ngowikiutil.close_database(True)

            url = pg.url(self.request)
            self.request.http_redirect(url, code=301)
        else:
            self.render_msg(self.make_form(), "dialog")