예제 #1
0
파일: explorer.py 프로젝트: kuj1pal/roswiki
    def username(self, d):
        """ Assemble the username link
        
        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request

        html = u''
        # 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
            html = (request.formatter.interwikilink(
                1, title=title, id="userhome", generated=True, *interwiki) +
                    request.formatter.text(name) +
                    request.formatter.interwikilink(
                        0, title=title, id="userhome", *interwiki))
        return html
예제 #2
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
예제 #3
0
파일: blank.py 프로젝트: happytk/moin
    def username(self, d):
        """ Assemble the username / userprefs link

        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request
        _ = request.getText

        userlinks = []

        text = ''
        # 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'))
            text = name

        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'))

            text = _("Login")

        if len(userlinks) > 0:
            userlinks_html = u'</li><li role="presentation">'.join(userlinks)
            return '<li>%s</li>' % userlinks_html
        else:
            return ''
예제 #4
0
 def wikiHomeLink(self):
     """ Return wiki markup usable as a link to the user homepage,
         it doesn't matter whether it already exists or not.
     """
     wikiname, pagename = wikiutil.getInterwikiHomePage(self._request, self.name)
     if wikiname == 'Self':
         if wikiutil.isStrictWikiname(self.name):
             markup = pagename
         else:
             markup = '[[%s]]' % pagename
     else:
         markup = '[[%s:%s]]' % (wikiname, pagename)
     return markup
예제 #5
0
파일: user.py 프로젝트: liugehao/wiki
 def wikiHomeLink(self):
     """ Return wiki markup usable as a link to the user homepage,
         it doesn't matter whether it already exists or not.
     """
     wikiname, pagename = wikiutil.getInterwikiHomePage(self._request, self.name)
     if wikiname == 'Self':
         if wikiutil.isStrictWikiname(self.name):
             markup = pagename
         else:
             markup = '[[%s]]' % pagename
     else:
         markup = '[[%s:%s]]' % (wikiname, pagename)
     return markup
예제 #6
0
	def username(self, d):
		"""
		Assemble the username / userprefs link

		@param d: parameter dictionary
		@rtype: unicode
		@return: username html
		"""
		request = self.request
		_ = request.getText

		userlinks = []
		# Add username/homepage link for registered users. We don't care
		# if it exists, the user can create it.
		if request.user.valid 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 class="nav pull-right">%s</div>' % userlinks_html
		return html
예제 #7
0
파일: editlog.py 프로젝트: steveyen/moingo
    def getInterwikiEditorData(self, request):
        """ Return a tuple of type id and string or Page object
            representing the user that did the edit.

            The type id is one of 'ip' (DNS or numeric IP), 'user' (user name)
            or 'homepage' (Page instance of user's homepage).
        """
        result = 'ip', request.cfg.show_hosts and self.hostname or ''
        if self.userid:
            if self.userid not in self._usercache:
                self._usercache[self.userid] = user.User(request, self.userid, auth_method="editlog:75")
            userdata = self._usercache[self.userid]
            if userdata.mailto_author and userdata.email:
                return ('email', userdata.email)
            elif userdata.name:
                interwiki = wikiutil.getInterwikiHomePage(request, username=userdata.name)
                if interwiki:
                    result = ('interwiki', interwiki)
        return result
