예제 #1
0
	def _get_page_operations(self, source_env, local_env):

		operations = {}

		# Open source and destination wikis
		source_wiki_system = WikiSystem(source_env)
		dest_wiki_system = WikiSystem(local_env)

		# Extract wiki pages from both wikis 
		local_pages = []
		for page in dest_wiki_system.get_pages():
			local_pages.append(page)
		source_pages = []
		for page in source_wiki_system.get_pages():
			source_pages.append(page)
			operations[page] = 'create'

		# Create operations list
		for page in local_pages:
			if page in source_pages:
				operations[page] = 'update'

		# Do not update pages with identical contents
		for page, operation in operations.items():
			local_page = WikiPage(self.env, page)
			source_page = WikiPage(source_env, page)
			if local_page.text == source_page.text:
				del operations[page]	

		return operations
예제 #2
0
    def _get_page_operations(self, source_env, local_env):

        operations = {}

        # Open source and destination wikis
        source_wiki_system = WikiSystem(source_env)
        dest_wiki_system = WikiSystem(local_env)

        # Extract wiki pages from both wikis
        local_pages = []
        for page in dest_wiki_system.get_pages():
            local_pages.append(page)
        source_pages = []
        for page in source_wiki_system.get_pages():
            source_pages.append(page)
            operations[page] = 'create'

        # Create operations list
        for page in local_pages:
            if page in source_pages:
                operations[page] = 'update'

        # Do not update pages with identical contents
        for page, operation in operations.items():
            local_page = WikiPage(self.env, page)
            source_page = WikiPage(source_env, page)
            if local_page.text == source_page.text:
                del operations[page]

        return operations
예제 #3
0
파일: macros.py 프로젝트: lkraav/trachacks
 def _render_feeds(self, req, content):
     wiki = WikiSystem(self.env)
     prefix = req.args['page'].value
     if not prefix.endswith('/'):
         prefix += '/'
     pages = sorted(page for page in wiki.get_pages(prefix) if page != prefix)
     buf = StringIO()
     print >>buf, '<h1>Available Feeds</h1>'
     if pages:
         print >>buf, '<ul>'
         href = self.env.href
         for page in pages:
             rel_name = page[len(prefix):]
             print >>buf, Markup(
                 '<li><a href="%s">%s</a> <a href="%s">[rss]</a> <a href="%s">[edit]</a></li>',
                 href.wiki(page), rel_name, href.changesetrss(page), href.wiki(page, action='edit')
             )
         print >>buf, '</ul>'
     else:
         print >>buf, '<p>None</p>'
     print >>buf, Markup('''<script type="text/javascript">
     var new_filter = function(form) {
         window.location = '%s'.replace(/deadbeef/, form.page_name.value);
     };
     </script>
     ''', href.wiki(prefix + 'deadbeef', action='edit', text=DEFAULT_CONTENT)
     )
     print >>buf, Markup('''<form onsubmit="new_filter(this); return false;">
         <input type="text" name="page_name">
         <input type="submit" value="Add Filter">
     </form>
     ''')
     return buf.getvalue()
예제 #4
0
    def render_macro(self, req, name, content):
        prefix = content or None

        wiki = WikiSystem(self.env)

        return html.UL([html.LI(html.A(wiki.format_page_name(page),
                                       href=req.href.wiki(page)))
                        for page in sorted(wiki.get_pages(prefix))])
예제 #5
0
    def render_macro(self, req, name, content):
        prefix = content or None

        wiki = WikiSystem(self.env)

        return html.UL([html.LI(html.A(wiki.format_page_name(page),
                                       href=req.href.wiki(page)))
                        for page in sorted(wiki.get_pages(prefix))])
예제 #6
0
    def render_macro(self, req, name, content):
        prefix = None
        if content:
            prefix = content.replace('\'', '\'\'')

        wiki = WikiSystem(self.env)
        pages = list(wiki.get_pages(prefix))
        pages.sort()

        buf = StringIO()
        buf.write('<ul>')
        for page in pages:
            buf.write('<li><a href="%s">' % escape(self.env.href.wiki(page)))
            buf.write(escape(page))
            buf.write('</a></li>\n')
        buf.write('</ul>')

        return buf.getvalue()
예제 #7
0
def _wrapped_get_pages(original_callable,
                       the_class,
                       prefix=None,
                       *args,
                       **kwargs):

    #Call the original _do_login
    for page in original_callable(the_class, prefix, *args, **kwargs):
        yield page

    env = get_master_env(the_class.env)
    if env.path == the_class.env.path: return

    wiki_system = WikiSystem(env)

    if not WikiModule.PAGE_TEMPLATES_PREFIX.startswith(prefix or ''): return

    for prefix in SharedTemplates(the_class.env).global_template_prefixes:
        for page in wiki_system.get_pages(prefix):
            yield WikiModule.PAGE_TEMPLATES_PREFIX + page
예제 #8
0
파일: nav.py 프로젝트: nyuhuhuu/trachacks
 def post_process_request(self, req, template, data, content_type):
     if data and 'context' in data and \
             data['context'].resource.realm == 'wiki' and \
             'action' not in req.args and \
             'version' not in req.args:
         page = data['page']
         prefix = '/' in page.name and page.name[:page.name.rindex('/') + 1] or ''
         wiki = WikiSystem(self.env)
         start = prefix.count('/')
         pages = sorted(page for page in wiki.get_pages(prefix) \
                if (start >= page.count('/'))
                and 'WIKI_VIEW' in req.perm('wiki', page))
         if page.name in pages:
             index = pages.index(page.name)
             if index > 0:
                 add_link(req, 'prev', req.href.wiki(pages[index - 1]))
             if index < len(pages) - 1:
                 add_link(req, 'next', req.href.wiki(pages[index + 1]))
             prevnext_nav(req, _('Previous Page'), _('Next Page'))
     return template, data, content_type
예제 #9
0
 def post_process_request(self, req, template, data, content_type):
     if data and 'context' in data and \
             data['context'].resource.realm == 'wiki' and \
             'action' not in req.args and \
             'version' not in req.args:
         page = data['page']
         prefix = '/' in page.name and page.name[:page.name.rindex('/') +
                                                 1] or ''
         wiki = WikiSystem(self.env)
         start = prefix.count('/')
         pages = sorted(page for page in wiki.get_pages(prefix) \
                if (start >= page.count('/'))
                and 'WIKI_VIEW' in req.perm('wiki', page))
         if page.name in pages:
             index = pages.index(page.name)
             if index > 0:
                 add_link(req, 'prev', req.href.wiki(pages[index - 1]))
             if index < len(pages) - 1:
                 add_link(req, 'next', req.href.wiki(pages[index + 1]))
             prevnext_nav(req, _('Previous Page'), _('Next Page'))
     return template, data, content_type
