예제 #1
0
    def __call__(self):
        """
        sets workflow state to sending and then redirects to step2 with UID as
        parameter as simple safety belt.
        """
        PostOnly(self.request)
        if self.is_test:  # test must not modify the state
            self.send()
            api.portal.show_message(
                message=_("The issue test sending has been initiated."),
                request=self.request,
            )
            return self.request.response.redirect(self.context.absolute_url())

        # XXX implement this:
        # if self.context.issue_queue is not None:
        #     self._send_issue_prepare()
        #     self.context.queue_issue_for_sendout()
        #     api.portal.show_message(
        #         message=_("The issue sending has been initiated in the background."),
        #         request=self.request,
        #     )
        #     return self.request.response.redirect(self.context.absolute_url())

        # No queuing but direct send
        # self._send_issue_prepare()
        self.send_issue_immediately()
        api.portal.show_message(
            message=_(
                "The issue has been generated and sent to the mail server."),
            request=self.request,
        )
        return self.request.response.redirect(self.context.absolute_url())
예제 #2
0
    def save_action(self):
        """ Save a script.
        """

        PostOnly(self.context.REQUEST)
        CheckAuthenticator(self.request)

        form = self.request.form
        content_type = form['content_type']
        field_name = form['field_name']
        script = form['script']
        body = form['data']

        result = 'failure'
        if script == 'edit_default':
            default_script.updateDefaultScript(content_type, field_name, body)
            result = 'success'
        elif script == 'edit_validator':
            validator_script.updateValidatorScript(content_type, field_name,
                                                   body)
            result = 'success'
        elif script == 'edit_vocabulary':
            vocabulary_script.updateVocabularyScript(content_type, field_name,
                                                     body)
            result = 'success'
        elif script == 'edit_view':
            ad_view.updateViewTemplate(content_type, body)
            result = 'success'

        result = dict(result=result)
        self.request.RESPONSE.setHeader('Content-Type', 'application/json')
        self.request.RESPONSE.setHeader('Cache-Control', 'no-cache')
        return json.dumps(result)
예제 #3
0
    def __call__(self, **kwargs):
        PostOnly(self.request)
        form = self.request.form
        recurse = form.get('workflow_unarchive_recurse', False)

        context = self.context
        ploneview = getMultiAdapter((context, self.request), name='plone')
        if ploneview.isDefaultPageInFolder():
            context = self.context.getParentNode()

        if recurse:
            catalog = getToolByName(context, 'portal_catalog')
            query = {'path': '/'.join(context.getPhysicalPath())}
            brains = catalog.searchResults(query)

            for brain in brains:
                obj = brain.getObject()
                if IObjectArchived.providedBy(obj):
                    storage = queryAdapter(obj, IObjectArchivator)
                    storage.unarchive(obj)
            msg = "Object and contents have been unarchived"
        else:
            storage = queryAdapter(context, IObjectArchivator)
            storage.unarchive(context)
            msg = "Object has been unarchived"

        IStatusMessage(context.REQUEST).add(msg, 'info')

        return self.request.response.redirect(context.absolute_url())
예제 #4
0
    def __call__(self, **kwargs):
        PostOnly(self.request)
        form = self.request.form
        recurse = form.get('workflow_archive_recurse', False)
        prev_versions = form.get('workflow_archive_previous_versions', False)
        val = {'initiator': form.get('workflow_archive_initiator', ''),
               'custom_message': form.get('workflow_other_reason', '').strip(),
               'reason': form.get('workflow_reasons_radio', 'other'),
        }

        context = self.context
        ploneview = getMultiAdapter((context, self.request), name='plone')
        if ploneview.isDefaultPageInFolder():
            context = self.context.getParentNode()

        if recurse and not prev_versions:
            archive_obj_and_children(context, **val)
        elif recurse and prev_versions:
            archive_obj_and_children(context, **val)
            archive_previous_versions(context, also_children=True, **val)
        elif prev_versions and not recurse:
            archive_object(context, **val)
            archive_previous_versions(context, **val)
        else:
            archive_object(context, **val)

        return "OK"
예제 #5
0
    def __call__(self):
        email = self.request.form.get('email')
        if email is not None:
            CheckAuthenticator(self.request)
            PostOnly(self.request)
            self.invite_user(email)

        return self.index()
