Example #1
0
    def logo(self):
        """ Assemble logo with link to front page

        Changed: * we don't need a div wrapper for the textlogo
                 * append text "FrontPage" to the logo string
        
        @rtype: unicode
        @return: logo html
        """
        _ = self.request.getText
        html = u''
        if self.cfg.logo_string:
            page = wikiutil.getFrontPage(self.request)
            logo_string = self.cfg.logo_string
            logo_append = '<span class="screenreader_info"> %s</span>' % _('FrontPage', formatted=False) 
            logo_string = logo_string + logo_append
            # Try..except for backwards compatibility of Moin versions only
            try:
                logo = page.link_to_raw(self.request, logo_string)
            except:
                pagename = wikiutil.getFrontPage(self.request).page_name
                pagename = wikiutil.quoteWikinameURL(pagename)
                logo = wikiutil.link_tag(self.request, pagename, logo_string)
            html = u'%s' % logo
        return html
Example #2
0
 def logo(self):
     html = u''
     if self.cfg.logo_string:
         page = wikiutil.getFrontPage(self.request)
         logo = page.link_to_raw(self.request, self.cfg.logo_string)
         html = u'<h1>%s</h1>' % logo
     return html
Example #3
0
 def logo(self):
     logo = u''
     if self.cfg.logo_string:
         pagename = wikiutil.getFrontPage(self.request).page_name
         pagename = wikiutil.quoteWikinameURL(pagename)
         logo = wikiutil.link_tag(self.request, pagename, self.cfg.logo_string, css_class="logo")
     return logo
    def bs_breadcrumb(self, d):
        html = [u'<ul class="breadcrumb">']

        try:
            _var = self.cfg.bs_breadcrumb
            for text, url in self.cfg.bs_breadcrumb:
                markup = u'<li><a href="%s">%s</a> <span class="divider">&raquo;</span></li>' % (url, text)
                html.append(markup)
        except AttributeError:
            pass

        if self.request.action not in [u'show', u'', u'refresh']:
            action = self.request.action
        else:
            action = False
        page = wikiutil.getFrontPage(self.request)
        frontpage = page.link_to_raw(self.request, text=self.request.cfg.sitename)
        html.append(u'<li>%s <span class="divider">&raquo;</span></li>' % frontpage)
        segments = d['page_name'].split('/')
        if action:
            segments.append(action)
        curpage = ''
        for s in segments[:-1]:
            curpage += s
            html.append(u'<li>%s  <span class="divider">&raquo;</span></li>' % Page(self.request, curpage).link_to(self.request, s))
            curpage += '/'

        html.append(u'<li class="active">%s</li>' % segments[-1])
        html.append(u'<li class="pull-right">%s</li>' % self.username(d))
        html.append(u'</ul>')
        return '\n'.join(html)
Example #5
0
    def logo(self):
        """ Assemble logo with link to front page

        The logo contain an image and or text or any html markup the
        admin inserted in the config file. Everything it enclosed inside
        a div with id="logo".

        @rtype: unicode
        @return: logo html
        """
        html = u''
        page = wikiutil.getFrontPage(self.request)
        html = page.link_to_raw(self.request, '<img src="%s/FrontPage?action=AttachFile&do=get&target=logo.png" valign="bottom" alt="MoinMoin Logo">' % self.request.script_root)

        # page = wikiutil.getFrontPage(self.request)
        # #text = random.choice(['#','|','+','-','~','`','^','*','=','_',';',':',',','.'])#self.request.cfg.interwikiname or 'Self'
        # text = "%02d" % datetime.today().day
        # link = page.link_to(self.request, text=text, rel='nofollow')

        # #randomcolor
        # a = map(str, range(0,9))
        # a.extend(list('abcdef'))

        # color_str = []
        # for i in range(0,6):
        #     color_str.append(random.choice(a))
        # html = u'<span id="logo" style="background-color:#%s;">%s</span>' % (''.join(color_str), link)

        return html
Example #6
0
 def logo(self):
     html = u''
     if self.cfg.logo_string:
         page = wikiutil.getFrontPage(self.request)
         logo = page.link_to_raw(self.request, self.cfg.logo_string)
         html = u'<h1>%s</h1>' %logo
     return html
Example #7
0
    def username(self, d):
        """ Assemble the username / userprefs link

        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """

        if not self.is_mobile:
            return ThemeBase.username(self, d)

        request = self.request
        _ = request.getText

        if self.request.cfg.show_interwiki:
            page = wikiutil.getFrontPage(self.request)
            text = self.request.cfg.interwikiname or 'Self'
            link = page.link_to(self.request, text=text, rel='nofollow')
            # html = u'<span id="interwiki">%s<span class="sep">: </span></span>' % link
            userlinks = [link]
        else:
            userlinks = []

        # Add username/homepage link for registered users. We don't care
        # if it exists, the user can create it.
        if request.user.valid and request.user.name:
            interwiki = wikiutil.getInterwikiHomePage(request)
            name = request.user.name
            aliasname = request.user.aliasname
            if not aliasname:
                aliasname = name
            title = "%s @ %s" % (aliasname, interwiki[0])
            # link to (interwiki) user homepage
            homelink = (request.formatter.interwikilink(1, title=title, id="userhome", generated=True, *interwiki) +
                        request.formatter.text(name) +
                        request.formatter.interwikilink(0, title=title, id="userhome", *interwiki))
            userlinks.append(homelink)
            # link to userprefs action
            if 'userprefs' not in self.request.cfg.actions_excluded:
                userlinks.append(d['page'].link_to(request, text=_('Settings'),
                                               querystr={'action': 'userprefs'}, id='userprefs', rel='nofollow'))

        if request.user.valid:
            if request.user.auth_method in request.cfg.auth_can_logout:
                userlinks.append(d['page'].link_to(request, text=_('Logout'),
                                                   querystr={'action': 'logout', 'logout': 'logout'}, id='logout', rel='nofollow'))
        else:
            query = {'action': 'login'}
            # special direct-login link if the auth methods want no input
            if request.cfg.auth_login_inputs == ['special_no_input']:
                query['login'] = '******'
            if request.cfg.auth_have_login:
                userlinks.append(d['page'].link_to(request, text=_("Login"),
                                                   querystr=query, id='login', rel='nofollow'))

        userlinks_html = u'<span class="sep"> | </span>'.join(userlinks)
        html = u'<div id="username">%s</div>' % userlinks_html
        return html
Example #8
0
def handle_action(context, pagename, action_name='show'):
    """ Actual dispatcher function for non-XMLRPC actions.

    Also sets up the Page object for this request, normalizes and
    redirects to canonical pagenames and checks for non-allowed
    actions.
    """
    _ = context.getText
    cfg = context.cfg

    # pagename could be empty after normalization e.g. '///' -> ''
    # Use localized FrontPage if pagename is empty
    if not pagename:
        context.page = wikiutil.getFrontPage(context)
    else:
        context.page = Page(context, pagename)
        if '_' in pagename and not context.page.exists():
            pagename = pagename.replace('_', ' ')
            page = Page(context, pagename)
            if page.exists():
                url = page.url(context)
                return context.http_redirect(url)

    msg = None
    # Complain about unknown actions
    if not action_name in get_names(cfg):
        msg = _("Unknown action %(action_name)s.") % {
                'action_name': wikiutil.escape(action_name), }

    # Disallow non available actions
    elif action_name[0].isupper() and not action_name in \
            get_available_actions(cfg, context.page, context.user):
        msg = _("You are not allowed to do %(action_name)s on this page.") % {
                'action_name': wikiutil.escape(action_name), }
        if not context.user.valid:
            # Suggest non valid user to login
            msg += " " + _("Login and try again.")

    if msg:
        context.theme.add_msg(msg, "error")
        context.page.send_page()
    # Try action
    else:
        from MoinMoin import action
        handler = action.getHandler(context, action_name)
        if handler is None:
            msg = _("You are not allowed to do %(action_name)s on this page.") % {
                    'action_name': wikiutil.escape(action_name), }
            if not context.user.valid:
                # Suggest non valid user to login
                msg += " " + _("Login and try again.")
            context.theme.add_msg(msg, "error")
            context.page.send_page()
        else:
            handler(context.page.page_name, context)

    return context
Example #9
0
def handle_action(context, pagename, action_name='show'):
    """ Actual dispatcher function for non-XMLRPC actions.

    Also sets up the Page object for this request, normalizes and
    redirects to canonical pagenames and checks for non-allowed
    actions.
    """
    _ = context.getText
    cfg = context.cfg

    # pagename could be empty after normalization e.g. '///' -> ''
    # Use localized FrontPage if pagename is empty
    if not pagename:
        context.page = wikiutil.getFrontPage(context)
    else:
        context.page = Page(context, pagename)
        if '_' in pagename and not context.page.exists():
            pagename = pagename.replace('_', ' ')
            page = Page(context, pagename)
            if page.exists():
                url = page.url(context)
                return context.http_redirect(url)

    msg = None
    # Complain about unknown actions
    if not action_name in get_names(cfg):
        msg = _("Unknown action %(action_name)s.") % {
                'action_name': wikiutil.escape(action_name), }

    # Disallow non available actions
    elif action_name[0].isupper() and not action_name in \
            get_available_actions(cfg, context.page, context.user):
        msg = _("You are not allowed to do %(action_name)s on this page.") % {
                'action_name': wikiutil.escape(action_name), }
        if not context.user.valid:
            # Suggest non valid user to login
            msg += " " + _("Login and try again.")

    if msg:
        context.theme.add_msg(msg, "error")
        context.page.send_page()
    # Try action
    else:
        from MoinMoin import action
        handler = action.getHandler(context, action_name)
        if handler is None:
            msg = _("You are not allowed to do %(action_name)s on this page.") % {
                    'action_name': wikiutil.escape(action_name), }
            if not context.user.valid:
                # Suggest non valid user to login
                msg += " " + _("Login and try again.")
            context.theme.add_msg(msg, "error")
            context.page.send_page()
        else:
            handler(context.page.page_name, context)

    return context
Example #10
0
    def username(self, d):
        html = _Theme.username(self, d)
        first_tag = html.index('>') + 1

        page = wikiutil.getFrontPage(self.request)

        return u'{} {} <span class="sep"> | </span> {}'.format(
            html[:first_tag], page.link_to_raw(self.request, "Home"),
            html[first_tag:])
