Пример #1
0
 def sidebar_menu(self):
     try:
         l = []
         moderate_link = None
         forum_links = []
         forums = DM.Forum.query.find(dict(
                         app_config_id=c.app.config._id,
                         parent_id=None, deleted=False))
         for f in forums:
             if has_access(f,'read')():
                 if f.url() in request.url and h.has_access(f, 'moderate')():
                     moderate_link = SitemapEntry('Moderate', "%smoderate/" % f.url(), ui_icon=g.icons['pencil'],
                     small = DM.ForumPost.query.find({'discussion_id':f._id, 'status':{'$ne': 'ok'}}).count())
                 forum_links.append(SitemapEntry(f.name, f.url(), small=f.num_topics))
         l.append(SitemapEntry('Create Topic', c.app.url + 'create_topic', ui_icon=g.icons['plus']))
         if has_access(c.app, 'configure')():
             l.append(SitemapEntry('Add Forum', c.app.url + 'new_forum', ui_icon=g.icons['conversation']))
             l.append(SitemapEntry('Admin Forums', c.project.url()+'admin/'+self.config.options.mount_point+'/forums', ui_icon=g.icons['pencil']))
         if moderate_link:
             l.append(moderate_link)
         # if we are in a thread and not anonymous, provide placeholder links to use in js
         if '/thread/' in request.url and c.user not in (None, M.User.anonymous()):
             l.append(SitemapEntry(
                     'Mark as Spam', 'flag_as_spam',
                     ui_icon=g.icons['flag'], className='sidebar_thread_spam'))
         if forum_links:
             l.append(SitemapEntry('Forums'))
             l = l + forum_links
         l.append(SitemapEntry('Help'))
         l.append(SitemapEntry('Formatting Help', c.app.url + 'markdown_syntax'))
         return l
     except: # pragma no cover
         log.exception('sidebar_menu')
         return []
Пример #2
0
 def sidebar_menu(self):
     try:
         l = []
         moderate_link = None
         forum_links = []
         forums = DM.Forum.query.find(
             dict(app_config_id=c.app.config._id,
                  parent_id=None,
                  deleted=False))
         for f in forums:
             if has_access(f, 'read')():
                 if f.url() in request.url and h.has_access(f,
                                                            'moderate')():
                     moderate_link = SitemapEntry(
                         'Moderate',
                         "%smoderate/" % f.url(),
                         ui_icon=g.icons['pencil'],
                         small=DM.ForumPost.query.find({
                             'discussion_id': f._id,
                             'status': {
                                 '$ne': 'ok'
                             }
                         }).count())
                 forum_links.append(
                     SitemapEntry(f.name, f.url(), small=f.num_topics))
         url = c.app.url + 'create_topic/'
         url = h.urlquote(url + c.forum.shortname
                          if getattr(c, 'forum', None) and c.forum else url)
         l.append(SitemapEntry('Create Topic', url,
                               ui_icon=g.icons['plus']))
         if has_access(c.app, 'configure')():
             l.append(
                 SitemapEntry('Add Forum',
                              c.app.url + 'new_forum',
                              ui_icon=g.icons['conversation']))
             l.append(
                 SitemapEntry('Admin Forums',
                              c.project.url() + 'admin/' +
                              self.config.options.mount_point + '/forums',
                              ui_icon=g.icons['pencil']))
         if moderate_link:
             l.append(moderate_link)
         # if we are in a thread and not anonymous, provide placeholder links to use in js
         if '/thread/' in request.url and c.user not in (
                 None, M.User.anonymous()):
             l.append(
                 SitemapEntry('Mark as Spam',
                              'flag_as_spam',
                              ui_icon=g.icons['flag'],
                              className='sidebar_thread_spam'))
         if forum_links:
             l.append(SitemapEntry('Forums'))
             l = l + forum_links
         l.append(SitemapEntry('Help'))
         l.append(
             SitemapEntry('Formatting Help', c.app.url + 'markdown_syntax'))
         return l
     except:  # pragma no cover
         log.exception('sidebar_menu')
         return []
Пример #3
0
 def create_common_wiki_menu(self, has_create_access, admin_menu=False):
     links = []
     if has_create_access:
         links += [SitemapEntry('Create Page', self.url + 'create_wiki_page/',
                                ui_icon=g.icons['add'],
                                className='admin_modal')]
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Wiki Home', self.url, className='wiki_home')]
     links += [SitemapEntry('Browse Pages', self.url + 'browse_pages/'),
               SitemapEntry('Browse Labels', self.url + 'browse_tags/')]
     discussion = self.config.discussion
     pending_mod_count = M.Post.query.find({
         'discussion_id': discussion._id,
         'status': 'pending',
         'deleted': False
     }).count() if discussion else 0
     if pending_mod_count and h.has_access(discussion, 'moderate')():
         links.append(
             SitemapEntry(
                 'Moderate', discussion.url() + 'moderate', ui_icon=g.icons['moderate'],
                 small=pending_mod_count))
     if not c.user.is_anonymous() and not admin_menu:
         subscribed = M.Mailbox.subscribed(app_config_id=self.config._id)
         subscribe_action = 'unsubscribe' if subscribed else 'subscribe'
         subscribe_title = '{}{}'.format(
             subscribe_action.capitalize(),
             '' if subscribed else ' to wiki')
         subscribe_url = '{}#toggle-{}'.format(self.url + 'subscribe', subscribe_action)
         links.append(SitemapEntry(None))
         links.append(SitemapEntry(subscribe_title, subscribe_url, ui_icon=g.icons['mail']))
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Formatting Help', self.url + 'markdown_syntax/')]
     return links