예제 #6
0
    def toggle_follow(self):
        """Follow/unfollow context."""
        PostOnly(self.request)

        if self.is_followed:
            self.util.unfollow(self.follow_type, self.followed_id,
                               self.follower)
        else:
            self.util.follow(self.follow_type, self.followed_id, self.follower)
        self.is_followed = not self.is_followed
예제 #7
0
    def __call__(self, REQUEST=None, *args, **kwargs):
        if REQUEST['SERVER_NAME'] != 'Zope Clock Server':
            PostOnly(REQUEST)
            CheckAuthenticator(REQUEST)
        elif IDisableCSRFProtection:
            alsoProvides(REQUEST, IDisableCSRFProtection)

        self.output = self.context.restrictedTraverse(
            'publisher.executeQueue')()
        self.output = self.output.replace('\n', '<br/>')
        return super(ExecuteJobs, self).__call__(self, *args, **kwargs)
예제 #8
0
    def handle_toggle(self):
        """
        Perform the actual like/unlike action.
        Since this does a db write it cannot be called with a GET.
        """
        PostOnly(self.request)

        if not self.is_liked:
            self.util.like(self.like_type, self.item_id)
        else:
            self.util.unlike(self.like_type, self.item_id)
        self.is_liked = not self.is_liked
예제 #9
0
 def update_roster(self, REQUEST=None):
     """
     If workspace is team managed, users can add/remove participants.
     Any user with the manage workspace permission can add/remove
     participants and admins.
     """
     CheckAuthenticator(self.request)
     PostOnly(self.request)
     form = self.request.form
     entries = form.get('entries', [])
     self.update_users(entries)
     api.portal.show_message(message=_(u'Roster updated.'),
                             request=self.request)
     return self.request.response.redirect('%s/@@edit-roster' %
                                           self.context.absolute_url())
예제 #10
0
 def __call__(self):
     """Returns the number of tasks in the queue ar-create, responsible of
     creating Analysis Requests asynchronously"""
     try:
         PostOnly(self.context.REQUEST)
     except:
         logger.error(traceback.format_exc())
         return json.dumps({"count": 0})
     try:
         CheckAuthenticator(self.request.form)
     except:
         logger.error(traceback.format_exc())
         return json.dumps({"count": 0})
     task_queue = queryUtility(ITaskQueue, name="ar-create")
     count = len(task_queue) if task_queue is not None else 0
     return json.dumps({"count": count})
예제 #11
0
 def __call__(self):
     """
     Returns the number of tasks in the sanitation-tasks queue
     """
     try:
         PostOnly(self.context.REQUEST)
     except:
         logger.error(traceback.format_exc())
         return json.dumps({'count': 0})
     try:
         CheckAuthenticator(self.request.form)
     except:
         logger.error(traceback.format_exc())
         return json.dumps({'count': 0})
     task_queue = queryUtility(ITaskQueue, name='sanitation-tasks')
     count = len(task_queue) if task_queue is not None else 0
     return json.dumps({'count': count})
예제 #12
0
    def __call__(
        self,
        workflow_action=None,
        paths=None,
        comment="No comment",
        expiration_date=None,
        effective_date=None,
        include_children=False,
    ):
        # Use plone.protect.
        PostOnly(self.request)
        CheckAuthenticator(self.request)

        plone_utils = getToolByName(self.context, "plone_utils")
        if workflow_action is None:
            plone_utils.addPortalMessage(
                _("You must select a publishing action."), "error"
            )
            return self.redirect()
        if not paths:
            plone_utils.addPortalMessage(
                _("You must select content to change."), "error"
            )
            return self.redirect()

        self.transition_objects_by_paths(
            workflow_action,
            paths,
            comment,
            expiration_date,
            effective_date,
            include_children,
        )

        transaction_note(str(paths) + " transitioned " + workflow_action)
        plone_utils.addPortalMessage(_("Item state changed."))
        return self.redirect()