Example #11
0
 def interwiki(self, d):
     """ Assemble the interwiki name display, linking to page_front_page
     
     @param d: parameter dictionary
     @rtype: string
     @return: interwiki html
     """
     html = u''
     if self.request.cfg.show_interwiki:
         # Show our interwikiname or Self (and link to page_front_page)
         pagename = wikiutil.getFrontPage(self.request).page_name
         pagename = wikiutil.quoteWikinameURL(pagename)
         link = wikiutil.link_tag(self.request, pagename, self.request.cfg.interwikiname or 'Self')
         html = u'<div id="interwiki"><span>%s</span></div>' % link
     return html
    def interwiki(self, d):
        """ Assemble the interwiki name display, linking to page_front_page

        @param d: parameter dictionary
        @rtype: string
        @return: interwiki html
        """
        if self.request.cfg.show_interwiki:
            page = wikiutil.getFrontPage(self.request)
            text = self.request.cfg.interwikiname or 'Self'
            link = page.link_to(self.request, text=text, rel='nofollow')
            html = u'<span id="interwiki">%s<span class="sep">:</span></span>' % link
        else:
            html = u''
        return html
Example #13
0
File: utils.py Project: aahlad/soar
def redirect_last_visited(request):
    pagetrail = request.user.getTrail()
    if pagetrail:
        # Redirect to last page visited
        last_visited = pagetrail[-1]
        wikiname, pagename = wikiutil.split_interwiki(last_visited)
        if wikiname != 'Self':
            wikitag, wikiurl, wikitail, error = wikiutil.resolve_interwiki(request, wikiname, pagename)
            url = wikiurl + wikiutil.quoteWikinameURL(wikitail)
        else:
            url = Page(request, pagename).url(request)
    else:
        # Or to localized FrontPage
        url = wikiutil.getFrontPage(request).url(request)
    url = request.getQualifiedURL(url)
    return abort(redirect(url))
Example #14
0
def redirect_last_visited(request):
    pagetrail = request.user.getTrail()
    if pagetrail:
        # Redirect to last page visited
        last_visited = pagetrail[-1]
        wikiname, pagename = wikiutil.split_interwiki(last_visited)
        if wikiname != request.cfg.interwikiname and wikiname != 'Self':
            wikitag, wikiurl, wikitail, error = wikiutil.resolve_interwiki(request, wikiname, pagename)
            url = wikiurl + wikiutil.quoteWikinameURL(wikitail)
        else:
            url = Page(request, pagename).url(request)
    else:
        # Or to localized FrontPage
        url = wikiutil.getFrontPage(request).url(request)
    url = request.getQualifiedURL(url)
    return abort(redirect(url))
Example #15
0
    def logo(self):
        """ Assemble logo with link to front page

        The logo contain an image and or text or any html markup the
        admin inserted in the config file. Everything it enclosed inside
        a div with id="logo".
        
        @rtype: unicode
        @return: logo html
        """
        html = u''
        if self.cfg.logo_string:
            pagename = wikiutil.getFrontPage(self.request).page_name
            pagename = wikiutil.quoteWikinameURL(pagename)
            logo = wikiutil.link_tag(self.request, pagename, self.cfg.logo_string)
            html = u'''<div id="logo">%s</div>''' % logo
        return html
Example #16
0
    def _verify_endpoint_identity(self, identity):
        """
           Verify that the given identity matches the current endpoint.

           We always serve out /UserName?action=... for the UserName
           OpenID and this is pure paranoia to make sure it is that way
           on incoming data.

           Also verify that the given identity is allowed to have an OpenID.
        """
        request = self.request
        cfg = request.cfg

        # we can very well split on the last slash since usernames
        # must not contain slashes
        base, received_name = identity.rsplit('/', 1)
        check_name = received_name

        if received_name == '':
            pg = wikiutil.getFrontPage(request)
            if pg:
                received_name = pg.page_name
                check_name = received_name
                if 'openid.user' in pg.pi:
                    received_name = pg.pi['openid.user']

        # some sanity checking
        # even if someone goes to http://johannes.sipsolutions.net/
        # we'll serve out http://johannes.sipsolutions.net/JohannesBerg?action=serveopenid
        # (if JohannesBerg is set as page_front_page)
        # For the #OpenIDUser PI, we need to allow the page that includes the PI,
        # hence use check_name here (see above for how it is assigned)
        fullidentity = '/'.join([base, check_name])
        thisurl = request.getQualifiedURL(request.page.url(request))
        if not thisurl == fullidentity:
            return False

        # again, we never put an openid.server link on this page...
        # why are they here?
        openid_group_name = cfg.openid_server_restricted_users_group
        if openid_group_name and received_name not in request.groups.get(
                openid_group_name, []):
            return False

        return True
Example #17
0
    def _verify_endpoint_identity(self, identity):
        """
           Verify that the given identity matches the current endpoint.

           We always serve out /UserName?action=... for the UserName
           OpenID and this is pure paranoia to make sure it is that way
           on incoming data.

           Also verify that the given identity is allowed to have an OpenID.
        """
        request = self.request
        cfg = request.cfg

        # we can very well split on the last slash since usernames
        # must not contain slashes
        base, received_name = rsplit(identity, '/', 1)
        check_name = received_name

        if received_name == '':
            pg = wikiutil.getFrontPage(request)
            if pg:
                received_name = pg.page_name
                check_name = received_name
                if 'openid.user' in pg.pi:
                    received_name = pg.pi['openid.user']

        # some sanity checking
        # even if someone goes to http://johannes.sipsolutions.net/
        # we'll serve out http://johannes.sipsolutions.net/JohannesBerg?action=serveopenid
        # (if JohannesBerg is set as page_front_page)
        # For the #OpenIDUser PI, we need to allow the page that includes the PI,
        # hence use check_name here (see above for how it is assigned)
        fullidentity = '/'.join([base, check_name])
        thisurl = request.getQualifiedURL(request.page.url(request))
        if not thisurl == fullidentity:
            return False

        # again, we never put an openid.server link on this page...
        # why are they here?
        if cfg.openid_server_restricted_users_group:
            request.dicts.addgroup(request, cfg.openid_server_restricted_users_group)
            if not request.dicts.has_member(cfg.openid_server_restricted_users_group, received_name):
                return False

        return True
    def logo(self):
        """ Assemble logo with link to front page
        Using <a> tag only instead of wrapping with div

        The logo may contain an image and or text or any html markup.
        Just note that everything is enclosed in <a> tag.

        @rtype: unicode
        @return: logo html
        """
        html = u''
        if self.cfg.logo_string:
            page = wikiutil.getFrontPage(self.request)
            html = page.link_to_raw(self.request, self.cfg.logo_string, css_class="navbar-brand")
            html = u'''
          <div class="navbar-brand-wrapper">
            %s
          </div>
          ''' % html
        return html