Пример #4
0
 def create_common_wiki_menu(self, has_create_access, admin_menu=False):
     links = []
     if has_create_access:
         links += [SitemapEntry('Create Page', self.url + 'create_wiki_page/',
                                ui_icon=g.icons['add'],
                                className='admin_modal')]
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Wiki Home', self.url, className='wiki_home')]
     links += [SitemapEntry('Browse Pages', self.url + 'browse_pages/'),
               SitemapEntry('Browse Labels', self.url + 'browse_tags/')]
     discussion = self.config.discussion
     pending_mod_count = M.Post.query.find({
         'discussion_id': discussion._id,
         'status': 'pending',
         'deleted': False
     }).count() if discussion else 0
     if pending_mod_count and h.has_access(discussion, 'moderate')():
         links.append(
             SitemapEntry(
                 'Moderate', discussion.url() + 'moderate', ui_icon=g.icons['moderate'],
                 small=pending_mod_count))
     if not c.user.is_anonymous() and not admin_menu:
         subscribed = M.Mailbox.subscribed(app_config_id=self.config._id)
         subscribe_action = 'unsubscribe' if subscribed else 'subscribe'
         subscribe_title = '{}{}'.format(
             subscribe_action.capitalize(),
             '' if subscribed else ' to wiki')
         subscribe_url = '{}#toggle-{}'.format(self.url + 'subscribe', subscribe_action)
         links.append(SitemapEntry(None))
         links.append(SitemapEntry(subscribe_title, subscribe_url, ui_icon=g.icons['mail']))
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Formatting Help', self.url + 'markdown_syntax/')]
     return links
Пример #5
0
 def __json__(self):
     return dict(
         shortname=self.shortname,
         name=self.name,
         _id=str(self._id),
         url=h.absurl(self.url()),
         private=self.private,
         short_description=self.short_description,
         summary=self.summary,
         external_homepage=self.external_homepage,
         socialnetworks=[dict(n) for n in self.socialnetworks],
         status=self.removal or 'active',
         moved_to_url=self.moved_to_url,
         preferred_support_tool=self.support_page,
         preferred_support_url=self.support_page_url,
         developers=[u.__json__() for u in self.users_with_role('Developer')],
         tools=[dict(name=t.tool_name, mount_point=t.options.mount_point, label=t.options.mount_label)
                for t in self.app_configs if h.has_access(t, 'read')],
         labels=list(self.labels),
         categories={
             n: [t.__json__() for t in ts] for n, ts in self.all_troves().items()},
         icon_url=h.absurl(self.url() + 'icon') if self.icon else None,
         screenshots = [
             dict(
                 url = h.absurl(self.url() + 'screenshot/' + urllib.quote(ss.filename)),
                 thumbnail_url = h.absurl(self.url() + 'screenshot/' + urllib.quote(ss.filename) + '/thumb'),
                 caption = ss.caption,
             )
             for ss in self.get_screenshots()
         ]
     )
Пример #6
0
 def create_common_wiki_menu(self,
                             has_create_access,
                             create_page_url,
                             create_page_class,
                             admin_menu=False):
     links = []
     if has_create_access:
         links += [SitemapEntry('Create Page', create_page_url,
                                ui_icon=g.icons['plus'],
                                className=create_page_class)]
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Wiki Home', self.url, className='wiki_home')]
     links += [SitemapEntry('Browse Pages', self.url + 'browse_pages/'),
               SitemapEntry('Browse Labels', self.url + 'browse_tags/')]
     discussion = c.app.config.discussion
     pending_mod_count = M.Post.query.find(
         {'discussion_id': discussion._id, 'status': 'pending'}).count() if discussion else 0
     if pending_mod_count and h.has_access(discussion, 'moderate')():
         links.append(
             SitemapEntry(
                 'Moderate', discussion.url() + 'moderate', ui_icon=g.icons['pencil'],
                 small=pending_mod_count))
     if not admin_menu:
         links += [SitemapEntry(''),
                   SitemapEntry('Formatting Help', self.url + 'markdown_syntax/')]
     return links
Пример #7
0
 def index(self, new_forum=False, **kw):
     c.new_topic = self.W.new_topic
     c.new_topic = self.W.new_topic
     c.add_forum = self.W.add_forum
     c.announcements_table = self.W.announcements_table
     announcements = model.ForumThread.query.find(
         dict(
             app_config_id=c.app.config._id,
             flags='Announcement',
         )).all()
     forums = model.Forum.query.find(
         dict(app_config_id=c.app.config._id, parent_id=None,
              deleted=False)).all()
     forums = [f for f in forums if h.has_access(f, 'read')()]
     threads = dict()
     for forum in forums:
         threads[forum._id] = model.ForumThread.query.find(
             dict(discussion_id=forum._id,
                  num_replies={'$gt':
                               0})).sort('mod_date',
                                         pymongo.DESCENDING).limit(6).all()
     return dict(forums=forums,
                 threads=threads,
                 announcements=announcements,
                 hide_forum=(not new_forum))
Пример #8
0
 def get_projects(self):
     return [
         project for project in self.user.my_projects()
         if project != c.project and (
             self.user == c.user or h.has_access(project, 'read'))
         and not project.is_nbhd_project and not project.is_user_project
     ]
