Ejemplo n.º 1
0
    def get_query(self):
        url_tool = getToolByName(self.context, "portal_url")
        portal_path = url_tool.getPortalPath()
        query = {"object_provides": {"query": ["ftw.news.interfaces.INews"]}}
        parent = aq_parent(aq_inner((self.context)))

        if self.context.current_context:
            path = "/".join(parent.getPhysicalPath())
            query["path"] = {"query": path}
        elif self.context.filter_by_path:
            cat_path = []
            for item in self.context.filter_by_path:
                cat_path.append("/".join([portal_path, item]))
            query["path"] = {"query": cat_path}

        subjects = self.context.subjects
        if subjects:
            query["Subject"] = map(make_utf8, subjects)

        if self.context.maximum_age > 0:
            date = DateTime() - self.context.maximum_age
            query["start"] = {"query": date, "range": "min"}

        news_on_homepage = getattr(self.context, "news_on_homepage", False)
        if news_on_homepage and IPloneSiteRoot.providedBy(parent):
            query["object_provides"]["operator"] = "and"
            query["object_provides"]["query"].append(IShowOnHomepage.__identifier__)

        query["sort_on"] = "start"
        query["sort_order"] = "descending"
        return query
Ejemplo n.º 2
0
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        self.context = aq_inner(self.context)

        # use came_from to decide which UI action was clicked.
        # "workflow_action" is the action name specified in the
        # portal_workflow transition url.
        came_from = "workflow_action"
        action = form.get(came_from, '')
        if not action and not form.get('bika_listing_filter_bar_submit', ''):
            # workflow_action_button is the action name specified in
            # the bika_listing_view table buttons.
            came_from = "workflow_action_button"
            action = form.get('workflow_action_id', '')
            if not action:
                if self.destination_url == "":
                    self.destination_url = self.request.get_header(
                        "referer", self.context.absolute_url())
                self.request.response.redirect(self.destination_url)
                return

        if action == "sample":
            self.workflow_action_sample()
        else:
            ClientWorkflowAction.__call__(self)
Ejemplo n.º 3
0
    def __init__(self, context, request):
        super(StatusMessageControlPanel, self).__init__(context, request)

        if is_profile_installed('profile-ftw.publisher.sender:default'):
            self.form_instance = PublishingStatusMessageEditForm(
                aq_inner(context), request
            )
            self.form_instance.__name__ = self.__name__
Ejemplo n.º 4
0
def renameObjectsByPaths(self, paths, new_ids, new_titles,
                         handle_errors=True, REQUEST=None):
    """ CMFPlone override
    """
    smanager = getSecurityManager()
    obj = self
    if not smanager.checkPermission('Delete objects', obj) and not \
                        smanager.checkPermission('Copy or Move', obj):
        return Unauthorized("You may not modify this object")
    failure = {}
    success = {}
    # use the portal for traversal in case we have relative paths
    portal = getToolByName(self, 'portal_url').getPortalObject()
    traverse = portal.restrictedTraverse
    for i, path in enumerate(paths):
        new_id = new_ids[i]
        new_title = new_titles[i]
        if handle_errors:
            sp = transaction.savepoint(optimistic=True)
        try:
            obj = traverse(path, None)
            obid = obj.getId()
            title = obj.Title()
            change_title = new_title and title != new_title
            changed = False
            if change_title:
                getSecurityManager().validate(obj, obj, 'setTitle',
                                              obj.setTitle)
                obj.setTitle(new_title)
                notify(ObjectModifiedEvent(obj))
                changed = True
            if new_id and obid != new_id:
                parent = aq_parent(aq_inner(obj))

                # Don't forget default page.
                if hasattr(parent, 'getDefaultPage'):
                    default_page = getDefaultPage(parent, request=REQUEST)
                    if default_page == obid:
                        parent.setDefaultPage(new_id)

                parent.manage_renameObjects((obid,), (new_id,))
                changed = True

            elif change_title:
                # the rename will have already triggered a reindex
                obj.reindexObject()
            if changed:
                success[path] = (new_id, new_title)
        except ConflictError:
            raise
        except Exception, e:
            if handle_errors:
                # skip this object but continue with sub-objects.
                sp.rollback()
                failure[path] = e
            else:
                raise