Example #19
0
    def header(self, d, **kw):
        """ Assemble wiki header

        @param d: parameter dictionary
        @rtype: unicode
        @return: page header html
        """
        html = [
            # Pre header custom html
            self.emit_custom_html(self.cfg.page_header1),
            self.username(d),
            # '<div id="header">%s</div>' % self.logo(), 
            u'<div id="header"><div id="logo">%s %s</div></div>' % (wikiutil.getFrontPage(self.request).link_to_raw(self.request, 'PineTri'),  u'오라클모니터링/튜닝도구'),

            # Start of left panels. 
            u'<div id="sidebar">',

            self.menubarpanel(d),

            # Rick: rebuild below so we can put a cute little box around it:  self.navibar(d),
            self.navibarpanel(d),

            # Rick: rebuild below so we can put a cute little box around it:  self.searchform(d),
            self.searchpanel(d),

            # Rick: rebuild below so we can put a cute little box around it:  self.trail(d),
            self.trailpanel(d),
            
            # Rick: rebuild below so we can put a cute little box around it:  self.navibar(d),
            self.editbarpanel(d),
            u'</div>',

            # Post header custom html (not recommended)
            self.emit_custom_html(self.cfg.page_header2),

            # Start of page
            self.msg(d),
            self.startPage(),
            self.title_with_separators(d),
        ]
        return u'\n'.join(html)
    def menu(self, d):
        """
        Build dropdown menu html. Incompatible with original actionsMenu() method.

        Menu can be customized by adding a config variable 'memodump_menuoverride'.
        The variable will override the default menu set.
        Additional menu definitions are given via config method 'memodump_menu_def(request)'.
        See the code below or project wiki for details.

        @param d: parameter dictionary
        @rtype: string
        @return: menu html
        """
        request = self.request
        _ = request.getText
        rev = request.rev
        page = d['page']

        page_recent_changes = wikiutil.getLocalizedPage(request, u'RecentChanges')
        page_find_page = wikiutil.getLocalizedPage(request, u'FindPage')
        page_help_contents = wikiutil.getLocalizedPage(request, u'HelpContents')
        page_help_formatting = wikiutil.getLocalizedPage(request, u'HelpOnFormatting')
        page_help_wikisyntax = wikiutil.getLocalizedPage(request, u'HelpOnMoinWikiSyntax')
        page_title_index = wikiutil.getLocalizedPage(request, u'TitleIndex')
        page_word_index = wikiutil.getLocalizedPage(request, u'WordIndex')
        page_front_page = wikiutil.getFrontPage(request)
        page_sidebar = Page(request, request.getPragma('sidebar', u'SideBar'))
        quicklink = self.menuQuickLink(page)
        subscribe = self.menuSubscribe(page)

        try:
            menu = request.cfg.memodump_menuoverride
        except AttributeError:
            # default list of items in dropdown menu.
            # menu items are assembled in this order.
            # see wiki for detailed info on customization.
            menu = [
                '===== Navigation =====',
                'RecentChanges',
                'FindPage',
                'LocalSiteMap',
                '__separator__',
                '===== Help =====',
                'HelpContents',
                'HelpOnMoinWikiSyntax',
                '__separator__',
                '===== Display =====',
                'AttachFile',
                'info',
                'raw',
                'print',
                '__separator__',
                '===== Edit =====',
                'RenamePage',
                'DeletePage',
                'revert',
                'CopyPage',
                'Load',
                'Save',
                'Despam',
                'editSideBar',
                '__separator__',
                '===== User =====',
                'quicklink',
                'subscribe',
            ]

        # menu element definitions
        menu_def = {
            'raw': {
                # Title for this menu entry
                'title': _('Raw Text'),
                # href and args are for normal entries ('special': False), otherwise ignored.
                # 'href': Nonexistent or empty for current page
                'href': '',
                # 'args': {'query1': 'value1', 'query2': 'value2', }
                # Optionally specify this for <a href="href?query1=value1&query2=value2">
                # If href and args are both nonexistent or empty, key is automatically interpreted to be an action name
                # and href and args are automatically set.
                'args': '',
                # 'special' can be:
                #   'disabled', 'removed', 'separator' or 'header' for whatever they say,
                #    False, None or nonexistent for normal menu display.
                # 'separator' and 'header' are automatically removed when there are no entries to show among them.
                'special': False,
            },
            'print': {'title': _('Print View'), },
            'refresh': {
                'title': _('Delete Cache'),
                'special': not (self.memodumpIsAvailableAction(page, 'refresh') and page.canUseCache()) and 'removed',
            },
            'SpellCheck': {'title': _('Check Spelling'), },
            'RenamePage': {'title': _('Rename Page'), },
            'CopyPage':   {'title': _('Copy Page'), },
            'DeletePage': {'title': _('Delete Page'), },
            'LikePages':  {'title': _('Like Pages'), },
            'LocalSiteMap': {'title': _('Local Site Map'), },
            'MyPages':    {'title': _('My Pages'), },
            'SubscribeUser': {
                'title': _('Subscribe User'),
                'special': not (self.memodumpIsAvailableAction(page, 'SubscribeUser')
                                and request.user.may.admin(page.page_name)) and 'removed',
            },
            'Despam': {
                'title': _('Remove Spam'),
                'special': not (self.memodumpIsAvailableAction(page, 'Despam') and request.user.isSuperUser()) and 'removed',
            },
            'revert': {
                'title': _('Revert to this revision'),
                'special': not (self.memodumpIsAvailableAction(page, 'revert')
                                and rev
                                and request.user.may.revert(page.page_name)) and 'removed',
            },
            'PackagePages': {'title': _('Package Pages'), },
            'RenderAsDocbook': {'title': _('Render as Docbook'), },
            'SyncPages': {'title': _('Sync Pages'), },
            'AttachFile': {'title': _('Attachments'), },
            'quicklink': {
                'title': quicklink[1], 'args': dict(action=quicklink[0], rev=rev),
                'special': not quicklink[0] and 'removed',
            },
            'subscribe': {
                'title': subscribe[1], 'args': dict(action=subscribe[0], rev=rev),
                'special': not subscribe[0] and 'removed',
            },
            'info': {'title': _('Info'), },
# menu items not in menu_def will be assumed to be action names,
# and receive appropriate title, href, and args automatically.
#           'Load': {'title': _('Load'), },
#           'Save': {'title': _('Save'), },
            # menu decorations
            '__separator__':   {'title': _('------------------------'), 'special': 'separator', },
            '----':            {'title': _('------------------------'), 'special': 'separator', },
            '-----':           {'title': _('------------------------'), 'special': 'separator', },
            '------':          {'title': _('------------------------'), 'special': 'separator', },
            '-------':         {'title': _('------------------------'), 'special': 'separator', },
            '--------':        {'title': _('------------------------'), 'special': 'separator', },
            '---------':       {'title': _('------------------------'), 'special': 'separator', },
            '----------':      {'title': _('------------------------'), 'special': 'separator', },
            # header example
            '__title_navigation__': {'title': _('Navigation'), 'special': 'header', },
            # useful pages
            'RecentChanges':   {'title': page_recent_changes.page_name, 'href': page_recent_changes.url(request)},
            'FindPage':        {'title': page_find_page.page_name, 'href': page_find_page.url(request)},
            'HelpContents':    {'title': page_help_contents.page_name, 'href': page_help_contents.url(request)},
            'HelpOnFormatting': {'title': page_help_formatting.page_name, 'href': page_help_formatting.url(request)},
            'HelpOnMoinWikiSyntax': {'title': page_help_wikisyntax.page_name, 'href': page_help_wikisyntax.url(request)},
            'TitleIndex':      {'title': page_title_index.page_name, 'href': page_title_index.url(request)},
            'WordIndex':       {'title': page_word_index.page_name, 'href': page_word_index.url(request)},
            'FrontPage':       {'title': page_front_page.page_name, 'href': page_front_page.url(request)},
            'SideBar':         {'title': page_sidebar.page_name, 'href': page_sidebar.url(request)},
            'editSideBar': {
                'title': _('Edit SideBar'), 'href': page_sidebar.url(request),
                'args': dict(action='edit'),
                'special': not self.memodumpIsEditablePage(page_sidebar) and 'removed'
            },
        }

        # register state determining functions on request for use in config
        request.memodumpIsAvailableAction = self.memodumpIsAvailableAction
        request.memodumpIsEditablePage = self.memodumpIsEditablePage

        try:
            menu_def.update(request.cfg.memodump_menu_def(request))
        except AttributeError:
            pass

        compiled = self.menuCompile(d, menu, menu_def)
        menubody = self.menuRender(compiled)

        if menubody:
            html = u'''
            <li class="dropdown">
              <!-- Menu button -->
              <a href="#" class="menu-nav-menu dropdown-toggle" data-toggle="dropdown">
                %s<span class="padding"></span><span class="caret"></span>
              </a>
              <!-- Dropdown contents -->
              <ul class="dropdown-menu">
%s
              </ul>
            </li> <!-- /dropdown -->
''' % (_('Menu'), menubody)
        else:
            html = u''

        return html
Example #21
0
File: h1ds.py Project: dpretty/h1ds
    def send_title(self, text, **keywords):
        """
        Output the page header (and title).

        @param text: the title text
        @keyword page: the page instance that called us - using this is more efficient than using pagename..
        @keyword pagename: 'PageName'
        @keyword print_mode: 1 (or 0)
        @keyword editor_mode: 1 (or 0)
        @keyword media: css media type, defaults to 'screen'
        @keyword allow_doubleclick: 1 (or 0)
        @keyword html_head: additional <head> code
        @keyword body_attr: additional <body> attributes
        @keyword body_onload: additional "onload" JavaScript code
        """
        request = self.request
        _ = request.getText
        rev = request.rev

        if keywords.has_key('page'):
            page = keywords['page']
            pagename = page.page_name
        else:
            pagename = keywords.get('pagename', '')
            page = Page(request, pagename)
        if keywords.get('msg', ''):
            raise DeprecationWarning(
                "Using send_page(msg=) is deprecated! Use theme.add_msg() instead!"
            )
        scriptname = request.script_root

        # get name of system pages
        page_front_page = wikiutil.getFrontPage(request).page_name
        page_help_contents = wikiutil.getLocalizedPage(
            request, 'HelpContents').page_name
        page_title_index = wikiutil.getLocalizedPage(request,
                                                     'TitleIndex').page_name
        page_site_navigation = wikiutil.getLocalizedPage(
            request, 'SiteNavigation').page_name
        page_word_index = wikiutil.getLocalizedPage(request,
                                                    'WordIndex').page_name
        page_help_formatting = wikiutil.getLocalizedPage(
            request, 'HelpOnFormatting').page_name
        page_find_page = wikiutil.getLocalizedPage(request,
                                                   'FindPage').page_name
        home_page = wikiutil.getInterwikiHomePage(
            request
        )  # sorry theme API change!!! Either None or tuple (wikiname,pagename) now.
        page_parent_page = getattr(page.getParentPage(), 'page_name', None)

        # Prepare the HTML <head> element
        user_head = [request.cfg.html_head]

        # include charset information - needed for moin_dump or any other case
        # when reading the html without a web server
        user_head.append(
            '''<meta http-equiv="Content-Type" content="%s;charset=%s">\n''' %
            (page.output_mimetype, page.output_charset))

        meta_keywords = request.getPragma('keywords')
        meta_desc = request.getPragma('description')
        if meta_keywords:
            user_head.append('<meta name="keywords" content="%s">\n' %
                             wikiutil.escape(meta_keywords, 1))
        if meta_desc:
            user_head.append('<meta name="description" content="%s">\n' %
                             wikiutil.escape(meta_desc, 1))

        # search engine precautions / optimization:
        # if it is an action or edit/search, send query headers (noindex,nofollow):
        if request.query_string:
            user_head.append(request.cfg.html_head_queries)
        elif request.method == 'POST':
            user_head.append(request.cfg.html_head_posts)
        # we don't want to have BadContent stuff indexed:
        elif pagename in [
                'BadContent',
                'LocalBadContent',
        ]:
            user_head.append(request.cfg.html_head_posts)
        # if it is a special page, index it and follow the links - we do it
        # for the original, English pages as well as for (the possibly
        # modified) frontpage:
        elif pagename in [
                page_front_page,
                request.cfg.page_front_page,
                page_title_index,
                'TitleIndex',
                page_find_page,
                'FindPage',
                page_site_navigation,
                'SiteNavigation',
                'RecentChanges',
        ]:
            user_head.append(request.cfg.html_head_index)
        # if it is a normal page, index it, but do not follow the links, because
        # there are a lot of illegal links (like actions) or duplicates:
        else:
            user_head.append(request.cfg.html_head_normal)

        if 'pi_refresh' in keywords and keywords['pi_refresh']:
            user_head.append(
                '<meta http-equiv="refresh" content="%d;URL=%s">' %
                keywords['pi_refresh'])

        # output buffering increases latency but increases throughput as well
        output = []
        # later: <html xmlns=\"http://www.w3.org/1999/xhtml\">
        output.append("""\
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>%(title)s</title>
  <meta name="description" content="">
  <meta name="author" content="">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="%(static_url)scss/style.css">
  <script src="%(static_url)sjs/libs/moin.common.js"></script>
<script type="text/javascript">
<!--
var search_hint = "Search";
//-->
</script>
  <script src="%(static_url)sjs/libs/modernizr-2.0.6.min.js"></script>
""" % {
            'title': text,
            'static_url': django_settings.STATIC_URL
        })

        # Links
        output.append('<link rel="Start" href="%s">\n' %
                      request.href(page_front_page))
        if pagename:
            output.append(
                '<link rel="Alternate" title="%s" href="%s">\n' %
                (_('Wiki Markup'), request.href(pagename, action='raw')))
            output.append(
                '<link rel="Alternate" media="print" title="%s" href="%s">\n' %
                (_('Print View'), request.href(pagename, action='print')))

            # !!! currently disabled due to Mozilla link prefetching, see
            # http://www.mozilla.org/projects/netlib/Link_Prefetching_FAQ.html
            #~ all_pages = request.getPageList()
            #~ if all_pages:
            #~     try:
            #~         pos = all_pages.index(pagename)
            #~     except ValueError:
            #~         # this shopuld never happend in theory, but let's be sure
            #~         pass
            #~     else:
            #~         request.write('<link rel="First" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[0]))
            #~         if pos > 0:
            #~             request.write('<link rel="Previous" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos-1])))
            #~         if pos+1 < len(all_pages):
            #~             request.write('<link rel="Next" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos+1])))
            #~         request.write('<link rel="Last" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[-1])))

            if page_parent_page:
                output.append('<link rel="Up" href="%s">\n' %
                              request.href(page_parent_page))

        # write buffer because we call AttachFile
        request.write(''.join(output))
        output = []

        # XXX maybe this should be removed completely. moin emits all attachments as <link rel="Appendix" ...>
        # and it is at least questionable if this fits into the original intent of rel="Appendix".
        if pagename and request.user.may.read(pagename):
            from MoinMoin.action import AttachFile
            AttachFile.send_link_rel(request, pagename)

        output.extend([
            '<link rel="Search" href="%s">\n' % request.href(page_find_page),
            '<link rel="Index" href="%s">\n' % request.href(page_title_index),
            '<link rel="Glossary" href="%s">\n' %
            request.href(page_word_index),
            '<link rel="Help" href="%s">\n' %
            request.href(page_help_formatting),
        ])

        output.append("</head>\n")
        request.write(''.join(output))
        output = []

        # start the <body>
        bodyattr = []
        if keywords.has_key('body_attr'):
            bodyattr.append(' ')
            bodyattr.append(keywords['body_attr'])

        # Add doubleclick edit action
        if (pagename and keywords.get('allow_doubleclick', 0)
                and not keywords.get('print_mode', 0)
                and request.user.edit_on_doubleclick):
            if request.user.may.write(pagename):  # separating this gains speed
                url = page.url(request, {'action': 'edit'})
                bodyattr.append(''' ondblclick="location.href='%s'" ''' %
                                wikiutil.escape(url, True))

        # Set body to the user interface language and direction
        bodyattr.append(' %s' % self.ui_lang_attr())

        body_onload = keywords.get('body_onload', '')
        if body_onload:
            bodyattr.append(''' onload="%s"''' % body_onload)
        output.append('\n<body%s>\n' % ''.join(bodyattr))

        # Output -----------------------------------------------------------

        # If in print mode, start page div and emit the title
        if keywords.get('print_mode', 0):
            d = {
                'title_text': text,
                'page': page,
                'page_name': pagename or '',
                'rev': rev,
            }
            request.themedict = d
            output.append(self.startPage())
            output.append(self.interwiki(d))
            output.append(self.title(d))

        # In standard mode, emit theme.header
        else:
            exists = pagename and page.exists(includeDeleted=True)
            # prepare dict for theme code:
            d = {
                'theme': self.name,
                'script_name': scriptname,
                'title_text': text,
                'logo_string': request.cfg.logo_string,
                'site_name': request.cfg.sitename,
                'page': page,
                'rev': rev,
                'pagesize': pagename and page.size() or 0,
                # exists checked to avoid creation of empty edit-log for non-existing pages
                'last_edit_info': exists and page.lastEditInfo() or '',
                'page_name': pagename or '',
                'page_find_page': page_find_page,
                'page_front_page': page_front_page,
                'home_page': home_page,
                'page_help_contents': page_help_contents,
                'page_help_formatting': page_help_formatting,
                'page_parent_page': page_parent_page,
                'page_title_index': page_title_index,
                'page_word_index': page_word_index,
                'user_name': request.user.name,
                'user_valid': request.user.valid,
                'msg': self._status,
                'trail': keywords.get('trail', None),
                # Discontinued keys, keep for a while for 3rd party theme developers
                'titlesearch': 'use self.searchform(d)',
                'textsearch': 'use self.searchform(d)',
                'navibar': ['use self.navibar(d)'],
                'available_actions':
                ['use self.request.availableActions(page)'],
            }

            # add quoted versions of pagenames
            newdict = {}
            for key in d:
                if key.startswith('page_'):
                    if not d[key] is None:
                        newdict['q_' + key] = wikiutil.quoteWikinameURL(d[key])
                    else:
                        newdict['q_' + key] = None
            d.update(newdict)
            request.themedict = d

            # now call the theming code to do the rendering
            if keywords.get('editor_mode', 0):
                output.append(self.editorheader(d))
            else:
                output.append(self.header(d))

        # emit it
        request.write(''.join(output))
        output = []
        self._send_title_called = True