Пример #9
0
 def get_projects(self):
     return [
         project
         for project in self.user.my_projects()
         if project != c.project
            and (self.user == c.user or h.has_access(project, 'read'))
            and not project.is_nbhd_project
            and not project.is_user_project]
Пример #10
0
 def prepare_context(self, context):
     context['projects'] = [
         project
         for project in self.user.my_projects()
         if project != c.project
         and (self.user == c.user or h.has_access(project, 'read'))
         and not project.is_nbhd_project
         and not project.is_user_project]
     return context
Пример #11
0
 def index(self, **kw):
     return dict(name=c.project.shortname,
                 tools=[
                     dict(name=t.tool_name,
                          mount_point=t.options.mount_point,
                          label=t.options.mount_label)
                     for t in c.project.app_configs
                     if h.has_access(t, 'read')
                 ])
Пример #12
0
 def index(self, **kw):
     return dict(
         name=c.project.shortname,
         tools=[
             dict(name=t.tool_name, mount_point=t.options.mount_point, label=t.options.mount_label)
             for t in c.project.app_configs
             if h.has_access(t, "read")
         ],
     )
Пример #13
0
    def sitemap(self, excluded_tools=None):
        """Return the project sitemap.

        :param list excluded_tools: tool names (AppConfig.tool_name) to
                                    exclude from sitemap
        """
        from allura.app import SitemapEntry
        entries = []

        anchored_tools = self.neighborhood.get_anchored_tools()
        i = len(anchored_tools)
        new_tools = self.install_anchored_tools()

        # Set menu mode
        delta_ordinal = i
        max_ordinal = i

        for sub in self.direct_subprojects:
            ordinal = sub.ordinal + delta_ordinal
            if ordinal > max_ordinal:
                max_ordinal = ordinal
            entries.append({'ordinal':sub.ordinal + delta_ordinal,'entry':SitemapEntry(sub.name, sub.url())})
        for ac in self.app_configs + [a.config for a in new_tools]:
            if excluded_tools and ac.tool_name in excluded_tools:
                continue
            # Tool could've been uninstalled in the meantime
            try:
                App = ac.load()
            # If so, we don't want it listed
            except KeyError as e:
                log.exception('AppConfig %s references invalid tool %s', ac._id, ac.tool_name)
                continue
            app = App(self, ac)
            if app.is_visible_to(c.user):
                for sm in app.main_menu():
                    entry = sm.bind_app(app)
                    entry.tool_name = ac.tool_name
                    entry.ui_icon = 'tool-%s' % entry.tool_name.lower()
                    if not self.is_nbhd_project and (entry.tool_name.lower() in anchored_tools.keys()):
                        ordinal = anchored_tools.keys().index(entry.tool_name.lower())
                    elif ac.tool_name == 'admin':
                        ordinal = 100
                    else:
                        ordinal = int(ac.options.get('ordinal', 0)) + delta_ordinal
                    if self.is_nbhd_project and entry.label == 'Admin':
                        entry.matching_urls.append('%s_admin/' % self.url())
                    if ordinal > max_ordinal:
                        max_ordinal = ordinal
                    entries.append({'ordinal':ordinal,'entry':entry})

        if self == self.neighborhood.neighborhood_project and h.has_access(self.neighborhood, 'admin'):
            entries.append({'ordinal': max_ordinal + 1,'entry':SitemapEntry('Moderate', "%s_moderate/" % self.neighborhood.url(), ui_icon="tool-admin")})
            max_ordinal += 1

        entries = sorted(entries, key=lambda e: e['ordinal'])
        return [e['entry'] for e in entries]
Пример #14
0
 def index(self, sort='alpha', limit=25, page=0, **kw):
     c.project = self.neighborhood.neighborhood_project
     if self.neighborhood.redirect:
         redirect(self.neighborhood.redirect)
     if not self.neighborhood.has_home_tool:
         mount = c.project.first_mount()
         if mount is not None:
             if 'ac' in mount:
                 redirect(mount['ac'].options.mount_point + '/')
             elif 'sub' in mount:
                 redirect(mount['sub'].url())
         else:
             redirect(c.project.app_configs[0].options.mount_point + '/')
     c.project_summary = W.project_summary
     c.page_list = W.page_list
     limit, page, start = g.handle_paging(limit, page)
     pq = M.Project.query.find(
         dict(
             neighborhood_id=self.neighborhood._id,
             deleted=False,
             is_nbhd_project=False,
         ))
     if sort == 'alpha':
         pq.sort('name')
     else:
         pq.sort('last_updated', pymongo.DESCENDING)
     count = pq.count()
     nb_max_projects = self.neighborhood.get_max_projects()
     projects = pq.skip(start).limit(int(limit)).all()
     categories = M.ProjectCategory.query.find({
         'parent_id': None
     }).sort('name').all()
     c.custom_sidebar_menu = []
     if h.has_access(self.neighborhood,
                     'register')() and (nb_max_projects is None
                                        or count < nb_max_projects):
         c.custom_sidebar_menu += [
             SitemapEntry('Add a Project',
                          self.neighborhood.url() + 'add_project',
                          ui_icon=g.icons['plus']),
             SitemapEntry('')
         ]
     c.custom_sidebar_menu = c.custom_sidebar_menu + [
         SitemapEntry(cat.label,
                      self.neighborhood.url() + 'browse/' + cat.name)
         for cat in categories
     ]
     return dict(neighborhood=self.neighborhood,
                 title="Welcome to " + self.neighborhood.name,
                 text=g.markdown.convert(self.neighborhood.homepage),
                 projects=projects,
                 sort=sort,
                 limit=limit,
                 page=page,
                 count=count)
