Ejemplo n.º 1
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.reports.generate.pdf',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate_test_pdf" % objId
         tmpDict['title'] = _(u"generate test pdf")
         tmpDict['href'] = u"%s/@@generate_test_pdf" % \
                (zapi.absoluteURL(self.context, self.request))
         tmpDict['tooltip'] = _(u"will generate a test pdf file")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.reports.generate.pdf',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate_all_pdf" % objId
         tmpDict['title'] = _(u"generate all pdf")
         tmpDict['href'] = u"%s/@@generate_all_pdf" % \
                (zapi.absoluteURL(self.context, self.request))
         tmpDict['tooltip'] = _(u"will generate a all pdf file")
         retList.append(tmpDict)
     return retList
Ejemplo n.º 2
0
 def __call__(self):
     if checkPermission('simplemanagement.EditCompass', self.context):
         return super(Compass, self).__call__()
     elif checkPermission('simplemanagement.ViewCompass', self.context):
         self.request.response.redirect('{0}history'.format(self.base_url()))
         return u''
     raise Unauthorized
Ejemplo n.º 3
0
def create_sittings_map(sittings, request):
    """Returns a dictionary that maps:

      (day, hour) -> {
         'record'   : sitting database record
         'actions'  : actions that apply to this sitting
         'class'    : sitting
         'span'     : span
         }
         
      (day, hour) -> ``None``
      
    If the mapped value is a sitting, then a sitting begins on that
    day and hour, if it's ``None``, then a sitting is reaching into
    this day and hour.
    
    The utility of the returned structure is to aid rendering a
    template with columns spanning several rows.
    """

    mapping = {}
    for sitting in sittings.values():
        day = sitting.start_date.weekday()
        hour = sitting.start_date.hour

        start_date = utils.timedict(sitting.start_date.hour, sitting.start_date.minute)

        end_date = utils.timedict(sitting.end_date.hour, sitting.end_date.minute)

        status = misc.get_wf_state(sitting)

        proxied = ProxyFactory(sitting)

        if checkPermission(u"bungeni.agendaitem.wf.schedule", proxied):
            link = "%s/schedule" % url.absoluteURL(sitting, request)
        else:
            link = url.absoluteURL(sitting, request)

        if checkPermission("zope.View", proxied):
            mapping[day, hour] = {
                "url": link,
                "record": sitting,
                "class": u"sitting",
                "actions": get_sitting_actions(sitting, request),
                "span": sitting.end_date.hour - sitting.start_date.hour,
                "formatted_start_time": start_date,
                "formatted_end_time": end_date,
                "status": status,
            }
            for hour in range(sitting.start_date.hour + 1, sitting.end_date.hour):
                mapping[day, hour] = None

        # make sure start- and end-date is the same DAY
        assert (
            (sitting.start_date.day == sitting.end_date.day)
            and (sitting.start_date.month == sitting.end_date.month)
            and (sitting.start_date.year == sitting.end_date.year)
        )

    return mapping
Ejemplo n.º 4
0
    def isAvailable(self):
        context = self.context
        if checkPermission('zojax.AddPhoto', context) or \
                checkPermission('zojax.SubmitPhoto', context):
            return True

        return False
Ejemplo n.º 5
0
 def available(self):
     if (checkPermission("cmf.ModifyPortalContent", self.context)
             or checkPermission("cmf.ReviewPortalContent", self.context)
         ) and (INewsletterIssue.providedBy(self.context)
                or INewsletter.providedBy(self.context)):
         return True
     return False
Ejemplo n.º 6
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.esx_vim.Admin',
                        self.context) and\
        zapi.queryMultiAdapter((self.context, self.request),
                               name='shutdown.html') is not None:
         tmpDict = {}
         tmpDict['oid'] = u"c%sshutdown" % objId
         tmpDict['title'] = _(u"shutdown")
         tmpDict['href'] = u"%s/@@shutdown.html" % \
                zapi.getPath(self.context)
         tmpDict['tooltip'] = _(u"shutdow the virtual machine")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.esx_vim.Admin',
                        self.context) and\
        zapi.queryMultiAdapter((self.context, self.request),
                               name='convertobj.html') is not None:
         tmpDict = {}
         tmpDict['oid'] = u"c%sconvertobj" % objId
         tmpDict['title'] = _(u"convert to intern")
         tmpDict['href'] = u"%s/@@convertobj.html" % \
                zapi.getPath(self.context)
         tmpDict['tooltip'] = _(u"convert to internal object")
         retList.append(tmpDict)
     return retList
Ejemplo n.º 7
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.compliance.generate.pdf',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate_all_pdf" % objId
         tmpDict['title'] = _(u"generate all pdf")
         tmpDict['href'] = u"%s/@@generate_all_pdf" % \
                (zapi.getPath(self.context))
         tmpDict['tooltip'] = _(u"will generate a all pdf file")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.compliance.Import',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%simport requirements" % objId
         tmpDict['title'] = _(u"import requirements")
         tmpDict['href'] = u"%s/@@import_requirements" % \
                (zapi.getPath(self.context))
         tmpDict['tooltip'] = _(u"will import requirements")
         retList.append(tmpDict)
     return retList