Example #22
0
    def header(self, d, **kw):
        """ Assemble wiki header

        @param d: parameter dictionary
        @rtype: unicode
        @return: page header html
        """

        page = d['page']
        html = [
            # Pre header custom html
            self.emit_custom_html(self.cfg.page_header1),

            u'<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">',
            u'<div class="container"><div class="navbar-header">',
            u'''<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>''',
            # self.title_with_separators(d),
            wikiutil.getFrontPage(self.request).link_to(self.request, text=self.cfg.sitename, rel='nofollow', css_class='navbar-brand'),
            u'</div>',#navbar-header
            u'<div class="navbar-collapse collapse">',
            self.navibar(d),
            self.searchform(d),
            u'</div>',#navbar-collapse
            u'</div>',#container
        #     u'''<div class="btn-group">
        # <div class="btn btn-small">
        # %s
        # </div>
        # <button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="#">
        # <span class="caret"></span>
        # </button>
        # <ul class="dropdown-menu">
        # <!-- dropdown menu links -->
        # %s
        # </ul>
        # </div>''' % (self.editorLink(d['page']), self.availableactions(d)),
        #     self.username(d),
            #self.actions(d),
            #self.interwiki(d),
            #self.titleEditorLink(page) if self.shouldShowEditbar(page) else '',
#             u'''<div class="btn-group">
#   <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
#     Action
#     <span class="caret"></span>
#   </a>
#   <ul class="dropdown-menu">
#     <!-- dropdown menu links -->
#     <li><a href="#">helloworld</a></li>
#     <li><a href="#">helloworld</a></li>
#     <li><a href="#">helloworld</a></li>
#   </ul>
# </div>''',
            # self.editbar(d),
            # u'<div class="row-fluid">',
            # u'<div class="span3">a</div>',
            # u'<div class="span9">',
            # u'</div>',
            # u'</div>',
            u'</div>',#navbar
            self.trail(d),
            #u'<hr id="pageline">',
            #u'<div id="pageline"><hr style="display:none;"></div>',
            # u'</div>',
            # u'<div class="bs-old-docs">',
            # u'<div class="container">',
            # u'<h3>',
            # self.title_with_separators(d),
            # u'</h3>',
            # u'<div class="container">',
            # u'</div>',
            u'<div class="page-header container"><h1>',
            self.title_with_separators(d),
            u'<small><span style="float:right; vertical-align:bottom;">',
            self.actions(d),
            u'</span></small>',
            u'</h1></div>',
            self.msg(d),
            # u'</div>',
            # u'</div>',

            u'<div class="container">',
            # Post header custom html (not recommended)
            self.emit_custom_html(self.cfg.page_header2),

            # Start of page
            self.startPage(),
        ]
        return u'\n'.join(html)
Example #23
0
    def navibar(self, d):
        """ Assemble the navibar

        Changed: * textlogo added as first entry of the navibar
                 * name attrib added for accesskeys
        """
        request = self.request
        _ = request.getText
        found = {} # pages we found. prevent duplicates
        items = [] # navibar items
        item = u'<li class="%s">%s</li>'
        current = d['page_name']

        # Add textlogo as first entry
        items.append(item % ('wikilink', self.logo()))
        found[wikiutil.getFrontPage(self.request).page_name] = 1
        found[_('FrontPage', formatted=False)] = 1

        # Process config navi_bar, eliminating dublicate to the FrontPage
        if request.cfg.navi_bar:
            for text in request.cfg.navi_bar:
                pagename, link = self.splitNavilink(text)
                if not pagename in found:
                    if pagename == current:
                        cls = 'wikilink current'
                    else:
                        cls = 'wikilink'
                    items.append(item % (cls, link))
                    found[pagename] = 1

        # Add user links to wiki links, eliminating duplicates.
        userlinks = request.user.getQuickLinks()
        for text in userlinks:
            # Split text without localization, user knows what he wants
            pagename, link = self.splitNavilink(text, localize=0)
            if not pagename in found:
                if pagename == current:
                    cls = 'userlink current'
                else:
                    cls = 'userlink'
                items.append(item % (cls, link))
                found[pagename] = 1

        # Add current page at end
        if not current in found:
            # Try..except for backwards compatibility of Moin versions only
            try:
                title = d['page'].split_title()
            except:
                title = d['page'].split_title(request)
            title = self.shortenPagename(title)
            link = d['page'].link_to(request, title, name="navbar_current_page")
            cls = 'current'
            items.append(item % (cls, link))

        # Assemble html
        items = u''.join(items)
        html = u'''
<ul id="navibar">
%s
</ul>
''' % items
        return html