Пример #15
0
    def sitemap(self, excluded_tools=None):
        """Return the project sitemap.

        :param list excluded_tools: tool names (AppConfig.tool_name) to
                                    exclude from sitemap
        """
        from allura.app import SitemapEntry

        entries = []

        # Set menu mode
        delta_ordinal = 0
        max_ordinal = 0

        if self.is_user_project:
            entries.append(
                {
                    "ordinal": delta_ordinal,
                    "entry": SitemapEntry("Profile", "%sprofile/" % self.url(), ui_icon="tool-home"),
                }
            )
            max_ordinal = delta_ordinal
            delta_ordinal = delta_ordinal + 1

        for sub in self.direct_subprojects:
            ordinal = sub.ordinal + delta_ordinal
            if ordinal > max_ordinal:
                max_ordinal = ordinal
            entries.append({"ordinal": sub.ordinal + delta_ordinal, "entry": SitemapEntry(sub.name, sub.url())})
        for ac in self.app_configs:
            if excluded_tools and ac.tool_name in excluded_tools:
                continue
            App = ac.load()
            app = App(self, ac)
            if app.is_visible_to(c.user):
                for sm in app.main_menu():
                    entry = sm.bind_app(app)
                    entry.ui_icon = "tool-%s" % ac.tool_name.lower()
                    ordinal = int(ac.options.get("ordinal", 0)) + delta_ordinal
                    if ordinal > max_ordinal:
                        max_ordinal = ordinal
                    entries.append({"ordinal": ordinal, "entry": entry})

        if self == self.neighborhood.neighborhood_project and h.has_access(self.neighborhood, "admin"):
            entries.append(
                {
                    "ordinal": max_ordinal + 1,
                    "entry": SitemapEntry("Moderate", "%s_moderate/" % self.neighborhood.url(), ui_icon="tool-admin"),
                }
            )
            max_ordinal += 1

        entries = sorted(entries, key=lambda e: e["ordinal"])
        return [e["entry"] for e in entries]
Пример #16
0
    def index(self, sort='alpha', limit=25, page=0, **kw):
        text = None
        if self.neighborhood.use_wiki_page_as_root:
            default_wiki_page = get_default_wiki_page()
            if default_wiki_page:
                text = default_wiki_page.html_text
        elif self.neighborhood.redirect:
            redirect(self.neighborhood.redirect)
        elif not self.neighborhood.has_home_tool:
            mount = c.project.ordered_mounts()[0]
            if mount is not None:
                if 'ac' in mount:
                    redirect(mount['ac'].options.mount_point + '/')
                elif 'sub' in mount:
                    redirect(mount['sub'].url())
            else:
                redirect(c.project.app_configs[0].options.mount_point + '/')
        else:
            text=g.markdown.cached_convert(
                self.neighborhood, 'homepage'),

        c.project_summary = W.project_summary
        c.page_list = W.page_list
        limit, page, start = g.handle_paging(limit, page)
        pq = M.Project.query.find(dict(
            neighborhood_id=self.neighborhood._id,
            deleted=False,
            is_nbhd_project=False,
        ))
        if sort == 'alpha':
            pq.sort('name')
        else:
            pq.sort('last_updated', pymongo.DESCENDING)
        count = pq.count()
        nb_max_projects = self.neighborhood.get_max_projects()
        projects = pq.skip(start).limit(int(limit)).all()
        categories = M.ProjectCategory.query.find(
            {'parent_id': None}).sort('name').all()
        c.custom_sidebar_menu = []
        if h.has_access(self.neighborhood, 'register')() and (nb_max_projects is None or count < nb_max_projects):
            c.custom_sidebar_menu += [
                SitemapEntry('Add a Project', self.neighborhood.url()
                             + 'add_project', ui_icon=g.icons['add']),
                SitemapEntry('')
            ]
        c.custom_sidebar_menu = c.custom_sidebar_menu + [
            SitemapEntry(cat.label, self.neighborhood.url() + 'browse/' + cat.name) for cat in categories
        ]
        return dict(neighborhood=self.neighborhood,
                    title="Welcome to " + self.neighborhood.name,
                    text=text,
                    projects=projects,
                    sort=sort,
                    limit=limit, page=page, count=count)
Пример #17
0
 def index(self, new_forum=False, **kw):
     c.add_forum = self.W.add_forum
     c.announcements_table = self.W.announcements_table
     announcements = model.ForumThread.query.find(dict(
         app_config_id=c.app.config._id,
         flags='Announcement',
     )).all()
     forums = model.Forum.query.find(dict(
         app_config_id=c.app.config._id,
         parent_id=None, deleted=False)).all()
     forums = [f for f in forums if h.has_access(f, 'read')()]
     return dict(forums=forums,
                 announcements=announcements,
                 hide_forum=(not new_forum))
Пример #18
0
 def index(self, new_forum=False, **kw):
     c.add_forum = self.W.add_forum
     c.announcements_table = self.W.announcements_table
     announcements = model.ForumThread.query.find(
         dict(
             app_config_id=c.app.config._id,
             flags='Announcement',
         )).all()
     forums = model.Forum.query.find(
         dict(app_config_id=c.app.config._id, parent_id=None,
              deleted=False)).all()
     forums = [f for f in forums if h.has_access(f, 'read')()]
     return dict(forums=forums,
                 announcements=announcements,
                 hide_forum=(not new_forum))
