def __call__(self): # Add a status message, showing whether the login has # succeeded or not. status = IStatusMessage(self.request) pps = getMultiAdapter((self.context, self.request), name='plone_portal_state') anonymous = pps.anonymous() if anonymous and not self.show_group_options(): success = False msg = PMF(u"Login failed") msg = translate(msg, 'plone', context=self.request) status.addStatusMessage(msg, type='error') elif anonymous: success = False else: success = True msg = PMF(u"heading_you_are_now_logged_in", default=u"You are now logged in") msg = translate(msg, 'plone', context=self.request) status.addStatusMessage(msg, type='info') if anonymous and self.request.cookies.get('aselectattributes'): success = False logger.debug("We have an A-Select cookie but are still anonymous.") if (not success) or self.request.get('noredirect'): # Show the template. Manually adding '?noredirect=1' to # the url may be handy for debugging: this way you stay on # this url, which means you can inspect the cookies. return self._template() logger.debug('Redirecting to Plone Site root.') # We are only defined on the Plone Site root, so we can just # redirect to the context. self.request.RESPONSE.redirect(self.context.absolute_url())
def getTransitionVocab(context): if AccessControl.getSecurityManager().getUser( ) == AccessControl.SpecialUsers.nobody: return SimpleVocabulary([]) wftool = getToolByName(context, 'portal_workflow') transitions = [] if opengever.task.task.ITask.providedBy(context) and \ context.REQUEST.URL.find('++add++opengever.task.task') == -1: for tdef in wftool.getTransitionsFor(context): transitions.append( SimpleVocabulary.createTerm( tdef['id'], tdef['id'], PMF(tdef['id'], default=tdef['title_or_id']))) return SimpleVocabulary(transitions) else: wf = wftool.get(wftool.getChainForPortalType('opengever.task.task')[0]) state = wf.states.get(wf.initial_state) for tid in state.transitions: tdef = wf.transitions.get(tid, None) transitions.append( SimpleVocabulary.createTerm( tdef.id, tdef.id, PMF(tdef.id, default=tdef.title_or_id))) return SimpleVocabulary(transitions)
def __call__(self, context): values = [ { "draft": PMF("draft") }, { "deposited": PMF("deposited") }, { "project_analysis": PMF("project_analysis") }, { "vote": PMF("vote") }, { "result_analysis": PMF("result_analysis") }, { "selected": PMF("selected") }, { "rejected": PMF("rejected") }, { "study_in_progress": PMF("study_in_progress") }, { "in_progress": PMF("in_progress") }, { "realized": PMF("realized") }, ] return dict_list_2_vocabulary(values)
class IGroupsUsers(Interface): group = GroupField(title=PMF('text_group'), vocabulary='plone.app.vocabularies.Groups', required=False) user = DGFVocabularyField(title=PMF('text_user'), vocabulary='plone.app.vocabularies.Users', required=False)
def transitions(self): """Return a list of available transitions for the claim. """ wftool = api.portal.get_tool('portal_workflow') available_transitions = wftool.getTransitionsFor(self.context) current_state = api.content.get_state(self.context) # as first, we add the current state as a no-change condition transitions = [dict(id=current_state, title=PMF('No change'))] # now we add the all available transitions for i in available_transitions: transitions.append(dict(id=i['id'], title=PMF(i['name']))) return transitions
class IActivitystreamPortlet(IPortletDataProvider): """A portlet to render the activitystream. """ title = schema.TextLine(title=PMF(u"Title"), description=_(u"A title for this portlet"), required=True, default=u"Activity Stream") count = schema.Int(title=_(u"Number of updates to display"), description=_(u"Maximum number of updates to show"), required=True, default=5) compact = schema.Bool(title=_(u"Compact rendering"), description=_(u"Hide portlet header and footer"), default=True) show_microblog = schema.Bool( title=_(u"Show microblog"), description=_(u"Show microblog status updates"), default=True) show_content = schema.Bool(title=_(u"Show content creation"), description=_(u"Show creation of new content"), default=True) show_discussion = schema.Bool(title=_(u"Show discussion"), description=_(u"Show discussion replies"), default=True)
def getLinkContent(self, item): down_img = u"<img title='{0}' src='{1}' />".format( safe_unicode(translate(PMF('Download'), context=self.request)), u"{0}/{1}".format(self.table.portal_url, 'download_icon.png')) down_img = u"<img src='{0}' />".format( u"{0}/{1}".format(self.table.portal_url, 'download_icon.png')) return down_img
def renderCell(self, item): state = api.content.get_state(item) if state: state_title = self.table.wtool.getTitleForStateOnType( state, item.portal_type) return translate(PMF(state_title), context=self.request) return ''
class TitleColumn(LinkColumn): """Column that displays title.""" header = PMF("Title") weight = 10 cssClasses = {'td': 'title-column'} i_cache = {} def _icons(self, item): """See docstring in interfaces.py.""" if item.portal_type not in self.i_cache: icon_link = '' purl = api.portal.get_tool('portal_url')() typeInfo = api.portal.get_tool('portal_types')[item.portal_type] if typeInfo.icon_expr: # we assume that stored icon_expr is like string:${portal_url}/myContentIcon.png # or like string:${portal_url}/++resource++imio.dashboard/dashboardpodtemplate.png contentIcon = '/'.join(typeInfo.icon_expr.split('/')[1:]) title = translate(typeInfo.title, domain=typeInfo.i18n_domain, context=self.request) icon_link = u'<img title="%s" src="%s/%s" />' % (safe_unicode(title), purl, contentIcon) self.i_cache[item.portal_type] = icon_link return self.i_cache[item.portal_type] def getLinkCSS(self, item): return ' class="pretty_link state-%s"' % (api.content.get_state(obj=item)) def getLinkContent(self, item): return u'<span class="pretty_link_icons">%s</span>' \ u'<span class="pretty_link_content">%s</span>' % (self._icons(item), safe_unicode(item.title))
def get_possible_task_states(context): wftool = getToolByName(context, 'portal_workflow') chain = wftool.getChainForPortalType('opengever.task.task')[0] states = [] for state in wftool.get(chain).states: states.append(SimpleVocabulary.createTerm(state, state, PMF(state))) return SimpleVocabulary(states)
class IOrganisationsUsers(Interface): group = OrganizationField(title=_ccc(u'Organization'), required=False) user = DGFVocabularyField(title=PMF('text_user'), vocabulary='plone.app.vocabularies.Users', required=False)
def _claims(self): """Return a list of claims inside the current Ombuds Office. :returns: a list of claims sorted by modified reverse :rtype: list of dictionaries """ results = self.context.listFolderContents({'portal_type': 'Claim'}) claims = [] for i in results: review_state = api.content.get_state(i) klass = 'state-' + review_state state = review_state review_state = self.wftool.getTitleForStateOnType(review_state, 'Claim') claims.append(dict( title=i.title, description=i.description, url=i.absolute_url(), klass=klass, state=state, review_state=PMF(review_state), created=i.created(), modified=i.modified(), area=i.area, )) return sorted(claims, key=lambda m: m['modified'], reverse=True)
def translations(self): return json.dumps({ 'label_search': self.plone_translate('label_search'), 'label_inherit_local_roles': self.plone_translate('label_inherit_local_roles'), 'help_inherit_local_roles': self.translate( _(u'help_inherit_local_roles', default=u'By default, permissions from the container of this ' u'item are inherited. If you disable this, only the ' u'explicitly defined sharing permissions will be valid.')), 'image_link_icon': self.plone_translate('image_link_icon'), 'image_confirm_icon': self.plone_translate('image_confirm_icon'), 'principal_search_placeholder': self.translate( _(u'principal_search_placeholder', default=u'Search for Users and Groups')), 'label_name': self.plone_translate('label_name'), 'label_acquired': self.translate( _(u'label_acquired_permission', default=u'Acquired permission')), 'label_local': self.translate( _(u'label_local_permission', default=u'Local permission')), 'label_save': self.translate(PMF(u'Save')), 'label_cancel': self.translate(PMF(u'Cancel')), 'label_automatic_permission': self.translate( _(u'label_automatic_permission', default=u'Automatic permission')), 'label_local_permission': self.translate( _(u'label_local_permission', default=u'Local permission')), 'label_save_failed': self.translate( _(u'message_save_failed', default=u'Local roles save failed.')), 'message_title_error': self.translate(base_mf('message_title_error', default=u"Error")), })
class BudgetSplitForm(EditForm): label = _(u"Split action budget") fields = Fields(IPSTAction).select('budget_split') fields['budget_split'].widgetFactory = DataGridFieldFactory def getContent(self): if base_hasattr(self.context, 'symbolic_link'): return self.context._link else: return self.context @button.buttonAndHandler(PMF('Save'), name='save') def handleAdd(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return self.applyChanges(data) IStatusMessage(self.request).addStatusMessage( _(u"Budget split saved"), "info", ) @button.buttonAndHandler(PMF(u'return_to_view'), name='cancel') def handleCancel(self, action): self.request.response.redirect(self.request.get('URL1')) def datagridUpdateWidgets(self, subform, widgets, widget): widget.columns[0]['mode'] = HIDDEN_MODE widgets['uid'].mode = HIDDEN_MODE def updateWidgets(self): super(EditForm, self).updateWidgets() self.widgets['budget_split'].allow_reorder = False self.widgets['budget_split'].allow_insert = False self.widgets['budget_split'].allow_delete = False self.widgets['budget_split'].auto_append = False # Prevent pickling error when auto_append = False self.widgets['budget_split'].value = [ {} if raw == NO_VALUE else raw for raw in self.widgets['budget_split'].value ]
def get_submitted_proposal_transition_vocab(context): transitions = [] for transition in context.get_transitions(): transitions.append( SimpleVocabulary.createTerm( transition.name, transition.name, PMF(transition.name, default=transition.title))) return SimpleVocabulary(transitions)
def month_names(self): """ Return a list of translated month names used for the header of the table. """ results = [] for m in self.months: month = PMF(safe_unicode(m.strftime('%b'))) year = safe_unicode(str(m.year)) results.append(' '.join([month, year])) results.reverse() return results
class TitleColumn(LinkColumn): """Column that displays title.""" header = PMF("Title") weight = 10 cssClasses = {'td': 'title-column'} def getLinkCSS(self, item): return ' state-%s"' % (api.content.get_state(obj=item)) def getLinkContent(self, item): return item.title
class ReviewStateColumn(Column): """Column that displays review state.""" header = PMF("Review state") weight = 60 cssClasses = {'td': 'state-column'} def renderCell(self, item): state = api.content.get_state(item) if state: state_title = self.table.wtool.getTitleForStateOnType(state, item.portal_type) return translate(PMF(state_title), context=self.request) return ''
def transitions_for_display(self): """Display the available transitions for this issue. """ context = aq_inner(self.context) if not self.memship.checkPermission(permissions.ModifyIssueState, context): return [] wftool = getToolByName(context, 'portal_workflow') transitions = [] transitions.append(dict(value='', label=PMF(u'No change'), checked="checked")) for tdef in wftool.getTransitionsFor(context): transitions.append(dict(value=tdef['id'], label=tdef['title_or_id'], checked='')) return transitions
def __call__(self): # noqa self.request.response.setHeader('Content-Type', 'application/json; charset=utf-8') self.request.response.setHeader('Expires', '-1') self.request.response.setHeader('Cache-Control', 'private') retval = [] new = [] max_zindex = 0 items = self.contents() check_perm = getSecurityManager().checkPermission delete_url = None settings = NoticeboardSettings(self.context) hide_after = settings.hide_after_days if hide_after: limit = datetime.now() - timedelta(days=hide_after) for item in items: if isinstance(item, CatalogContentListingObject): item = item.getObject() item = aq_inner(item) if hide_after: # ignore items that are older than the limit modified = item.modified().utcdatetime() if modified <= limit: continue if isinstance(item.exclude_from_nav, bool): if item.exclude_from_nav: continue else: if item.exclude_from_nav(): continue actions = [] note = INote(item) if check_perm(permissions.ModifyPortalContent, item): if note.review_state == 'private': actions.append( dict(content=self.context.translate(PMF('Publish')), title="", class_='publish', url=item.absolute_url() + '/content_status_modify?workflow_action=publish')) # alternatively use a popup with the form from /content_status_history actions.append( dict(content=self.context.translate(_('Color')), title=self.context.translate(_("Change color")), class_='change_color', url=item.absolute_url() + '/change_color')) actions.append( dict(content=self.context.translate(PMF('Edit')), title='', class_='edit', url=item.absolute_url() + '/edit')) if check_perm(permissions.DeleteObjects, item): delete_url = item.absolute_url() \ + '/delete_confirmation' actions.append( dict(content=self.context.translate(PMF('Delete')), title='', class_='delete', url=delete_url)) notedata = note.jsonable try: max_zindex = max(max_zindex, int(note.zIndex)) except ValueError: new.append(notedata) notedata.update(dict(hasactions=bool(actions))) notedata.update(dict(actions=actions)) if delete_url: notedata.update(dict(delete_url=delete_url)) are_you_sure = self.context.translate(_('Are you sure')) notedata.update(dict(are_you_sure=are_you_sure)) retval.append(notedata) for (new_note, new_index) in zip( new, range(max_zindex + 1, max_zindex + len(new) + 1)): new_note['zIndex'] = new_index return json.dumps(retval)
class ProjectmanagerRole(object): implements(ISharingPageRole) title = PMF("title_projectmanager_role", default="Can manage project") required_permission = 'Manage portal'
class ManageOwnGroupUsers(EditForm): """ Manage own groups users """ label = _(u'Own groups management view') description = _(u'Own groups management description') successMessage = _(u'Own groups users succesfully updated.') noChangesMessage = _(u'No changes were made.') def __init__(self, context, request): self.context = context self.request = request self.functions = {} # will contain function title by function id self.functions_orgs = {} # will contain org list by function id self.groupids = {} # will contain group title by group id self.fieldnames = [] def init(self): """ user is now recognized """ self.current_user = api.user.get_current() # self.current_user = api.user.get(userid='chef') self.current_user_id = self.current_user.getId() self.current_user_groups = [ g for g in api.group.get_groups(user=self.current_user) if g ] def get_manageable_functions(self): """ get all manageable functions """ for fct in get_registry_functions(as_copy=False): if fct['fct_management']: self.functions[fct['fct_id']] = fct['fct_title'] return self.functions.keys() def get_user_manageable_functions(self): """ get user manageable functions """ manageable_functions = self.get_manageable_functions() for group in self.current_user_groups: parts = group.id.split('_') if len(parts) == 1: continue group_suffix = '_'.join(parts[1:]) if group_suffix not in manageable_functions: continue if group_suffix not in self.functions_orgs: self.functions_orgs[group_suffix] = [] org = get_organization(parts[0]) if org not in self.functions_orgs[group_suffix]: self.functions_orgs[group_suffix].append( get_organization(parts[0])) def get_manageable_groups(self): """ get selected manageable groups """ return get_registry_groups_mgt() def get_user_manageable_groups(self): """ get user manageable groups """ manageable_groups = self.get_manageable_groups() for group in self.current_user_groups: if group.id not in manageable_groups: continue self.groupids[group.id] = group.getProperty('title') def getContent(self): return GroupsConfigurationAdapter(self) @property def fields(self): self.init() # second init with user recognized fields = [] description = _( u'You can <span class="cross_icon">remove</span> an assignment with the ' u'<span class="cross_icon">cross icon</span>. ' u'You can <span class="auto_append">add</span> a new assignment with the ' u'<span class="auto_append">blue line</span>. ' u'You can <span class="new_line">complete</span> it on the ' u'<span class="new_line">brown line</span>.') self.get_user_manageable_functions() for function in self.functions_orgs: fld = DGFListField( __name__=function, title=_( u"Assignments for groups related to '${function}' function", mapping={'function': self.functions[function]}), description=description, required=False, value_type=DictRow(title=u"org_users", schema=IOrganisationsUsers, required=False)) fields.append(fld) fields = sorted(fields, key=lambda x: x.title) self.get_user_manageable_groups() if self.groupids: fld = DGFListField(__name__='_groups_', title=_('Global groups assignments.'), description=description, required=False, value_type=DictRow(title=u"users", schema=IGroupsUsers, required=False)) fields.insert(0, fld) fld = schema.TextLine( __name__='_old_values_', title=u'not_showed', required=False, ) fields.append(fld) self.fieldnames = [afield.__name__ for afield in fields] return field.Fields(*fields) # def datagridInitialise(self, subform, widget): # pass # def datagridUpdateWidgets(self, subform, widgets, widget): # pass def updateWidgets(self): super(ManageOwnGroupUsers, self).updateWidgets() for wid in self.widgets: if wid == '_old_values_': self.widgets[wid].mode = HIDDEN_MODE else: self.widgets[wid].allow_reorder = False self.widgets[wid].allow_insert = False self.widgets[wid].allow_delete = True self.widgets[wid].auto_append = True @button.buttonAndHandler(_z3cf('Apply'), name='apply') def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return changes = False users = {} old_values = eval(data.pop('_old_values_')) for name in old_values: try: new_value = data[ name] # If the field is not in the data, then go on to the next one except KeyError: continue new_value = set([(dic['group'], dic['user']) for dic in data[name]]) old_value = set([(dic['group'], dic['user']) for dic in old_values[name]]) if old_value == new_value: continue for action, result in (('removed', old_value - new_value), ('added', new_value - old_value)): for (group_id, user_id) in result: if group_id is None or user_id is None: required_message = _( u"There was a problem in added assignments. " u"Don't forget to complete the 2 columns! " u"You have to redo all the manipulations.") api.portal.show_message(message=required_message, request=self.request, type='error') raise Redirect(self.request.get('ACTUAL_URL')) if user_id == self.current_user_id: user_message = _( u"You cannot remove your user from a group!") api.portal.show_message(message=user_message, request=self.request, type='error') raise Redirect(self.request.get('ACTUAL_URL')) if name != '_groups_': group_id = get_plone_group_id(group_id, name) if group_id not in users: users[group_id] = [ u.id for u in api.user.get_users(groupname=group_id) ] if action == 'removed' and user_id in users[group_id]: api.group.remove_user(groupname=group_id, username=user_id) changes = True elif action == 'added' and user_id not in users[group_id]: api.group.add_user(groupname=group_id, username=user_id) changes = True if changes: api.portal.show_message(message=self.successMessage, request=self.request) else: api.portal.show_message(message=self.noChangesMessage, request=self.request, type='warn') self.request.response.redirect(self.request.get('ACTUAL_URL')) @button.buttonAndHandler(PMF(u'return_to_view'), name='cancel') def handleCancel(self, action): self.request.response.redirect(self.request.get('URL1'))
class EmployeeRole(object): implements(ISharingPageRole) title = PMF("title_employee_role", default="Works on project") required_permission = 'eXtremeManagement: Add Project'
class CustomerRole(object): implements(ISharingPageRole) title = PMF("title_customer_role", default="Customer can track project") required_permission = 'eXtremeManagement: Add Project'
def active_label(self): if self.context.model.is_active: return PMF('Yes') return PMF('No')
def getMenuItems(self, context, request): """Return menu item entries in a TAL-friendly form.""" results = [] locking_info = queryMultiAdapter((context, request), name='plone_lock_info') if locking_info and locking_info.is_locked_for_current_user(): return [] workflow = getToolByName(context, 'portal_workflow') workflowActions = workflow.listActionInfos(object=context) for action in workflowActions: if action['category'] != 'workflow': continue cssClass = 'kssIgnore' actionUrl = action['url'] if actionUrl == "": actionUrl = '%s/content_status_modify?workflow_action=%s' % ( context.absolute_url(), action['id']) cssClass = '' description = '' transition = action.get('transition', None) if transition is not None: description = transition.description for bogus in self.BOGUS_WORKFLOW_ACTIONS: if actionUrl.endswith(bogus): if getattr(context, bogus, None) is None: actionUrl = '%s/content_status_modify?workflow_action=%s' % ( context.absolute_url(), action['id'], ) cssClass = '' break if action['allowed']: results.append({ 'title': action['title'], 'description': description, 'action': actionUrl, 'selected': False, 'icon': None, 'extra': { 'id': 'workflow-transition-%s' % action['id'], 'separator': None, 'class': cssClass }, 'submenu': None, }) url = context.absolute_url() if len(results) > 0: results.append({ 'title': PMF(u'label_advanced', default=u'Advanced...'), 'description': '', 'action': url + '/content_status_history', 'selected': False, 'icon': None, 'extra': { 'id': 'advanced', 'separator': 'actionSeparator', 'class': 'kssIgnore' }, 'submenu': None, }) if getToolByName(context, 'portal_placeful_workflow', None) is not None: if _checkPermission(ManageWorkflowPolicies, context): results.append({ 'title': PMF(u'workflow_policy', default=u'Policy...'), 'description': '', 'action': url + '/placeful_workflow_configuration', 'selected': False, 'icon': None, 'extra': { 'id': 'policy', 'separator': None, 'class': 'kssIgnore' }, 'submenu': None, }) return results
def get_review_state_title(self, review_state): wftool = api.portal.get_tool('portal_workflow') title = wftool.getTitleForStateOnType(review_state, 'Claim') return PMF(title)
class BaseBatchActionForm(Form): label = _(u"Batch action form") fields = Fields(IBaseBatchActionsFormSchema) fields['uids'].mode = HIDDEN_MODE fields['referer'].mode = HIDDEN_MODE ignoreContext = True brains = [] # easy way to hide the "Apply" button when required conditions # are not met for the action to be applied do_apply = True # the title of the apply button to fit current action apply_button_title = None # this will add a specific class to the generated button action # so it is possible to skin it with an icon button_with_icon = False overlay = True weight = 100 # useful when dispalying batch actions on several views for same context section = "default" def available(self): """Will the action be available for current context?""" return True def _update(self): """Method to override if you need to do something in the update.""" return def _final_update(self): """Method to override if you need to do something when everything have been updated.""" return def _update_widgets(self): """Method to override if you need to do something after the updateWidgets method.""" return @property def description(self): """ """ # update description depending on number of brains return _('This action will affect ${number} element(s).', mapping={'number': len(self.brains)}) def _apply(self, **data): """This method receives in data the form content and does the apply logic. It is the method to implement if default handleApply is enough.""" raise NotImplementedError def update(self): form = self.request.form if 'form.widgets.uids' in form: uids = form['form.widgets.uids'] else: uids = self.request.get('uids', '') form['form.widgets.uids'] = uids if 'form.widgets.referer' not in form: form['form.widgets.referer'] = self.request.get( 'referer', '').replace('@', '&').replace('!', '#') self.brains = self.brains or brains_from_uids(uids) # sort buttons self._old_buttons = self.buttons self.buttons = self.buttons.select('apply', 'cancel') self._update() super(BaseBatchActionForm, self).update() self._update_widgets() if self.apply_button_title is not None and 'apply' in self.actions: self.actions['apply'].title = self.apply_button_title self._final_update() @button.buttonAndHandler(_(u'Apply'), name='apply', condition=lambda fi: fi.do_apply) def handleApply(self, action): """ """ if not self.available(): raise Unauthorized data, errors = self.extractData() if errors: self.status = self.formErrorsMessage else: # log in fingerpointing before executing job extras = 'action={0} number_of_elements={1}'.format( repr(self.label), len(self.brains)) fplog('apply_batch_action', extras=extras) # call the method that does the job applied = self._apply(**data) # redirect if not using an overlay if not self.request.form.get('ajax_load', ''): self.request.response.redirect( self.request.form['form.widgets.referer']) else: # make sure we return nothing, taken into account by ajax query if not applied: self.request.RESPONSE.setStatus(204) return applied or "" @button.buttonAndHandler(PMF(u'Cancel'), name='cancel') def handleCancel(self, action): self.request.response.redirect(self.request.get('HTTP_REFERER'))
def getLinkTitle(self, item): """Setup link title.""" return ' title="%s"' % html.escape(safe_unicode(translate(PMF('Download'), context=self.request)), quote=True)
def getLinkContent(self, item): down_img = u"<img class='svg-icon' title='{0}' src='{1}' />".format( safe_unicode(translate(PMF('Download'), context=self.request)), u'%s/++resource++collective.documentgenerator/download_icon.svg' % self.table.portal_url) return down_img