Ejemplo n.º 5
0
def async_move(context, success_event, fail_event, **kwargs):
    """ Async job
    """
    newid = kwargs.get('newid', '')
    email = kwargs.get('email', '')

    anno = IAnnotations(context)
    job_id = anno.get('async_move_job')

    if not newid:
        wrapper = IContextWrapper(context)(
            error=u'Invalid newid'
        )
        notify(fail_event(wrapper))
        raise CopyError(eNoItemsSpecified)

    try:
        _op, mdatas = _cb_decode(newid)
    except:
        raise CopyError(eInvalid)
    oblist = []
    app = context.getPhysicalRoot()

    for mdata in mdatas:
        m = loadMoniker(mdata)
        try:
            ob = m.bind(app)
        except ConflictError:
            raise
        except:
            raise CopyError(eNotFound)

        oblist.append(ob)

    wrapper = IContextWrapper(context)(
        folder_move_from=oblist and aq_parent(
            aq_inner(oblist[0])).absolute_url(),
        folder_move_to=context.absolute_url(),
        folder_move_objects=', '.join([obj.getId() for obj in oblist]),
        asyncmove_email=email
    )

    try:
        manage_pasteObjects_no_events(context, cb_copy_data=newid)
    except Exception, err:
        logger.exception(err)

        wrapper.error = err.message
        wrapper.job_id = job_id

        notify(fail_event(wrapper))
        raise CopyError(MessageDialog(
            title='Error',
            message=err.message,
            action='manage_main',
        ))
Ejemplo n.º 6
0
    def get_query(self, start=None, end=None):
        query = {
            'object_provides': IEventPage.__identifier__,
            'sort_on': 'start',
        }

        # Inspired by `plone.app.event.base.get_events`.
        if start:
            # All events from start date ongoing:
            # The minimum end date of events is the date from which we search.
            query['end'] = {'query': start, 'range': 'min'}
        if end:
            # All events until end date:
            # The maximum start date must be the date until we search.
            query['start'] = {'query': end, 'range': 'max'}

        parent = aq_parent(aq_inner(self.context))
        if self.context.current_context:
            # `parent` is the object containing this block.
            path = '/'.join(parent.getPhysicalPath())
            query['path'] = {'query': path}

        elif self.context.filter_by_path:
            portal_path = '/'.join(api.portal.get().getPhysicalPath())
            paths = ['/'.join([portal_path, path])
                     for path in self.context.filter_by_path]
            query['path'] = {'query': paths}

        subjects = self.context.subjects
        if subjects:
            query['Subject'] = map(safe_utf8, subjects)

        # Show inactive events if the current user is allowed to add events on the
        # parent of the event listing block. We must only render the inactive events
        # if the block renders events from its parent (in order not to allow the user
        # to view news items he is not allowed to see).
        if self.context.current_context \
                and not self.context.filter_by_path \
                and api.user.has_permission('ftw.events: Add Event Page', obj=parent):
            query['show_inactive'] = True

        return query
Ejemplo n.º 7
0
 def nextURL(self):
     editview = aq_parent(aq_inner(self.context))
     context = aq_parent(aq_inner(editview))
     url = str(getMultiAdapter((context, self.request),
                               name=u"absolute_url"))
     return url + '/@@manage-portlets'
Ejemplo n.º 8
0
 def __call__(self):
     IPortletPermissionChecker(aq_parent(aq_inner(self.context)))()
     return super(AddForm, self).__call__()