예제 #10
0
 def _render_feeds(self, req, content):
     wiki = WikiSystem(self.env)
     prefix = req.args['page'].value
     if not prefix.endswith('/'):
         prefix += '/'
     pages = sorted(page for page in wiki.get_pages(prefix)
                    if page != prefix)
     buf = StringIO()
     print >> buf, '<h1>Available Feeds</h1>'
     if pages:
         print >> buf, '<ul>'
         href = self.env.href
         for page in pages:
             rel_name = page[len(prefix):]
             print >> buf, Markup(
                 '<li><a href="%s">%s</a> <a href="%s">[rss]</a> <a href="%s">[edit]</a></li>',
                 href.wiki(page), rel_name, href.changesetrss(page),
                 href.wiki(page, action='edit'))
         print >> buf, '</ul>'
     else:
         print >> buf, '<p>None</p>'
     print >> buf, Markup(
         '''<script type="text/javascript">
     var new_filter = function(form) {
         window.location = '%s'.replace(/deadbeef/, form.page_name.value);
     };
     </script>
     ''', href.wiki(prefix + 'deadbeef',
                    action='edit',
                    text=DEFAULT_CONTENT))
     print >> buf, Markup(
         '''<form onsubmit="new_filter(this); return false;">
         <input type="text" name="page_name">
         <input type="submit" value="Add Filter">
     </form>
     ''')
     return buf.getvalue()