Example #24
0
    def credits(self, d, **keywords):
        """ Create credits html from credits list
        
        Changed: If no credits are set, the default Moin credits are disabled and replaced by
                 a Creative Common License hint for the wiki content.
        """
        # Try..except for backwards compatibility of Moin versions only
        try:
            from MoinMoin.config.multiconfig import DefaultConfig
        except:
            from MoinMoin.multiconfig import DefaultConfig

        page_credits = self.cfg.page_credits
        cc_img = self.getImageURI('cc-wiki.png')
        page = wikiutil.getFrontPage(self.request)
        # Try..except for backwards compatibility of Moin versions only
        try:
            cc_src = page.link_to_raw(self.request, self.request.cfg.sitename)
        except:
            pagename = wikiutil.getFrontPage(self.request).page_name
            pagename = wikiutil.quoteWikinameURL(pagename)
            cc_src = wikiutil.link_tag(self.request, pagename, self.request.cfg.sitename)
         
        _credits = u'''<div id="creditos">
<!--Creative Commons License-->
%s is licensed under a
<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0  License</a> 
<br>
<img alt="Creative Commons License" style="border-width: 0" src="%s"/>.
<!--/Creative Commons License-->
</div>
<!--
<rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
<Work rdf:about="">
    <license rdf:resource="http://creativecommons.org/licenses/by-sa/3.0/" />
</Work>
<License rdf:about="http://creativecommons.org/licenses/by-sa/3.0/">
    <permits rdf:resource="http://web.resource.org/cc/Reproduction"/>
    <permits rdf:resource="http://web.resource.org/cc/Distribution"/>
    <requires rdf:resource="http://web.resource.org/cc/Notice"/>
    <requires rdf:resource="http://web.resource.org/cc/Attribution"/>
    <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/>
    <requires rdf:resource="http://web.resource.org/cc/ShareAlike"/>
</License>
</rdf:RDF> -->''' % (cc_src, cc_img)

        if self.cfg.page_credits != DefaultConfig.page_credits:
            # Admin has set in wikiconfig.py new credits. Disable simplemente credits.
            _credits = ''
        else:
            # Admin hasn't set new credits. Throw away the default credits and display simplemente credits only.
            page_credits = []
        
        if isinstance(page_credits, (list, tuple)):
            if page_credits != []:
                items = ['<li>%s</li>' % i for i in page_credits]
                html = '<ul id="credits">\n%s\n</ul>%s\n' % (''.join(items), _credits)
            else:
                html = _credits
        else:
            # Old config using string, output as is
            html = page_credits + _credits
        return html
Example #25
0
    def title(self, d):
        """ Assemble breadcrumbs

        Changed: - ImmutablePage added to the end of page name if page is not writeable
                 - Virtual page of an action causes a new crumb and is appended to the
                   end (i.e. to the underlying current wikipage)
        
        @param d: parameter dictionary
        @rtype: string
        @return: title html
        """
        _ = self.request.getText
        content = []
        curpage = ''
        segments = d['page_name'].split('/')
        for s in segments[:-1]:
            curpage += s
            if curpage == s:
                content.append("%s" % Page(self.request, curpage).link_to(self.request, s))
            else:
                content.append(" / %s" % Page(self.request, curpage).link_to(self.request, s))
            curpage += '/'

        link_text = segments[-1]
        # Check whether an action has created a virtual page. No backlinking in this case.
        if d['title_text'] == d['page_name']: 
            link_title = _('Click to do a full-text search for this title')
            link_query = {
                'action': 'fullsearch',
                'value': 'linkto:"%s"' % d['page_name'],
                'context': '180', }
            link = d['page'].link_to(self.request, link_text, querystr=link_query, title=link_title, css_class='backlink', rel='nofollow')
        else:
            curpage += link_text
            link = Page(self.request, curpage).link_to(self.request, link_text)

        # Show interwiki?
        if self.cfg.interwikiname and self.cfg.show_interwiki:
            page = wikiutil.getFrontPage(self.request)
            text = self.request.cfg.interwikiname or 'Self'
            interwiki = page.link_to(self.request, text=text, rel='nofollow')
            content.insert(1, '%s : ' % interwiki)

        if len(segments) > 1:
            content.append(' / %s' % link)
        else:
            content.append('%s' % link)
            
        # Check whether page ist writeable. If not: add a note on that
        if not (d['page'].isWritable() and self.request.user.may.write(d['page'].page_name)):
            content.append(' (%s)' % _('Immutable Page', formatted=False))

        # Check whether an action has created a virtual page e.g. "Diff for..". Add this virtual page to the end of the breadcrumb navigation.
        if d['title_text'] != d['page_name']: 
            content.append(' / %s' % wikiutil.escape(d['title_text']))

        html = '''
<p id="pagelocation">
%s
</p>
''' % "".join(content)
        return html
Example #26
0
    def send_title(self, text, **keywords):
        """
        An almost verbatim copy of MoinMoin.theme.__init__.ThemeBase.send_title, 
        that replaces hard coded HTML string template with Jinja2. 
        """
        req = self.request
        _ = req.getText
        rev = req.rev

        if keywords.has_key('page'):
            page = keywords['page']
            pagename = page.page_name
        else:
            pagename = keywords.get('pagename', '')
            page = Page(req, pagename)
        if keywords.get('msg', ''):
            raise DeprecationWarning("Using send_page(msg=) is deprecated! "
                                     "Use theme.add_msg() instead!")
        scriptname = req.script_root

        # get name of system pages
        page_front_page = wikiutil.getFrontPage(req).page_name
        page_help_contents = getLocalizedPage(req, 'HelpContents').page_name
        page_title_index = getLocalizedPage(req, 'TitleIndex').page_name
        page_site_navigation = getLocalizedPage(req,
                                                'SiteNavigation').page_name
        page_word_index = getLocalizedPage(req, 'WordIndex').page_name
        page_help_formatting = getLocalizedPage(req,
                                                'HelpOnFormatting').page_name
        page_find_page = getLocalizedPage(req, 'FindPage').page_name
        home_page = wikiutil.getInterwikiHomePage(req)
        page_parent_page = getattr(page.getParentPage(), 'page_name', None)

        # set content_type, including charset, so web server doesn't touch it:
        req.content_type = "text/html; charset=%s" % config.charset

        meta_keywords = req.getPragma('keywords') or ""
        meta_description = req.getPragma('description') or ""

        rss_link = self.rsslink({'page': page})
        universal_edit_button = self.universal_edit_button({'page': page})
        stylesheets = self.html_stylesheets({
            'print_media':
            keywords.get('print_mode', False),
            'media':
            keywords.get('media', 'screen')
        })
        gui_edit_link = self.guiEditorScript({'page': page})

        context = {
            'title':
            Markup(wikiutil.escape(text)),
            'sitename':
            wikiutil.escape(req.cfg.html_pagetitle or req.cfg.sitename),
            'charset':
            page.output_charset,
            'meta_keywords':
            wikiutil.escape(meta_keywords, 1),
            'meta_description':
            wikiutil.escape(meta_description, 1),
            'robots':
            None,  # might be "index", "noindex", or None
            'refresh_seconds':
            None,
            'refresh_url':
            None,
            'static_base':
            "%s/%s/" % (self.cfg.url_prefix_static, self.name),
            'stylesheets':
            stylesheets,
            'rss_link_title':
            rss_link[0],
            'rss_link_href':
            rss_link[1],
            'universal_edit_button_title':
            universal_edit_button[0],
            'universal_edit_button_href':
            universal_edit_button[1],
            'common_js':
            '%s/common/js/%s.js' % (req.cfg.url_prefix_static, 'common'),
            'search_hint':
            req.getText('Search'),
            'gui_editor_link_href':
            gui_edit_link[0],
            'gui_editor_link_text':
            gui_edit_link[1],
            'extra_html_head':
            Markup(keywords.get('html_head', '')),
            'page_start_href':
            req.href(page_front_page),
            'page_alternate_title':
            None,
            'page_alternate_href':
            '',
            'print_alternate_title':
            None,
            'print_alternate_href':
            '',
            'page_up_href':
            None,
        }

        # search engine precautions / optimization:
        # if it is an action or edit/search, send query headers (noindex,nofollow):
        if req.query_string or req.method == 'POST':
            context['robots'] = "noindex"
        # we don't want to have BadContent stuff indexed:
        elif pagename in [
                'BadContent',
                'LocalBadContent',
        ]:
            context['robots'] = "noindex"
        # if it is a special page, index it and follow the links - we do it
        # for the original, English pages as well as for (the possibly
        # modified) frontpage:
        elif pagename in [
                page_front_page,
                req.cfg.page_front_page,
                page_title_index,
                'TitleIndex',
                page_find_page,
                'FindPage',
                page_site_navigation,
                'SiteNavigation',
                'RecentChanges',
        ]:
            context['robots'] = "index"

        if 'pi_refresh' in keywords and keywords['pi_refresh']:
            context.update({
                'refresh_seconds': keywords['pi_refresh'][0],
                'refresh_url': keywords['pi_refresh'][1]
            })

        # Links
        if pagename:
            context.update({
                'page_alternate_title':
                _('Wiki Markup'),
                'page_alternate_href':
                page.url(req, querystr=dict(action='raw'))
            })
            context.update({
                'print_alternate_title':
                _('Print View'),
                'print_alternate_href':
                page.url(req, querystr=dict(action='print'))
            })
            if page_parent_page:
                context['page_up'] = req.href(page_parent_page)

        output = StringIO()
        write_f_onhold = req.write
        req.write = lambda s: output.write(s.encode('utf-8'))

        if pagename and req.user.may.read(pagename):
            from MoinMoin.action import AttachFile
            AttachFile.send_link_rel(req, pagename)

        context['attached_links'] = Markup(output.getvalue())
        req.write = write_f_onhold

        context['extra_links'] = [
            {
                'rel': "Search",
                'href': "%s" % req.href(page_find_page)
            },
            {
                'rel': "Index",
                'href': "%s" % req.href(page_title_index)
            },
            {
                'rel': "Glossary",
                'href': "%s" % req.href(page_word_index)
            },
            {
                'rel': "Help",
                'href': "%s" % req.href(page_help_formatting)
            },
        ]

        template = self.j2env.get_template('bits/head.html')
        output = template.render(context)
        req.write(output)

        output = []

        # start the <body>
        bodyattr = []
        if keywords.has_key('body_attr'):
            bodyattr.append(' ')
            bodyattr.append(keywords['body_attr'])

        # Set body to the user interface language and direction
        bodyattr.append(' %s' % self.ui_lang_attr())

        body_onload = keywords.get('body_onload', '')
        if body_onload:
            bodyattr.append(''' onload="%s"''' % body_onload)
        output.append('\n<body%s>\n' % ''.join(bodyattr))

        # Output -----------------------------------------------------------

        # If in print mode, start page div and emit the title
        if keywords.get('print_mode', 0):
            d = {
                'title_text': text,
                'page': page,
                'page_name': pagename or '',
                'rev': rev,
            }
            req.themedict = d
            output.append(self.startPage())
            output.append(self.interwiki(d))
            output.append(self.title(d))

        # In standard mode, emit theme.header
        else:
            exists = pagename and page.exists(includeDeleted=False)
            # prepare dict for theme code:
            d = {
                'theme': self.name,
                'script_name': scriptname,
                'title_text': text,
                'logo_string': req.cfg.logo_string,
                'site_name': req.cfg.sitename,
                'page': page,
                'rev': rev,
                'pagesize': pagename and page.size() or 0,
                # exists checked to avoid creation of empty edit-log for non-existing pages
                'last_edit_info': exists and page.lastEditInfo() or '',
                'page_name': pagename or '',
                'page_find_page': page_find_page,
                'page_front_page': page_front_page,
                'home_page': home_page,
                'page_help_contents': page_help_contents,
                'page_help_formatting': page_help_formatting,
                'page_parent_page': page_parent_page,
                'page_title_index': page_title_index,
                'page_word_index': page_word_index,
                'user_name': req.user.name,
                'user_valid': req.user.valid,
                'msg': self._status,
                'trail': keywords.get('trail', None),
                # Discontinued keys, keep for a while for 3rd party theme developers
                'titlesearch': 'use self.searchform(d)',
                'textsearch': 'use self.searchform(d)',
                'navibar': ['use self.navibar(d)'],
                'available_actions':
                ['use self.request.availableActions(page)'],
            }

            # add quoted versions of pagenames
            newdict = {}
            for key in d:
                if key.startswith('page_'):
                    if not d[key] is None:
                        newdict['q_' + key] = wikiutil.quoteWikinameURL(d[key])
                    else:
                        newdict['q_' + key] = None
            d.update(newdict)
            req.themedict = d

            # now call the theming code to do the rendering
            if keywords.get('editor_mode', 0):
                output.append(self.editorheader(d))
            else:
                output.append(self.header(d))

        # emit it
        req.write(''.join(output))
        output = []
        self._send_title_called = True