Пример #19
0
    def projects_count(self):
        from allura import model as M
        from allura.lib import helpers as h

        q = dict(deleted=False,
                 is_nbhd_project=False,
                 neighborhood_id=self._id)

        total = 0

        for p in M.Project.query.find(q):
            if h.has_access(p, 'read')():
                total = total + 1
                if total == 100:
                    return total

        return total
Пример #20
0
    def projects_count(self):
        from allura import model as M
        from allura.lib import helpers as h

        q = dict(
            deleted=False,
            is_nbhd_project=False,
            neighborhood_id=self._id)

        total = 0

        for p in M.Project.query.find(q):
            if h.has_access(p, 'read')():
                total = total + 1
                if total == 100:
                    return total

        return total
Пример #21
0
 def index(self, new_forum=False, **kw):
     c.new_topic = self.W.new_topic
     c.new_topic = self.W.new_topic
     c.add_forum = self.W.add_forum
     c.announcements_table = self.W.announcements_table
     announcements=model.ForumThread.query.find(dict(
             app_config_id=c.app.config._id,
             flags='Announcement',
             )).all()
     forums = model.Forum.query.find(dict(
                     app_config_id=c.app.config._id,
                     parent_id=None, deleted=False)).all()
     forums = [f for f in forums if h.has_access(f, 'read')()]
     threads = dict()
     for forum in forums:
         threads[forum._id] = model.ForumThread.query.find(dict(
             discussion_id=forum._id, num_replies={'$gt': 0})).sort('mod_date', pymongo.DESCENDING).limit(6).all()
     return dict(forums=forums,
                 threads=threads,
                 announcements=announcements,
                 hide_forum=(not new_forum))
Пример #22
0
 def __json__(self):
     return dict(shortname=self.shortname,
                 name=self.name,
                 _id=str(self._id),
                 url=h.absurl(self.url()),
                 private=self.private,
                 short_description=self.short_description,
                 summary=self.summary,
                 external_homepage=self.external_homepage,
                 socialnetworks=[dict(n) for n in self.socialnetworks],
                 status=self.removal or 'active',
                 moved_to_url=self.moved_to_url,
                 preferred_support_tool=self.support_page,
                 preferred_support_url=self.support_page_url,
                 developers=[
                     u.__json__() for u in self.users_with_role('Developer')
                 ],
                 tools=[
                     dict(name=t.tool_name,
                          mount_point=t.options.mount_point,
                          label=t.options.mount_label)
                     for t in self.app_configs if h.has_access(t, 'read')
                 ],
                 labels=list(self.labels),
                 categories={
                     n: [t.__json__() for t in ts]
                     for n, ts in self.all_troves().items()
                 },
                 icon_url=h.absurl(self.url() +
                                   'icon') if self.icon else None,
                 screenshots=[
                     dict(
                         url=h.absurl(self.url() + 'screenshot/' +
                                      urllib.quote(ss.filename)),
                         thumbnail_url=h.absurl(self.url() + 'screenshot/' +
                                                urllib.quote(ss.filename) +
                                                '/thumb'),
                         caption=ss.caption,
                     ) for ss in self.get_screenshots()
                 ])
Пример #23
0
    def related_artifacts(self, user=None):
        """Return all Artifacts that are related to this one.

        """
        related_artifacts = []
        for ref_id in self.refs + self.backrefs:
            ref = ArtifactReference.query.get(_id=ref_id)
            if ref is None:
                continue
            artifact = ref.artifact
            if artifact is None:
                continue
            artifact = artifact.primary()
            if artifact is None:
                continue
            # don't link to artifacts in deleted tools
            if hasattr(artifact, 'app_config') and artifact.app_config is None:
                continue
            try:
                if user and not h.has_access(artifact, 'read', user):
                    continue
            except Exception:
                log.debug(
                    'Error doing permission check on related artifacts of {}, '
                    'probably because the "artifact" is a Commit not a real artifact'
                    .format(self.index_id()),
                    exc_info=True)

            # TODO: This should be refactored. We shouldn't be checking
            # artifact type strings in platform code.
            if artifact.type_s == 'Commit' and not artifact.repo:
                ac = AppConfig.query.get(
                    _id=ref.artifact_reference['app_config_id'])
                app = ac.project.app_instance(ac) if ac else None
                if app:
                    artifact.set_context(app.repo)
            if artifact not in related_artifacts and (getattr(
                    artifact, 'deleted', False) is False):
                related_artifacts.append(artifact)
        return sorted(related_artifacts, key=lambda a: a.url())
Пример #24
0
 def create_common_wiki_menu(self,
                             has_create_access,
                             create_page_url,
                             create_page_class,
                             admin_menu=False):
     links = []
     if has_create_access:
         links += [
             SitemapEntry('Create Page',
                          create_page_url,
                          ui_icon=g.icons['plus'],
                          className=create_page_class)
         ]
     if not admin_menu:
         links += [
             SitemapEntry(''),
             SitemapEntry('Wiki Home', self.url, className='wiki_home')
         ]
     links += [
         SitemapEntry('Browse Pages', self.url + 'browse_pages/'),
         SitemapEntry('Browse Labels', self.url + 'browse_tags/')
     ]
     discussion = c.app.config.discussion
     pending_mod_count = M.Post.query.find({
         'discussion_id': discussion._id,
         'status': 'pending'
     }).count() if discussion else 0
     if pending_mod_count and h.has_access(discussion, 'moderate')():
         links.append(
             SitemapEntry('Moderate',
                          discussion.url() + 'moderate',
                          ui_icon=g.icons['pencil'],
                          small=pending_mod_count))
     if not admin_menu:
         links += [
             SitemapEntry(''),
             SitemapEntry('Formatting Help', self.url + 'markdown_syntax/')
         ]
     return links