예제 #11
0
파일: wiki.py 프로젝트: nyuhuhuu/trachacks
class WikiExtRPC(Component):
    """ Additional Wiki XML-RPC API. """

    implements(IXMLRPCHandler)
    
    VERSION = '1.0'

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return 'wikiext'

    def xmlrpc_methods(self):
        yield ('WIKI_VIEW', ((list, str), ), self.getPageVersions)
        yield ('WIKI_VIEW', ((bool, str), ), self.hasChildren)
        yield ('WIKI_VIEW', ((list, str), ), self.getChildren)
        yield ('WIKI_VIEW', ((dict,), ), self.getMacros)
        yield ('WIKI_VIEW', ((dict,), ), self.getVersion)

    def _page_info(self, name, time, author, version, comment=''):
        return dict(name=name, 
                    lastModified=xmlrpclib.DateTime(int(time)),
                    author=author, 
                    version=int(version), 
                    comment=(comment or '') )

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            return page.text
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += ' at version %s' % version
            raise xmlrpclib.Fault(0, msg)
            
    def getPageVersions(self, req, pagename):
        '''Return an array of page versions info'''
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute('SELECT version, author, comment, time FROM wiki'
                       ' WHERE name = %s ORDER BY version DESC', (pagename,))
        result = []
        for version, author, comment, time in cursor:
            result.append(self._page_info(pagename, time, author, version, comment))
        return result
    
    def hasChildren(self, req, pagename):
        """ Returns true if the page has children. """
        if pagename: pagename += '/'
        res = False
        for i in self.wiki.get_pages( pagename ):
            res = True
            break
        return res

    def getChildren(self, req, pagename):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """
        
        cond  = ''
        # params = () 
        
        if pagename:
            pagename += '/'
            cond = "WHERE name LIKE '%s%%'" % pagename
            # params = (pagename,)
            
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT name, MAX(version) FROM wiki %s GROUP BY name" % cond )

        pages = []
        for name, version in cursor:
            pages.append( (name, version) )
            
        children = {}
        for page, version in pages:
            relname = page.replace( pagename, '' )
            
            if relname.find( '/' ) == -1:
                # We only look for direct children
                children[ page ] = { 'exists' : True,
                                     'hasChildren' : False, 
                                     'version' : version }
            else:
                # The page does not really exists, but it does have
                # children, so we have to return it,
                name = pagename + relname.split( '/', 1 )[0]
                if not children.has_key( name ):
                    children[ name ] = { 'exists' : False, 
                                         'hasChildren' : True, 
                                         'version' : version }
                else:
                    children[ name ][ 'hasChildren' ] = True
                    
        return children    
    
    def getMacros(self, req):
        '''Return the list of registered wiki macros'''
        macros = {}
        for plugin in self.wiki.macro_providers:
            for macro in plugin.get_macros():
                desc = plugin.get_macro_description( macro )
                if not desc:
                    desc = ''
                macros[ macro ] = desc 
        return macros
    
    def getVersion( self, req ):
        '''Return the module version'''
        return { 'version' : self.VERSION }
예제 #12
0
파일: web_ui.py 프로젝트: starworldx/trac
    def _render_view(self, req, page):
        version = page.resource.version

        # Add registered converters
        if page.exists:
            for conversion in Mimeview(self.env) \
                              .get_supported_conversions('text/x-trac-wiki'):
                conversion_href = req.href.wiki(page.name, version=version,
                                                format=conversion.key)
                add_link(req, 'alternate', conversion_href, conversion.name,
                         conversion.in_mimetype)

        data = self._page_data(req, page)
        if page.name == self.START_PAGE:
            data['title'] = ''

        ws = WikiSystem(self.env)
        context = web_context(req, page.resource)
        higher, related = [], []
        if not page.exists:
            if 'WIKI_CREATE' not in req.perm(page.resource):
                raise ResourceNotFound(_("Page %(name)s not found",
                                         name=page.name))
            formatter = OneLinerFormatter(self.env, context)
            if '/' in page.name:
                parts = page.name.split('/')
                for i in xrange(len(parts) - 2, -1, -1):
                    name = '/'.join(parts[:i] + [parts[-1]])
                    if not ws.has_page(name):
                        higher.append(ws._format_link(formatter, 'wiki',
                                                      '/' + name, name, False))
            else:
                name = page.name
            name = name.lower()
            related = [each for each in ws.pages
                       if name in each.lower()
                          and 'WIKI_VIEW' in req.perm(self.realm, each)]
            related.sort()
            related = [ws._format_link(formatter, 'wiki', '/' + each, each,
                                       False)
                       for each in related]

        latest_page = WikiPage(self.env, page.name)

        prev_version = next_version = None
        if version:
            version = as_int(version, None)
            if version is not None:
                for hist in latest_page.get_history():
                    v = hist[0]
                    if v != version:
                        if v < version:
                            if not prev_version:
                                prev_version = v
                                break
                        else:
                            next_version = v

        prefix = self.PAGE_TEMPLATES_PREFIX
        templates = [template[len(prefix):]
                     for template in ws.get_pages(prefix)
                     if 'WIKI_VIEW' in req.perm(self.realm, template)]

        # -- prev/up/next links
        if prev_version:
            add_link(req, 'prev',
                     req.href.wiki(page.name, version=prev_version),
                     _("Version %(num)s", num=prev_version))

        parent = None
        if version:
            add_link(req, 'up', req.href.wiki(page.name, version=None),
                     _("View latest version"))
        elif '/' in page.name:
            parent = page.name[:page.name.rindex('/')]
            add_link(req, 'up', req.href.wiki(parent, version=None),
                     _("View parent page"))

        if next_version:
            add_link(req, 'next',
                     req.href.wiki(page.name, version=next_version),
                     _('Version %(num)s', num=next_version))

        # Add ctxtnav entries
        if version:
            prevnext_nav(req, _("Previous Version"), _("Next Version"),
                         _("View Latest Version"))
        else:
            if parent:
                add_ctxtnav(req, _('Up'), req.href.wiki(parent))
            self._wiki_ctxtnav(req, page)

        # Plugin content validation
        fields = {'text': page.text}
        for manipulator in self.page_manipulators:
            manipulator.prepare_wiki_page(req, page, fields)
        text = fields.get('text', '')

        data.update({
            'context': context,
            'text': text,
            'latest_version': latest_page.version,
            'attachments': AttachmentModule(self.env).attachment_data(context),
            'start_page': self.START_PAGE,
            'default_template': self.DEFAULT_PAGE_TEMPLATE,
            'templates': templates,
            'version': version,
            'higher': higher, 'related': related,
            'resourcepath_template': 'wiki_page_path.html',
            'fullwidth': req.session.get('wiki_fullwidth'),
        })
        add_script(req, 'common/js/wiki.js')
        return 'wiki_view.html', data
예제 #13
0
    def _render_view(self, req, page):
        version = page.resource.version

        # Add registered converters
        if page.exists:
            for conversion in Mimeview(self.env).get_supported_conversions(
                                                 'text/x-trac-wiki'):
                conversion_href = req.href.wiki(page.name, version=version,
                                                format=conversion[0])
                # or...
                conversion_href = get_resource_url(self.env, page.resource,
                                                req.href, format=conversion[0])
                add_link(req, 'alternate', conversion_href, conversion[1],
                         conversion[3])

        data = self._page_data(req, page)
        if page.name == 'WikiStart':
            data['title'] = ''

        ws = WikiSystem(self.env)
        context = web_context(req, page.resource)
        higher, related = [], []
        if not page.exists:
            if 'WIKI_CREATE' not in req.perm(page.resource):
                raise ResourceNotFound(_('Page %(name)s not found',
                                         name=page.name))
            formatter = OneLinerFormatter(self.env, context)
            if '/' in page.name:
                parts = page.name.split('/')
                for i in range(len(parts) - 2, -1, -1):
                    name = '/'.join(parts[:i] + [parts[-1]])
                    if not ws.has_page(name):
                        higher.append(ws._format_link(formatter, 'wiki',
                                                    '/' + name, name, False))
            else:
                name = page.name
            name = name.lower()
            related = [each for each in ws.pages
                       if name in each.lower()
                          and 'WIKI_VIEW' in req.perm('wiki', each)]
            related.sort()
            related = [ws._format_link(formatter, 'wiki', '/' + each, each,
                                       False)
                       for each in related]

        latest_page = WikiPage(self.env, page.name, version=None)
        req.perm(latest_page.resource).require('WIKI_VIEW')

        prev_version = next_version = None
        if version:
            try:
                version = int(version)
                for hist in latest_page.get_history():
                    v = hist[0]
                    if v != version:
                        if v < version:
                            if not prev_version:
                                prev_version = v
                                break
                        else:
                            next_version = v
            except ValueError:
                version = None

        prefix = self.PAGE_TEMPLATES_PREFIX
        templates = [template[len(prefix):]
                     for template in ws.get_pages(prefix)
                     if 'WIKI_VIEW' in req.perm('wiki', template)]

        # -- prev/up/next links
        if prev_version:
            add_link(req, 'prev',
                     req.href.wiki(page.name, version=prev_version),
                     _('Version %(num)s', num=prev_version))

        parent = None
        if version:
            add_link(req, 'up', req.href.wiki(page.name, version=None),
                     _('View latest version'))
        elif '/' in page.name:
            parent = page.name[:page.name.rindex('/')]
            add_link(req, 'up', req.href.wiki(parent, version=None),
                     _("View parent page"))

        if next_version:
            add_link(req, 'next',
                     req.href.wiki(page.name, version=next_version),
                     _('Version %(num)s', num=next_version))

        # Add ctxtnav entries
        if version:
            prevnext_nav(req, _('Previous Version'), _('Next Version'),
                         _('View Latest Version'))
        else:
            if parent:
                add_ctxtnav(req, _('Up'), req.href.wiki(parent))
            self._wiki_ctxtnav(req, page)

        # Plugin content validation
        fields = {'text': page.text}
        for manipulator in self.page_manipulators:
            manipulator.prepare_wiki_page(req, page, fields)
        text = fields.get('text', '')

        data.update({
            'context': context,
            'text': text,
            'latest_version': latest_page.version,
            'attachments': AttachmentModule(self.env).attachment_data(context),
            'default_template': self.DEFAULT_PAGE_TEMPLATE,
            'templates': templates,
            'version': version,
            'higher': higher, 'related': related,
            'resourcepath_template': 'wiki_page_path.html',
        })
        add_script(req, 'common/js/folding.js')
        return 'wiki_view.html', data, None
예제 #14
0
class WikiRPC(Component):
    """Superset of the
    [http://www.jspwiki.org/Wiki.jsp?page=WikiRPCInterface2 WikiRPC API]. """

    implements(IXMLRPCHandler)

    manipulators = ExtensionPoint(IWikiPageManipulator)

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return 'wiki'

    def xmlrpc_methods(self):
        yield (None, ((dict, datetime),), self.getRecentChanges)
        yield ('WIKI_VIEW', ((int,),), self.getRPCVersionSupported)
        yield (None, ((str, str), (str, str, int),), self.getPage)
        yield (None, ((str, str, int),), self.getPage, 'getPageVersion')
        yield (None, ((str, str), (str, str, int)), self.getPageHTML)
        yield (None, ((str, str), (str, str, int)), self.getPageHTML, 'getPageHTMLVersion')
        yield (None, ((list,),), self.getAllPages)
        yield (None, ((dict, str), (dict, str, int)), self.getPageInfo)
        yield (None, ((dict, str, int),), self.getPageInfo, 'getPageInfoVersion')
        yield (None, ((bool, str, str, dict),), self.putPage)
        yield (None, ((list, str),), self.listAttachments)
        yield (None, ((Binary, str),), self.getAttachment)
        yield (None, ((bool, str, Binary),), self.putAttachment)
        yield (None, ((bool, str, str, str, Binary),
                               (bool, str, str, str, Binary, bool)),
                               self.putAttachmentEx)
        yield (None, ((bool, str),(bool, str, int)), self.deletePage)
        yield (None, ((bool, str),), self.deleteAttachment)
        yield ('WIKI_VIEW', ((list, str),), self.listLinks)
        yield ('WIKI_VIEW', ((str, str),), self.wikiToHtml)

    def _fetch_page(self, req, pagename, version=None):
        # Helper for getting the WikiPage that performs basic checks
        page = WikiPage(self.env, pagename, version)
        req.perm(page.resource).require('WIKI_VIEW')
        if page.exists:
            return page
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += ' at version %s' % version
            raise ResourceNotFound(msg)

    def _page_info(self, name, when, author, version, comment):
        return dict(name=name, lastModified=when,
                    author=author, version=int(version), comment=comment)

    def getRecentChanges(self, req, since):
        """ Get list of changed pages since timestamp """
        since = to_utimestamp(since)
        wiki_realm = Resource('wiki')
        query = ('SELECT name, time, author, version, comment '
                 'FROM wiki w1 '
                 'WHERE time >= %s '
                 'AND version = (SELECT MAX(version) '
                 '               FROM wiki w2 '
                 '               WHERE w2.name=w1.name) '
                 'ORDER BY time DESC')
        if hasattr(self.env, 'db_query'):
            generator = self.env.db_query(query, (since,))
        else:
            db = self.env.get_db_cnx()
            cursor = db.cursor()
            cursor.execute(query, (since,))
            generator = cursor
        result = []
        for name, when, author, version, comment in generator:
            if 'WIKI_VIEW' in req.perm(wiki_realm(id=name, version=version)):
                result.append(
                    self._page_info(name, from_utimestamp(when),
                                    author, version, comment))
        return result

    def getRPCVersionSupported(self, req):
        """ Returns 2 with this version of the Trac API. """
        return 2

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = self._fetch_page(req, pagename, version)
        return page.text

    def getPageHTML(self, req, pagename, version=None):
        """ Return latest version of page as rendered HTML, utf8 encoded. """
        page = self._fetch_page(req, pagename, version)
        fields = {'text': page.text}
        for manipulator in self.manipulators:
            manipulator.prepare_wiki_page(req, page, fields)
        context = web_context(req, page.resource, absurls=True)
        html = format_to_html(self.env, context, fields['text'])
        return '<html><body>%s</body></html>' % html.encode('utf-8')

    def getAllPages(self, req):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """
        pages = []
        for page in self.wiki.get_pages():
            if 'WIKI_VIEW' in req.perm(Resource('wiki', page)):
                pages.append(page)
        return pages

    def getPageInfo(self, req, pagename, version=None):
        """ Returns information about the given page. """
        page = WikiPage(self.env, pagename, version)
        req.perm(page.resource).require('WIKI_VIEW')
        if page.exists:
            last_update = page.get_history().next()
            return self._page_info(page.name, last_update[1],
                                   last_update[2], page.version, page.comment)

    def putPage(self, req, pagename, content, attributes):
        """ writes the content of the page. """
        page = WikiPage(self.env, pagename)
        if page.readonly:
            req.perm(page.resource).require('WIKI_ADMIN')
        elif not page.exists:
            req.perm(page.resource).require('WIKI_CREATE')
        else:
            req.perm(page.resource).require('WIKI_MODIFY')

        page.text = content
        if req.perm(page.resource).has_permission('WIKI_ADMIN'):
            page.readonly = attributes.get('readonly') and 1 or 0

        page.save(attributes.get('author', req.authname),
                  attributes.get('comment'), req.remote_addr)
        return True

    def deletePage(self, req, name, version=None):
        """Delete a Wiki page (all versions) or a specific version by
        including an optional version number. Attachments will also be
        deleted if page no longer exists. Returns True for success."""
        wp = WikiPage(self.env, name, version)
        req.perm(wp.resource).require('WIKI_DELETE')
        try:
            wp.delete(version)
            return True
        except:
            return False

    def listAttachments(self, req, pagename):
        """ Lists attachments on a given page. """
        for a in Attachment.select(self.env, 'wiki', pagename):
            if 'ATTACHMENT_VIEW' in req.perm(a.resource):
                yield pagename + '/' + a.filename

    def getAttachment(self, req, path):
        """ returns the content of an attachment. """
        pagename, filename = os.path.split(path)
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        req.perm(attachment.resource).require('ATTACHMENT_VIEW')
        return Binary(attachment.open().read())

    def putAttachment(self, req, path, data):
        """ (over)writes an attachment. Returns True if successful.
        
        This method is compatible with WikiRPC.  `putAttachmentEx` has a more
        extensive set of (Trac-specific) features. """
        pagename, filename = os.path.split(path)
        self.putAttachmentEx(req, pagename, filename, None, data)
        return True

    def putAttachmentEx(self, req, pagename, filename, description, data, replace=True):
        """ Attach a file to a Wiki page. Returns the (possibly transformed)
        filename of the attachment.
        
        Use this method if you don't care about WikiRPC compatibility. """
        if not WikiPage(self.env, pagename).exists:
            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
        if replace:
            try:
                attachment = Attachment(self.env, 'wiki', pagename, filename)
                req.perm(attachment.resource).require('ATTACHMENT_DELETE')
                attachment.delete()
            except TracError:
                pass
        attachment = Attachment(self.env, 'wiki', pagename)
        req.perm(attachment.resource).require('ATTACHMENT_CREATE')
        attachment.author = req.authname
        attachment.description = description
        attachment.insert(filename, StringIO(data.data), len(data.data))
        return attachment.filename

    def deleteAttachment(self, req, path):
        """ Delete an attachment. """
        pagename, filename = os.path.split(path)
        if not WikiPage(self.env, pagename).exists:
            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        req.perm(attachment.resource).require('ATTACHMENT_DELETE')
        attachment.delete()
        return True

    def listLinks(self, req, pagename):
        """ ''Not implemented'' """
        return []

    def wikiToHtml(self, req, text):
        """ Render arbitrary Wiki text as HTML. """
        context = web_context(req)
        return unicode(format_to_html(self.env, context, text, absurls=True))
예제 #15
0
class WikiExtRPC(Component):
    """ Additional Wiki XML-RPC API. """

    implements(IXMLRPCHandler)

    VERSION = '1.0'

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return 'wikiext'

    def xmlrpc_methods(self):
        yield ('WIKI_VIEW', ((list, str), ), self.getPageVersions)
        yield ('WIKI_VIEW', ((bool, str), ), self.hasChildren)
        yield ('WIKI_VIEW', ((list, str), ), self.getChildren)
        yield ('WIKI_VIEW', ((dict, ), ), self.getMacros)
        yield ('WIKI_VIEW', ((dict, ), ), self.getVersion)

    def _page_info(self, name, time, author, version, comment=''):
        return dict(name=name,
                    lastModified=xmlrpclib.DateTime(int(time)),
                    author=author,
                    version=int(version),
                    comment=(comment or ''))

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            return page.text
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += ' at version %s' % version
            raise xmlrpclib.Fault(0, msg)

    def getPageVersions(self, req, pagename):
        '''Return an array of page versions info'''
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            'SELECT version, author, comment, time FROM wiki'
            ' WHERE name = %s ORDER BY version DESC', (pagename, ))
        result = []
        for version, author, comment, time in cursor:
            result.append(
                self._page_info(pagename, time, author, version, comment))
        return result

    def hasChildren(self, req, pagename):
        """ Returns true if the page has children. """
        if pagename: pagename += '/'
        res = False
        for i in self.wiki.get_pages(pagename):
            res = True
            break
        return res

    def getChildren(self, req, pagename):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """

        cond = ''
        # params = ()

        if pagename:
            pagename += '/'
            cond = "WHERE name LIKE '%s%%'" % pagename
            # params = (pagename,)

        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT name, MAX(version) FROM wiki %s GROUP BY name" %
                       cond)

        pages = []
        for name, version in cursor:
            pages.append((name, version))

        children = {}
        for page, version in pages:
            relname = page.replace(pagename, '')

            if relname.find('/') == -1:
                # We only look for direct children
                children[page] = {
                    'exists': True,
                    'hasChildren': False,
                    'version': version
                }
            else:
                # The page does not really exists, but it does have
                # children, so we have to return it,
                name = pagename + relname.split('/', 1)[0]
                if not children.has_key(name):
                    children[name] = {
                        'exists': False,
                        'hasChildren': True,
                        'version': version
                    }
                else:
                    children[name]['hasChildren'] = True

        return children

    def getMacros(self, req):
        '''Return the list of registered wiki macros'''
        macros = {}
        for plugin in self.wiki.macro_providers:
            for macro in plugin.get_macros():
                desc = plugin.get_macro_description(macro)
                if not desc:
                    desc = ''
                macros[macro] = desc
        return macros

    def getVersion(self, req):
        '''Return the module version'''
        return {'version': self.VERSION}
예제 #16
0
class WikiRPC(Component):
    """ Implementation of the [http://www.jspwiki.org/Wiki.jsp?page=WikiRPCInterface2 WikiRPC API]. """

    implements(IXMLRPCHandler)

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return 'wiki'

    def xmlrpc_methods(self):
        yield ('WIKI_VIEW', ((dict, xmlrpclib.DateTime), ),
               self.getRecentChanges)
        yield ('WIKI_VIEW', ((int, ), ), self.getRPCVersionSupported)
        yield ('WIKI_VIEW', (
            (str, str),
            (str, str, int),
        ), self.getPage)
        yield ('WIKI_VIEW', ((str, str, int), ), self.getPage,
               'getPageVersion')
        yield ('WIKI_VIEW', ((str, str), (str, str, int)), self.getPageHTML)
        yield ('WIKI_VIEW', ((str, str), (str, str, int)), self.getPageHTML,
               'getPageHTMLVersion')
        yield ('WIKI_VIEW', ((list, ), ), self.getAllPages)
        yield ('WIKI_VIEW', ((dict, str), (dict, str, int)), self.getPageInfo)
        yield ('WIKI_VIEW', ((dict, str, int), ), self.getPageInfo,
               'getPageInfoVersion')
        yield ('WIKI_CREATE', ((bool, str, str, dict), ), self.putPage)
        yield ('WIKI_VIEW', ((list, str), ), self.listAttachments)
        yield ('WIKI_VIEW', ((xmlrpclib.Binary, str), ), self.getAttachment)
        yield ('WIKI_MODIFY', ((bool, str, xmlrpclib.Binary), ),
               self.putAttachment)
        yield ('WIKI_MODIFY', ((bool, str, str, str, xmlrpclib.Binary),
                               (bool, str, str, str, xmlrpclib.Binary, bool)),
               self.putAttachmentEx)
        yield ('WIKI_DELETE', ((bool, str), ), self.deleteAttachment)
        yield ('WIKI_VIEW', ((list, str), ), self.listLinks)
        yield ('WIKI_VIEW', ((str, str), ), self.wikiToHtml)

    def _page_info(self, name, time, author, version):
        return dict(name=name,
                    lastModified=xmlrpclib.DateTime(int(time)),
                    author=author,
                    version=int(version))

    def getRecentChanges(self, req, since):
        """ Get list of changed pages since timestamp """
        since = to_timestamp(since)
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            'SELECT name, max(time), author, version FROM wiki'
            ' WHERE time >= %s GROUP BY name ORDER BY max(time) DESC',
            (since, ))
        result = []
        for name, time, author, version in cursor:
            result.append(self._page_info(name, time, author, version))
        return result

    def getRPCVersionSupported(self, req):
        """ Returns 2 with this version of the Trac API. """
        return 2

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            return page.text
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += ' at version %s' % version
            raise xmlrpclib.Fault(0, msg)

    def getPageHTML(self, req, pagename, version=None):
        """ Return page in rendered HTML, latest version. """
        text = self.getPage(req, pagename, version)
        html = wiki_to_html(text, self.env, req, absurls=1)
        return '<html><body>%s</body></html>' % html

    def getAllPages(self, req):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """
        return list(self.wiki.get_pages())

    def getPageInfo(self, req, pagename, version=None):
        """ Returns information about the given page. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            last_update = page.get_history().next()
            return self._page_info(page.name, last_update[1], last_update[2],
                                   page.version)

    def putPage(self, req, pagename, content, attributes):
        """ writes the content of the page. """
        page = WikiPage(self.env, pagename)
        if page.readonly:
            req.perm.assert_permission('WIKI_ADMIN')
        elif not page.exists:
            req.perm.assert_permission('WIKI_CREATE')
        else:
            req.perm.assert_permission('WIKI_MODIFY')

        page.text = content
        if req.perm.has_permission('WIKI_ADMIN'):
            page.readonly = attributes.get('readonly') and 1 or 0

        page.save(attributes.get('author', req.authname),
                  attributes.get('comment'), req.remote_addr)
        return True

    def listAttachments(self, req, pagename):
        """ Lists attachments on a given page. """
        return [
            pagename + '/' + a.filename
            for a in Attachment.select(self.env, 'wiki', pagename)
        ]

    def getAttachment(self, req, path):
        """ returns the content of an attachment. """
        pagename, filename = posixpath.split(path)
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        return xmlrpclib.Binary(attachment.open().read())

    def putAttachment(self, req, path, data):
        """ (over)writes an attachment. Returns True if successful.
        
        This method is compatible with WikiRPC.  `putAttachmentEx` has a more
        extensive set of (Trac-specific) features. """
        pagename, filename = posixpath.split(path)
        self.putAttachmentEx(req, pagename, filename, None, data)
        return True

    def putAttachmentEx(self,
                        req,
                        pagename,
                        filename,
                        description,
                        data,
                        replace=True):
        """ Attach a file to a Wiki page. Returns the (possibly transformed)
        filename of the attachment.
        
        Use this method if you don't care about WikiRPC compatibility. """
        if not WikiPage(self.env, pagename).exists:
            raise TracError, 'Wiki page "%s" does not exist' % pagename
        if replace:
            try:
                attachment = Attachment(self.env, 'wiki', pagename, filename)
                attachment.delete()
            except TracError:
                pass
        attachment = Attachment(self.env, 'wiki', pagename)
        attachment.author = req.authname or 'anonymous'
        attachment.description = description
        attachment.insert(filename, StringIO(data.data), len(data.data))
        return attachment.filename

    def deleteAttachment(self, req, path):
        """ Delete an attachment. """
        pagename, filename = posixpath.split(path)
        if not WikiPage(self.env, pagename).exists:
            raise TracError, 'Wiki page "%s" does not exist' % pagename
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        attachment.delete()
        return True

    def listLinks(self, req, pagename):
        """ ''Not implemented'' """
        return []

    def wikiToHtml(self, req, text):
        """ Render arbitrary Wiki text as HTML. """
        return unicode(wiki_to_html(text, self.env, req, absurls=1))