Example #27
0
    def get_menu(self, dic, user_items=None):
        req = self.request
        rev = req.rev
        _ = req.getText
        page = dic['page']

        page_recent_changes = getLocalizedPage(req, u'RecentChanges')
        page_find_page = getLocalizedPage(req, u'FindPage')
        page_help_contents = getLocalizedPage(req, u'HelpContents')
        page_help_formatting = getLocalizedPage(req, u'HelpOnFormatting')
        page_help_wikisyntax = getLocalizedPage(req, u'HelpOnMoinWikiSyntax')
        page_title_index = getLocalizedPage(req, u'TitleIndex')
        page_word_index = getLocalizedPage(req, u'WordIndex')
        page_front_page = wikiutil.getFrontPage(req)
        page_sidebar = Page(req, req.getPragma('sidebar', u'SideBar'))
        quicklink = self._menu_quick_link(page)
        subscribe = self._menu_subscribe(page)

        menu_cfg = {
            'raw': {
                # Title for this menu entry
                'title': _('Raw Text'),
                # href and args are for normal entries ('special': False),
                # otherwise ignored.
                # 'href': Nonexistent or empty for current page
                'href': '',
                # 'args': {'query1': 'value1', 'query2': 'value2', }
                # Optionally specify this for:
                #  <a href="href?query1=value1&query2=value2">
                # If href and args are both nonexistent or empty, key is
                # automatically interpreted to be an action name and href
                # and args are automatically set.
                'args': '',
                # 'special' can be:
                #   'disabled', 'removed', 'separator' or 'header' for
                #   whatever they say, False, None or nonexistent for
                #   normal menu display.
                # 'separator' and 'header' are automatically removed when
                # there are no entries to show among them.
                'special': False,
                'icon': 'fa fa-file-o'
            },
            'print': {
                'title': _('Print View'),
                'icon': 'fa fa-print'
            },
            'refresh': {
                'title':
                _('Delete Cache'),
                'special':
                not (self._is_available_action(page, 'refresh')
                     and page.canUseCache()) and 'removed',
                'icon':
                'fa fa-refresh'
            },
            'SpellCheck': {
                'title': _('Check Spelling'),
                'icon': 'fa fa-check-square-o'
            },
            'RenamePage': {
                'title': _('Rename Page'),
                'icon': 'fa fa-repeat'
            },
            'CopyPage': {
                'title': _('Copy Page'),
                'icon': 'fa fa-clone'
            },
            'DeletePage': {
                'title': _('Delete Page'),
                'icon': 'fa fa-trash'
            },
            'LikePages': {
                'title': _('Like Pages'),
                'icon': 'fa fa-thumbs-o-up'
            },
            'LocalSiteMap': {
                'title': _('Local Site Map'),
                'icon': 'fa fa-sitemap'
            },
            'MyPages': {
                'title': _('My Pages'),
                'icon': 'fa fa-newspaper-o'
            },
            'SubscribeUser': {
                'title':
                _('Subscribe User'),
                'special':
                not (self._is_available_action(page, 'SubscribeUser')
                     and req.user.may.admin(page.page_name)) and 'removed',
                'icon':
                'fa fa-envelope-o'
            },
            'Despam': {
                'title':
                _('Remove Spam'),
                'special':
                not (self._is_available_action(page, 'Despam')
                     and req.user.isSuperUser()) and 'removed',
                'icon':
                'fa fa-fire'
            },
            'revert': {
                'title':
                _('Revert to this revision'),
                'special':
                not (self._is_available_action(page, 'revert') and rev
                     and req.user.may.revert(page.page_name)) and 'removed',
                'icon':
                'fa fa-undo'
            },
            'PackagePages': {
                'title': _('Package Pages'),
                'icon': 'fa fa-suitcase'
            },
            'RenderAsDocbook': {
                'title': _('Render as Docbook'),
                'icon': 'fa fa-book'
            },
            'SyncPages': {
                'title': _('Sync Pages'),
                'icon': 'fa fa-refresh'
            },
            'AttachFile': {
                'title': _('Attachments'),
                'icon': 'fa fa-paperclip'
            },
            'quicklink': {
                'title': quicklink[1] or _('Quick Link'),
                'args': dict(action=quicklink[0], rev=rev),
                'special': not quicklink[0] and 'removed',
                'icon': 'fa fa-share'
            },
            'subscribe': {
                'title': subscribe[1] or _('Subscribe'),
                'args': dict(action=subscribe[0], rev=rev),
                'special': not subscribe[0] and 'removed',
                'icon': 'fa fa-envelope'
            },
            'info': {
                'title': _('Info'),
                'icon': 'fa fa-info-circle'
            },
            'Load': {
                'title': _('Load'),
                'icon': 'fa fa-upload'
            },
            'Save': {
                'title': _('Save'),
                'icon': 'fa fa-download'
            },
            # useful pages
            'RecentChanges': {
                'title': page_recent_changes.page_name,
                'href': page_recent_changes.url(req),
                'icon': 'fa fa-clock-o'
            },
            'FindPage': {
                'title': page_find_page.page_name,
                'href': page_find_page.url(req),
                'icon': 'fa fa-search'
            },
            'HelpContents': {
                'title': page_help_contents.page_name,
                'href': page_help_contents.url(req),
                'icon': 'fa fa-question-circle'
            },
            'HelpOnFormatting': {
                'title': page_help_formatting.page_name,
                'href': page_help_formatting.url(req),
                'icon': 'fa fa-question-circle'
            },
            'HelpOnMoinWikiSyntax': {
                'title': page_help_wikisyntax.page_name,
                'href': page_help_wikisyntax.url(req),
                'icon': 'fa fa-question-circle'
            },
            'TitleIndex': {
                'title': page_title_index.page_name,
                'href': page_title_index.url(req),
                'icon': 'fa fa-list'
            },
            'WordIndex': {
                'title': page_word_index.page_name,
                'href': page_word_index.url(req),
                'icon': 'fa fa-list'
            },
            'FrontPage': {
                'title': page_front_page.page_name,
                'href': page_front_page.url(req),
                'icon': 'fa fa-home'
            },
            'SideBar': {
                'title': page_sidebar.page_name,
                'href': page_sidebar.url(req),
                'icon': 'fa fa-columns'
            },
            'editSideBar': {
                'title': _('Edit SideBar'),
                'href': page_sidebar.url(req),
                'args': dict(action='edit'),
                'special': (not self._is_editable_page(page_sidebar)
                            and 'removed'),
                'icon': 'fa fa-columns'
            },
        }

        output = []

        for group in self._menu:
            _group = {'label': _(group['label']), 'entries': []}
            for entry in group['entries']:
                data = menu_cfg.get(entry)
                if data:
                    if data.get('special'):
                        _group['entries'].append(data)
                    else:
                        if not (data.get('href') or data.get('args')):
                            # It's an Action.
                            if self._is_available_action(page, entry):
                                query = self._get_query_string({
                                    'action': entry,
                                    'rev': rev
                                })
                                _entry = {
                                    'title': data.get('title', _(entry)),
                                    'href': u'%s%s' % (page.url(req), query),
                                    'icon': data['icon'],
                                }
                                _group['entries'].append(_entry)
                            else:
                                continue
                        else:
                            # A normal menu entry.
                            if not data.get('href'):
                                data['href'] = page.url(req)
                            if data.get('args'):
                                data['href'] = u'%s%s' % (
                                    data['href'],
                                    self._get_query_string(data['args']))
                            _group['entries'].append({
                                'title':
                                data.get('title', _(entry)),
                                'href':
                                data['href'],
                                'icon':
                                data['icon'],
                            })
            if _group['label'] == 'User':
                for k in user_items.keys():
                    if user_items[k]:
                        _group['entries'].append({
                            'title':
                            _(user_items[k]['title']),
                            'href':
                            user_items[k]['url'],
                            'icon':
                            user_items[k]['icon']
                        })
            output.append(_group)
        return output
Example #28
0
			return name not in page_filter
		filter = name_filter

	# get list of all pages in wiki
	# hide underlay dir temporarily
	underlay_dir = request.rootpage.cfg.data_underlay_dir
	print(underlay_dir)
	request.rootpage.cfg.data_underlay_dir = None
	pages = request.rootpage.getPageList(user = '', exists = not convert_attic, filter = filter)
	pages = dict(zip(pages, pages))
	# restore
	request.rootpage.cfg.data_underlay_dir = underlay_dir

	# insert frontpage,
	# so that MoinMoin frontpage gets saved as DokuWiki frontpage based on their configs
	frontpage = wikiutil.getFrontPage(request)
	if pages.has_key(frontpage.page_name):
		del pages[frontpage.page_name]
	pages[dw.getId()] = frontpage.page_name

converted = 0
for output, pagename in pages.items():
	page = Page(request, pagename)
	res = convertfile(page, output = output, overwrite = overwrite)
	if res != None:
		converted += 1