예제 #13
0
    def button_action(self):
        """ Respond to button clicks.
        """

        PostOnly(self.request)
        CheckAuthenticator(self.request)

        form = self.request.form
        button_id = form['button_id']
        content_type = form['content_type']
        field_name = form['field_name']

        result = {}

        if button_id == 'add_default':
            default_script.addDefaultScript(content_type, field_name)
            models.setDefaultFactory(content_type, field_name)
        elif button_id == 'remove_default':
            default_script.rmDefaultScript(content_type, field_name)
            models.removeDefaultFactory(content_type, field_name)
        elif button_id == 'edit_default':
            result = dict(
                action='edit',
                source=getAmbidexterityFile(content_type, field_name,
                                            'default.py'),
            )
        elif button_id == 'add_validator':
            validator_script.addValidatorScript(content_type, field_name)
            models.setValidator(content_type, field_name)
        elif button_id == 'remove_validator':
            validator_script.rmValidatorScript(content_type, field_name)
            models.removeValidator(content_type, field_name)
        elif button_id == 'edit_validator':
            result = dict(
                action='edit',
                source=getAmbidexterityFile(content_type, field_name,
                                            'validate.py'),
            )
        elif button_id == 'add_vocabulary':
            vocabulary_script.addVocabularyScript(content_type, field_name)
            models.setVocabulary(content_type, field_name)
        elif button_id == 'remove_vocabulary':
            vocabulary_script.rmVocabularyScript(content_type, field_name)
            models.removeVocabulary(content_type, field_name)
        elif button_id == 'edit_vocabulary':
            result = dict(
                action='edit',
                source=getAmbidexterityFile(content_type, field_name,
                                            'vocabulary.py'),
            )
        elif button_id == 'add_view':
            ad_view.addViewTemplate(content_type)
            models.setAmbidexterityView(content_type)
        elif button_id == 'edit_view':
            result = dict(
                action='edit',
                source=getAmbidexterityFile(content_type, None, 'view.pt'),
            )
        elif button_id == 'remove_view':
            ad_view.rmViewTemplate(content_type)
            models.removeAmbidexterityView(content_type)

        self.request.RESPONSE.setHeader('Content-Type', 'application/json')
        self.request.RESPONSE.setHeader('Cache-Control', 'no-cache')
        return json.dumps(result)
예제 #14
0
 def __call__(self):
     PostOnly(self.request)
     CheckAuthenticator(self.request)
     audit.resynchronize_all()
     self.request.RESPONSE.redirect(self.context.absolute_url() +
                                    '/@@ambidexterityeditor')
    def handleSave(self, action):
        statusmessages = IStatusMessage(self.request)

        PostOnly(self.request)
        data, errors = self.extractData()
        if errors:
            statusmessages.add(_(u"status_parse_error",
                                 default="Failed to parse the Form."),
                               type="error")
            return False

        portal_transforms = api.portal.get_tool(name='portal_transforms')
        transformed = portal_transforms.convertTo(
            'text/html',
            data['text'],
            mimetype='text/restructured',
        )

        portal = api.portal.get()
        vars = {
            'subject': data['subject'],
            'body': transformed.getData(),
            'site_url': portal.absolute_url(),
            'site_title': portal.Title(),
        }

        html = Composer().render_template(
            data["template"],
            {},
            vars,
        )

        portal = api.portal.get()
        sender_mail = formataddr((
            portal.email_from_name,
            portal.email_from_address,
        ))

        mailSVocab = MailSenderVocabulary(self.context)
        msg = create_email_body(
            html,
            headers={"Reply-To": mailSVocab.getTerm(data['reply_to']).title})

        if not self.uids:
            self.uids = data['uids_input'].split(',')

        mailcount = 0
        failed = []
        for uid in self.uids:
            obj = api.content.get(UID=uid)

            if obj:
                if IHeldPosition.providedBy(obj):
                    obj = IHeldPosition(obj).get_person()

                recipient = IRecipientProvider(obj)()
                if recipient is None:
                    failed.append(safe_unicode(obj.Title()))
                    continue

                api.portal.send_email(recipient=recipient,
                                      sender=sender_mail,
                                      subject=data['subject'],
                                      body=msg)
                mailcount += 1

        statusmessages.add(_(u"status_mail_send",
                             default="Sent ${number} E-Mails.",
                             mapping={"number": mailcount}),
                           type="info")

        if failed:
            statusmessages.add(_(
                u"status_mails_failed",
                default="${num} contacts without email-address: ${names}",
                mapping={
                    'num': len(failed),
                    'names': u','.join(failed)
                }),
                               type="warning")

        self.request.response.redirect(self.context.absolute_url())