Ejemplo n.º 9
0
def manage_pasteObjects_no_events(self, cb_copy_data=None, REQUEST=None):
    """Paste previously copied objects into the current object.
    If calling manage_pasteObjects from python code, pass the result of a
    previous call to manage_cutObjects or manage_copyObjects as the first
    argument.
    Also sends IObjectCopiedEvent and IObjectClonedEvent
    or IObjectWillBeMovedEvent and IObjectMovedEvent.
    """
    anno = IAnnotations(self)
    job_id = anno.get('async_move_job')

    if not REQUEST:
        # Create a request to work with
        REQUEST = create_request()

    if cb_copy_data is not None:
        cp = cb_copy_data
    elif REQUEST is not None and REQUEST.has_key('__cp'):
        cp = REQUEST['__cp']
    else:
        cp = None
    if cp is None:
        raise CopyError(eNoData)

    try:
        op, mdatas = _cb_decode(cp)
    except:
        raise CopyError(eInvalid)

    oblist = []
    app = self.getPhysicalRoot()
    cat = getToolByName(self, 'portal_catalog')

    for mdata in mdatas:
        m = loadMoniker(mdata)
        try:
            ob = m.bind(app)
        except ConflictError:
            raise
        except:
            raise CopyError(eNotFound)
        # self._verifyObjectPaste(ob, validate_src=op+1)
        oblist.append(ob)

    result = []

    steps = oblist and int(100/len(oblist)) or 0

    notify(AsyncMoveSaveProgress(
        self, operation='initialize', job_id=job_id, oblist_id=[
            (o.getId(), o.Title()) for o in oblist
            ]))

    if op == 0:
        # Copy operation
        for i, ob in enumerate(oblist):
            orig_id = ob.getId()
            if not ob.cb_isCopyable():
                raise CopyError(eNotSupported % escape(orig_id))

            oid = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': oid})

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(), progress=.25
            ))

            ob = ob._getCopy(self)
            ob._setId(oid)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=.50
            ))

            self._setObject(oid, ob)
            ob = self._getOb(oid)
            ob.wl_clearLocks()

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=.75
            ))

            ob._postCopy(self, op=0)

            compatibilityCall('manage_afterClone', ob, ob)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=1
            ))

            notify(AsyncMoveSaveProgress(
                self,
                operation='progress',
                job_id=job_id,
                progress=steps*(i+1)/100
            ))

    if op == 1:
        # Move operation
        for i, ob in enumerate(oblist):
            orig_id = ob.getId()

            if not sanity_check(self, ob):
                raise CopyError(
                    "This object cannot be pasted into itself")

            orig_container = aq_parent(aq_inner(ob))
            if aq_base(orig_container) is aq_base(self):
                oid = orig_id
            else:
                oid = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': oid})

            unindex_object(ob, recursive=1)
            # try to make ownership explicit so that it gets carried
            # along to the new location if needed.
            ob.manage_changeOwnershipType(explicit=1)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=.25
            ))

            try:
                obj_path = '/'.join(
                    orig_container.getPhysicalPath()) + '/' + orig_id
                orig_container._delObject(orig_id, suppress_events=True)
                uncatalog_path = obj_path
                try:
                    uncatalog_objs = cat(path=obj_path)
                    for obj_brain in uncatalog_objs:
                        uncatalog_path = obj_brain.getPath()
                        cat.uncatalog_object(uncatalog_path)
                except AttributeError:
                    logger.warn("%s could not be found", uncatalog_path)
            except TypeError:
                orig_container._delObject(orig_id)
                logger.warn(
                    "%s._delObject without suppress_events is discouraged.",
                    orig_container.__class__.__name__)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=.50
            ))

            ob = aq_base(ob)
            ob._setId(oid)

            try:
                self._setObject(oid, ob, set_owner=0, suppress_events=True)
            except TypeError:
                self._setObject(oid, ob, set_owner=0)
                logger.warn(
                    "%s._setObject without suppress_events is discouraged.",
                    self.__class__.__name__)
            ob = self._getOb(oid)

            ob._postCopy(self, op=1)
            # try to make ownership implicit if possible
            ob.manage_changeOwnershipType(explicit=0)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=.75
            ))

            reindex_object(ob, recursive=1)

            notify(AsyncMoveSaveProgress(
                self,
                operation='sub_progress',
                job_id=job_id,
                obj_id=ob.getId(),
                progress=1
            ))

            notify(AsyncMoveSaveProgress(
                self,
                operation='progress',
                job_id=job_id,
                progress=steps*(i+1)/100
            ))

    notify(AsyncMoveSaveProgress(
        self, operation='progress', job_id=job_id,
        progress=1
    ))
    del anno['async_move_job']

    return result
Ejemplo n.º 10
0
def renameObjectsByPaths(self,
                         paths,
                         new_ids,
                         new_titles,
                         handle_errors=True,
                         REQUEST=None):
    """ CMFPlone override
    """
    smanager = getSecurityManager()
    obj = self
    if not smanager.checkPermission('Delete objects', obj) and not \
                        smanager.checkPermission('Copy or Move', obj):
        return Unauthorized("You may not modify this object")
    failure = {}
    success = {}
    # use the portal for traversal in case we have relative paths
    portal = getToolByName(self, 'portal_url').getPortalObject()
    traverse = portal.restrictedTraverse
    for i, path in enumerate(paths):
        new_id = new_ids[i]
        new_title = new_titles[i]
        if handle_errors:
            sp = transaction.savepoint(optimistic=True)
        try:
            obj = traverse(path, None)
            obid = obj.getId()
            title = obj.Title()
            change_title = new_title and title != new_title
            changed = False
            if change_title:
                getSecurityManager().validate(obj, obj, 'setTitle',
                                              obj.setTitle)
                obj.setTitle(new_title)
                notify(ObjectModifiedEvent(obj))
                changed = True
            if new_id and obid != new_id:
                parent = aq_parent(aq_inner(obj))

                # Don't forget default page.
                if hasattr(parent, 'getDefaultPage'):
                    default_page = getDefaultPage(parent, request=REQUEST)
                    if default_page == obid:
                        parent.setDefaultPage(new_id)

                parent.manage_renameObjects((obid, ), (new_id, ))
                changed = True

            elif change_title:
                # the rename will have already triggered a reindex
                obj.reindexObject()
            if changed:
                success[path] = (new_id, new_title)
        except ConflictError:
            raise
        except Exception, e:
            if handle_errors:
                # skip this object but continue with sub-objects.
                sp.rollback()
                failure[path] = e
            else:
                raise
Ejemplo n.º 11
0
 def can_add(self):
     context = aq_inner(self.context)
     mtool = getToolByName(context, 'portal_membership')
     permission = mtool.checkPermission(
         'ftw.simplelayout: Add TextBlock', context)
     return bool(permission)
Ejemplo n.º 12
0
 def can_add(self):
     context = aq_inner(self.context)
     mtool = getToolByName(context, 'portal_membership')
     permission = mtool.checkPermission('ftw.sliderblock: Add SliderBlock',
                                        context)
     return bool(permission)