Пример #25
0
 def __json__(self):
     result = dict(
         shortname=self.shortname,
         name=self.name,
         _id=str(self._id),
         url=h.absurl(self.url()),
         private=self.private,
         short_description=self.short_description,
         creation_date=plugin.ProjectRegistrationProvider.get().registration_date(self).strftime('%Y-%m-%d'),
         summary=self.summary,
         external_homepage=self.external_homepage,
         video_url=self.video_url,
         socialnetworks=[dict(n) for n in self.socialnetworks],
         status=self.removal or 'active',
         moved_to_url=self.moved_to_url,
         preferred_support_tool=self.support_page,
         preferred_support_url=self.support_page_url,
         developers=[u.__json__()
                     for u in self.users_with_role('Developer')],
         tools=[self.app_instance(t) for t in self.app_configs if h.has_access(t, 'read')],
         labels=list(self.labels),
         categories={n: [t.__json__() for t in ts]
                     for n, ts in self.all_troves().items()},
         icon_url=h.absurl(self.url() + 'icon') if self.icon else None,
         screenshots=[
             dict(
                 url=h.absurl(self.url() + 'screenshot/' +
                              urllib.quote(ss.filename.encode('utf8'))),
                 thumbnail_url=h.absurl(
                     self.url(
                     ) + 'screenshot/' + urllib.quote(ss.filename.encode('utf8')) + '/thumb'),
                 caption=ss.caption,
             )
             for ss in self.get_screenshots()
         ]
     )
     if self.is_user_project:
         result['profile_api_url'] = h.absurl('/rest' + self.url() + 'profile/')
     return result
Пример #26
0
    def related_artifacts(self, user=None):
        """Return all Artifacts that are related to this one.

        """
        related_artifacts = []
        for ref_id in self.refs + self.backrefs:
            ref = ArtifactReference.query.get(_id=ref_id)
            if ref is None:
                continue
            artifact = ref.artifact
            if artifact is None:
                continue
            artifact = artifact.primary()
            if artifact is None:
                continue
            # don't link to artifacts in deleted tools
            if hasattr(artifact, 'app_config') and artifact.app_config is None:
                continue
            try:
                if user and not h.has_access(artifact, 'read', user):
                    continue
            except Exception:
                log.debug('Error doing permission check on related artifacts of {}, '
                          'probably because the "artifact" is a Commit not a real artifact'.format(self.index_id()),
                          exc_info=True)

            # TODO: This should be refactored. We shouldn't be checking
            # artifact type strings in platform code.
            if artifact.type_s == 'Commit' and not artifact.repo:
                ac = AppConfig.query.get(_id=ref.artifact_reference['app_config_id'])
                app = ac.project.app_instance(ac) if ac else None
                if app:
                    artifact.set_context(app.repo)
            if artifact not in related_artifacts and (getattr(artifact, 'deleted', False) is False):
                related_artifacts.append(artifact)
        return sorted(related_artifacts, key=lambda a: a.url())
Пример #27
0
 def index(self, limit=None, page=0, count=0, **kw):
     latest = c.app.repo.latest(branch=self._branch)
     if not latest or (latest._id.split(':')[1] == '1' and h.has_access(c.app, 'write')()):
         return dict(allow_fork=False, log=[])
     redirect(latest.url() + 'tree/')
Пример #28
0
    def sitemap(self, excluded_tools=None):
        """Return the project sitemap.

        :param list excluded_tools: tool names (AppConfig.tool_name) to
                                    exclude from sitemap
        """
        from allura.app import SitemapEntry
        entries = []

        anchored_tools = self.neighborhood.get_anchored_tools()
        i = len(anchored_tools)
        new_tools = self.install_anchored_tools()
        self.app_config('admin').options.ordinal = 100

        # Set menu mode
        delta_ordinal = i
        max_ordinal = i

        for sub in self.direct_subprojects:
            ordinal = sub.ordinal + delta_ordinal
            if ordinal > max_ordinal:
                max_ordinal = ordinal
            entries.append({
                'ordinal': sub.ordinal + delta_ordinal,
                'entry': SitemapEntry(sub.name, sub.url())
            })
        for ac in self.app_configs + [a.config for a in new_tools]:
            if excluded_tools and ac.tool_name in excluded_tools:
                continue
            # Tool could've been uninstalled in the meantime
            try:
                App = ac.load()
            # If so, we don't want it listed
            except KeyError as e:
                log.exception('AppConfig %s references invalid tool %s',
                              ac._id, ac.tool_name)
                continue
            app = App(self, ac)
            if app.is_visible_to(c.user):
                for sm in app.main_menu():
                    entry = sm.bind_app(app)
                    entry.tool_name = ac.tool_name
                    entry.ui_icon = 'tool-%s' % entry.tool_name.lower()
                    if not self.is_nbhd_project and (entry.tool_name.lower()
                                                     in anchored_tools.keys()):
                        ordinal = anchored_tools.keys().index(
                            entry.tool_name.lower())
                    else:
                        ordinal = int(ac.options.get('ordinal',
                                                     0)) + delta_ordinal
                    if self.is_nbhd_project and entry.label == 'Admin':
                        entry.matching_urls.append('%s_admin/' % self.url())
                    if ordinal > max_ordinal:
                        max_ordinal = ordinal
                    entries.append({'ordinal': ordinal, 'entry': entry})

        if self == self.neighborhood.neighborhood_project and h.has_access(
                self.neighborhood, 'admin'):
            entries.append({
                'ordinal':
                max_ordinal + 1,
                'entry':
                SitemapEntry('Moderate',
                             "%s_moderate/" % self.neighborhood.url(),
                             ui_icon="tool-admin")
            })
            max_ordinal += 1

        entries = sorted(entries, key=lambda e: e['ordinal'])
        return [e['entry'] for e in entries]