print "Processed %d files, converted %d" % (len(pages), converted)

if redirect_conf:
	print "Writing %s: %d items" % (redirect_conf, len(redirect_map))
	content = [u"\t".join(pair) for pair in redirect_map.items()]
Example #29
0
    def send_title(self, text, **keywords):
        """ Override
        Output the page header (and title).

        @param text: the title text
        @keyword page: the page instance that called us - using this is more efficient than using pagename..
        @keyword pagename: 'PageName'
        @keyword print_mode: 1 (or 0)
        @keyword editor_mode: 1 (or 0)
        @keyword media: css media type, defaults to 'screen'
        @keyword allow_doubleclick: 1 (or 0)
        @keyword html_head: additional <head> code
        @keyword body_attr: additional <body> attributes
        @keyword body_onload: additional "onload" JavaScript code
        """
        request = self.request
        _ = request.getText
        rev = request.rev

        if keywords.has_key('page'):
            page = keywords['page']
            pagename = page.page_name
        else:
            pagename = keywords.get('pagename', '')
            page = Page(request, pagename)
        if keywords.get('msg', ''):
            raise DeprecationWarning("Using send_page(msg=) is deprecated! Use theme.add_msg() instead!")
        scriptname = request.script_root

        # get name of system pages
        page_front_page = wikiutil.getFrontPage(request).page_name
        page_help_contents = wikiutil.getLocalizedPage(request, 'HelpContents').page_name
        page_title_index = wikiutil.getLocalizedPage(request, 'TitleIndex').page_name
        page_site_navigation = wikiutil.getLocalizedPage(request, 'SiteNavigation').page_name
        page_word_index = wikiutil.getLocalizedPage(request, 'WordIndex').page_name
        page_help_formatting = wikiutil.getLocalizedPage(request, 'HelpOnFormatting').page_name
        page_find_page = wikiutil.getLocalizedPage(request, 'FindPage').page_name
        home_page = wikiutil.getInterwikiHomePage(request) # sorry theme API change!!! Either None or tuple (wikiname,pagename) now.
        page_parent_page = getattr(page.getParentPage(), 'page_name', None)

        # set content_type, including charset, so web server doesn't touch it:
        request.content_type = "text/html; charset=%s" % (config.charset, )

        # Prepare the HTML <head> element
        user_head = [request.cfg.html_head]

        # include charset information - needed for moin_dump or any other case
        # when reading the html without a web server
        user_head.append('''<meta charset="%s">\n''' % (page.output_charset))

        meta_keywords = request.getPragma('keywords')
        meta_desc = request.getPragma('description')
        if meta_keywords:
            user_head.append('<meta name="keywords" content="%s">\n' % wikiutil.escape(meta_keywords, 1))
        if meta_desc:
            user_head.append('<meta name="description" content="%s">\n' % wikiutil.escape(meta_desc, 1))

        #  add meta statement if user has doubleclick on edit turned on or it is default
        if (pagename and keywords.get('allow_doubleclick', 0) and
            not keywords.get('print_mode', 0) and
            request.user.edit_on_doubleclick):
            if request.user.may.write(pagename): # separating this gains speed
                user_head.append('<meta name="edit_on_doubleclick" content="%s">\n' % (request.script_root or '/'))

        # search engine precautions / optimization:
        # if it is an action or edit/search, send query headers (noindex,nofollow):
        if request.query_string:
            user_head.append(request.cfg.html_head_queries)
        elif request.method == 'POST':
            user_head.append(request.cfg.html_head_posts)
        # we don't want to have BadContent stuff indexed:
        elif pagename in ['BadContent', 'LocalBadContent', ]:
            user_head.append(request.cfg.html_head_posts)
        # if it is a special page, index it and follow the links - we do it
        # for the original, English pages as well as for (the possibly
        # modified) frontpage:
        elif pagename in [page_front_page, request.cfg.page_front_page,
                          page_title_index, 'TitleIndex',
                          page_find_page, 'FindPage',
                          page_site_navigation, 'SiteNavigation',
                          'RecentChanges', ]:
            user_head.append(request.cfg.html_head_index)
        # if it is a normal page, index it, but do not follow the links, because
        # there are a lot of illegal links (like actions) or duplicates:
        else:
            user_head.append(request.cfg.html_head_normal)

        if 'pi_refresh' in keywords and keywords['pi_refresh']:
            user_head.append('<meta http-equiv="refresh" content="%d;URL=%s">' % keywords['pi_refresh'])

        # output buffering increases latency but increases throughput as well
        output = []
        output.append("""\
<!DOCTYPE html>
<html lang="%s">
<head>
%s
<meta name="viewport" content="width=device-width, initial-scale=1.0">
%s
%s
""" % (
            self.cfg.language_default,
            ''.join(user_head),
            self.html_head({
                'page': page,
                'title': text,
                'sitename': request.cfg.html_pagetitle or request.cfg.sitename,
                'print_mode': keywords.get('print_mode', False),
                'media': keywords.get('media', 'screen'),
            }),
            keywords.get('html_head', ''),
        ))

        output.append("</head>\n")
        request.write(''.join(output))
        output = []

        # start the <body>
        bodyattr = []
        if keywords.has_key('body_attr'):
            bodyattr.append(' ')
            bodyattr.append(keywords['body_attr'])

        # Set body to the user interface language and direction
        bodyattr.append(' %s' % self.ui_lang_attr())

        body_onload = keywords.get('body_onload', '')
        if body_onload:
            bodyattr.append(''' onload="%s"''' % body_onload)
        output.append('\n<body%s>\n' % ''.join(bodyattr))

        # Output -----------------------------------------------------------

        # If in print mode, start page div and emit the title
        if keywords.get('print_mode', 0):
            d = {
                'title_text': text,
                'page': page,
                'page_name': pagename or '',
                'rev': rev,
            }
            request.themedict = d
            output.append(self.startPage())
            output.append(self.interwiki(d))
            output.append(self.title(d))

        # In standard mode, emit theme.header
        else:
            exists = pagename and page.exists(includeDeleted=True)
            # prepare dict for theme code:
            d = {
                'theme': self.name,
                'script_name': scriptname,
                'title_text': text,
                'logo_string': request.cfg.logo_string,
                'site_name': request.cfg.sitename,
                'page': page,
                'rev': rev,
                'pagesize': pagename and page.size() or 0,
                # exists checked to avoid creation of empty edit-log for non-existing pages
                'last_edit_info': exists and page.lastEditInfo() or '',
                'page_name': pagename or '',
                'page_find_page': page_find_page,
                'page_front_page': page_front_page,
                'home_page': home_page,
                'page_help_contents': page_help_contents,
                'page_help_formatting': page_help_formatting,
                'page_parent_page': page_parent_page,
                'page_title_index': page_title_index,
                'page_word_index': page_word_index,
                'user_name': request.user.name,
                'user_valid': request.user.valid,
                'msg': self._status,
                'trail': keywords.get('trail', None),
                # Discontinued keys, keep for a while for 3rd party theme developers
                'titlesearch': 'use self.searchform(d)',
                'textsearch': 'use self.searchform(d)',
                'navibar': ['use self.navibar(d)'],
                'available_actions': ['use self.request.availableActions(page)'],
            }

            # add quoted versions of pagenames
            newdict = {}
            for key in d:
                if key.startswith('page_'):
                    if not d[key] is None:
                        newdict['q_'+key] = wikiutil.quoteWikinameURL(d[key])
                    else:
                        newdict['q_'+key] = None
            d.update(newdict)
            request.themedict = d

            # now call the theming code to do the rendering
            if keywords.get('editor_mode', 0):
                output.append(self.editorheader(d))
            else:
                output.append(self.header(d))

        # emit it
        request.write(''.join(output))
        output = []
        self._send_title_called = True
Example #30
0
    # get list of all pages in wiki
    # hide underlay dir temporarily
    underlay_dir = request.rootpage.cfg.data_underlay_dir
    print(underlay_dir)
    request.rootpage.cfg.data_underlay_dir = None
    pages = request.rootpage.getPageList(user='',
                                         exists=not convert_attic,
                                         filter=filter)
    pages = dict(zip(pages, pages))
    # restore
    request.rootpage.cfg.data_underlay_dir = underlay_dir

    # insert frontpage,
    # so that MoinMoin frontpage gets saved as DokuWiki frontpage based on their configs
    frontpage = wikiutil.getFrontPage(request)
    if pages.has_key(frontpage.page_name):
        del pages[frontpage.page_name]
    pages[dw.getId()] = frontpage.page_name

print "--------------------------------------------------"
for output, pagename in pages.items():
    print " - %s" % pagename
print "--------------------------------------------------"

converted = 0
for output, pagename in pages.items():
    page = Page(request, pagename)
    res = convertfile(page, output=output, overwrite=overwrite)
    if res != None:
        converted += 1
