コード例 #1
0
class IWorkflowPanel(Interface):
    """Form for workflow panel"""
    workflow_action = schema.Choice(
        title=_(u'label_change_status', u"Change State"),
        description=_(
            u'help_change_status_action',
            default=
            u"Select the transition to be used for modifying the items state."
        ),
        source=WorkflowActionsSourceBinder(),
        required=False,
    )
    comment = schema.Text(
        title=_(u"label_comments", u"Comments"),
        description=_(
            u'help_publishing_comments',
            default=u"Will be added to the publishing history. If multiple "
            "items are selected, this comment will be attached to all of them."
        ),
        required=False,
    )
    effective_date = schema.Datetime(
        title=_(u'label_effective_date', u'Publishing Date'),
        description=_(
            u'help_effective_date',
            default=u"If this date is in the future, the content will "
            "not show up in listings and searches until this date."),
        required=False)
    expiration_date = schema.Datetime(
        title=_(u'label_expiration_date', u'Expiration Date'),
        description=_(u'help_expiration_date',
                      default=u"When this date is reached, the content will no"
                      "longer be visible in listings and searches."),
        required=False)
コード例 #2
0
 def __call__(self, context):
     wft = getToolByName(context, 'portal_workflow')
     return vocabulary.SimpleVocabulary([
         vocabulary.SimpleVocabulary.createTerm(t['id'], t['id'],
                                                _(t['name']))
         for t in wft.getTransitionsFor(context)
     ])
コード例 #3
0
class FileUploadForm(form.Form):
    implements(IWrappedForm)

    fields = field.Fields(IFileUploadForm)
    ignoreContext = True  # don't use context to get widget data
    label = _(u"Add content")

    @button.buttonAndHandler(_(u'Upload content'))
    def handleApply(self, action):
        data, errors = self.extractData()
        if errors:
            return

        # Context may not be a container, get one.
        context_state = getMultiAdapter((self.context, self.request),
                                        name="plone_context_state")
        container = context_state.folder()

        title = data['file'].filename
        # Generate a name based on the title..
        util = queryUtility(IIDNormalizer)
        id = util.normalize(title)

        # Make sure our chosen id is unique, iterate until we get one that is.
        chooser = INameChooser(container)
        id = chooser._findUniqueName(id, None)

        # Determine the Content Type
        ct_reg = getToolByName(self.context, 'content_type_registry')
        typeName = ct_reg.findTypeName(data['file'].filename,
                                       data['file'].contentType,
                                       data['file'].data)

        # Really, we want Image if it's an image, and File for everything else...
        typeName = 'Image' if typeName == 'Image' else 'File'

        # create the object
        container.invokeFactory(typeName,
                                id=id,
                                title=title,
                                file=data['file'].data)

        # Redirect to the view page.
        self.request.response.redirect("%s/view" %
                                       container[id].absolute_url())
コード例 #4
0
class AddNewContentForm(form.Form):

    fields = field.Fields(IAddNewContent)
    ignoreContext = True  # don't use context to get widget data
    label = _(u"Add content")
    css_class = 'overlayForm'

    def update(self):
        tn = self.fields['type_name']
        tn.mode = HIDDEN_MODE
        tn.field.default = unicode(getattr(self.request, 'type_name', ''))
        super(AddNewContentForm, self).update()

    @button.buttonAndHandler(_(u'Add content'))
    def handleApply(self, action):
        data, errors = self.extractData()
        if errors:
            return

        title = data['title']

        # Generate a name based on the title..
        util = queryUtility(IIDNormalizer)
        id = util.normalize(title)

        # Context may not be a container, get one.
        context_state = getMultiAdapter((self.context, self.request),
                                        name="plone_context_state")
        container = context_state.folder()

        # Make sure our chosen id is unique, iterate until we get one that is.
        chooser = INameChooser(container)
        id = chooser._findUniqueName(id, None)

        # create the object
        type_name = data['type_name']
        container.invokeFactory(type_name, id=id, title=title)
        if type_name in [u'Folder']:
            self.request.response.redirect("%s/@@cmsui-structure" %
                                           container[id].absolute_url())
        else:
            self.request.response.redirect("%s/edit" %
                                           container[id].absolute_url())
コード例 #5
0
    def history_list(self):
        version_history = self.version_history

        # Add workflow history to version history
        workflow = getToolByName(self.context, "portal_workflow")
        for r in workflow.getInfoFor(self.context, "review_history"):
            version_history.append(
                dict(
                    entry_type="workflow",
                    transition=workflow.getTitleForTransitionOnType(r["action"], self.context.portal_type),
                    principal=r.get("actor", _(u"label_anonymous_user", default=u"Anonymous User")),
                    timestamp=datetime.fromtimestamp(float(r["time"])),
                    comment=r["comments"],
                    klass="",
                )
            )
        return sorted(version_history, key=lambda k: datetime.now() - k["timestamp"])
コード例 #6
0
ファイル: workflowpanel.py プロジェクト: Doap/plone.app.cmsui
 def label(self):
     return _(u'Workflow for ${name}', mapping={'name': self.context.Title()})