Пример #29
0
    def sitemap(self, excluded_tools=None):
        """Return the project sitemap.

        :param list excluded_tools: tool names (AppConfig.tool_name) to
                                    exclude from sitemap
        """
        from allura.app import SitemapEntry
        entries = []

        # Set menu mode
        delta_ordinal = 0
        max_ordinal = 0

        if self.is_user_project:
            entries.append({
                'ordinal':
                delta_ordinal,
                'entry':
                SitemapEntry('Profile',
                             "%sprofile/" % self.url(),
                             ui_icon="tool-home")
            })
            max_ordinal = delta_ordinal
            delta_ordinal = delta_ordinal + 1

        for sub in self.direct_subprojects:
            ordinal = sub.ordinal + delta_ordinal
            if ordinal > max_ordinal:
                max_ordinal = ordinal
            entries.append({
                'ordinal': sub.ordinal + delta_ordinal,
                'entry': SitemapEntry(sub.name, sub.url())
            })
        for ac in self.app_configs:
            if excluded_tools and ac.tool_name in excluded_tools:
                continue
            App = ac.load()
            app = App(self, ac)
            if app.is_visible_to(c.user):
                for sm in app.main_menu():
                    entry = sm.bind_app(app)
                    entry.ui_icon = 'tool-%s' % ac.tool_name.lower()
                    ordinal = int(ac.options.get('ordinal', 0)) + delta_ordinal
                    if ordinal > max_ordinal:
                        max_ordinal = ordinal
                    entries.append({'ordinal': ordinal, 'entry': entry})

        if self == self.neighborhood.neighborhood_project and h.has_access(
                self.neighborhood, 'admin'):
            entries.append({
                'ordinal':
                max_ordinal + 1,
                'entry':
                SitemapEntry('Moderate',
                             "%s_moderate/" % self.neighborhood.url(),
                             ui_icon="tool-admin")
            })
            max_ordinal += 1

        entries = sorted(entries, key=lambda e: e['ordinal'])
        return [e['entry'] for e in entries]
