class PDFSchemaExtender(object): """ Schema extender """ implements(ISchemaExtender, IBrowserLayerAwareExtender) layer = ILayer fields = ( ExtendedStringField( name='pdfTheme', schemata='settings', default='', write_permission="Can customize PDF", vocabulary_factory='eea.pdf.vocabulary.Themes', widget=public.SelectionWidget( label=_(u"PDF Theme"), description=_( u"Disable PDF export or override theme used to export " u"this content as PDF." ) ) ), ExtendedIntegerField('tocdepth', schemata='settings', default=4, write_permission="Can customize PDF", widget=public.SelectionWidget( label=_(u"Table of contents depth level"), description=_( u"Which header tags should be taken into " u"consideration for the table of contents." ) ), vocabulary=IntDisplayList([(0, 'TOC Disabled'), (1, 'H1'), (2, 'H1,H2'), (3, 'H1,H2,H3'), (4, 'H1,H2,H3,H4')]) ), ) def __init__(self, context): self.context = context def getFields(self): """ Returns provenance list field """ if IPDFTool.providedBy(self.context): return [] if IPDFTheme.providedBy(self.context): return [] return self.fields
class EventSchemaExtender(object): """ Schema extender """ layer = IEniSeisContentLayer fields = ( CountriesField( name='countries', schemata='default', multiValued=1, vocabulary=NamedVocabulary('european_countries'), widget=public.MultiSelectionWidget(label=_(u"Countries"), description=_(u"Countries"))), ExtendedStringField( name='event_level', widget=public.SelectionWidget( label="Event Level", description=(u"Select Regional Level for events that belong " u"to both East and South")), default="National Level", required=True, vocabulary=["National Level", "Regional Level", "Other"], ), ) def __init__(self, context): self.context = context def getFields(self): """ Returns fields """ return self.fields
class PDFSchemaExtender(object): """ Schema extender """ implements(ISchemaExtender, IBrowserLayerAwareExtender) layer = ILayer fields = ( ExtendedStringField( name='pdfTheme', schemata='settings', default='', write_permission="Can customize PDF", vocabulary_factory='eea.pdf.vocabulary.Themes', widget=public.SelectionWidget( label=_(u"PDF Theme"), description=_( u"Disable PDF export or override theme used to export " u"this content as PDF." ) ) ), ) def __init__(self, context): self.context = context def getFields(self): """ Returns provenance list field """ if IPDFTool.providedBy(self.context): return [] if IPDFTheme.providedBy(self.context): return [] return self.fields
JalonRessourceExterneSchema = ATDocumentSchema.copy() + atpublic.Schema(( atpublic.StringField("sousTitre", required=False, accessor="getSousTitre", searchable=False, widget=atpublic.StringWidget( label=_(u"Sous titre"), )), atpublic.StringField("typeRessourceExterne", required=True, accessor="getTypeRessourceExterne", searchable=False, default="", vocabulary=ressourceType, widget=atpublic.SelectionWidget( label=_(u"Type de la Ressource Externe"), format="select", )), atpublic.TextField("auteurs", required=True, accessor="getAuteurs", searchable=False, widget=atpublic.TextAreaWidget(label=_(u"Auteurs"), )), atpublic.StringField("volume", required=False, accessor="getVolume", searchable=False, widget=atpublic.StringWidget(label=_(u"Volume"), )), atpublic.StringField("lieu", required=False, accessor="getLieu", searchable=False,
# PLONE_SCHEMA ############### plone_schema = atapi.Schema(( atapi.StringField('Secretaria', mode='rw', read_permission=permissions.VIEW_OTHER_PERMISSION, write_permission=permissions.EDIT_PROPERTIES_PERMISSION, vocabulary='secretarias', regfield=1, required=1, enforceVocabulary=1, user_property=True, widget=atapi.SelectionWidget( format='select', label='Secretaria', label_msgid='label_secretaria', description="Selecione a secretaria que voce " "trabalha. ", description_msgid='help_secretaria', i18n_domain='plone')), atapi.StringField('coordenadoria', mode='rw', regfield=1, read_permission=permissions.VIEW_PUBLIC_PERMISSION, write_permission=permissions.EDIT_PROPERTIES_PERMISSION, user_property=True, widget=atapi.StringWidget( label='Coordenadoria', label_msgid='label_coordenadoria', description="Sua coordenadoria.", description_msgid='help_coordenadoria', i18n_domain='plone')),
class ProcurementRequest(afapi.AlphaFlowed, BaseContent): """A procurement request. """ zope.interface.implement(IAlphaFlowed) schema = atapi.BaseSchema.copy() + atapi.Schema(( atapi.StringField( "article", required=True, widget=atapi.StringWidget( label="Article", description="XXX", ), ), atapi.StringField( "account", required=False, vocabulary=config.accounts, widget=atapi.SelectionWidget( label="Account", description="XXX", ), ), atapi.TextField( "reason", required=False, widget=atapi.TextAreaWidget( label="Reason", description="XXX", ), ), atapi.FloatField( "price", required=True, ), atapi.DateTimeField( "due", required=True, ), )) schema["id"].widget.visible = \ schema["title"].widget.visible = { 'edit':'hidden', 'view':'hidden' } schema["title"].required = False content_icon = "file_icon.gif" # XXX global_allow = 0 archetype_name = "Procurement Request" portal_type = meta_type = "ProcurementRequest" include_default_actions = False actions = ( { 'id': 'view', 'name': 'View', 'action': 'string:${object_url}/base_view', }, { 'id': 'edit', 'name': 'Edit', 'action': 'string:${object_url}/base_edit', }, ) def Title(self): """DC title.""" return self.getArticle() def manage_afterAdd(self, item, container): ProcurementRequest.inheritedAttribute('manage_afterAdd')(self, item, container) if len(self.getAllInstances()) > 0: return wftool = getToolByName(self, "workflow_manager") process = wftool.processes['procurement'].current() self.assignProcess(process) self.getInstance().start("Workflow started by request creation.") def getAccountGroup(self): """Return the name of the group responsible for this request's account.""" return utils.getGroupFromAccount(self.getAccount())
class FormSubmissionFolderAdapter( folder.ATFolder, saveDataAdapter.FormSaveDataAdapter): """ A form action adapter that saves form submissions as content in a folder. """ schema = folder.ATFolder.schema.copy( ) + public.Schema(( saveDataAdapter.FormSaveDataAdapter.schema['showFields'].copy(), public.StringField( 'titleField', vocabulary='allFieldDisplayList', default_method='getDefaultTitleField', required=0, searchable=0, widget=public.SelectionWidget( label=_(u'label_titlefield_text', default=u"Title Field"), description=_( u'help_titlefield_text', default=u"""\ You may select a form field to be used as the submissions Plone title. If left empty, the title will be left blank."""))), public.StringField( 'submissionType', required=0, searchable=0, default='Document', vocabulary='getFolderAddableTypes', widget=public.SelectionWidget( label=_(u'label_submissiontype_text', default=u"Submission Type"), description=_( u'help_submissiontype_text', default=u"""\ You may select another content type to create for form submissions. Note that the content type's schema will be overridden by the schema defined by the form, so choosing a non-default content type will only work as much as the form schema matches the content type's schema"""))), public.ReferenceField( 'submissionFolder', relationship='submissionFolder', allowed_types_method='getFolderishTypes', default_method='getSubmissionFolderDefault', required=0, searchable=0, widget=public.ReferenceWidget( label=_(u'label_submissionfolder_text', default=u"Submission Folder"), description=_( u'help_submissionfolder_text', default=u"""\ You may select a folder in which submissions will be saved. If left blank, submissions will be saved inside this adapter."""))), public.LinesField( 'submissionTransitions', vocabulary='getAvilableSubmissionTransitions', widget=public.PicklistWidget( label=_(u'label_submissiontransitions_text', default='Submission Workflow Transitions'), description=_(u'help_submissiontransitions_text', default=u"""\ Select a sequence of workflow transitions to be applied on the newly created submission object. If the Submission Type workflow doesn't start out in a private state, it is important to choose the right transitons to keep form submissions from being publicly available."""))), )) meta_type = 'FormSubmissionFolderAdapter' portal_type = 'FormSubmissionFolderAdapter' archetype_name = 'Submission Folder Adapter' immediate_view = default_view = 'folder_listing' suppl_views = ('folder_contents', ) security = ClassSecurityInfo() security.declarePrivate('onSuccess') def onSuccess(self, fields, REQUEST, loopstop=False): """ Add a Form Submission object to the folder on success. Manually check if the user has permission. If anonymous users have permissions to add submissions, then make sure the submission is owned by the adapter owner to prevent security issues such as various anonymous users accessing each others submissions. """ folder = self.getSubmissionFolder() portal_type = self.getSubmissionType() types = getToolByName(self, 'portal_types') allowed = types[portal_type].isConstructionAllowed(folder) membership = getToolByName(self, 'portal_membership') user = getSecurityManager().getUser() owner = self.getWrappedOwner() is_anon = membership.isAnonymousUser() try: if not allowed or is_anon: newSecurityManager(REQUEST, owner) submission, changed = self.addSubmission( REQUEST, folder, portal_type) finally: if not allowed or is_anon: newSecurityManager(REQUEST, user) if not allowed and not is_anon: submission.changeOwnership(user, recursive=1) submission.manage_setLocalRoles(user.getId(), ('Owner', )) if 'controller_state' in REQUEST: # Record the submission object where the CMFFormController # machinery can get at it. REQUEST['controller_state'].kwargs.update(**changed) # Use the catalog brain for anonymous access in TAL expressions catalog = getToolByName(self, 'portal_catalog') REQUEST['form_submission'] = catalog._catalog[ catalog.getrid('/'.join(submission.getPhysicalPath()))] def addSubmission(self, REQUEST, folder, portal_type): """ Perform content operations as the appropriate user. """ form = aq_parent(aq_inner(self)) if folder is None: folder = self order = folder.getOrdering() if not hasattr(order, '__contains__'): order = folder.contentIds() title_field_name = self.getTitleField() or 'title' changed = {} if title_field_name in form: # Get the title from a form field in the submission title_field = form[title_field_name] title, kwargs = title_field.fgField.widget.process_form( title_field, title_field.fgField, REQUEST.form) changed[title_field_name] = title else: # Generate a title from the form title title = '{0} Submission'.format(form.Title()) # Generate an id from the title, adding a suffix if existing id_ = str(norm_ifaces.IUserPreferredURLNormalizer( REQUEST).normalize(title)) if id_ in order: # Exising objects have the id, find the next index suffix order_idx = len(folder) - 1 base_id = id_ idx = 0 while id_ in order: while order_idx >= 0: # Start at the end to try and find the highest index order_id = order[order_idx] if order_id.startswith(base_id + '-'): idx = int(order_id[len(base_id + '-'):]) break order_idx -= 1 id_ = '{0}-{1}'.format(base_id, (idx + 1)) new_id = folder.invokeFactory(portal_type, id_, title=title) submission = folder[new_id] submission.addReference(self, relationship='submissionFolderAdapter') # Mark the item as a form submission so the schema is extended with the # form schema interface.alsoProvides(submission, IFormSubmission) # Set the submission field values now that the extender applies extender.disableCache(REQUEST) schema = submission.Schema() for field in schema.fields(): if field.__name__ in ('id', 'title'): # skip factory arguments continue result = field.widget.process_form( submission, field, REQUEST.form, empty_marker=BaseObject._marker, validating=False) if result is BaseObject._marker or result is None: continue changed[field.__name__] = result[0] if field.__name__ in ('id', 'title'): # already set in the factory continue field.set(submission, result[0], **result[1]) # Apply workflow transitions workflow = getToolByName(submission, 'portal_workflow') for transition in self.getSubmissionTransitions(): try: workflow.doActionFor(submission, transition) except WorkflowCore.WorkflowException: logger.exception( 'Workflow transition {0!r} failed on form submission: {1}' .format(transition, self.absolute_url)) submission.setLayout('base_view') return submission, changed security.declarePrivate('setDefaults') def getDefaultTitleField(self): """ Use the first form field as the default title field. """ form = aq_parent(aq_inner(self)) return form.fgFields()[0].__name__ security.declarePrivate('setDefaults') def getSubmissionFolderDefault(self): """ Use the adapter itself as the default submission folder. """ return self # TODO Currently there is a chicken and egg between finding out which types # can be added to the submission folder before we select the submission # folder and also which workflow transitions are available for the type. # In the future it would be nice to have AJAX support for updating the # other when one changes. security.declarePrivate('setDefaults') def getFolderishTypes(self, instance): """ List all portal types that allow creating the submission type. """ types = getToolByName(self, 'portal_types') return [self.getPortalTypeName()] + [ typeinfo.getId() for typeinfo in types.objectValues() if typeinfo.global_allow and not typeinfo.filter_content_types] security.declarePrivate('setDefaults') def getFolderAddableTypes(self): """ Return the allowed form submission types. """ # TODO See above # return self.getSubmissionFolder().allowedContentTypes() types = getToolByName(self, 'portal_types') return [ (typeinfo.getId(), typeinfo.title_or_id()) for typeinfo in types.objectValues() if typeinfo.global_allow] security.declarePrivate('setDefaults') def getAvilableSubmissionTransitions(self): """ List all the possible transitions for the submission type's workflow. """ workflow = getToolByName(self, 'portal_workflow') workflows = set() workflows.update(*[ workflow.getChainForPortalType(portal_type) for portal_type in self.Vocabulary('submissionType')[0].keys()]) # TODO See above # workflows = workflow.getChainForPortalType(self.getSubmissionType()) transitions = {} for workflow_id in workflows: workflow_obj = workflow[workflow_id] for state in workflow_obj.states.objectValues(): for transition in workflow_obj.transitions.objectValues(): transitions[transition.getId()] = ( transition.actbox_name or transition.title_or_id()) return transitions.items()
class ViewletConfigFieldsExtender(object): adapts(IViewletConfigFieldsExtender) implements(ISchemaExtender) fields = [ ExtensionBooleanField( "inherit_viewlet_settings", schemata="Listing", widget=atapi.BooleanWidget( label=_(u"Inherit viewlet settinngs"), description=_( u"If checked - the settings will be inherited from parent." ), ), ), ExtensionStringField( "viewlet_title", schemata="Listing", widget=atapi.StringWidget(label=_(u"Viewlet title"), ), ), ExtensionStringField( "script_name", vocabulary_factory="python-scripts-viewlet", schemata="Listing", required=False, widget=atapi.SelectionWidget( format='select', label=_(u"Python Script"), description=_( u"Python Script used to generate list of results"), ), ), ExtensionIntField( "limit_results", schemata="Listing", widget=atapi.IntegerWidget( label=_(u"Limit results"), description=_( u"How many results should be displayed (none means all)"), ), ), ExtensionStringField( "template_name", vocabulary_factory="python-scripts-viewlets-templates", schemata="Listing", required=False, widget=atapi.SelectionWidget( format='select', label=_(u"Template"), description=_(u"Template to use to render list of results"), ), ), ] def __init__(self, context): self.context = context def getFields(self): """ The list of fields """ # Return the 'inherit_viewlet_settings' field only if it's possible to inherit if any([i.get(self.context, inherit=True) for i in self.fields]): return self.fields else: return self.fields[1:]
class BaseWorkItem(DynamicLocalRoleSupport, ContentObjectRetrieverBase, LifeCycleObjectBase): zope.interface.implements( IWorkItem, zope.app.annotation.interfaces.IAttributeAnnotatable) alphaflow_type = "workitem" security = ClassSecurityInfo() global_allow = False content_object = None activity_type = "" activity_id = "" generated_by = None generated_workitems = () completed_by = None log_name = "work item" log_children_name = "checkpoints" schema = LifeCycleObjectBase.schema.copy() + atapi.Schema( (atapi.TextField("comment", widget=atapi.TextAreaWidget( description="Please enter any comments you " "have for this work item.")), atapi.StringField( "action", vocabulary="getActionVocabulary", widget=atapi.SelectionWidget( label="Workflow action", description="Select an action to perform after saving this " "form.")))) schema["id"].widget.visible = \ schema["title"].widget.visible = { 'edit':'hidden', 'view':'hidden' } schema["id"].write_permission = permissions.ManagePortal schema["title"].required = False schema["title"].write_permission = permissions.ManagePortal manage_options = \ ({'label' : 'Overview', 'action' : 'manage_overview'},) + \ LifeCycleObjectBase.manage_options local_role_fake_class = WorkItemLocalRoleFake _af_notified = True security.declareProtected(config.WORK_WITH_PROCESS, '__init__') def __init__(self, id, activity_id, content_object=None): BaseWorkItem.inheritedAttribute('__init__')(self, id) self.activity_id = activity_id self.content_object = content_object self.checkpoints_passed = persistent.list.PersistentList() def __repr__(self): try: state = ILifeCycleController(self).state except TypeError: state = 'n/a' return '<%s for %r (%s)>' % (self.__class__.__name__, self.activity_id, state) security.declarePrivate("getWorkItem") def getWorkItem(self): return self.aq_inner security.declarePublic('getCharset') def getCharset(self): """this is a skin method of archetypes returning the site encoding """ return config.SITE_ENCODING security.declarePublic('reindexObject') def reindexObject(self, idxs=[]): """workitems are very explicitly indexed""" pass security.declarePrivate('reindexWorkitem') def reindexWorkitem(self): BaseWorkItem.inheritedAttribute('reindexObject')(self) security.declarePrivate("beforeCreationItems") def beforeCreationItems(self, items, parent): """Trigger that gets called before new work items get active. Other work items can veto on the creation of those items and return a list of ids as a veto. After all work items have been triggered, the vetoed work items get removed again and never become active. """ return [] ######################### # ZMI convenience methods security.declareProtected(config.MANAGE_WORKFLOW, 'manage_userAction') def manage_userAction(self, actionId, REQUEST): """Performs an action defined by the activity.""" action = self.getActionById(actionId) action() REQUEST.RESPONSE.redirect(self.absolute_url() + "/manage_overview", lock=True) # IWorkItem security.declareProtected(config.WORK_WITH_PROCESS, 'getActions') def getActions(self): "Return a list of actions the user may perform on this work item." return [] security.declareProtected(config.WORK_WITH_PROCESS, 'getActionById') def getActionById(self, id): for action in self.getActions(): if action.id == id: return action raise KeyError(id) security.declareProtected(config.WORK_WITH_PROCESS, 'getGeneratedWorkItems') def getGeneratedWorkItems(self): inst = self.getInstance() wis = [inst[x] for x in self.generated_workitems] return wis security.declareProtected(config.WORK_WITH_PROCESS, 'isRelevant') def isRelevant(self, user): return user in self.listRelevantUsers() security.declareProtected(config.WORK_WITH_PROCESS, 'listRelevantUsers') def listRelevantUsers(self): return [] security.declareProtected(config.WORK_WITH_PROCESS, 'isChildOf') def isChildOf(self, workitem_id=None, workitem=None): """Returns True if the given work item is a predecessor of this work item (in regard to 'was generated by'). You only may give either workitem_id or workitem. """ if workitem_id is None: workitem_id = workitem.getId() if self.id == workitem_id: return False if self.generated_by == workitem_id: return True if self.generated_by == None: return False parent = self.getParent() if hasattr(parent, 'isChildOf'): return parent.isChildOf(workitem_id) return False security.declareProtected(config.WORK_WITH_PROCESS, 'getParent') def getParent(self): """Returns the parent WorkItem or None if this is a root workitem. """ if self.generated_by is None: return None parent = self.getInstance()[self.generated_by] # XXX This is a work-around; generated_by should never contain # the id of an instance. if not IWorkItem.providedBy(parent): return None else: return parent security.declareProtected(config.WORK_WITH_PROCESS, 'getShortInfo') def getShortInfo(self): """Returns a short information text.""" return "%s is in %s state" % (self.getId(), ILifeCycleController(self).state) security.declareProtected(config.WORK_WITH_PROCESS, 'getStatusInfo') def getStatusInfo(self): """Returns a short status information text.""" return ("WorkItems current status: %s" % ILifeCycleController(self).state) def onStart(self): self.passCheckpoint(config.CHECKPOINT_START) def onCompletion(self): self.passCheckpoint(config.CHECKPOINT_COMPLETE) self.completed_by = getSecurityManager().getUser().getUserName() security.declarePublic("getActivity") # XXX .... yurks def getActivity(self): activity = getattr(self, '_v_my_activity', None) if activity is None: process = self.getInstance().getProcess() if not hasattr(process, self.activity_id): ILifeCycleController(self).fail( "Could not find activity definition `%s` for workitem." % self.activity_id) raise AttributeError(self.activity_id) activity = getattr(process, self.activity_id) self._v_my_activity = activity activity = self._v_my_activity # wrapping magic return activity security.declarePublic("getActivityTitleOrId") def getActivityTitleOrId(self): try: activity = self.getActivity() except AttributeError: title = 'n/a' else: title = activity.title_or_id() return title security.declareProtected(config.WORK_WITH_PROCESS, "getDetailStatus") def getDetailStatus(self): """Return a (single line) string that describes the current status a bit more verbose.""" return ILifeCycleController(self).state security.declareProtected(config.WORK_WITH_PROCESS, 'getActionVocabulary') def getActionVocabulary(self): actions = [(action.id, action.title) for action in self.getActions() if action.enabled] # XXX This seems junk: actions.append(("", "No action")) return actions def absolute_url(self, inner=False): """A hackish way to use content objects as views. If this object is (directly) wrapped into an IAlphaFlowed, it will return the url of the IAlphaFlowed object""" absurl = BaseWorkItem.inheritedAttribute("absolute_url") if inner: return absurl(self) if not hasattr(self, 'aq_chain'): return absurl(self) if len(self.aq_chain) < 2: return absurl(self) if IAlphaFlowed.providedBy(self.aq_chain[1]): return self.aq_chain[1].absolute_url() return absurl(self) security.declareProtected(config.WORK_WITH_PROCESS, "getActivityConfiguration") def getActivityConfiguration(self, field, default=None): """Retrieves the configuration for this activity in the context of this instance. """ instance = self.getInstance() return instance.getActivityConfiguration(field, self.activity_id, default=default) security.declarePrivate("createWorkItems") def createWorkItems(self, activity_ids, content_object=None): """Creates a new workitem for the activity with the given name. Raises KeyError if any activity with the names is not known. """ instance = self.getInstance() return instance.createWorkItems(activity_ids, self, content_object=content_object) security.declarePrivate("notifyWorkItemStateChange") def notifyWorkItemStateChange(self, workitem): """Receives a notification that the work item <workitem> has changed it's state """ pass security.declarePrivate("notifyAssigneesChange") def notifyAssigneesChange(self): """notifies the workitem that the assignees might have changed """ alf = getToolByName(self, 'workflow_manager') alf.updateCacheByWorkItem(self) security.declarePrivate('passCheckpoint') def passCheckpoint(self, name): checkpoint = self.createChild(self.getActivity()[name]) self.checkpoints_passed.append(name) ILifeCycleController(checkpoint).start("Started by work item.") return checkpoint.generated_workitems ######################### # IContentObjectRetriever # Force acquisition of getContentObject by context instead of containment security.declareProtected(config.WORK_WITH_PROCESS, 'getContentObject') def getContentObject(self): if self.content_object is None: instance = self.getInstance() ob = instance.getContentObject() else: rc = getToolByName(self, "reference_catalog") ob = rc.lookupObject(self.content_object) return ob security.declareProtected(config.WORK_WITH_PROCESS, 'getContentObjectUID') def getContentObjectUID(self): if self.content_object is None: instance = self.getInstance() uid = instance.getContentObjectUID() else: uid = self.content_object return uid
u"Méthode".encode("utf-8"), u"Rappel".encode("utf-8"), u"Attention".encode("utf-8"), u"Syntaxe".encode("utf-8"), u"Conseil".encode("utf-8"), u"Confère".encode("utf-8"), u"Citation".encode("utf-8"), u"Activité".encode("utf-8") ] DocumentSemantiqueSchema = ATDocumentSchema.copy() + atpublic.Schema( (atpublic.StringField("typeSemantique", required=False, accessor="getTypeSemantique", default=0, searchable=False, vocabulary=contenuDocumentSemantique, widget=atpublic.SelectionWidget( label=_(u"label_typeSemantique", default=u"Type"), description=_(u"desc_typeSemantique", default=u"Description du type"), format="select")), )) class DocumentSemantique(ATDocumentBase): """ Un document sémantique pour JalonEdit """ implements(IDocumentSemantique) meta_type = 'DocumentSemantique' schema = DocumentSemantiqueSchema schema['title'].required = False schema['title'].mode = "r" schema['description'].required = False schema['description'].mode = "r"