예제 #17
0
파일: wiki.py 프로젝트: Puppet-Finland/trac
class WikiRPC(Component):
    """ Implementation of the [http://www.jspwiki.org/Wiki.jsp?page=WikiRPCInterface2 WikiRPC API]. """

    implements(IXMLRPCHandler)

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return 'wiki'

    def xmlrpc_methods(self):
        yield ('WIKI_VIEW', ((dict, xmlrpclib.DateTime),), self.getRecentChanges)
        yield ('WIKI_VIEW', ((int,),), self.getRPCVersionSupported)
        yield ('WIKI_VIEW', ((str, str), (str, str, int),), self.getPage)
        yield ('WIKI_VIEW', ((str, str, int),), self.getPage, 'getPageVersion')
        yield ('WIKI_VIEW', ((str, str), (str, str, int)), self.getPageHTML)
        yield ('WIKI_VIEW', ((str, str), (str, str, int)), self.getPageHTML, 'getPageHTMLVersion')
        yield ('WIKI_VIEW', ((list,),), self.getAllPages)
        yield ('WIKI_VIEW', ((dict, str), (dict, str, int)), self.getPageInfo)
        yield ('WIKI_VIEW', ((dict, str, int),), self.getPageInfo, 'getPageInfoVersion')
        yield ('WIKI_CREATE', ((bool, str, str, dict),), self.putPage)
        yield ('WIKI_VIEW', ((list, str),), self.listAttachments)
        yield ('WIKI_VIEW', ((xmlrpclib.Binary, str),), self.getAttachment)
        yield ('WIKI_MODIFY', ((bool, str, xmlrpclib.Binary),), self.putAttachment)
        yield ('WIKI_MODIFY', ((bool, str, str, str, xmlrpclib.Binary),
                               (bool, str, str, str, xmlrpclib.Binary, bool)),
                               self.putAttachmentEx)
        yield ('WIKI_DELETE', ((bool, str),), self.deleteAttachment)
        yield ('WIKI_VIEW', ((list, str),), self.listLinks)
        yield ('WIKI_VIEW', ((str, str),), self.wikiToHtml)

    def _page_info(self, name, time, author, version):
        return dict(name=name, lastModified=xmlrpclib.DateTime(int(time)),
                    author=author, version=int(version))

    def getRecentChanges(self, req, since):
        """ Get list of changed pages since timestamp """
        since = to_timestamp(since)
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute('SELECT name, max(time), author, version FROM wiki'
                       ' WHERE time >= %s GROUP BY name ORDER BY max(time) DESC', (since,))
        result = []
        for name, time, author, version in cursor:
            result.append(self._page_info(name, time, author, version))
        return result

    def getRPCVersionSupported(self, req):
        """ Returns 2 with this version of the Trac API. """
        return 2

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            return page.text
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += ' at version %s' % version
            raise xmlrpclib.Fault(0, msg)

    def getPageHTML(self, req, pagename, version=None):
        """ Return page in rendered HTML, latest version. """
        text = self.getPage(req, pagename, version)
        html = wiki_to_html(text, self.env, req, absurls=1)
        return '<html><body>%s</body></html>' % html

    def getAllPages(self, req):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """
        return list(self.wiki.get_pages())

    def getPageInfo(self, req, pagename, version=None):
        """ Returns information about the given page. """
        page = WikiPage(self.env, pagename, version)
        if page.exists:
            last_update = page.get_history().next()
            return self._page_info(page.name, last_update[1], last_update[2],
                                   page.version)

    def putPage(self, req, pagename, content, attributes):
        """ writes the content of the page. """
        page = WikiPage(self.env, pagename)
        if page.readonly:
            req.perm.assert_permission('WIKI_ADMIN')
        elif not page.exists:
            req.perm.assert_permission('WIKI_CREATE')
        else:
            req.perm.assert_permission('WIKI_MODIFY')

        page.text = content
        if req.perm.has_permission('WIKI_ADMIN'):
            page.readonly = attributes.get('readonly') and 1 or 0

        page.save(attributes.get('author', req.authname),
                  attributes.get('comment'),
                  req.remote_addr)
        return True

    def listAttachments(self, req, pagename):
        """ Lists attachments on a given page. """
        return [pagename + '/' + a.filename for a in Attachment.select(self.env, 'wiki', pagename)]

    def getAttachment(self, req, path):
        """ returns the content of an attachment. """
        pagename, filename = posixpath.split(path)
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        return xmlrpclib.Binary(attachment.open().read())

    def putAttachment(self, req, path, data):
        """ (over)writes an attachment. Returns True if successful.
        
        This method is compatible with WikiRPC.  `putAttachmentEx` has a more
        extensive set of (Trac-specific) features. """
        pagename, filename = posixpath.split(path)
        self.putAttachmentEx(req, pagename, filename, None, data)
        return True

    def putAttachmentEx(self, req, pagename, filename, description, data, replace=True):
        """ Attach a file to a Wiki page. Returns the (possibly transformed)
        filename of the attachment.
        
        Use this method if you don't care about WikiRPC compatibility. """
        if not WikiPage(self.env, pagename).exists:
            raise TracError, 'Wiki page "%s" does not exist' % pagename
        if replace:
            try:
                attachment = Attachment(self.env, 'wiki', pagename, filename)
                attachment.delete()
            except TracError:
                pass
        attachment = Attachment(self.env, 'wiki', pagename)
        attachment.author = req.authname or 'anonymous'
        attachment.description = description
        attachment.insert(filename, StringIO(data.data), len(data.data))
        return attachment.filename

    def deleteAttachment(self, req, path):
        """ Delete an attachment. """
        pagename, filename = posixpath.split(path)
        if not WikiPage(self.env, pagename).exists:
            raise TracError, 'Wiki page "%s" does not exist' % pagename
        attachment = Attachment(self.env, 'wiki', pagename, filename)
        attachment.delete()
        return True

    def listLinks(self, req, pagename):
        """ ''Not implemented'' """
        return []

    def wikiToHtml(self, req, text):
        """ Render arbitrary Wiki text as HTML. """
        return unicode(wiki_to_html(text, self.env, req, absurls=1))