Пример #30
0
    def doap(self):
        root = ET.Element('rdf:RDF', {
            'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
            'xmlns:rdfs': "http://www.w3.org/2000/01/rdf-schema#",
        })
        project = ET.SubElement(root, 'Project', {
            'xmlns': "http://usefulinc.com/ns/doap#",
            'xmlns:foaf': "http://xmlns.com/foaf/0.1/",
            'xmlns:sf': "http://sourceforge.net/api/sfelements.rdf#",
            'xmlns:rss': "http://purl.org/rss/1.0/",
            'xmlns:dc': "http://dublincore.org/documents/dcmi-namespace/",
            'xmlns:beer': "http://www.purl.org/net/ontology/beer.owl#",
            'rdf:about': "http://sourceforge.net/api/project/name/vivo/doap#",
        })
        # Basic fields
        ET.SubElement(project, 'name').text = self.shortname
        ET.SubElement(project, 'dc:title').text = self.name
        ET.SubElement(project, 'sf:id').text = str(self._id)
        ET.SubElement(project, 'sf:private').text = self.private
        ET.SubElement(project, 'shortdesc', {'xml:lang': 'en'}).text = self.short_description
        ET.SubElement(project, 'description', {'xml:lang': 'en'}).text = self.description
        if self.external_homepage:
            ET.SubElement(project, 'homepage', {'rdf:resource': self.external_homepage})

        # Categories
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_audience}}):
            ET.SubElement(project, 'audience').text = cat.fullname
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_os}}):
            ET.SubElement(project, 'os').text = cat.fullname
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_language}}):
            ET.SubElement(project, 'programming-language').text = cat.fullname
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_license}}):
            ET.SubElement(project, 'license').text = cat.fullname
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_environment}}):
            ET.SubElement(project, 'sf:environment').text = cat.fullname
        for cat in TroveCategory.query.find({'_id': {'$in': self.trove_root_database}}):
            ET.SubElement(project, 'sf:database').text = cat.fullname
        all_troves = (
            self.trove_root_database +
            self.trove_developmentstatus +
            self.trove_audience +
            self.trove_license +
            self.trove_topic +
            self.trove_os +
            self.trove_language +
            self.trove_natlanguage +
            self.trove_environment
        )
        for cat in TroveCategory.query.find({'_id': {'$in': all_troves}}):
            ET.SubElement(project, 'category', {'rdf:resource': 'http://sourceforge.net/api/trove/index/rdf#%s' % cat.trove_cat_id})

        # Awards
        for a in self.accolades:
            award = ET.SubElement(project, 'sf:awarded')
            award = ET.SubElement(award, 'beer:Award')
            ET.SubElement(award, 'beer:awardCategory').text = a.award.full
            ET.SubElement(award, 'beer:awardedAt').text = a.granted_by_neighborhood.name

        # Maintainers
        admins = self.admins()
        for u in admins:
            person = ET.SubElement(project, 'maintainer')
            person = ET.SubElement(person, 'foaf:Person', {
                'xmlns:foaf': "http://xmlns.com/foaf/0.1/",
                'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#"})
            ET.SubElement(person, 'foaf:name').text = u.display_name
            ET.SubElement(person, 'foaf:nick').text = u.username
            ET.SubElement(person, 'foaf:homepage', {'rdf:resource': h.absurl(u.url())})

        # Developers
        devs = [u for u in self.users_with_role('Developer') if u not in admins]
        for u in devs:
            person = ET.SubElement(project, 'developer')
            person = ET.SubElement(person, 'foaf:Person', {
                'xmlns:foaf': "http://xmlns.com/foaf/0.1/",
                'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#"})
            ET.SubElement(person, 'foaf:name').text = u.display_name
            ET.SubElement(person, 'foaf:nick').text = u.username
            ET.SubElement(person, 'foaf:homepage', {'rdf:resource': h.absurl(u.url())})

        # Basic tool info
        apps = [self.app_instance(ac) for ac in self.app_configs if h.has_access(ac, 'read')]
        for app in apps:
            app.doap(project)

        return ET.tostring(root, encoding='utf-8')
Пример #31
0
    def sitemap(self, excluded_tools=None, included_tools=None,
            tools_only=False, per_tool_limit=SITEMAP_PER_TOOL_LIMIT):
        """
        Return the project sitemap.

        :param list excluded_tools:
           Tool names (AppConfig.tool_name) to exclude from sitemap.

        :param list included_tools:
           Tool names (AppConfig.tool_name) to include. Use `None` to
           include all tool types.

        :param bool tools_only:
            Only include tools in the sitemap (exclude subprojects).

        :param int per_tool_limit:
            Max number of entries included in the sitemap for a single tool
            type. Use `None` to include all.

        """
        from allura.app import SitemapEntry
        entries = []

        anchored_tools = self.neighborhood.get_anchored_tools()
        i = len(anchored_tools)
        new_tools = self.install_anchored_tools()

        # Set menu mode
        delta_ordinal = i
        max_ordinal = i

        # Keep running count of entries per tool type
        tool_counts = Counter({tool_name: 0 for tool_name in g.entry_points['tool']})

        if not tools_only:
            for sub in self.direct_subprojects:
                ordinal = sub.ordinal + delta_ordinal
                if ordinal > max_ordinal:
                    max_ordinal = ordinal
                entries.append({'ordinal': sub.ordinal + delta_ordinal,
                               'entry': SitemapEntry(sub.name, sub.url())})

        for ac in self.app_configs + [a.config for a in new_tools]:
            if per_tool_limit:
                # We already have max entries for every tool type
                if min(tool_counts.values()) >= per_tool_limit:
                    break

                # We already have max entries for this tool type
                if tool_counts.get(ac.tool_name, 0) >= per_tool_limit:
                    continue

            if excluded_tools and ac.tool_name in excluded_tools:
                continue

            if included_tools and ac.tool_name not in included_tools:
                continue

            # Tool could've been uninstalled in the meantime
            try:
                App = ac.load()
            # If so, we don't want it listed
            except KeyError as e:
                log.exception('AppConfig %s references invalid tool %s',
                              ac._id, ac.tool_name)
                continue
            app = App(self, ac)
            if app.is_visible_to(c.user):
                for sm in app.main_menu():
                    entry = sm.bind_app(app)
                    entry.tool_name = ac.tool_name
                    entry.ui_icon = 'tool-%s' % entry.tool_name.lower()
                    if not self.is_nbhd_project and (entry.tool_name.lower() in anchored_tools.keys()):
                        ordinal = anchored_tools.keys().index(
                            entry.tool_name.lower())
                    elif ac.tool_name == 'admin':
                        ordinal = 100
                    else:
                        ordinal = int(ac.options.get('ordinal', 0)) + \
                            delta_ordinal
                    if self.is_nbhd_project and entry.label == 'Admin':
                        entry.matching_urls.append('%s_admin/' % self.url())
                    if ordinal > max_ordinal:
                        max_ordinal = ordinal
                    entries.append({'ordinal': ordinal, 'entry': entry})
                    tool_counts.update({ac.tool_name: 1})

        if (not tools_only and
                self == self.neighborhood.neighborhood_project and
                h.has_access(self.neighborhood, 'admin')):
            entries.append({
                'ordinal': max_ordinal + 1,
                'entry': SitemapEntry(
                    'Moderate',
                    "%s_moderate/" % self.neighborhood.url(),
                    ui_icon="tool-admin")
                })
            max_ordinal += 1

        entries = sorted(entries, key=lambda e: e['ordinal'])
        return [e['entry'] for e in entries]
Пример #32
0
 def index(self, limit=None, page=0, count=0, **kw):
     latest = c.app.repo.latest(branch=self._branch)
     if not latest or (latest._id.split(':')[1] == '1'
                       and h.has_access(c.app, 'write')()):
         return dict(allow_fork=False, log=[])
     redirect(latest.url() + 'tree/')