Ejemplo n.º 8
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     adapSize = ISized(self.context)
     if checkPermission('org.ict_ok.admin_utils.supervisor.ReindexDB',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sreindex_db" % objId
         tmpDict['title'] = _(u"reindex database")
         tmpDict['href'] = u"%s/@@reindex_db?nextURL=%s" % \
                (zapi.getPath( self.context),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will reindex the catalogs of all "\
                                u"tables in database")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.supervisor.PackDB',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%spack_db" % objId
         tmpDict['title'] = _(u"pack database")
         tmpDict['href'] = u"%s/@@pack_db?nextURL=%s" % \
                (zapi.getPath( self.context),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will pack the database and delete "\
                                u"all backups")
         retList.append(tmpDict)
     return retList
Ejemplo n.º 9
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = self.context.objectID
     except KeyError:
         objId = 1000
     retList = []
     adapSize = ISized(self.context)
     if checkPermission('org.ict_ok.admin_utils.supervisor.ReindexDB',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sreindex_db" % objId
         tmpDict['title'] = _(u"reindex database")
         tmpDict['href'] = u"%s/@@reindex_db?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will reindex the catalogs of all "\
                                u"tables in database")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.supervisor.RemoveIndices',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sremove_indices" % objId
         tmpDict['title'] = _(u"Remove indices")
         tmpDict['href'] = u"%s/@@remove_indices?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will remove all indices of all "\
                                u"tables in database")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.supervisor.CreateIndices',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%screate_indices" % objId
         tmpDict['title'] = _(u"Create indices")
         tmpDict['href'] = u"%s/@@create_indices?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will create all indices in database")
         retList.append(tmpDict)
     if not self.isInIctSite() and \
         checkPermission('org.ict_ok.admin_utils.supervisor.PackDB',
                         self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%spack_db" % objId
         tmpDict['title'] = _(u"pack database")
         tmpDict['href'] = u"%s/@@pack_db?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will pack the database and delete "\
                                u"all backups")
         retList.append(tmpDict)
     return retList
Ejemplo n.º 10
0
    def update(self):
        if self.updated:
            return

        self.updated = True

        context = self.context
        if checkPermission('zojax.ModifyTaskStatus', context):
            self.severity = getUtility(
                IVocabularyFactory, 'project.task.severity')(context)

        if checkPermission('zojax.ModifyTaskAttributes', context):
            self.allowAttributes = True

        if checkPermission('zojax.AssignTo', context):
            self.allowAssign = True

        if checkPermission('zojax.AddContentAttachment', context):
            self.allowAttachments = True

        self.wfinfo = IWorkflowInfo(context)
        self.wfinfo.fireAutomatic()

        # subscribers
        auth = getUtility(IAuthentication)

        subs = getSubscribers(('tasks',), context)
        assignees = getSubscribers(('assigneetasks'), context)

        for pid in IAssignments(context).assignees:
            if pid in assignees:
                subs.add(pid)

        subscribers = []
        for subs in subs:
            try:
                principal = auth.getPrincipal(subs)
            except PrincipalLookupError:
                continue

            profile = IPersonalProfile(principal)

            subscribers.append(profile.title)

        subscribers.sort()
        self.subscribers = subscribers

        task = removeAllProxies(context)
        if checkPermission('zojax.ModifyContent', task.__parent__.__parent__):
            self.manageSubscribers = absoluteURL(
                task.__parent__.__parent__, self.request)

        super(TaskCommentForm, self).update()

        include('jquery-plugins')

        if 'file' in self.widgets:
            self.widgets['file'].klass = 'multi'
Ejemplo n.º 11
0
    def reply(self):
        # return 401/403 Forbidden if the user has no permission
        if not checkPermission("cmf.AddPortalContent", self.context):
            pm = getToolByName(self.context, "portal_membership")
            if bool(pm.isAnonymousUser()):
                self.request.response.setStatus(401)
            else:
                self.request.response.setStatus(403)
            return

        data = json_body(self.request)

        source = data.get("source", None)

        if not source:
            raise BadRequest("Property 'source' is required")

        # Disable CSRF protection
        if "IDisableCSRFProtection" in dir(plone.protect.interfaces):
            alsoProvides(self.request,
                         plone.protect.interfaces.IDisableCSRFProtection)

        if not isinstance(source, list):
            source = [source]

        parents_ids = {}
        for item in source:
            obj = self.get_object(item)
            if obj is not None:
                if self.is_moving:
                    # To be able to safely move the object, the user requires
                    # permissions on the parent
                    if not checkPermission("zope2.DeleteObjects",
                                           obj) and not checkPermission(
                                               "zope2.DeleteObjects",
                                               aq_parent(obj)):
                        self.request.response.setStatus(403)
                        return
                parent = aq_parent(obj)
                if parent in parents_ids:
                    parents_ids[parent].append(obj.getId())
                else:
                    parents_ids[parent] = [obj.getId()]

        results = []
        for parent, ids in parents_ids.items():
            result = self.context.manage_pasteObjects(
                cb_copy_data=self.clipboard(parent, ids))
            for res in result:
                results.append({
                    "source":
                    "{}/{}".format(parent.absolute_url(), res["id"]),
                    "target":
                    "{}/{}".format(self.context.absolute_url(), res["new_id"]),
                })
        return results
Ejemplo n.º 12
0
    def update(self):
        context = self.context
        request = self.request

        self.noIcon = not bool(self.context.icon)

        principal = self.request.principal
        if not IUnauthenticatedPrincipal.providedBy(principal):
            self.menu = True

            self.submitTopic = \
                checkPermission('zojax.forum.AddTopic', context) or \
                checkPermission('zojax.forum.SubmitTopic', context)

            notifications = getAdapter(context, IContentNotification, 'forum')
            self.subscribed = notifications.isSubscribed(principal.id)

        if len(self.context) > 1:
            self.searching = True

        data = ISession(request)[SESSIONKEY]
        forum = removeAllProxies(context)
        key = getUtility(IIntIds).getId(forum)

        if 'form.button.search' in request:
            searchableText = request['form.searchforum']
            data[key] = (searchableText, True)

        if 'form.button.clear' in request:
            searchableText = None
            if key in data:
                del data[key]

        else:
            searchtext, searching = data.get(key, (u'', False))
            if searchtext and searching:
                searchableText = searchtext
            else:
                searchableText = None

        if searchableText:
            query = {'searchableText': searchableText,
                     'type': {'any_of': ('forum.message',)},
                     'traversablePath': {'any_of': (forum,)},
                     'noPublishing': True, 'noSecurityChecks': True}

            try:
                results = getUtility(ICatalog).searchResults(**query)
            except Exception, e:
                IStatusMessage(self.request).add(e, 'error')
                return

            self.total = len(results)
            self.searchableText = searchableText
            self.searchResults = Batch(results, size=20, request=request)
Ejemplo n.º 13
0
    def isAvailable(self):
        ws = IContentWorkspace(self.request.principal, None)
        if ws is None:
            return False

        context = self.context
        if not IPhotosWorkspace.providedBy(context.get('photos')):
            return False

        if checkPermission('zojax.AddPhoto', context) or \
                checkPermission('zojax.SubmitPhoto', context):
            return True

        return False
Ejemplo n.º 14
0
 def getMenuItems(self, context, request):
     """Return menu item entries in a TAL-friendly form."""
     _url = url.absoluteURL(context, request)
     if checkPermission("bungeni.translation.Add", context):
         language = get_language(context)
         available = get_available_translations(context)
         results = []
         for name, obj in get_all_languages().items():
             title = obj["name"]
             # skip the current language
             if name == language:
                 continue
             action_url = "%s/translate?language=%s" % (_url, name)
             extra = {
                 "id": "translation-action-%s" % name,
                 "separator": None,
                 "class": ""
             }
             translation_id = available.get(name)
             results.append(
                 dict(title=title,
                      description="",
                      action=action_url,
                      selected=translation_id is not None,
                      icon=None,
                      extra=extra,
                      submenu=None))
         return results
     else:
         return None
Ejemplo n.º 15
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     adapSize = ISized(self.context)
     # adapSize.sizeForSorting() returns ('item', n)
     if checkPermission('org.ict_ok.components.host.Add', self.context) and \
        (adapSize.sizeForSorting()[1] < 1):
         tmpDict = {}
         tmpDict['oid'] = u"c%sstart_scanner" % objId
         tmpDict['title'] = _(u"start scanner")
         tmpDict['href'] = u"%s/@@start_scanner.html" % \
                zapi.absoluteURL(self.context, self.request)
         tmpDict['tooltip'] = _(u"starts the network scanner (as user:%s)"\
                                % self.request.principal.title)
         retList.append(tmpDict)
     #tmpDict = {}
     #tmpDict['oid'] = u"a%s" % objId
     #tmpDict['title'] = u"ich bin ein Titel"
     #tmpDict['href'] = u"http://www.essen.de"
     #tmpDict['tooltip'] = u"ich bin der \"aa\" 'bb' dazugehörige T"
     #retList.append(tmpDict)
     return retList
Ejemplo n.º 16
0
 def getMenuItems(self, context, request):
     results = []
     unproxied = proxy.removeSecurityProxy(context.__parent__)
     try:
         items = unproxied.items()
     except AttributeError:
         items = []
         for key, info in capi.iter_type_info():
             if IScheduleContent.implementedBy(info.domain_model):
                 name = naming.plural(key)
                 if hasattr(unproxied, name):
                     items.append((name, getattr(unproxied, name)))
     for key, item in items:
         if not IAlchemistContainer.providedBy(item): continue
         if not IScheduleContent.implementedBy(item.domain_model): continue
         type_info = capi.get_type_info(item.domain_model)
         permission = "bungeni.%s.Add" % (
             type_info.workflow_key
             or naming.type_key("model_name", item.domain_model.__name__))
         if not checkPermission(permission, context): continue
         dc_adapter = IDCDescriptiveProperties(item, None)
         if dc_adapter:
             _title = dc_adapter.title
         else:
             _title = getattr(item, "title", "Unknown")
         results.append(
             dict(title=_title,
                  description=_title,
                  action=url.absoluteURL(item, request),
                  selected=False,
                  icon=None,
                  extra={},
                  submenu=None))
     return results
Ejemplo n.º 17
0
    def tileTypes(self):
        """Get a list of addable ITileType objects representing tiles
        which are addable in the current context
        """
        tiles = []

        factory = getUtility(IVocabularyFactory,
                             name=ALLOWED_TILES_VOCABULARY)
        vocabulary = factory(self.context)

        for item in vocabulary:
            tiletype = item.value
            # check if we have permission to add this tile
            if tiletype and checkPermission(
                    tiletype.add_permission, self.context):
                # tile actions
                # TODO: read from registry
                tiletype.actions = [{
                    'name': 'edit',
                    'url': '@@edit-tile',
                    'title': _('Edit'),
                }, {
                    'name': 'remove',
                    'url': '@@delete-tile',
                    'title': _('Remove'),
                }]
                tiles.append(tiletype)

        tiles.sort(key=attrgetter('title'))
        return tiles
Ejemplo n.º 18
0
 def values(self):
     workflow = get_workflow(self.context.domain_model.__name__.lower())
     public_wfstates = workflow.get_state_ids(tagged=["public"],
         restrict=False)
     return [ x for x in self.context.values()
         if checkPermission("zope.View", x)
              and x.status in public_wfstates ]
Ejemplo n.º 19
0
    def reply(self):
        # return 403 Forbidden if the user has no DelegateRoles permission
        if not checkPermission("plone.DelegateRoles", self.context):
            self.request.response.setStatus(403)
            return

        deserializer = queryMultiAdapter(
            (self.context, self.request),
            interface=IDeserializeFromJson,
            name="local_roles",
        )
        # Disable CSRF protection
        if "IDisableCSRFProtection" in dir(plone.protect.interfaces):
            alsoProvides(self.request,
                         plone.protect.interfaces.IDisableCSRFProtection)

        if deserializer is None:
            self.request.response.setStatus(501)
            return dict(error=dict(
                message="Cannot deserialize local roles for type {}".format(
                    self.context.portal_type)))

        try:
            deserializer()
        except DeserializationError as e:
            self.request.response.setStatus(400)
            return dict(
                error=dict(type="DeserializationError", message=str(e)))

        # TODO: alternativley return the patched object with a 200
        return self.reply_no_content()
Ejemplo n.º 20
0
def list_container_items(container, permission="zope.View"):
    """Generate list of container items with permission check
    """
    trusted = proxy.removeSecurityProxy(container)
    for contained in trusted.values():
        if checkPermission(permission, contained):
            yield contained
Ejemplo n.º 21
0
    def source_timeline(self):
        """
        Return back references from source object on specified attribute_name
        """
        catalog = getUtility(ICatalog)
        intids = getUtility(IIntIds)

        source_object = self.context
        attribute_name = 'issue'

        result = []
        sorted_effective = []

        for rel in catalog.findRelations(
                dict(to_id=intids.getId(aq_inner(source_object)),
                     from_attribute=attribute_name)):

            obj = intids.queryObject(rel.from_id)

            if obj is not None and checkPermission('zope2.View', obj):
                if obj.portal_type == 'Issue Source':
                    result.append(obj)

            sorted_effective = sorted(result,
                                      key=methodcaller('effective'),
                                      reverse=True)
        if sorted_effective:
            return sorted_effective
        else:
            return None
Ejemplo n.º 22
0
    def update(self):
        super(Topic, self).update()

        context = self.context
        request = self.request

        context = removeSecurityProxy(context)

        if not IDraftedContent.providedBy(context) and \
                checkPermission('zojax.forum.AddMessage', context):
            self.reply = getMultiAdapter((context, request), name='reply.html')

        info = {'replies': len(context)-1, 'next': None, 'prev': None}

        forum = context.__parent__

        if IForum.providedBy(IForum):
            topics = forum.topics

            next = topics.next(context)
            if next is not None:
                info['prev'] = {'name': next.__name__,
                                'title': next.title}

            prev = topics.previous(context)
            if prev is not None:
                info['next'] = {'name': prev.__name__,
                                'title': prev.title}

        self.topicInfo = info

        if self.reply is not None:
            self.reply.update()
            if self.reply.isRedirected:
                self.redirect()
Ejemplo n.º 23
0
    def update(self):
        try:
            author = getUtility(IAuthentication).getPrincipal(
                self.context.author)
        except:
            author = None

        if author is not None:
            profile = IPersonalProfile(author)
            self.avatar = profile.avatarUrl(self.request)
            self.author = profile.title

            if profile.space is not None:
                self.url = absoluteURL(profile.space, self.request)
        else:
            self.avatar = u'%s/@@profile.avatar/0'%absoluteURL(
                getSite(), self.request)

        if author is not None or author == u'Unauthenticated User':
            if getattr(self.context, 'authorName'):
                self.author = self.context.authorName
                if 'social_avatar_url' in dir(self.context) and self.context.social_type:
                    self.social_avatar = self.context.social_avatar_url
                    if self.context.social_type==1:
                        self.social_name = 'Twitter'
                    elif self.context.social_type==2:
                        self.social_name = 'Facebook'

        self.comment = self.context.comment

        content = self.context.content
        self.postsAllowed = (
            IContentDiscussion(content).status in [1, 4] and
            checkPermission('zojax.AddComment', content))
Ejemplo n.º 24
0
 def can_modify(self, itemob=None):
     try:
         itemob = itemob or self.context
         return checkPermission('cmf.ModifyPortalContent', itemob)
     except Exception as e:
         import pdb
         pdb.set_trace()
Ejemplo n.º 25
0
def list_container_items(container, permission="zope.View"):
    """Generate list of container items with permission check
    """
    trusted = proxy.removeSecurityProxy(container)
    for contained in trusted.values():
        if checkPermission(permission, contained):
            yield contained
Ejemplo n.º 26
0
 def __call__(self, force=None):
     """ try executing all pending request with dates older than "now" """
     if not checkPermission('synchro.Execute', self.context):
         raise Forbidden
     if self.storage.busy:
         if force:
             LOG_INFO("Forcing synchro on busy storage")
         else:
             LOG_ERROR("Synchro is busy, use force=true to force execution")
             raise BadRequest("Synchro is busy")
     LOG_INFO("Locking synchro", BLATHER)
     self.storage.busy = True
     transaction.commit()
     LOG_INFO("Starting synchro processing", BLATHER)
     processed = 0
     try:
         for entry in self.olderPending():
             self.process(entry)
             processed += 1
         return "Synchro finished. %s entries processed" % processed
     finally:
         LOG_INFO("Unlocking synchro", BLATHER)
         self.storage.busy = False
         transaction.commit()
         LOG_INFO("Synchro finished. %s entries processed" % processed, BLATHER)
Ejemplo n.º 27
0
 def execute_static_deployment(self, entry):
     """
     executes defined staticdeployment process
     @rtype: dict
     """
     response = {}
     action = entry.action
     
     def handle_error(msg):
         LOG_ERROR(msg)
         response['status'] = 'error'
         response['data'] = [msg]
         
     if not checkPermission('static.Export', self.context):
         mtool = getToolByName(self.context, 'portal_membership')
         username = mtool.getMemberInfo().get('username', '')
         errmsg = "User '%s' has no 'static.Export' permission" % username
         handle_error(errmsg)
         return response
     
     action_items = getattr(entry, 'props', {})
     staticdeployment = getMultiAdapter((self.context, self.request),
                                         name='staticdeployment-controlpanel')
     if not action_items.has_key('section_choice'):
         errmsg = "Deployment skin is not defined in config file"
         handle_error(errmsg)
         return response
     
     staticdeployment._on_save(dict(action_items))
     response['status'] = 'ok'
           
     return response
Ejemplo n.º 28
0
    def __call__(self, *args, **kw):
        context = self.context

        if not checkPermission('zope.View', context):
            self.space = context
            self.__parent__ = context.__parent__
            return super(PersonalSpace, self).__call__()

        workspaces = []
        defaultWorkspace = IWorkspacesManagement(context).defaultWorkspace

        redirectWorkspace = None

        for name, factory in getAdapters((context,), IWorkspaceFactory):
            if context.isEnabled(factory):
                workspaces.append((factory.weight, factory.title, name))
                if defaultWorkspace == name:
                    redirectWorkspace = name

        if workspaces:
            if redirectWorkspace is None:
                workspaces.sort()
                redirectWorkspace = workspaces[0][2]
            self.redirect('./%s/'%redirectWorkspace)
        else:
            self.redirect('./listing.html')
Ejemplo n.º 29
0
 def can_manage_portlets(self):
     # ftool = getToolByName(context, 'portal_factory', None)
     # if ftool and ftool.isTemporary(context) or \
     #     not ILocalPortletAssignable.providedBy(context):
     #     return False
     return checkPermission("plone.app.portlets.ManagePortlets",
                            self._context())
Ejemplo n.º 30
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sshutdownHost" % objId
         tmpDict['title'] = _(u"shutdown host")
         tmpDict['href'] = u"%s/@@shutdownHost.html?nextURL=%s" % \
                (zapi.getPath( self.context),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%senterMaintenanceMode" % objId
         tmpDict['title'] = _(u"enter maintenance mode")
         tmpDict['href'] = u"%s/@@enterMaintenanceMode.html?nextURL=%s" % \
                (zapi.getPath( self.context),
                 quoter.quote())
         retList.append(tmpDict)
     return SuperHostDetails.actions(self) + retList
Ejemplo n.º 31
0
 def groups_data(self):
     group_list = []
     try:
         group = self.context.get_group()
         if model_interfaces.ICommittee.providedBy(group):
             group_container = group.parent_group.committees
         else:
             group = self.context.get_group()
             group_container = group.committees
             group_list.append({
                 "key":
                 self.context.group_id,
                 "label":
                 IDCDescriptiveProperties(group).title,
             })
         group_list += [
             {
                 "key": comm.committee_id,
                 "label": IDCDescriptiveProperties(comm).title
             } for comm in group_container.values()
             if checkPermission("bungeni.committee_member.Add", comm)
         ]
     except AttributeError:
         log.warn("Context %s has no committees", self.context)
     return group_list
Ejemplo n.º 32
0
    def getMenuItems(self, context, request):
        """Return menu item entries in a TAL-friendly form."""

        types = []
        for type_ in getAllUtilitiesRegisteredFor(ITileType):
            if checkPermission(type_.add_permission, context):
                try:
                    if request.traverseName(
                        context, "@@" + type_.__name__):
                        types.append(type_)
                except NotFound:
                    continue
        types.sort(lambda x, y: cmp(x.title, y.title))

        normalizer = getUtility(IIDNormalizer)
        return [{
                'title': type_.title,
                'description': type_.description,
                'action': "%s/@@add-tile?form.button.Create=1&type=%s"\
                    % (context.absolute_url(), type_.__name__),
                'selected': False,
                'icon': None,
                'extra': {
                    'id': "add-%s" % normalizer.normalize(type_.__name__),
                    'separator': None, 'class': ''
                    },
                'submenu': None,
                } for type_ in types]
Ejemplo n.º 33
0
    def sittings_and_sessions(self):
        event_list = []
        try:
            date = self.request.get("from")
            dateobj = datetime.datetime(*time.strptime(date, "%Y-%m-%d")[0:5])
            start_date = utils.datetimedict.fromdate(dateobj)
        except:
            start_date = None

        try:
            date = self.request.get("to")
            dateobj = datetime.datetime(*time.strptime(date, "%Y-%m-%d")[0:5])
            end_date = utils.datetimedict.fromdate(dateobj)
        except:
            end_date = None

        if start_date is None:
            start_date = utils.datetimedict.fromdate(datetime.date.today())
            days = tuple(start_date + timedelta(days=d) for d in range(7))
            end_date = days[-1]
        elif end_date is None:
            start_date = utils.datetimedict.fromdate(datetime.date.today())
            days = tuple(start_date + timedelta(days=d) for d in range(7))
            end_date = days[-1]
        sittings = self.context.get_sittings(start_date, end_date)
        for sitting in sittings.values():
            if checkPermission("bungeni.sitting.View", sitting):
                trusted = removeSecurityProxy(sitting)
                trusted.text = dict(sitting_status=_(
                    misc.get_wf_state(trusted, trusted.status)))
                event_list.append(trusted)
        if model_interfaces.IParliament.providedBy(self.context.get_group()):
            return event_list + self.get_sessions()
        else:
            return event_list
Ejemplo n.º 34
0
    def get_options(self):
        registry = queryUtility(IRegistry)
        adapted = IMosaicRegistryAdapter(registry)
        pt = self.obtainType()
        kwargs = {
            'type': pt,
            'context': self.context,
            'request': self.request,
        }
        result = adapted(**kwargs)

        result['canChangeLayout'] = checkPermission(
            'plone.CustomizeContentLayouts', self.context)
        result['context_url'] = self.context.absolute_url()
        result['tinymce'] = get_tinymce_options(self.context, self.field,
                                                self.request)
        if 'pattern_options' in result['tinymce']:
            # BBB Plone 4.3.x
            result['tinymce'] = result['tinymce']['pattern_options']

        result['customContentLayout_selector'] = '#formfield-{0:s}'.format(
            self.name.replace('.', '-'))
        result['contentLayout_selector'] = '#formfield-{0:s}'.format(
            self.name.replace('.', '-').replace('-content', '-contentLayout'))
        result['customContentLayout_field_selector'] = '[name="{0:s}"]'.format(
            self.name)
        result['contentLayout_field_selector'] = '[name="{0:s}"]'.format(
            self.name.replace('.content', '.contentLayout'))

        result['available_layouts'] = getContentLayoutsForType(pt)

        return {'data': result}
    def stories(self):
        """
        Return back references from source object where

        """
        catalog = getUtility(ICatalog)
        intids = getUtility(IIntIds)

        source_object = self.context.issue.to_object
        attribute_names = ['issue']

        result = []

        for attribute_name in attribute_names:

            for rel in catalog.findRelations(
                dict(to_id=intids.getId(aq_inner(source_object)),
                     from_attribute=attribute_name)
                  ):

                obj = intids.queryObject(rel.from_id)

                if obj is not None and checkPermission('zope2.View', obj):
                    if obj.portal_type == 'Issue Source':
                        if obj.id != self.context.id:
                            result.append(obj)

        unique = list(dict.fromkeys(result))

        sorted_effective = sorted(unique,
                                  key=methodcaller('effective'),
                                  reverse=True)

        return sorted_effective
Ejemplo n.º 36
0
 def render(self, template=None):
     if template is None:
         template = self.template
     if (not checkPermission(u"bungeni.sitting.Add", self.context)) or \
         (IBusinessSectionLayer.providedBy(self.request)):
         self.edit = False
     else:
         self.edit = True
     session = Session()
     venues = session.query(domain.Venue).all()
     languages = get_all_languages()
     session.close()
     #defaults to english
     self.display_language = 'en'
     if self.request.get('I18N_LANGUAGES'):
         self.display_language = self.request.get('I18N_LANGUAGES')
     #html is hardcoded in here because doing it in the template
     #would have been a colossal pain
     #TODO: FIX THIS
     s = '<div class="dhx_cal_ltext" style="height:90px;">'
     s += '<table>'
     s += '<tr><td>Venue</td><td><select id="select_sitting_venue">'
     for venue in venues:
         s += '<option value="' + str(
             venue.venue_id) + '">' + venue.short_name + '</option>'
     s += '</select></td></tr>'
     s += '<tr><td>Language</td><td><select id="select_sitting_lang">'
     for lang in languages:
         if lang == 'en':
             s += '<option value="' + lang + '" selected>' + lang + '</option>'
         else:
             s += '<option value="' + lang + '">' + lang + '</option>'
     s += '</select></td></tr></table></div>'
     self.sitting_details_form = s
     return template()
Ejemplo n.º 37
0
 def getMenuItems(self, context, request):
     """Return menu item entries in a TAL-friendly form."""
     _url = url.absoluteURL(context, request)
     if checkPermission("bungeni.translation.Add", context):
         language = get_language(context)
         available = get_available_translations(context)
         results = []
         for name, obj in get_all_languages().items():
             title = obj["name"]
             # skip the current language
             if name == language:
                 continue
             action_url = "%s/translate?language=%s" % (_url, name)
             extra = {
                 "id": "translation-action-%s" % name,
                 "separator": None,
                 "class": ""
             }
             translation_id = available.get(name)
             results.append(
                 dict(title=title,
                      description="",
                      action=action_url,
                      selected=translation_id is not None,
                      icon=None,
                      extra=extra,
                      submenu=None))
         return results
     else:
         return None
Ejemplo n.º 38
0
    def stories(self):
        """
        Return back references from source object where

        """
        catalog = getUtility(ICatalog)
        intids = getUtility(IIntIds)

        source_object = self.context
        attribute_names = [
            'implicated', 'directly_implicated', 'circumstantial_implicated'
        ]

        result = []

        for attribute_name in attribute_names:

            for rel in catalog.findRelations(
                    dict(to_id=intids.getId(aq_inner(source_object)),
                         from_attribute=attribute_name)):

                obj = intids.queryObject(rel.from_id)

                if obj is not None and checkPermission('zope2.View', obj):
                    if obj.portal_type == 'Issue Source':
                        result.append(obj)

        unique = list(dict.fromkeys(result))

        return unique
Ejemplo n.º 39
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%spoweroff" % objId
         tmpDict['title'] = _(u"Power off")
         tmpDict['href'] = u"%s/@@poweroff.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%spoweron" % objId
         tmpDict['title'] = _(u"Power on")
         tmpDict['href'] = u"%s/@@poweron.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
     return SuperHostDetails.actions(self) + retList
Ejemplo n.º 40
0
    def update(self):
        super(MemberMessageNotification, self).update()

        context = self.context
        request = self.request

        group = removeAllProxies(context.context).__parent__
        visible = checkPermission('zope.View', group)

        owner = IOwnership(group).owner
        profile = IPersonalProfile(owner, None)

        message = cgi.escape(context.message)
        message = message.replace(' ', '&nbsp;')
        message = message.replace('\n', '<br />')

        self.title = group.title
        self.sender = getattr(profile, 'title', 'Unknown member')

        self.info = {
            'title': group.title,
            'description': group.description,
            'created': IDCTimes(group).created,
            'members': len(group),
            'url': '%s/'%absoluteURL(group, request),
            'message': message,
            'default': not visible or not bool(getattr(group, 'logo', None)),
            'sender': self.sender}

        if profile is not None:
            self.addHeader(u'From', formataddr((self.sender, profile.email),))

        self.site = getSite()
        self.siteTitle = getattr(self.site, 'title', u'') or self.site.__name__
        self.siteURL = u'%s'%absoluteURL(self.site, request)
Ejemplo n.º 41
0
 def showCreateCommunity(self):
     """ The Contributor role is assumed that will be applied at the group in
         the portal root.
     """
     if IHomePage.providedBy(self.context) and \
        checkPermission('ulearn.addCommunity', self.portal()):
         return True
Ejemplo n.º 42
0
    def __call__(self):
        self.request.response.setHeader('X-Theme-Disabled', '1')
        try:
            res = self.render()
            if self.global_editable and checkPermission(
                    'cmf.ModifyPortalContent', self.context):
                # wrap with tile url div
                config = json.dumps({
                    'label': self.edit_label,
                    'url': self.view_url,
                    'editUrl': self.edit_url
                })
                res = """
<div class="castle-tile-wrapper pat-edittile"
     data-pat-edittile='%s'>%s</div>""" % (config, res)
            else:
                if self.wrap:
                    res = '<div class="castle-tile-wrapper">%s</div>' % res
            return '<html><body>' + res + '</body></html>'
        except:
            path = ['']
            if hasattr(self.context, 'getPhysicalPath'):
                path = self.context.getPhysicalPath()
            logger.error(
                'Error rendering tile on context: %s, data: %s,\n%s' %
                ('/'.join(path), repr(self.data), traceback.format_exc()))
            return """<html><body>
Ejemplo n.º 43
0
 def can_modify(self, itemob=None):
     try:
         itemob = itemob or self.context
         return checkPermission('cmf.ModifyPortalContent', itemob)
     except Exception as e:
         import pdb
         pdb.set_trace()
    def backrefs(self, attribute_name):
        """
        Return back references from source object on specified attribute_name
        """
        catalog = getUtility(ICatalog)
        intids = getUtility(IIntIds)

        source_object = self.context
        result = []

        for rel in catalog.findRelations(
                dict(to_id=intids.getId(aq_inner(source_object)),
                     from_attribute=attribute_name)):

            obj = intids.queryObject(rel.from_id)

            if obj is not None and checkPermission('zope2.View', obj):
                if obj.portal_type == 'Ownership Control Statement':

                    # Temporary workaround for broken objects
                    if obj.absolute_url():
                        # Only for Statements that are linked to an
                        # Issue
                        if obj.interestedParty:
                            result.append(obj)

        return result
Ejemplo n.º 45
0
    def __call__(self):
        try:
            date = self.request.get("from")
            dateobj = datetime.datetime(*time.strptime(date, "%Y-%m-%d")[0:5])
            start_date = utils.datetimedict.fromdate(dateobj)
        except:
            start_date = None

        try:
            date = self.request.get("to")
            dateobj = datetime.datetime(*time.strptime(date, "%Y-%m-%d")[0:5])
            end_date = utils.datetimedict.fromdate(dateobj)
        except:
            end_date = None

        if start_date is None:
            start_date = utils.datetimedict.fromdate(datetime.date.today())
            days = tuple(start_date + timedelta(days=d) for d in range(7))
            end_date = days[-1]
        elif end_date is None:
            start_date = utils.datetimedict.fromdate(datetime.date.today())
            days = tuple(start_date + timedelta(days=d) for d in range(7))
            end_date = days[-1]
        sittings = self.context.get_sittings(start_date, end_date)
        self.sittings = []
        for sitting in sittings.values():
            if checkPermission("zope.View", sitting):
                trusted = removeSecurityProxy(sitting)
                trusted.text = dict(sitting_status=_(misc.get_wf_state(trusted, trusted.status)))
                self.sittings.append(trusted)
        self.request.response.setHeader("Content-type", self.content_mimetype)
        return self.render()
Ejemplo n.º 46
0
    def isAvailable(self):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            return False

        principal = self.context.__principal__
        principalId = principal.id

        if self.request.principal.id == principalId:
            return False

        invitations = [
            invitation.object.id for invitation in
            getUtility(IInvitations).getInvitationsByPrincipal(
                principalId, ('invitation.member',))]

        for group in getUtility(ICatalog).searchResults(
            type = {'any_of': ('content.group',)},
            members = {'any_of': (self.request.principal.id,)}):

            if group.id in invitations:
                continue

            if principalId not in group.members and \
                    checkPermission('zojax.InviteGroupMember', group):
                return True

        return False
Ejemplo n.º 47
0
    def tileTypes(self):
        """Get a list of addable ITileType objects representing tiles
        which are addable in the current context
        """
        tiles = []

        for tile_name in getUtility(IRegistry)['plone.app.tiles']:
            tiletype = getUtility(ITileType, tile_name)
            # check if we have permission to add this tile
            if checkPermission(tiletype.add_permission, self.context):
                # tile actions
                # TODO: read from registry
                tiletype.actions = [{
                    'name': 'edit',
                    'url': '@@edit-tile',
                    'title': _('Edit'),
                }, {
                    'name': 'remove',
                    'url': '@@delete-tile',
                    'title': _('Remove'),
                }]
                tiles.append(tiletype)

        tiles.sort(self.tileSortKey)
        return tiles
Ejemplo n.º 48
0
    def tileTypes(self):
        """Get a list of addable ITileType objects representing tiles
        which are addable in the current context
        """
        tiles = []

        for tile_name in getUtility(IRegistry)['plone.app.tiles']:
            tiletype = queryUtility(ITileType, tile_name.strip())
            # check if we have permission to add this tile
            if tiletype and checkPermission(tiletype.add_permission,
                                            self.context):
                # tile actions
                # TODO: read from registry
                tiletype.actions = [{
                    'name': 'edit',
                    'url': '@@edit-tile',
                    'title': _('Edit'),
                }, {
                    'name': 'remove',
                    'url': '@@delete-tile',
                    'title': _('Remove'),
                }]
                tiles.append(tiletype)

        tiles.sort(self.tileSortKey)
        return tiles
Ejemplo n.º 49
0
    def show_controls(self):
        """ Returns True if the sources should be modifyable/removeable. """

        # not exactly the required permission, but that's not the point:
        # if the user has the permission to edit the context the permission
        # to edit the sources probably inherited.
        return checkPermission('cmf.ModifyPortalContent', self.context)
    def _format_iteration(self, item):
        start = None
        if item.start:
            start = item.start.isoformat()

        end = None
        if item.end:
            end = item.end.isoformat()

        totals, stories = self._get_stories(item)

        return {
            "title": item.title,
            "description": item.description,
            "url": item.absolute_url(),
            "status": "TODO",  # TODO: get iteration status and display it
            "stories": [],  # retrieved dynamically
            "is_sortable": self.user_can_manage_project(item),
            "start": start,
            "start_str": self.context.toLocalizedTime(start),
            "end": end,
            "end_str": self.context.toLocalizedTime(end),
            "can_edit": checkPermission("cmf.ModifyPortalContent", item),
            "warning_delta_percent": self._settings.warning_delta_percent,
            "totals": totals,
        }
Ejemplo n.º 51
0
    def translate(self, source_lang, value, is_translatable):
        """ Renders a translated cell based on lang and original value

        We have a special template for not-translatable values, to be
        integrated in the general format that is required by the styling
        """

        value = normalize(value)
        # if isinstance(value, str):      # BBB: with older implementation
        #     value = value.decode('utf-8')      # TODO: should use decode?

        if (not value) or (not is_translatable):
            return self.cell_tpl(value=value)

        if not isinstance(value, basestring):
            return self.cell_tpl(value=value)

        # if detected language is english render cell template
        lang = None
        try:
            lang = get_detected_lang(value)
        except LangDetectException:
            lang = 'en'

        if lang == 'en':
            return self.cell_tpl(value=value)

        translated = get_translated(value, source_lang)

        can_edit = checkPermission('wise.EditTranslations', self.context)

        return self.translate_tpl(text=value,
                                  translation=translated,
                                  can_translate=can_edit,
                                  source_lang=source_lang)
Ejemplo n.º 52
0
 def get_sessions(self):
     sessions = [ removeSecurityProxy(session) for key, session in 
         self.context.get_group().sessions.items()
         if checkPermission("bungeni.session.View", session)
     ]
     sessions.sort(key=lambda sess:sess.start_date)
     return sessions
Ejemplo n.º 53
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_online" % objId
         tmpDict['title'] = _(u"Trigger online")
         tmpDict['href'] = u"%s/@@trigger_online?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_offline" % objId
         tmpDict['title'] = _(u"Trigger offline")
         tmpDict['href'] = u"%s/@@trigger_offline?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_not1" % objId
         tmpDict['title'] = _(u"Trigger notification1")
         tmpDict['href'] = u"%s/@@trigger_not1?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
     return retList
Ejemplo n.º 54
0
 def readOnly(self):
     """ Read-only inline comments?
     """
     if not checkPermission('eea.annotator.edit', self.context):
         return True
     storage = queryAdapter(self.context, IAnnotatorStorage)
     return storage.readOnly if storage else False
Ejemplo n.º 55
0
def _back_references(source_object, attribute_name, translation=None):
    catalog = getUtility(ICatalog)
    intids = getUtility(IIntIds)

    lang = queryAdapter(source_object, ILanguage).get_language()
    if translation:
        lang = queryAdapter(translation, ILanguage).get_language()

    gsm = getSecurityManager()
    result = []
    for rel in catalog.findRelations({
            'to_id': intids.getId(aq_inner(source_object)),
            'from_attribute':attribute_name
        }):
        obj = intids.queryObject(rel.from_id)
        if obj is not None and checkPermission('zope2.View', obj):
            if ITranslatable.providedBy(obj):
                trans_manager = ITranslationManager(aq_inner(obj))
                try:
                    trans_obj = trans_manager.get_translation(lang)
                except Unauthorized, e:
                    continue

                if trans_obj:
                    result.append(trans_obj)
                    continue

            if gsm.checkPermission('zope2.View', obj):
                result.append(obj)
Ejemplo n.º 56
0
    def __call__(self, *args, **kw):
        workspaces = []
        space = self.context
        default = space.defaultWorkspace

        factory = queryAdapter(space, IWorkspaceFactory, default)
        if factory is not None:
            if space.isEnabled(factory):
                if IOverviewWorkspaceFactory.providedBy(factory):
                    return getMultiAdapter(
                        (space, self.request), name='overview')()

                self.request.response.redirect('./%s/'%default)
                return

        for name, factory in getAdapters((space,), IWorkspaceFactory):
            if space.isEnabled(factory) and \
                    checkPermission('zope.View', factory.get()):
                workspaces.append((factory.weight, factory.title, name))

        if workspaces:
            workspaces.sort()
            self.request.response.redirect('./%s/'%workspaces[0][2])
        else:
            self.request.response.redirect('./listing.html')
Ejemplo n.º 57
0
    def listDrafts(self):
        ids = getUtility(IIntIds)
        request = self.request
        context = self.context

        drafts = []
        for name in context:
            draft = context[name]
            if not checkPermission('zope.View', draft):
                continue

            try:
                loc = ids.queryObject(draft.location)
                locTitle = loc.title
                locUrl = '%s/'%absoluteURL(loc, request)
            except:
                locTitle = _('Unknown')
                locUrl = u''

            dc = ICMFDublinCore(draft.content)

            info = {'name': name,
                    'title': draft.title or _('[No title]'),
                    'description': draft.description,
                    'url': '%s/'%absoluteURL(draft, request),
                    'location': locTitle,
                    'locationURL': locUrl,
                    'icon': queryMultiAdapter((draft, request), name='zmi_icon'),
                    'draft': draft,
                    'modified': dc.modified,
                    'status': ISubmittedDraftContent.providedBy(draft),
                    'contentType': IContentType(draft.content)}
            drafts.append(info)

        return drafts
Ejemplo n.º 58
0
    def posts(self):
        """
        Return back references from source object on specified attribute_name
        """
        catalog = getUtility(ICatalog)
        intids = getUtility(IIntIds)

        source_object = self.context
        attribute_name = 'organization'

        result = []

        for rel in catalog.findRelations(
                dict(to_id=intids.getId(aq_inner(source_object)),
                     from_attribute=attribute_name)):

            obj = intids.queryObject(rel.from_id)

            if obj is not None and checkPermission('zope2.View', obj):
                if obj.portal_type == 'Post':

                    obj.members = []

                    for membership in catalog.findRelations(
                            dict(to_id=intids.getId(aq_inner(obj)), )):
                        member = intids.queryObject(membership.from_id)
                        # check for person
                        if member.person:
                            obj.members.append(member)

                    result.append(obj)

        return result
Ejemplo n.º 59
0
 def render(self, template=None):
     if template is None:
         template = self.template
     if (not checkPermission(u"bungeni.sitting.Add", self.context)) or \
         (IBusinessSectionLayer.providedBy(self.request)):
         self.edit = False
     else:
         self.edit = True
     session = Session()
     venues = session.query(domain.Venue).all()
     languages = get_all_languages()
     session.close()
     self.display_language = get_default_language()
     if self.request.get("I18N_LANGUAGE"):
         self.display_language = self.request.get("I18N_LANGUAGE")
     #html is hardcoded in here because doing it in the template
     #would have been a colossal pain
     #TODO: FIX THIS
     s = '<div class="dhx_cal_ltext" style="height:90px;">' 
     s += '<table>'
     s += '<tr><td>Venue</td><td><select id="select_sitting_venue">'
     for venue in venues:
         s += '<option value="'+str(venue.venue_id)+'">'+venue.short_name+'</option>'
     s += '</select></td></tr>'
     s += '<tr><td>Language</td><td><select id="select_sitting_lang">'
     for lang in languages:
         if lang == 'en':
             s += '<option value="'+lang+'" selected>'+lang+'</option>'
         else:
             s += '<option value="'+lang+'">'+lang+'</option>'
     s += '</select></td></tr></table></div>'
     self.sitting_details_form = s
     return template()