예제 #18
0
 def expand_macro(self, formatter, name, content):
     env = formatter.env
     req = formatter.req
     if not content:
         args = []
         kw = {}
     else:
         args, kw = parse_args(content)
     if name == 'ProjectStats':
         if 'wiki' in kw.keys():
             prefix = 'prefix' in kw.keys() and kw['prefix'] or None
             wiki = WikiSystem(env)
             if kw['wiki'] == 'count' or 'count' in args:
                 return tag(len(list(wiki.get_pages(prefix))))
     elif name == 'UserQuery':
         msg_no_perm = tag.p(tag_("(required %(perm)s missing)",
                                  perm=tag.strong('USER_VIEW')),
                             class_='hint')
         if 'perm' in kw.keys():
             perm_sys = PermissionSystem(self.env)
             users = perm_sys.get_users_with_permission(kw['perm'].upper())
         else:
             acct_mgr = AccountManager(env)
             users = list(set(acct_mgr.get_users()))
         if 'locked' in kw.keys() or 'locked' in args:
             guard = AccountGuard(env)
             locked = []
             for user in users:
                 if guard.user_locked(user):
                     locked.append(user)
             if kw.get('locked', 'True').lower() in ('true', 'yes', '1'):
                 users = locked
             else:
                 users = list(set(users) - set(locked))
         elif 'visit' in kw.keys() or 'visit' in args:
             if 'USER_VIEW' not in req.perm:
                 return msg_no_perm
             cols = []
             data = {'accounts': fetch_user_data(env, req), 'cls': 'wiki'}
             for col in ('email', 'name'):
                 if col in args:
                     cols.append(col)
             data['cols'] = cols
             return Chrome(env).render_template(
                 req, 'user_table.html', data, 'text/html', True)
         if kw.get('format') == 'count' or 'count' in args:
             return tag(len(users))
         if 'USER_VIEW' not in req.perm:
             return msg_no_perm
         if 'email' in args or 'name' in args:
             # Replace username with full name, add email if available.
             for username, name, email in self.env.get_known_users():
                 if username in users:
                     if 'name' not in args or name is None:
                         name = username
                     if 'email' in args and email is not None:
                         email = ''.join(['<', email, '>'])
                         name = ' '.join([name, email])
                     if not username == name:
                         users.pop(users.index(username))
                         users.append(name)
         if not users and 'nomatch' in kw.keys():
             return format_to_oneliner(env, formatter.context,
                                       kw['nomatch'])
         users = sorted(users)
         if kw.get('format') == 'list':
             return tag.ul([tag.li(Chrome(env).format_author(req, user))
                            for user in users])
         else:
             # Default output format: comma-separated list.
             return tag(', '.join([Chrome(env).format_author(req, user)
                                   for user in users]))