コード例 #7
0
 def __call__(self):
     context = self.context
     #TODO: Is this how to do it?
     if not(_checkPermission(AccessPreviousVersions, self.context)):
         raise Unauthorized
     
     # Get editing history
     self.repo_tool=getToolByName(self.context, "portal_repository")
     if self.repo_tool is None or not self.repo_tool.isVersionable(context):
         # Item isn't versionable
         self.sel_to = self.sel_from = 0
         return super(HistoryPanel, self).__call__()
     edit_history=self.repo_tool.getHistoryMetadata(context);
     if not(hasattr(edit_history,'getLength')):
         # No history metadata
         self.sel_to = self.sel_from = 0
         return super(HistoryPanel, self).__call__()
     
     # Go through revision history backwards
     history_list = []
     for i in xrange(edit_history.getLength(countPurged=False)-1, -1, -1):
         data = edit_history.retrieve(i, countPurged=False)
         meta = data["metadata"]["sys_metadata"]
         
         # Get next version, updating which is latest and previous if need be
         version_id = edit_history.getVersionId(i, countPurged=False)
         if self.sel_to == 'latest':
             self.sel_to = version_id
         elif self.sel_from == 'previous' and version_id < self.sel_to:
             self.sel_from = version_id
         
         # Add block describing this revision
         h = dict(entry_type='edit',
             version_id=version_id,
             principal=meta['principal'],
             timestamp=datetime.fromtimestamp(meta['timestamp']),
             comment=meta['comment'] or _("Edit"),
             klass='',
         )
         if self.sel_from == h['version_id']:
           h['klass'] = 'sel_from'
           self.sel_from_version = h
         if self.sel_to == h['version_id']:
           h['klass'] = 'sel_to'
           self.sel_to_version = h
         history_list.append(h)
     
     # Add workflow history to version history
     workflow = getToolByName(self.context, 'portal_workflow')
     for r in workflow.getInfoFor(self.context, 'review_history'):
         title = workflow.getTitleForTransitionOnType(r['action'], self.context.portal_type)
         if title is None: continue # No title means 'Create', and there'll be a edit_history entry for this.
         history_list.append(dict(entry_type='workflow',
             transition=title,
             principal=r.get('actor', _(u'label_anonymous_user', default=u'Anonymous User')),
             timestamp=datetime.fromtimestamp(float(r['time'])),
             comment=r['comments'] or _("Transition"),
             klass='',
         ))
     
     # Insert a date marker for every unique month
     date_markers = dict()
     for e in history_list:
         date_string = e['timestamp'].strftime('%B %Y')
         if date_markers.has_key(date_string): continue
         date_markers[date_string] = dict(
             entry_type='date-marker',
             # Timestamp one month ahead so it's on top of all the entries it refers to
             timestamp=datetime(e['timestamp'].year,e['timestamp'].month,1)+relativedelta(months=+1),
             date=e['timestamp'].strftime('%B %Y'),
         )
     history_list += date_markers.values()
     
     # Sort list into reverse order
     self.history_list = history_list = sorted(history_list, key=lambda k: datetime.now() - k['timestamp'])
     
     return super(HistoryPanel, self).__call__()
コード例 #8
0
 def _versionTitle(self, version):
     return translate(
         _(u"version ${version}",
           mapping=dict(version=version)),
         context=self.request
     )
コード例 #9
0
class IAddNewContent(interface.Interface):

    title = schema.TextLine(title=_(u"Title"))
    type_name = schema.TextLine(title=_(u"Type"))
コード例 #10
0
 def label(self):
     return _(u'Workflow for ${name}',
              mapping={'name': safe_unicode(self.context.Title())})
コード例 #11
0
class WorkflowPanel(form.Form):
    """Shows a panel with the advanced workflow options
    """
    @property
    def label(self):
        return _(u'Workflow for ${name}',
                 mapping={'name': safe_unicode(self.context.Title())})

    def render(self):
        return self.index()

    css_class = 'overlayForm'

    fields = field.Fields(IWorkflowPanel)
    fields['workflow_action'].widgetFactory = RadioFieldWidget
    ignoreContext = True

    def updateActions(self):
        super(WorkflowPanel, self).updateActions()
        self.actions["cancel"].addClass("overlayCloseAction")

    @button.buttonAndHandler(_(u'Save'))
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # Context might be temporary
        real_context = self.context.portal_factory.doCreate(self.context)

        # Read form
        workflow_action = data.get('workflow_action', '')
        effective_date = data.get('effective_date', None)
        if workflow_action and not effective_date and real_context.EffectiveDate(
        ) == 'None':
            effective_date = DateTime()
        expiration_date = data.get('expiration_date', None)

        # Try editing content, might not be able to yet
        retryContentEdit = False
        try:
            self._editContent(real_context, effective_date, expiration_date)
        except Unauthorized:
            retryContentEdit = True

        postwf_context = None
        if workflow_action is not None:
            postwf_context = real_context.portal_workflow.doActionFor(
                self.context, workflow_action, comment=data.get('comment', ''))
        if postwf_context is None:
            postwf_context = real_context

        # Retry if need be
        if retryContentEdit:
            self._editContent(postwf_context, effective_date, expiration_date)

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

    @button.buttonAndHandler(_(u'Cancel'))
    def cancel(self, action):
        self.request.response.redirect(self.context.absolute_url())

    def _editContent(self, context, effective, expiry):
        kwargs = {}
        if isinstance(effective, datetime):
            kwargs['effective_date'] = DateTime(effective)
        # may contain the year
        elif effective and (isinstance(effective, DateTime)
                            or len(effective) > 5):
            kwargs['effective_date'] = effective
        if isinstance(expiry, datetime):
            kwargs['expiration_date'] = DateTime(expiry)
        # may contain the year
        elif expiry and (isinstance(expiry, DateTime) or len(expiry) > 5):
            kwargs['expiration_date'] = expiry
        context.plone_utils.contentEdit(context, **kwargs)
コード例 #12
0
 def __call__(self, context):
     wft = getToolByName(context, 'portal_workflow')
     return vocabulary.SimpleVocabulary([
         vocabulary.SimpleVocabulary.createTerm(t['id'], t['id'], _(t['name']))
         for t in wft.getTransitionsFor(context)
     ])