예제 #8
0
파일: __init__.py 프로젝트: imosts/flume
    def username(self, d):
        """ Assemble the username / userprefs link
        
        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request
        _ = request.getText
        
        userlinks = []
        # Add username/homepage link for registered users. We don't care
        # if it exists, the user can create it.
        if request.user.valid 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
            prefpage = wikiutil.getSysPage(request, 'UserPreferences')
            userlinks.append(prefpage.link_to(request, text=_('Preferences', formatted=False),
                                              querystr={'action': 'userprefs'}, id="userprefs"))
           
        if request.cfg.show_login:
            if request.user.valid:
                userlinks.append(d['page'].link_to(request, text=_('Logout', formatted=False),
                                                   querystr={'action': 'logout', 'logout': 'logout'}, id="logout"))
            else:
                userlinks.append(d['page'].link_to(request, text=_("Login", formatted=False),
                                                   querystr={'action': 'login'}, id="login"))

        userlinks = [u'<li>%s</li>' % link for link in userlinks]
        html = u'<ul id="username">%s</ul>' % ''.join(userlinks)
        return html
예제 #9
0
파일: editlog.py 프로젝트: aahlad/soar
    def getInterwikiEditorData(self, request):
        """ Return a tuple of type id and string or Page object
            representing the user that did the edit.

            The type id is one of 'ip' (DNS or numeric IP), 'user' (user name)
            or 'homepage' (Page instance of user's homepage) or 'anon' ('').
        """
        result = 'anon', ''
        if request.cfg.show_hosts and self.hostname:
            result = 'ip', self.hostname
        if self.userid:
            if self.userid not in self._usercache:
                self._usercache[self.userid] = user.User(
                    request, self.userid, auth_method="editlog:75")
            userdata = self._usercache[self.userid]
            if userdata.mailto_author and userdata.email:
                return ('email', userdata.email)
            elif userdata.name:
                interwiki = wikiutil.getInterwikiHomePage(
                    request, username=userdata.name)
                if interwiki:
                    result = ('interwiki', interwiki)
        return result
예제 #10
0
파일: explorer.py 프로젝트: 130s/roswiki
    def username(self, d):
        """ Assemble the username link
        
        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request

        html = u''
        # 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
            html = (request.formatter.interwikilink(1, title=title, id="userhome", generated=True, *interwiki) +
                        request.formatter.text(name) +
                        request.formatter.interwikilink(0, title=title, id="userhome", *interwiki))
        return html
예제 #11
0
파일: user.py 프로젝트: imosts/flume
 def signature(self):
     """ Return user signature using markup
     
     Users sign with a link to their homepage, or with text if they
     don't have one. The text may be parsed as a link if it's using
     CamelCase. Visitors return their host address.
     
     TODO: The signature use wiki format only, for example, it will
     not create a link when using rst format. It will also break if
     we change wiki syntax.
     """
     if not self.name:
         return self.host()
     
     wikiname, pagename = wikiutil.getInterwikiHomePage(self._request,
                                                        self.name)
     if wikiname == 'Self':
         if not wikiutil.isStrictWikiname(self.name):
             markup = '["%s"]' % pagename
         else:
             markup = pagename
     else:
         markup = '%s:%s' % (wikiname, pagename.replace(" ","_")) 
     return markup
예제 #12
0
파일: MyPages.py 프로젝트: steveyen/moingo
def execute(pagename, request):
    from MoinMoin import wikiutil
    from MoinMoin.Page import Page

    _ = request.getText
    thispage = Page(request, pagename)

    if request.user.valid:
        username = request.user.name
    else:
        username = ''

    if not username:
        request.theme.add_msg(_('Please log in first.'), "error")
        return thispage.send_page()

    userhomewiki = request.cfg.user_homewiki
    if userhomewiki != 'Self' and userhomewiki != request.cfg.interwikiname:
        interwiki = wikiutil.getInterwikiHomePage(request, username=username)
        wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_interwiki(request, *interwiki)
        wikiurl = wikiutil.mapURL(request, wikiurl)
        homepageurl = wikiutil.join_wiki(wikiurl, wikitail)
        request.http_redirect('%s?action=MyPages' % homepageurl)

    homepage = Page(request, username)
    if not homepage.exists():
        request.theme.add_msg(_('Please first create a homepage before creating additional pages.'), "error")
        return homepage.send_page()

    pagecontent = _("""\
You can add some additional sub pages to your already existing homepage here.

You can choose how open to other readers or writers those pages shall be,
access is controlled by group membership of the corresponding group page.

Just enter the sub page's name and click on the button to create a new page.

Before creating access protected pages, make sure the corresponding group page
exists and has the appropriate members in it. Use HomepageGroupsTemplate for creating
the group pages.

||'''Add a new personal page:'''||'''Related access control list group:'''||
||<<NewPage(HomepageReadWritePageTemplate,read-write page,%(username)s)>>||[[%(username)s/ReadWriteGroup]]||
||<<NewPage(HomepageReadPageTemplate,read-only page,%(username)s)>>||[[%(username)s/ReadGroup]]||
||<<NewPage(HomepagePrivatePageTemplate,private page,%(username)s)>>||%(username)s only||

""")
    pagecontent = pagecontent % locals()

    pagecontent = pagecontent.replace('\n', '\r\n')

    from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
    request.emit_http_headers()

    # This action generate data using the user language
    request.setContentLanguage(request.lang)
    request.theme.send_title(_('MyPages management'), page=homepage)

    parser = WikiParser(pagecontent, request)
    p = Page(request, "$$$")
    request.formatter.setPage(p)
    parser.format(request.formatter)

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

    request.write(request.formatter.endContent())
    request.theme.send_footer(homepage.page_name)
    request.theme.send_closing_html()
예제 #13
0
파일: MyPages.py 프로젝트: aahlad/soar
def execute(pagename, request):
    from MoinMoin import wikiutil
    from MoinMoin.Page import Page

    _ = request.getText
    thispage = Page(request, pagename)

    if request.user.valid:
        username = request.user.name
    else:
        username = ''

    if not username:
        request.theme.add_msg(_('Please log in first.'), "error")
        return thispage.send_page()

    userhomewiki = request.cfg.user_homewiki
    if userhomewiki != 'Self' and userhomewiki != request.cfg.interwikiname:
        interwiki = wikiutil.getInterwikiHomePage(request, username=username)
        wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_interwiki(
            request, *interwiki)
        wikiurl = wikiutil.mapURL(request, wikiurl)
        homepageurl = wikiutil.join_wiki(wikiurl, wikitail)
        request.http_redirect('%s?action=MyPages' % homepageurl)

    homepage = Page(request, username)
    if not homepage.exists():
        request.theme.add_msg(
            _('Please first create a homepage before creating additional pages.'
              ), "error")
        return homepage.send_page()

    pagecontent = _("""\
You can add some additional sub pages to your already existing homepage here.

You can choose how open to other readers or writers those pages shall be,
access is controlled by group membership of the corresponding group page.

Just enter the sub page's name and click on the button to create a new page.

Before creating access protected pages, make sure the corresponding group page
exists and has the appropriate members in it. Use HomepageGroupsTemplate for creating
the group pages.

||'''Add a new personal page:'''||'''Related access control list group:'''||
||<<NewPage(HomepageReadWritePageTemplate,read-write page,%(username)s)>>||[[%(username)s/ReadWriteGroup]]||
||<<NewPage(HomepageReadPageTemplate,read-only page,%(username)s)>>||[[%(username)s/ReadGroup]]||
||<<NewPage(HomepagePrivatePageTemplate,private page,%(username)s)>>||%(username)s only||

""")
    pagecontent = pagecontent % locals()

    pagecontent = pagecontent.replace('\n', '\r\n')

    from MoinMoin.parser.text_moin_wiki import Parser as WikiParser

    # This action generate data using the user language
    request.setContentLanguage(request.lang)
    request.theme.send_title(_('MyPages management'), page=homepage)

    parser = WikiParser(pagecontent, request)
    p = Page(request, "$$$")
    request.formatter.setPage(p)
    parser.format(request.formatter)

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

    request.write(request.formatter.endContent())
    request.theme.send_footer(homepage.page_name)
    request.theme.send_closing_html()
예제 #14
0
파일: h1ds.py 프로젝트: 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
예제 #15
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
예제 #16
0
    def headscript(self, d):
        """ Return html head script with common functions

        Changed: Added GoogleAnalytics support and support for customizable accesskeys

        @param d: parameter dictionary
        @rtype: unicode
        @return: script for html head
        """
        # Don't add script for print view
        # Try..except for backwards compatibility of Moin versions only
        try:
            if self.request.action == 'print':
                return u''
        except:
            if self.request.form.get('action', [''])[0] == 'print':
                return u''

        # Searchbox stuff
        _ = self.request.getText
        script = u"""
<script type="text/javascript">
<!--
var search_hint = "%(search_hint)s";
//-->
</script>
""" % { 'search_hint': _('Search', formatted=False), }
        
        # GoogleAnalytics stuff
        if hasattr(self.request.cfg, 'google_analytics_account_number'):
            account_number = self.request.cfg.google_analytics_account_number
            script += u"""
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
_uacct = "%(account_number)s";
urchinTracker();
//-->
</script>""" % { 'account_number': account_number, }

        # Accesskey customization
        user = self.request.user
        content = ''
        if user.valid and user.name: 
            homewiki, homepage = wikiutil.getInterwikiHomePage(self.request)
            # We don't support interwiki homepages at the moment.
            # In the long run better move accesskey customization to the userprefs menu instead
            # of using an attached file 'shortcuts.js" to the user's homepage.
            # This will solve most security, perfomance and interwiki homepage problems
            if homewiki == 'Self':
                from MoinMoin.action import AttachFile
                import os
                pagename, filename = AttachFile.absoluteName('shortcuts.js', homepage)
                fname = wikiutil.taintfilename(filename)
                fpath = AttachFile.getFilename(self.request, pagename, fname)
                base, ext = os.path.splitext(filename)
                try:
                    # Try to get the user's shortcut list
                    content = file(fpath, 'r').read()
                    content = wikiutil.decodeUnknownInput(content)
                    # Escape malicious code
## Turned off due to i18n problems with regex checking
##                    paras = []
##                    try:
##                        paras = content.split(',')
##                    except:
##                        paras[0] = content
##                    import re
##                    pattern1 = re.compile('^"(name|id)\#[-_a-zA-Z0-9]+\=[a-zA-Z0-9]+"$')
##                    pattern2 = re.compile('^"(name|id)\#[-_a-zA-Z0-9]+\=[a-zA-Z0-9]+\![ -_a-zA-Z0-9]+"$')
##                    for para in paras:
##                        fail1 = fail2 = False
##                        if re.search(pattern1, para.strip()) == None:
##                            fail1 = True
##                        if re.search(pattern2, para.strip()) == None:
##                            fail2 = True
##                        if fail1 and fail2:
##                            content = ''
##                            break
                    
                    content = content.replace(')', '')
                    content = content.replace(';', '')

                except:
                    # User hasn't specified a shortcut list
                    pass

        if not content: 
            # If there is no user shortcut list: Do we have some global shortcut lists
            # set in wikiconfig.py?
            lang_keydefaults = 'accesskey_defaults_%s' % self.request.lang
            # Check whether there is a shortcut list fitting to the request.lang object
            if hasattr(self.request.cfg, lang_keydefaults):
                content = getattr(self.request.cfg, lang_keydefaults)
            # Otherwise check if 'accesskey_defaults' is set
            elif hasattr(self.request.cfg, 'accesskey_defaults'):
                content = self.request.cfg.accesskey_defaults
                
        script += u"""
<script type="text/javascript">
<!--
var shortcut_list = new Array (%(shortcut_list)s);
//-->
</script>
""" % { 'shortcut_list': content,}

        return script
예제 #17
0
파일: h1ds.py 프로젝트: 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
예제 #18
0
    def username(self, d):
        """ Assemble the username / userprefs link

        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request
        _ = request.getText

        userlinks = []
        # Add username/homepage link for registered users. We don't care
        # if it exists, the user can create it.
        if request.user.valid and request.user.name:
            interwiki = wikiutil.getInterwikiHomePage(request)
            name = request.user.name
            aliasname = request.user.aliasname
            if not aliasname:
                aliasname = name
            title = "%s" % aliasname
            # 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 = [u'<li>%s' % link for link in userlinks]
        links = ' <span class="divider">|</span></li>'.join(userlinks)

        links += "%s" %  request.cfg

        if request.cfg.navi_bar:
            links += ' <span class="divider">|</span></li>'
            userlinks = []

            for text in request.cfg.navi_bar:
                pagename, url = self.splitNavilink(text)
                userlinks.append(url)

            userlinks = [u'<li>%s' % link for link in userlinks]
            links += ' <span class="divider">|</span></li>'.join(userlinks)

        html = u'<ul>%s</li></ul>' % links
        return html
예제 #19
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
    def username(self, d):
        """ Assemble the username / userprefs link as dropdown menu
        Assemble a login link instead in case of no login user.

        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request
        _ = request.getText

        userlinks = []
        userbutton = u''
        loginbutton = u''

        # 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])
            # make user button
            userbutton = u'%s<span class="nav-maxwidth-100">%s</span><span class="padding"></span><span class="caret"></span>%s' % (
                request.formatter.url(1, url="#", css="menu-nav-user dropdown-toggle", **{"data-toggle": "dropdown", "rel": "nofollow"}),
                request.formatter.text(name),
                request.formatter.url(0),
                )
            # link to (interwiki) user homepage
            wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_interwiki(self.request, *interwiki)
            wikiurl = wikiutil.mapURL(self.request, wikiurl)
            href = wikiutil.join_wiki(wikiurl, wikitail)
            homelink = (request.formatter.url(1, href, title=title, css='menu-dd-userhome', rel="nofollow") +
                       request.formatter.text(name) +
                       request.formatter.url(0))
            userlinks.append(homelink)

            # link to userprefs action
            if 'userprefs' not in self.request.cfg.actions_excluded:
                userlinks.append(d['page'].link_to_raw(request, text=_('Settings'), css_class='menu-dd-userprefs',
                                                       querystr={'action': 'userprefs'}, rel='nofollow'))
            # logout link
            if request.user.auth_method in request.cfg.auth_can_logout:
                userlinks.append(d['page'].link_to_raw(request, text=_('Logout'), css_class='menu-dd-logout',
                                                       querystr={'action': 'logout', 'logout': '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:
                loginbutton = (d['page'].link_to_raw(request, text=_("Login"),
                                                     querystr=query, css_class='menu-nav-login', rel='nofollow'))

        if userbutton:
            userlinks_html = u'</li>\n                <li>'.join(userlinks)
            html = u'''
            <li class="dropdown">
              %s
              <ul class="dropdown-menu">
                <li>%s</li>
              </ul>
            </li> <!-- /dropdown -->
''' % (userbutton, userlinks_html)

        elif loginbutton:
            html = u'''
            <li>
              %s
            </li>
''' % loginbutton

        else:
            html = u''

        return html
예제 #21
0
    def username(self, d):
        request = self.request
        _ = request.getText

        urls = []

        # 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)
            linkpage = '#'
            if interwiki[0] == 'Self':
                wikitail = wikiutil.url_unquote(interwiki[1])
                linkpage = request.script_root + '/' + wikitail

            name = wikiutil.escape(request.user.name)
            urls.append('<li class="nav-header"><a href="%s">%s</a></li>'
                    % (linkpage, name))

            plugins = wikiutil.getPlugins('userprefs', request.cfg)
            for sub in plugins:
                if sub in request.cfg.userprefs_disabled:
                    continue
                cls = wikiutil.importPlugin(request.cfg, 'userprefs',
                                            sub, 'Settings')
                obj = cls(request)
                if not obj.allowed():
                    continue
                url = request.page.url(request, {'action': 'userprefs',
                                                 'sub': sub})
                urls.append('<li><a href="%s">%s</a></li>' % (url, obj.title))

        if request.user.valid:
            if request.user.auth_method in request.cfg.auth_can_logout:
                query = {'action': 'logout', 'logout': 'logout'}
                url = request.page.url(request, query)
                urls.append('<li><a href="%s">%s</a></li>' % (url, _('Logout')))
        elif request.cfg.auth_have_login:
            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'] = '******'
            url = request.page.url(request, query)
            urls.append('<li><a href="%s">%s</a></li>' % (url, _('Login')))

        formadd = getattr(request.cfg, 'user_form_add', ())
        # Please note that you need to have a function of the form
        # lambda self, req: ... to the config as the function is
        # defined within a class.
        formcond = getattr(request.cfg, 'user_form_addcondition',
                           lambda req: True)
        if formcond(request):
            for url, text in formadd:
                urls.append('<li><a href="%s">%s</a></li>' % (url, _(text)))

        out = ""

        if urls:
            out = u"""
        <ul class="nav navbar-nav navbar-right">
            <li>
            <a class="dropdown-toggle" data-toggle="dropdown" title="%s">
              <i class="glyphicon glyphicon-user"></i>
            </a>
            <ul class="dropdown-menu navbar-right">
                %s
            </ul>
            </li>
        </ul>""" % (_('User Preferences'), ("\n" + " " * 16).join(urls))

        return out