예제 #19
0
파일: wiki.py 프로젝트: nextview/tracxmlrpc
class WikiRPC(Component):
    """Superset of the
    [http://www.jspwiki.org/Wiki.jsp?page=WikiRPCInterface2 WikiRPC API]. """

    implements(IXMLRPCHandler)

    manipulators = ExtensionPoint(IWikiPageManipulator)

    def __init__(self):
        self.wiki = WikiSystem(self.env)

    def xmlrpc_namespace(self):
        return "wiki"

    def xmlrpc_methods(self):
        yield (None, ((dict, datetime),), self.getRecentChanges)
        yield ("WIKI_VIEW", ((int,),), self.getRPCVersionSupported)
        yield (None, ((str, str), (str, str, int)), self.getPage)
        yield (None, ((str, str, int),), self.getPage, "getPageVersion")
        yield (None, ((str, str), (str, str, int)), self.getPageHTML)
        yield (None, ((str, str), (str, str, int)), self.getPageHTML, "getPageHTMLVersion")
        yield (None, ((list,),), self.getAllPages)
        yield (None, ((dict, str), (dict, str, int)), self.getPageInfo)
        yield (None, ((dict, str, int),), self.getPageInfo, "getPageInfoVersion")
        yield (None, ((bool, str, str, dict),), self.putPage)
        yield (None, ((list, str),), self.listAttachments)
        yield (None, ((Binary, str),), self.getAttachment)
        yield (None, ((bool, str, Binary),), self.putAttachment)
        yield (None, ((bool, str, str, str, Binary), (bool, str, str, str, Binary, bool)), self.putAttachmentEx)
        yield (None, ((bool, str), (bool, str, int)), self.deletePage)
        yield (None, ((bool, str),), self.deleteAttachment)
        yield ("WIKI_VIEW", ((list, str),), self.listLinks)
        yield ("WIKI_VIEW", ((str, str),), self.wikiToHtml)

    def _fetch_page(self, req, pagename, version=None):
        # Helper for getting the WikiPage that performs basic checks
        page = WikiPage(self.env, pagename, version)
        req.perm(page.resource).require("WIKI_VIEW")
        if page.exists:
            return page
        else:
            msg = 'Wiki page "%s" does not exist' % pagename
            if version is not None:
                msg += " at version %s" % version
            raise ResourceNotFound(msg)

    def _page_info(self, name, when, author, version, comment):
        return dict(name=name, lastModified=when, author=author, version=int(version), comment=comment)

    def getRecentChanges(self, req, since):
        """ Get list of changed pages since timestamp """
        since = to_utimestamp(since)
        wiki_realm = Resource("wiki")
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            "SELECT name, time, author, version, comment "
            "FROM wiki w1 "
            "WHERE time >= %s "
            "AND version = (SELECT MAX(version) "
            "               FROM wiki w2 "
            "               WHERE w2.name=w1.name) "
            "ORDER BY time DESC",
            (since,),
        )
        result = []
        for name, when, author, version, comment in cursor:
            if "WIKI_VIEW" in req.perm(wiki_realm(id=name, version=version)):
                result.append(self._page_info(name, from_utimestamp(when), author, version, comment))
        return result

    def getRPCVersionSupported(self, req):
        """ Returns 2 with this version of the Trac API. """
        return 2

    def getPage(self, req, pagename, version=None):
        """ Get the raw Wiki text of page, latest version. """
        page = self._fetch_page(req, pagename, version)
        return page.text

    def getPageHTML(self, req, pagename, version=None):
        """ Return latest version of page as rendered HTML, utf8 encoded. """
        page = self._fetch_page(req, pagename, version)
        fields = {"text": page.text}
        for manipulator in self.manipulators:
            manipulator.prepare_wiki_page(req, page, fields)
        context = Context.from_request(req, page.resource, absurls=True)
        html = format_to_html(self.env, context, fields["text"])
        return "<html><body>%s</body></html>" % html.encode("utf-8")

    def getAllPages(self, req):
        """ Returns a list of all pages. The result is an array of utf8 pagenames. """
        pages = []
        for page in self.wiki.get_pages():
            if "WIKI_VIEW" in req.perm(Resource("wiki", page)):
                pages.append(page)
        return pages

    def getPageInfo(self, req, pagename, version=None):
        """ Returns information about the given page. """
        page = WikiPage(self.env, pagename, version)
        req.perm(page.resource).require("WIKI_VIEW")
        if page.exists:
            last_update = page.get_history().next()
            return self._page_info(page.name, last_update[1], last_update[2], page.version, page.comment)

    def putPage(self, req, pagename, content, attributes):
        """ writes the content of the page. """
        page = WikiPage(self.env, pagename)
        if page.readonly:
            req.perm(page.resource).require("WIKI_ADMIN")
        elif not page.exists:
            req.perm(page.resource).require("WIKI_CREATE")
        else:
            req.perm(page.resource).require("WIKI_MODIFY")

        page.text = content
        if req.perm(page.resource).has_permission("WIKI_ADMIN"):
            page.readonly = attributes.get("readonly") and 1 or 0

        page.save(attributes.get("author", req.authname), attributes.get("comment"), req.remote_addr)
        return True

    def deletePage(self, req, name, version=None):
        """Delete a Wiki page (all versions) or a specific version by
        including an optional version number. Attachments will also be
        deleted if page no longer exists. Returns True for success."""
        wp = WikiPage(self.env, name, version)
        req.perm(wp.resource).require("WIKI_DELETE")
        try:
            wp.delete(version)
            return True
        except:
            return False

    def listAttachments(self, req, pagename):
        """ Lists attachments on a given page. """
        for a in Attachment.select(self.env, "wiki", pagename):
            if "ATTACHMENT_VIEW" in req.perm(a.resource):
                yield pagename + "/" + a.filename

    def getAttachment(self, req, path):
        """ returns the content of an attachment. """
        pagename, filename = os.path.split(path)
        attachment = Attachment(self.env, "wiki", pagename, filename)
        req.perm(attachment.resource).require("ATTACHMENT_VIEW")
        return Binary(attachment.open().read())

    def putAttachment(self, req, path, data):
        """ (over)writes an attachment. Returns True if successful.
        
        This method is compatible with WikiRPC.  `putAttachmentEx` has a more
        extensive set of (Trac-specific) features. """
        pagename, filename = os.path.split(path)
        self.putAttachmentEx(req, pagename, filename, None, data)
        return True

    def putAttachmentEx(self, req, pagename, filename, description, data, replace=True):
        """ Attach a file to a Wiki page. Returns the (possibly transformed)
        filename of the attachment.
        
        Use this method if you don't care about WikiRPC compatibility. """
        if not WikiPage(self.env, pagename).exists:
            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
        if replace:
            try:
                attachment = Attachment(self.env, "wiki", pagename, filename)
                req.perm(attachment.resource).require("ATTACHMENT_DELETE")
                attachment.delete()
            except TracError:
                pass
        attachment = Attachment(self.env, "wiki", pagename)
        req.perm(attachment.resource).require("ATTACHMENT_CREATE")
        attachment.author = req.authname
        attachment.description = description
        attachment.insert(filename, StringIO(data.data), len(data.data))
        return attachment.filename

    def deleteAttachment(self, req, path):
        """ Delete an attachment. """
        pagename, filename = os.path.split(path)
        if not WikiPage(self.env, pagename).exists:
            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
        attachment = Attachment(self.env, "wiki", pagename, filename)
        req.perm(attachment.resource).require("ATTACHMENT_DELETE")
        attachment.delete()
        return True

    def listLinks(self, req, pagename):
        """ ''Not implemented'' """
        return []

    def wikiToHtml(self, req, text):
        """ Render arbitrary Wiki text as HTML. """
        return unicode(wiki_to_html(text, self.env, req, absurls=1))