Example #31
0
File: h1ds.py Project: dpretty/h1ds
    def send_title(self, text, **keywords):
        """
        Output the page header (and title).

        @param text: the title text
        @keyword page: the page instance that called us - using this is more efficient than using pagename..
        @keyword pagename: 'PageName'
        @keyword print_mode: 1 (or 0)
        @keyword editor_mode: 1 (or 0)
        @keyword media: css media type, defaults to 'screen'
        @keyword allow_doubleclick: 1 (or 0)
        @keyword html_head: additional <head> code
        @keyword body_attr: additional <body> attributes
        @keyword body_onload: additional "onload" JavaScript code
        """
        request = self.request
        _ = request.getText
        rev = request.rev

        if keywords.has_key('page'):
            page = keywords['page']
            pagename = page.page_name
        else:
            pagename = keywords.get('pagename', '')
            page = Page(request, pagename)
        if keywords.get('msg', ''):
            raise DeprecationWarning("Using send_page(msg=) is deprecated! Use theme.add_msg() instead!")
        scriptname = request.script_root

        # get name of system pages
        page_front_page = wikiutil.getFrontPage(request).page_name
        page_help_contents = wikiutil.getLocalizedPage(request, 'HelpContents').page_name
        page_title_index = wikiutil.getLocalizedPage(request, 'TitleIndex').page_name
        page_site_navigation = wikiutil.getLocalizedPage(request, 'SiteNavigation').page_name
        page_word_index = wikiutil.getLocalizedPage(request, 'WordIndex').page_name
        page_help_formatting = wikiutil.getLocalizedPage(request, 'HelpOnFormatting').page_name
        page_find_page = wikiutil.getLocalizedPage(request, 'FindPage').page_name
        home_page = wikiutil.getInterwikiHomePage(request) # sorry theme API change!!! Either None or tuple (wikiname,pagename) now.
        page_parent_page = getattr(page.getParentPage(), 'page_name', None)

        # Prepare the HTML <head> element
        user_head = [request.cfg.html_head]

        # include charset information - needed for moin_dump or any other case
        # when reading the html without a web server
        user_head.append('''<meta http-equiv="Content-Type" content="%s;charset=%s">\n''' % (page.output_mimetype, page.output_charset))

        meta_keywords = request.getPragma('keywords')
        meta_desc = request.getPragma('description')
        if meta_keywords:
            user_head.append('<meta name="keywords" content="%s">\n' % wikiutil.escape(meta_keywords, 1))
        if meta_desc:
            user_head.append('<meta name="description" content="%s">\n' % wikiutil.escape(meta_desc, 1))

        # search engine precautions / optimization:
        # if it is an action or edit/search, send query headers (noindex,nofollow):
        if request.query_string:
            user_head.append(request.cfg.html_head_queries)
        elif request.method == 'POST':
            user_head.append(request.cfg.html_head_posts)
        # we don't want to have BadContent stuff indexed:
        elif pagename in ['BadContent', 'LocalBadContent', ]:
            user_head.append(request.cfg.html_head_posts)
        # if it is a special page, index it and follow the links - we do it
        # for the original, English pages as well as for (the possibly
        # modified) frontpage:
        elif pagename in [page_front_page, request.cfg.page_front_page,
                          page_title_index, 'TitleIndex',
                          page_find_page, 'FindPage',
                          page_site_navigation, 'SiteNavigation',
                          'RecentChanges', ]:
            user_head.append(request.cfg.html_head_index)
        # if it is a normal page, index it, but do not follow the links, because
        # there are a lot of illegal links (like actions) or duplicates:
        else:
            user_head.append(request.cfg.html_head_normal)

        if 'pi_refresh' in keywords and keywords['pi_refresh']:
            user_head.append('<meta http-equiv="refresh" content="%d;URL=%s">' % keywords['pi_refresh'])

        # output buffering increases latency but increases throughput as well
        output = []
        # later: <html xmlns=\"http://www.w3.org/1999/xhtml\">
        output.append("""\
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>%(title)s</title>
  <meta name="description" content="">
  <meta name="author" content="">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="%(static_url)scss/style.css">
  <script src="%(static_url)sjs/libs/moin.common.js"></script>
<script type="text/javascript">
<!--
var search_hint = "Search";
//-->
</script>
  <script src="%(static_url)sjs/libs/modernizr-2.0.6.min.js"></script>
""" %{'title':text, 'static_url':django_settings.STATIC_URL})

        # Links
        output.append('<link rel="Start" href="%s">\n' % request.href(page_front_page))
        if pagename:
            output.append('<link rel="Alternate" title="%s" href="%s">\n' % (
                    _('Wiki Markup'), request.href(pagename, action='raw')))
            output.append('<link rel="Alternate" media="print" title="%s" href="%s">\n' % (
                    _('Print View'), request.href(pagename, action='print')))

            # !!! currently disabled due to Mozilla link prefetching, see
            # http://www.mozilla.org/projects/netlib/Link_Prefetching_FAQ.html
            #~ all_pages = request.getPageList()
            #~ if all_pages:
            #~     try:
            #~         pos = all_pages.index(pagename)
            #~     except ValueError:
            #~         # this shopuld never happend in theory, but let's be sure
            #~         pass
            #~     else:
            #~         request.write('<link rel="First" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[0]))
            #~         if pos > 0:
            #~             request.write('<link rel="Previous" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos-1])))
            #~         if pos+1 < len(all_pages):
            #~             request.write('<link rel="Next" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos+1])))
            #~         request.write('<link rel="Last" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[-1])))

            if page_parent_page:
                output.append('<link rel="Up" href="%s">\n' % request.href(page_parent_page))

        # write buffer because we call AttachFile
        request.write(''.join(output))
        output = []

        # XXX maybe this should be removed completely. moin emits all attachments as <link rel="Appendix" ...>
        # and it is at least questionable if this fits into the original intent of rel="Appendix".
        if pagename and request.user.may.read(pagename):
            from MoinMoin.action import AttachFile
            AttachFile.send_link_rel(request, pagename)

        output.extend([
            '<link rel="Search" href="%s">\n' % request.href(page_find_page),
            '<link rel="Index" href="%s">\n' % request.href(page_title_index),
            '<link rel="Glossary" href="%s">\n' % request.href(page_word_index),
            '<link rel="Help" href="%s">\n' % request.href(page_help_formatting),
                      ])

        output.append("</head>\n")
        request.write(''.join(output))
        output = []

        # start the <body>
        bodyattr = []
        if keywords.has_key('body_attr'):
            bodyattr.append(' ')
            bodyattr.append(keywords['body_attr'])

        # Add doubleclick edit action
        if (pagename and keywords.get('allow_doubleclick', 0) and
            not keywords.get('print_mode', 0) and
            request.user.edit_on_doubleclick):
            if request.user.may.write(pagename): # separating this gains speed
                url = page.url(request, {'action': 'edit'})
                bodyattr.append(''' ondblclick="location.href='%s'" ''' % wikiutil.escape(url, True))

        # Set body to the user interface language and direction
        bodyattr.append(' %s' % self.ui_lang_attr())

        body_onload = keywords.get('body_onload', '')
        if body_onload:
            bodyattr.append(''' onload="%s"''' % body_onload)
        output.append('\n<body%s>\n' % ''.join(bodyattr))

        # Output -----------------------------------------------------------

        # If in print mode, start page div and emit the title
        if keywords.get('print_mode', 0):
            d = {
                'title_text': text,
                'page': page,
                'page_name': pagename or '',
                'rev': rev,
            }
            request.themedict = d
            output.append(self.startPage())
            output.append(self.interwiki(d))
            output.append(self.title(d))

        # In standard mode, emit theme.header
        else:
            exists = pagename and page.exists(includeDeleted=True)
            # prepare dict for theme code:
            d = {
                'theme': self.name,
                'script_name': scriptname,
                'title_text': text,
                'logo_string': request.cfg.logo_string,
                'site_name': request.cfg.sitename,
                'page': page,
                'rev': rev,
                'pagesize': pagename and page.size() or 0,
                # exists checked to avoid creation of empty edit-log for non-existing pages
                'last_edit_info': exists and page.lastEditInfo() or '',
                'page_name': pagename or '',
                'page_find_page': page_find_page,
                'page_front_page': page_front_page,
                'home_page': home_page,
                'page_help_contents': page_help_contents,
                'page_help_formatting': page_help_formatting,
                'page_parent_page': page_parent_page,
                'page_title_index': page_title_index,
                'page_word_index': page_word_index,
                'user_name': request.user.name,
                'user_valid': request.user.valid,
                'msg': self._status,
                'trail': keywords.get('trail', None),
                # Discontinued keys, keep for a while for 3rd party theme developers
                'titlesearch': 'use self.searchform(d)',
                'textsearch': 'use self.searchform(d)',
                'navibar': ['use self.navibar(d)'],
                'available_actions': ['use self.request.availableActions(page)'],
            }

            # add quoted versions of pagenames
            newdict = {}
            for key in d:
                if key.startswith('page_'):
                    if not d[key] is None:
                        newdict['q_'+key] = wikiutil.quoteWikinameURL(d[key])
                    else:
                        newdict['q_'+key] = None
            d.update(newdict)
            request.themedict = d

            # now call the theming code to do the rendering
            if keywords.get('editor_mode', 0):
                output.append(self.editorheader(d))
            else:
                output.append(self.header(d))

        # emit it
        request.write(''.join(output))
        output = []
        self._send_title_called = True
Example #32
0
    def header(self, dic, **kw):
        """ Assemble wiki header

        @param d: parameter dictionary
        @rtype: unicode
        @return: page header html
        """
        # html = [
        #     # Pre header custom html
        #     self.emit_custom_html(self.cfg.page_header1),

        #     # Header
        #     u'<div id="header">',
        #     self.logo(),
        #     self.searchform(dic),
        #     self.username(dic),
        #     u'<div id="locationline">',
        #     self.interwiki(dic),
        #     self.title(dic),
        #     u'</div>',
        #     self.trail(dic),
        #     self.navibar(dic),
        #     #u'<hr id="pageline">',
        #     u'<div id="pageline"><hr style="display:none;"></div>',
        #     self.msg(dic),
        #     self.editbar(dic),
        #     u'</div>',

        #     # Post header custom html (not recommended)
        #     self.emit_custom_html(self.cfg.page_header2),

        #     # Start of page
        #     self.startPage(),
        # ]

        frontpage = wikiutil.getFrontPage(self.request)
        findpage = getLocalizedPage(self.request, 'FindPage')
        helpcontents = getLocalizedPage(self.request, 'HelpContents')

        navigation_items = self.get_navigation_items(dic)
        trail_items = self.get_trail_items(
            dic, exclude=[i['name'] for i in navigation_items])

        form = self.request.values

        if self.cfg.logo_markup:
            logo_markup = Markup(self.cfg.logo_markup)
        else:
            logo_markup = Markup(self.cfg.logo_string)

        user_items = self.get_user_items(dic)
        context = {
            'page_name': dic['page'].page_name,
            'logo_markup': logo_markup,
            'logo_string': Markup(self.cfg.logo_string),
            'user_items': user_items,
            'homepage_url': self.request.href(frontpage.page_name),
            'findpage_url': self.request.href(findpage.page_name),
            'edit_button': self.get_edit_button(dic),
            'menu_label': self.request.getText('Menu'),
            'menu': self.get_menu(dic, user_items=user_items),
            'helpcontents_url': self.request.href(helpcontents.page_name),
            'navigation_items': navigation_items,
            'trail_items': trail_items,
            'search_form_action': self.request.href(dic['page'].page_name),
            'search_form_label': self.request.getText('Search'),
            'search_form_value': wikiutil.escape(form.get('value', ''), 1),
            'msgs': self.get_msgs(dic),
        }

        template = self.j2env.get_template('bits/body_header.html')
        output = template.render(context)
        return output