예제 #20
0
 def expand_macro(self, formatter, name, content):
     env = formatter.env
     req = formatter.req
     if not content:
         args = []
         kw = {}
     else:
         args, kw = parse_args(content)
     if name == 'ProjectStats':
         if 'wiki' in kw.keys():
             prefix = 'prefix' in kw.keys() and kw['prefix'] or None
             wiki = WikiSystem(env)
             if kw['wiki'] == 'count' or 'count' in args:
                 return tag(len(list(wiki.get_pages(prefix))))
     elif name == 'UserQuery':
         msg_no_perm = tag.p(tag_("(required %(perm)s missing)",
                                  perm=tag.strong('USER_VIEW')),
                             class_='hint')
         if 'perm' in kw.keys():
             perm_sys = PermissionSystem(self.env)
             users = perm_sys.get_users_with_permission(kw['perm'].upper())
         else:
             acct_mgr = AccountManager(env)
             users = list(set(acct_mgr.get_users()))
         if 'locked' in kw.keys() or 'locked' in args:
             guard = AccountGuard(env)
             locked = []
             for user in users:
                 if guard.user_locked(user):
                     locked.append(user)
             if kw.get('locked', 'True').lower() in ('true', 'yes', '1'):
                 users = locked
             else:
                 users = list(set(users) - set(locked))
         elif 'visit' in kw.keys() or 'visit' in args:
             if 'USER_VIEW' not in req.perm:
                 return msg_no_perm
             cols = []
             data = {'accounts': fetch_user_data(env, req), 'cls': 'wiki'}
             for col in ('email', 'name'):
                 if col in args:
                     cols.append(col)
             data['cols'] = cols
             return Chrome(env).render_template(req, 'user_table.html',
                                                data, 'text/html', True)
         if kw.get('format') == 'count' or 'count' in args:
             return tag(len(users))
         if 'USER_VIEW' not in req.perm:
             return msg_no_perm
         if 'email' in args or 'name' in args:
             # Replace username with full name, add email if available.
             for username, name, email in self.env.get_known_users():
                 if username in users:
                     if 'name' not in args or name is None:
                         name = username
                     if 'email' in args and email is not None:
                         email = ''.join(['<', email, '>'])
                         name = ' '.join([name, email])
                     if not username == name:
                         users.pop(users.index(username))
                         users.append(name)
         if not users and 'nomatch' in kw.keys():
             return format_to_oneliner(env, formatter.context,
                                       kw['nomatch'])
         users = sorted(users)
         if kw.get('format') == 'list':
             return tag.ul([
                 tag.li(Chrome(env).format_author(req, user))
                 for user in users
             ])
         else:
             # Default output format: comma-separated list.
             return tag(', '.join(
                 [Chrome(env).format_author(req, user) for user in users]))