Пример #1
0
    def parse_daterange(self, request, field_id, field_title):
        from_date = request.get('%s_fromdate' % field_id, None)
        from_date = from_date and from_date + ' 00:00' or None
        to_date = request.get('%s_todate' % field_id, None)
        to_date = to_date and to_date + ' 23:59' or None
        if from_date and to_date:
            query = {'query': [from_date, to_date], 'range': 'min:max'}
        elif from_date or to_date:
            query = {'query': from_date or to_date,
                     'range': from_date and 'min' or 'max'}
        else:
            return None

        if from_date and to_date:
            parms = translate(_("From ${start_date} to ${end_date}",
                               mapping={"start_date":from_date, "end_date":to_date}))
        elif from_date:
            parms = translate(_("Before ${start_date}",
                               mapping={"start_date":from_date}))
        elif to_date:
            parms = translate(_("After ${end_date}",
                               mapping={"end_date":to_date}))

        res = {}
        res['contentFilter'] = (field_id, query)
        res['parms'] = {'title': field_title, 'value': parms}
        res['titles'] = parms
        return res
Пример #2
0
 def __call__( self ):
     """Render the widget to HTML."""
     value = self._getFormValue()
     html = "<label for='%s'>%s</label>\n" % (self.name , translate(self.context.title, context=self.request))
     if self.__required:
         html += "<span class='fieldRequired' title='%s'>%s</span>" % (translate(_(u'title_required', default='Required'), context=self.request), translate(_(u'label_required', default='(Required)'), context=self.request))
     if self.context.description:
         html += "<div class='formHelp'>%s</div>" % translate(self.context.description, context=self.request)
     if super(BaseWidget, self).error() != '':
         html += "<div>%s</div>" % translate(super(BaseWidget, self).error(), context=self.request)
     
     if value == 'on':
         kw = {'checked': 'checked'}
     else:
         kw = {}
     if self.disabled:
         kw['disabled'] = 'disabled'
     return "%s  %s %s" % (
         renderElement(self.tag,
                       type='hidden',
                       name=self.name+".used",
                       id=self.name+".used",
                       value=""
                       ),
         renderElement(self.tag,
                       type=self.type,
                       name=self.name,
                       id=self.name,
                       cssClass=self.cssClass,
                       extra=self.extra,
                       value="on",
                       **kw),
         html
         )
Пример #3
0
    def form_name(self):
        if IVersion.providedBy(self.context):
            context = self.context.head
        else:
            context = self.context
        props = IDCDescriptiveProperties.providedBy(context) and context or IDCDescriptiveProperties(context)

        if self.is_translation:
            language = get_language_by_name(self.context.language)["name"]
            return _(
                u"edit_translation_legend",
                default=u"Editing $language translation of '$title'",
                mapping={"title": translate(props.title, context=self.request), "language": language},
            )

        elif IVersion.providedBy(self.context):
            return _(
                u"edit_version_legend",
                default=u'Editing "$title" (version $version)',
                mapping={"title": translate(props.title, context=self.request), "version": self.context.version_id},
            )

        return _(
            u"edit_item_legend",
            default=u'Editing "$title"',
            mapping={"title": translate(props.title, context=self.request)},
        )
Пример #4
0
 def getBandoState(self):
     """
     return corretc bando state
     """
     scadenza_bando = getattr(self.context, 'scadenza_bando', None)
     chiusura_procedimento_bando = getattr(
         self.context, 'chiusura_procedimento_bando', None
     )
     state = ('open', translate(_(u'Open'), context=self.request))
     if scadenza_bando and scadenza_bando < datetime.now():
         if chiusura_procedimento_bando and (
             chiusura_procedimento_bando < datetime.now().date()
         ):
             state = ('closed', translate(
                 _(u'Closed'), context=self.request)
             )
         else:
             state = ('inProgress', translate(
                 _(u'In progress'), context=self.request)
             )
     elif chiusura_procedimento_bando and (
         chiusura_procedimento_bando < datetime.now().date()
     ):
         state = ('closed', translate(
             _(u'Closed'), context=self.request)
         )
     return state
Пример #5
0
    def delete(self, path):
        """Delete the item at the given path.
        """

        path = path.encode('utf-8')

        npath = self.normalizePath(path)
        parentPath = '/'.join(npath.split('/')[:-1])
        name = npath.split('/')[-1]
        code = 0
        error = ''

        try:
            parent = self.getObject(parentPath)
        except KeyError:
            error = translate(_(u'filemanager_invalid_parent',
                              default=u'Parent folder not found.'),
                              context=self.request)
            code = 1
        else:
            try:
                del parent[name]
            except KeyError:
                error = translate(_(u'filemanager_error_file_not_found',
                                  default=u'File not found.'),
                                  context=self.request)
                code = 1

        return {
            'path': self.normalizeReturnPath(path),
            'error': error,
            'code': code,
        }
    def render(self):
        widget_id = self.request.get("widget_id")

        if widget_id:
            setHeader = self.request.response.setHeader
            setHeader("Content-Type", "text/javascript")

            upload_utility = getUtility(IUpload)
            url = upload_utility.upload_url()
            # XXX: Workaround for translating the JS strings
            # XXX: We need to get the lang from the request, instead of like this.
            upload_error = _(u"Error uploading file, please try again or use a diferent file")
            upload_error = translate(upload_error, domain="openmultimedia.reporter", target_language="es")
            upload_success = _(u"File uploaded correctly")
            upload_success = translate(upload_success, domain="openmultimedia.reporter", target_language="es")
            already_uploaded = _(u"Your file was already uploaded, no need to do it again.")
            already_uploaded = translate(already_uploaded, domain="openmultimedia.reporter", target_language="es")

            return self.js_template_input % dict(
                id=widget_id,
                id_uploader=widget_id + "-uploader",
                upload_url=url,
                upload_error=upload_error,
                upload_success=upload_success,
                already_uploaded=already_uploaded,
            )
Пример #7
0
 def send_email(self, userid):
     """ Send email to nominated address """
     registry = getUtility(IRegistry)
     mail_settings = registry.forInterface(IMailSchema, prefix='plone')
     mTo = self.getSurveyNotificationEmail()
     mFrom = mail_settings.email_from_address
     mSubj = translate(_(
         '[${survey_title}] New survey submitted',
         mapping={'survey_title': self.Title()}),
         context=self.REQUEST)
     message = []
     message.append(translate(_(
         'Survey ${survey_title}',
         mapping={'survey_title': self.Title()}),
         context=self.REQUEST))
     message.append(translate(_(
         'has been completed by user: ${userid}',
         mapping={'userid': userid}),
         context=self.REQUEST))
     message.append(self.absolute_url() +
                    '/@@Products.PloneSurvey.survey_view_results')
     mMsg = '\n\n'.join(message)
     try:
         self.MailHost.send(mMsg.encode('utf-8'), mTo, mFrom, mSubj)
     except ConflictError:
         raise
     except:
         # XXX too many things can go wrong
         pass
Пример #8
0
    def update(self):
        super(DigestIcon, self).update()
        self.anonymous = self.portal_state.anonymous()
        if self.anonymous:
            return

        user_id = api.user.get_current().getId()
        utility = get_tool()
        storage, recursive = utility.get_subscription(user_id, self.context)
        if not storage:
            self.icon = 'maildigest.png'
            self.title = _('folder_digesticon_title',
                           default=u"Subscribe to recurring digest of activity in this folder")

        else:
            self.icon = storage.icon
            if recursive:
                self.title = _('title_digesticon_recursives',
                               default=u"You have subscribed to ${delay} digest on this folder and all its subfolders",
                               mapping={'delay': translate(storage.label, context=self.request).lower()})
            else:
                self.title = _('title_digesticon',
                               default=u"You have subscribed to ${delay} digest on this folder",
                               mapping={'delay': translate(storage.label, context=self.request).lower()})

        self.form_url = "%s/digest-subscribe" % self.context.absolute_url()
Пример #9
0
def get_relateditems_options(context, value, separator, vocabulary_name,
                             vocabulary_view, field_name=None):
    if IForm.providedBy(context):
        context = context.context
    request = getRequest()
    site = get_top_site_from_url(context, request)
    options = get_ajaxselect_options(site, value, separator,
                                     vocabulary_name, vocabulary_view,
                                     field_name)
    msgstr = translate(_(u'Search'), context=request)
    options.setdefault('searchText', msgstr)
    msgstr = translate(_(u'Entire site'), context=request)
    options.setdefault('searchAllText', msgstr)
    msgstr = translate(_('tabs_home',
                       default=u'Home'),
                       context=request)
    options.setdefault('homeText', msgstr)
    options.setdefault('folderTypes', ['Folder'])
    options.setdefault('sort_on', 'sortable_title')
    options.setdefault('sort_order', 'ascending')

    nav_root = getNavigationRootObject(context, site)
    options['basePath'] = '/'.join(nav_root.getPhysicalPath()) if nav_root else '/'  # noqa
    options['rootPath'] = '/'.join(site.getPhysicalPath()) if site else '/'
    options['rootUrl'] = site.absolute_url() if site else ''
    return options
Пример #10
0
    def page_title(self):
        '''
        Get the page title. If we are in the portal_factory we want use the
        "Add $FTI_TITLE" form (see #12117).

        NOTE: other implementative options can be:
         - to use "Untitled" instead of "Add" or
         - to check the isTemporary method of the edit view instead of the
           creation_flag
        '''
        if (hasattr(aq_base(self.context), 'isTemporary') and
            self.context.isTemporary()):
            # if we are in the portal_factory we want the page title to be
            # "Add fti title"
            portal_types = getToolByName(self.context, 'portal_types')
            fti = portal_types.getTypeInfo(self.context)
            return translate('heading_add_item',
                             domain='plone',
                             mapping={'itemtype': fti.Title()},
                             context=self.request,
                             default='New ${itemtype}')
        if IAddForm.providedBy(self.view):
            portal_types = getToolByName(self.context, 'portal_types')
            fti = portal_types.getTypeInfo(self.view.portal_type)
            return translate('heading_add_item',
                             domain='plone',
                             mapping={'itemtype': fti.Title()},
                             context=self.request,
                             default='New ${itemtype}')
        title = getattr(self.view, 'title', None)
        if not title:
            context_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_context_state')
            title = context_state.object_title()
        return escape(safe_unicode(title))
Пример #11
0
 def translate(self, msgid, *args, **kwargs):
     """Return localized string for given msgid"""
     # XXX: It seems that **kwargs does not yet work with Robot Framework
     # remote library interface and that's why we need to unpack the
     # keyword arguments from positional args list.
     mapping = {}
     for arg in args:
         name, value = arg.split('=', 1)
         kwargs[name] = value
     for key, value in kwargs.items():
         if not key in ('target_language', 'domain', 'default'):
             mapping[key] = value
     if kwargs.get('target_language'):
         return translate(
             msgid, target_langauge=kwargs.get('target_language'),
             domain=kwargs.get('domain') or 'plone',
             default=kwargs.get('default') or msgid, mapping=mapping)
     else:
         # XXX: Should self.REQUEST be replaced with
         # zope.globalrequest.getRequest()?
         request = getRequest()
         return translate(
             msgid, context=request,
             domain=kwargs.get('domain') or 'plone',
             default=kwargs.get('default') or msgid, mapping=mapping)
Пример #12
0
 def __call__(self):
     form = self.request.form
     context = aq_inner(self.context)
     status = IStatusMessage(self.request)
     if not self.can_edit_response:
         msg = _(u"You are not allowed to edit responses.")
         msg = translate(msg, 'Poi', context=self.request)
         status.addStatusMessage(msg, type='error')
     else:
         response_id = form.get('response_id', None)
         if response_id is None:
             msg = _(u"No response selected for saving.")
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='error')
         else:
             response = self.folder[response_id]
             response_text = form.get('response', u'')
             response.text = response_text
             # Remove cached rendered response.
             response.rendered_text = None
             msg = _(u"Changes saved to response id ${response_id}.",
                     mapping=dict(response_id=response_id))
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='info')
             # Fire event.  We put the context in the descriptions
             # so event handlers can use this fully acquisition
             # wrapped object to do their thing.  Feels like
             # cheating, but it gets the job done.  Arguably we
             # could turn the two arguments around and signal that
             # the issue has changed, with the response in the
             # event descriptions.
             modified(response, context)
     self.request.response.redirect(context.absolute_url())
Пример #13
0
def get_date_options(request):
    calendar = request.locale.dates.calendars['gregorian']
    today = datetime.today()
    return {
        'time': False,
        'date': {
            'firstDay': calendar.week.get('firstDay') == 1 and 1 or 0,
            'weekdaysFull': [
                calendar.days.get(t, (None, None))[0]
                for t in (7, 1, 2, 3, 4, 5, 6)],
            'weekdaysShort': [
                calendar.days.get(t, (None, None))[1]
                for t in (7, 1, 2, 3, 4, 5, 6)],
            'monthsFull': calendar.getMonthNames(),
            'monthsShort': calendar.getMonthAbbreviations(),
            'selectYears': 200,
            'min': [today.year - 100, 1, 1],
            'max': [today.year + 20, 1, 1],
            'format': translate(
                _('pickadate_date_format', default='mmmm d, yyyy'),
                context=request),
            'placeholder': translate(_plone('Enter date...'), context=request),
            'today': translate(_plone(u"Today"), context=request),
            'clear': translate(_plone(u"Clear"), context=request),
        }
    }
Пример #14
0
    def validate_response_id(self):
        """Validate the response id from the request.

        Return -1 if for example the response id does not exist.
        Return the response id otherwise.

        Side effect: an informative status message is set.
        """
        status = IStatusMessage(self.request)
        response_id = self.request.form.get('response_id', None)
        if response_id is None:
            msg = _(u"No response selected.")
            msg = translate(msg, 'Poi', context=self.request)
            status.addStatusMessage(msg, type='error')
            return -1
        else:
            try:
                response_id = int(response_id)
            except ValueError:
                msg = _(u"Response id ${response_id} is no integer.",
                        mapping=dict(response_id=response_id))
                msg = translate(msg, 'Poi', context=self.request)
                status.addStatusMessage(msg, type='error')
                return -1
            if response_id >= len(self.folder):
                msg = _(u"Response id ${response_id} does not exist.",
                        mapping=dict(response_id=response_id))
                msg = translate(msg, 'Poi', context=self.request)
                status.addStatusMessage(msg, type='error')
                return -1
            else:
                return response_id
        # fallback
        return -1
Пример #15
0
    def set_portal_message(self, message, msg_type='info'):
        """ Adds or update the portal message.

        It hides both portal messages (the normal one and the KSS
        one and recreates a fresh one.
        """ 

        # We hide the existing ones.
        self('dl.portalMessage').hide()

        # We delete our portal message.
        self('#jq_portal_msg').remove() 

        # And create a fresh one.
        html = '<dl id="jq_portal_msg" class="portalMessage %s">' +\
               '<dt>%s</dt><dd>%s</dd></dl>'

        # We get the correct title (Info, Warning, Error)
        if not msg_type in ['info', 'warning', 'error']:
            msg_type='info'

        lang = self._get_default_language()
        msg_title = translate(_p(unicode(msg_type.capitalize())),
                              target_language=lang)

        # The message might not be translated.
        if type(message) == Message:
            message = translate(message, target_language=lang)
 
        self('#viewlet-above-content').before(html % (msg_type,
                                                      msg_title,
                                                      message))
Пример #16
0
    def current_workflow(self):
        context = aq_inner(self.context)
        portal_workflow = getToolByName(context, 'portal_workflow')
        default_workflow = self.default_workflow(False)
        nondefault = [info[0] for info in portal_workflow.listChainOverrides()]
        chain = portal_workflow.getChainForPortalType(self.type_id)
        empty_workflow_dict = dict(id='[none]',
                                   title=_(u"label_no_workflow"),
                                   description= [_(u"description_no_workflow",
                                   default=u"This type has no workflow. The visibilty "
                                       u"of items of this type is determined by "
                                       u"the folder they are in.")])

        if self.type_id in nondefault:
            if chain:
                wf_id = chain[0]
                wf = getattr(portal_workflow, wf_id)
                title = translate(wf.title, domain='plone', context=self.request)
                return dict(id=wf.id, title=title, description=format_description(wf.description, self.request))
            else:
                return empty_workflow_dict

        if default_workflow == '[none]':
            return empty_workflow_dict

        default_title = translate(default_workflow.title, domain='plone',
                                  context=self.request)
        return dict(id='(Default)',
                    title=_(u"label_default_workflow_title",
                        default=u"Default workflow (${title})",
                        mapping=dict(title=default_title)),
                    description=format_description(default_workflow.description, self.request))
Пример #17
0
    def handle_apply(self, action):
        data, errors = self.extractData()
        if errors:
            return

        portal = getSite()

        # create a new rand
        expires = datetime.now() + timedelta(days=2)
        data = {'email': data['email']}
        rand = IFridgeManager(self.context).add_entry(data, expires)

        # send mail to user
        mail_to = data['email']
        url = u"%s/%s/%s" % (self.context.absolute_url(), FORM_ID, rand)
        link = u'<a href="%s">%s</a>' % (url, url)
        message = translate(msgid=u'request_registration_mail_text',
                            domain=DOMAIN,
                            mapping={'link': link,
                                     'expires': expires.strftime('%d.%m.%Y %H:%M')},
                            context=self.request,
                            default=u'Finish your registration here ${link} by ${expires}.',
                            )
        mail_subject = translate(msgid="request_registration_mail_subject",
                                 domain=DOMAIN,
                                 context=self.request,
                                 default=u'Registration',
                                 )
        notify(MailEvent(message, mail_to, subject=mail_subject))

        IStatusMessage(self.request).add(_(u'request_registration_success_notification'),
                                        type='warn')
        return self._redirect()
Пример #18
0
    def available_workflows(self):
        vocab_factory = getUtility(IVocabularyFactory,
                                   name="plone.app.vocabularies.Workflows")
        workflows = []
        for v in vocab_factory(self.context):
            if v.title:
                title = translate(v.title, context=self.request)
            else:
                title = translate(v.token, domain='plone', context=self.request)
            workflows.append(dict(id=v.value, title=title) )
        def _key(v):
            return v['title']
        workflows.sort(key=_key)

        default_workflow = self.default_workflow(False)
        if self.type_id and default_workflow != '[none]':
            # Only offer a default workflow option on a real type
            default_workflow = self.default_workflow(False)
            default_title = translate(default_workflow.title,
                                      domain='plone', context=self.request)
            workflows.insert(0, dict(id='(Default)',
                    title=_(u"label_default_workflow_title",
                            default=u"Default workflow (${title})",
                            mapping=dict(title=default_title)),
                    description=format_description(default_workflow.description, self.request)))

        return workflows
Пример #19
0
 def __init__(self, context, request):
     super(Status, self).__init__(context, request)
     default_risks_by_status = lambda: {
         'present': {
             'high': [],
             'medium': [],
             'low': [],
         },
         'possible': {
             'postponed': [],
             'todo': [],
         },
     }
     self.risks_by_status = defaultdict(default_risks_by_status)
     now = datetime.now()
     lang = date_lang = getattr(self.request, 'LANGUAGE', 'en')
     # Special handling for Flemish, for which LANGUAGE is "nl-be". For
     # translating the date under plone locales, we reduce to generic "nl".
     # For the specific oira translation, we rewrite to "nl_BE"
     if "-" in lang:
         date_lang = lang.split("-")[0]
         elems = lang.split("-")
         lang = "{0}_{1}".format(elems[0], elems[1].upper())
     self.date = u"{0} {1} {2}".format(
         now.strftime('%d'),
         translate(
             PloneLocalesFactory(
                 "month_{0}".format(now.strftime('%b').lower()),
                 default=now.strftime('%B'),
             ),
             target_language=date_lang,),
         now.strftime('%Y')
     )
     self.label_page = translate(_(u"label_page", default=u"Page"), target_language=lang)
     self.label_page_of = translate(_(u"label_page_of", default=u"of"), target_language=lang)
Пример #20
0
    def query(self, default=None):
        status = ISubmittedDraftContent.providedBy(self.content)

        if status:
            return translate(u'Not Yet Approved', 'zojax.personal.content')
        else:
            return translate(u'Draft', 'zojax.personal.content')
Пример #21
0
    def Title(self):
        """The title of the comment.
        """

        if self.title:
            return self.title

        if not self.author_name:
            author_name = translate(
                Message(_(
                    u"label_anonymous",
                    default=u"Anonymous"
                ))
            )
        else:
            author_name = self.author_name

        # Fetch the content object (the parent of the comment is the
        # conversation, the parent of the conversation is the content object).
        content = aq_base(self.__parent__.__parent__)
        title = translate(
            Message(COMMENT_TITLE,
                    mapping={'author_name': safe_unicode(author_name),
                             'content': safe_unicode(content.Title())}))
        return title
Пример #22
0
    def issuePortalMessage(self, message, msgtype='info'):
        if message is None:
            message = ''

        if isinstance(message, Message):
            msgtype = message.type
            # The translation domain of the message is not known.  We
            # can only assume that it is 'plone'.
            message = translate(message.message, domain='plone',
                                context=self.request)
        elif isinstance(message, i18nmessage):
            # Here the message has a domain itself, which is good.
            message = translate(message, context=self.request)

        # The 'dt' of the definition list we generate should contain
        # something like Info, Warning or Error.  Those messages are
        # available in the plone domain.
        msgtype_name = translate(msgtype.capitalize(), domain='plone',
                                 context=self.request)

        # XXX The macro has to take in account that there might be more than
        # one status message.
        ksscore = self.getCommandSet('core')
        selector = ksscore.getHtmlIdSelector('kssPortalMessage')

        # We hide the standard Plone Portal Message
        standard_portal_message_selector = ksscore.getCssSelector('.portalMessage')
        ksscore.setStyle(standard_portal_message_selector, 'display','none')

        # Now there is always a portal message but it has to be
        # rendered visible or invisible, accordingly
        html = '<dt>%s</dt><dd>%s</dd>' % (msgtype_name, message)
        ksscore.replaceInnerHTML(selector, html)
        ksscore.setAttribute(selector, 'class', "portalMessage %s" % msgtype)
        ksscore.setStyle(selector, 'display', message and 'block' or 'none')
Пример #23
0
    def getBandoState(self, bando):
        """
        """

        scadenza_bando = bando.getScadenza_bando
        chiusura_procedimento_bando = bando.getChiusura_procedimento_bando
        state = ("open", translate(_(u"Open"), context=self.request))
        if scadenza_bando and scadenza_bando.isPast():
            if (
                chiusura_procedimento_bando
                and chiusura_procedimento_bando.isPast()
            ):
                state = (
                    "closed",
                    translate(_(u"Closed"), context=self.request),
                )
            else:
                state = (
                    "inProgress",
                    translate(_(u"In progress"), context=self.request),
                )
        else:
            if (
                chiusura_procedimento_bando
                and chiusura_procedimento_bando.isPast()
            ):
                state = (
                    "closed",
                    translate(_(u"Closed"), context=self.request),
                )

        return state
Пример #24
0
    def comment_transform_message(self):
        """Returns the description that shows up above the comment text,
           dependent on the text_transform setting and the comment moderation
           workflow in the discussion control panel.
        """
        context = aq_inner(self.context)
        registry = queryUtility(IRegistry)
        settings = registry.forInterface(IDiscussionSettings, check=False)

        # text transform setting
        if settings.text_transform == "text/x-web-intelligent":
            message = translate(Message(COMMENT_DESCRIPTION_INTELLIGENT_TEXT),
                                context=self.request)
        elif settings.text_transform == "text/x-web-markdown":
            message = translate(Message(COMMENT_DESCRIPTION_MARKDOWN),
                                context=self.request)
        else:
            message = translate(Message(COMMENT_DESCRIPTION_PLAIN_TEXT),
                                context=self.request)

        # comment workflow
        wftool = getToolByName(context, "portal_workflow", None)
        workflow_chain = wftool.getChainForPortalType('Discussion Item')
        if workflow_chain:
            comment_workflow = workflow_chain[0]
            comment_workflow = wftool[comment_workflow]
            # check if the current workflow implements a pending state. If this
            # is true comments are moderated
            if 'pending' in comment_workflow.states:
                message = message + " " + \
                    translate(Message(COMMENT_DESCRIPTION_MODERATION_ENABLED),
                              context=self.request)

        return message
def sendNotificationToMinistry(date):
    """
    send a notification to the ministry stating
    all questions that are approaching the deadline
    """
    text = translate("notification_email_to_ministry_question_pending_response",
                     target_language="en",
                     domain="bungeni",
                     default="Questions pending responses.")
    ministries = _getAllMinistries(date)
    for ministry in ministries:
        questions = _getQuestionsPendingResponse(date, ministry)
        text = translate("notification_email_to_ministry_question_pending_response",
                     target_language="en",
                     domain="bungeni",
                     default="Questions assigned to the ministry pending responses.")
        if questions: 
            text = "%s\n%s: \n" % (text, ministry.full_name) + \
                "\n".join([ question.subject for question in questions ])
            emails = [ utils.formatted_user_email(minister)
                for minister in dbutils.get_ministers(ministry) ]
            msg = MIMEText(text)
            msg["Subject"] = "Questions pending response"
            msg["From"] = prefs.getClerksOfficeEmail()
            msg["To"] = " ,".join(emails)
            print msg
            # !+SENDMAIL(ah,18-03-2010)
            #Mail sending is commented out 
            dispatch(msg)
Пример #26
0
 def update(self):
     base_url = self.context.absolute_url()
     base_vocabulary = '%s/@@getStorageVocabulary' % base_url
     push_state_url = '%s/storage_contents{path}' % base_url
     options = {
         'vocabularyUrl': base_vocabulary,
         'pushStateUrl': push_state_url,
         'traverseView': True,
         # TODO verify that get_url result in a valid location dir.
         'traverseSubpath': self.get_current_path(),
         'indexOptionsUrl': '%s/@@qsOptions' % base_url,
         'contextInfoUrl': '%s/@@sc-contextInfo' % base_url,
         'attributes': attributes,
         'activeColumns': ['ModificationDate', 'getObjSize'],
         'activeColumnsCookie': 'activeStorageColumns',
         'availableColumns': {
             'id': translate(_('ID'), context=self.request),
             'ModificationDate': translate(_('Last modified'), context=self.request),  # noqa
             'getObjSize': translate(_('Object Size'), context=self.request),  # noqa
         },
         'upload': False,
         'rearrange': False,
         'buttons': self.get_actions(),
         'menuGenerator': 'repodonostorage-url/js/actionmenu',
         'tableRowItemAction': {
             # switch off the default navigation js method
             'other': None,
         },
         'collectionConstructor': 'repodonostorage-url/js/collection',
     }
     self.options = json.dumps(options)
Пример #27
0
    def createCommentRule(self):
        context = self.context

        subject = translate(_('notify_subj_comments',
                             default=u'[${room_title}] New comment has been created',
                             mapping={"room_title": context.Title().decode('utf-8')}),
                          context=context.REQUEST,
                          target_language=self.language)
        message = translate(_('notify_msg_comments',
                            default=u'A new comment has been added by ${user} to document ${parent_title}.\n'
                                    u'\n'
                                    u'${text}\n'
                                    u'\n'
                                    u'You can click on the following link to see the comment:\n'
                                    u'${url}'),
                          context=context.REQUEST,
                          target_language=self.language)
        rule_title = translate(_('notify_title_comments',
                                 default=u'[${room_title}] notify for new comments',
                                 mapping={"room_title": context.Title().decode('utf-8')}),
                               context=context.REQUEST,
                               target_language=self.language)
        rule_description = translate(_('notify_description_comments',
                                       default=u'All users inside the comments notification group of the room '
                                               u'will be mailed when new comments are added'),
                                     context=context.REQUEST,
                                     target_language=self.language)

        room = self._getParentRoom(context)
        self.createRule(context, room, rule_id="%s-comments" % context.getId(), rule_title=rule_title,
                        rule_description=rule_description, rule_event=IObjectAddedEvent,
                        subject=subject, message=message, for_types=('Discussion Item',), area_id="comments")
Пример #28
0
    def reminder_options(self):
        options = []
        reminder_option = TaskReminder().get_reminder(self.context)

        options.append({
            'option_type': 'no-reminder',
            'option_title': translate(_('no_reminder', default='No reminder'),
                                      context=self.request),
            'sort_order': -1,
            'selected': reminder_option is None,
            'showSpinner': False,
            })

        for option in TASK_REMINDER_OPTIONS.values():
            selected = option.option_type == reminder_option.option_type if \
                reminder_option else None
            options.append({
                'option_type': option.option_type,
                'sort_order': option.sort_order,
                'option_title': translate(
                    option.option_title, context=self.request),
                'selected': selected,
                'showSpinner': False,
            })

        return options
Пример #29
0
    def items(self):
        items = []
        for system in self.unit_systems:
            dimensions = interfaces.UNITS.get(system, None)
            if not dimensions:
                continue
            units = []
            available_units = dimensions.get(self.unit_dimension, [])
            if self.level_max is not None:
                level_max = self.level_max + 1
            else:
                level_max = None
            available_units = available_units[self.level_min:level_max]
            for unit in available_units:
                abbr, label_short, label, info = unit
                subtext = translate(label, context=self.request)
                if info:
                    info = translate(info, context=self.request)
                    subtext = subtext + ' (%s)' % info
                units.append({
                    'id': abbr,
                    'value': abbr,
                    'content': label_short,
                    'subtext': subtext,
                    'selected': self.isSelected(abbr),
                })

            item = {}
            item['title'] = interfaces.LABELS.get(system)
            item['member'] = units
            items.append(item)

        return items
Пример #30
0
def notify_moderator(obj, event):
    """Tell the moderator when a comment needs attention.

       This method sends an email to the moderator if comment moderation a new
       comment has been added that needs to be approved.

       The moderator_notification setting has to be enabled in the discussion
       control panel.

       Configure the moderator e-mail address in the discussion control panel.
       If no moderator is configured but moderator notifications are turned on,
       the site admin email (from the mail control panel) will be used.
    """
    # Check if moderator notification is enabled
    registry = queryUtility(IRegistry)
    settings = registry.forInterface(IDiscussionSettings, check=False)
    if not settings.moderator_notification_enabled:
        return

    # Get informations that are necessary to send an email
    mail_host = getToolByName(obj, 'MailHost')
    portal_url = getToolByName(obj, 'portal_url')
    portal = portal_url.getPortalObject()
    sender = portal.getProperty('email_from_address')

    if settings.moderator_email:
        mto = settings.moderator_email
    else:
        mto = sender

    # Check if a sender address is available
    if not sender:
        return

    conversation = aq_parent(obj)
    content_object = aq_parent(conversation)

    # Compose email
    subject = translate(_(u"A comment has been posted."), context=obj.REQUEST)
    message = translate(Message(MAIL_NOTIFICATION_MESSAGE_MODERATOR,
        mapping={
            'title': safe_unicode(content_object.title),
            'link': content_object.absolute_url() + '/view#' + obj.id,
            'text': obj.text,
            'link_approve': obj.absolute_url() + '/@@moderate-publish-comment',
            'link_delete': obj.absolute_url() + '/@@moderate-delete-comment',
            }),
        context=obj.REQUEST)

    # Send email
    try:
        mail_host.send(message, mto, sender, subject, charset='utf-8')
    except SMTPException, e:
        logger.error('SMTP exception (%s) while trying to send an ' +
                     'email notification to the comment moderator ' +
                     '(from %s to %s, message: %s)',
                     e,
                     sender,
                     mto,
                     message)
Пример #31
0
 def safe_call(self):
     return translate(self.context.Type(), context=self.context.REQUEST)
Пример #32
0
def i18n_message_converter(value):
    value = translate(value, context=getRequest())
    return value
Пример #33
0
 def get_title(self):
     return translate(_(u'latex_label_events', u'Tasks'),
                      context=self.request)
Пример #34
0
 def initDialog(self):
     super(DeleteEventDialog, self).initDialog()
     title = _(u'Delete event ${event}',
               mapping={'event': self.event.title})
     self.ajax_settings['dialog']['title'] = translate(
         title, context=self.request)
Пример #35
0
def create_order_summary(context, order_data):
    """Create summary for notification mail.
    """
    attrs = order_data.order.attrs
    cart_total = order_data.total
    # no costs at all
    if not cart_total:
        return ''
    lines = []
    request = getRequest()
    # currency
    currency = order_data.currency
    # cart net and vat
    cart_net = order_data.net
    if cart_net:
        # cart net
        order_summary_cart_net = _('order_summary_cart_net',
                                   default=u'Net: ${value} ${currency}',
                                   mapping={
                                       'value': ascur(cart_net),
                                       'currency': currency,
                                   })
        lines.append(translate(order_summary_cart_net, context=request))
        # cart vat
        cart_vat = order_data.vat
        order_summary_cart_vat = _('order_summary_cart_vat',
                                   default=u'VAT: ${value} ${currency}',
                                   mapping={
                                       'value': ascur(cart_vat),
                                       'currency': currency,
                                   })
        lines.append(translate(order_summary_cart_vat, context=request))
    # cart discount
    discount_net = order_data.discount_net
    if discount_net:
        # discount net
        order_summary_discount_net = _(
            'order_summary_discount_net',
            default=u'Discount Net: ${value} ${currency}',
            mapping={
                'value': ascur(discount_net),
                'currency': currency,
            })
        lines.append(translate(order_summary_discount_net, context=request))
        # discount vat
        discount_vat = order_data.discount_vat
        order_summary_discount_vat = _(
            'order_summary_discount_vat',
            default=u'Discount VAT: ${value} ${currency}',
            mapping={
                'value': ascur(discount_vat),
                'currency': currency,
            })
        lines.append(translate(order_summary_discount_vat, context=request))
        # discount total
        discount_total = discount_net + discount_vat
        order_summary_discount_total = _(
            'order_summary_discount_total',
            default=u'Discount Total: ${value} ${currency}',
            mapping={
                'value': ascur(discount_total),
                'currency': currency,
            })
        lines.append(translate(order_summary_discount_total, context=request))
    # shipping costs
    shipping_net = order_data.shipping_net
    if shipping_net:
        # shiping label
        shipping_label = attrs['shipping_label']
        order_summary_shipping_label = _('order_summary_shipping_label',
                                         default=u'Shipping: ${label}',
                                         mapping={
                                             'label':
                                             translate(shipping_label,
                                                       context=request),
                                         })
        lines.append(translate(order_summary_shipping_label, context=request))
        # shiping description
        shipping_description = attrs['shipping_description']
        lines.append(translate(shipping_description, context=request))
        # shiping net
        order_summary_shipping_net = _(
            'order_summary_shipping_net',
            default=u'Shipping Net: ${value} ${currency}',
            mapping={
                'value': ascur(shipping_net),
                'currency': currency,
            })
        lines.append(translate(order_summary_shipping_net, context=request))
        # shiping vat
        shipping_vat = order_data.shipping_vat
        order_summary_shipping_vat = _(
            'order_summary_shipping_vat',
            default=u'Shipping VAT: ${value} ${currency}',
            mapping={
                'value': ascur(shipping_vat),
                'currency': currency,
            })
        lines.append(translate(order_summary_shipping_vat, context=request))
        # shiping total
        shipping_total = shipping_net + shipping_vat
        order_summary_shipping_total = _(
            'order_summary_shipping_total',
            default=u'Shipping Total: ${value} ${currency}',
            mapping={
                'value': ascur(shipping_total),
                'currency': currency,
            })
        lines.append(translate(order_summary_shipping_total, context=request))
    # cart total
    order_summary_cart_total = _('order_summary_cart_total',
                                 default=u'Total: ${value} ${currency}',
                                 mapping={
                                     'value': ascur(cart_total),
                                     'currency': currency,
                                 })
    lines.append(translate(order_summary_cart_total, context=request))
    summary_title = translate(_('order_summary_label', default=u'Summary:'),
                              context=request)
    summary_text = '\n' + '\n'.join([safe_encode(line) for line in lines])
    return '\n' + safe_encode(summary_title) + summary_text + '\n'
Пример #36
0
def format_description(text, request=None):
    # We expect the workflow to be a text of '- ' divided bullet points.
    text = translate(text.strip(), domain='plone', context=request)
    return [s.strip() for s in text.split('- ') if s]
Пример #37
0
 def msg_unexpected_error(self):
     return translate(_('An unexpected error has occurred',
                        default='An unexpected error has occurred'),
                      context=self.request)
Пример #38
0
    def navtree(self):
        ret = defaultdict(list)
        navtree_path = self.navtree_path
        for tab in self.portal_tabs:
            entry = {}
            entry.update({
                "path": "/".join((navtree_path, tab["id"])),
                "description": tab["description"],
                "@id": tab["url"],
            })
            if "review_state" in tab:
                entry["review_state"] = json_compatible(tab["review_state"])
            else:
                entry["review_state"] = None

            if "title" not in entry:
                entry["title"] = tab.get("name") or tab.get(
                    "description") or tab["id"]
            else:
                # translate Home tab
                entry["title"] = translate(entry["title"],
                                           domain="plone",
                                           context=self.request)

            entry["title"] = safe_unicode(entry["title"])
            ret[navtree_path].append(entry)

        query = {
            "path": {
                "query": self.navtree_path,
                "depth": self.depth,
            },
            "portal_type": {
                "query": self.settings["displayed_types"]
            },
            "Language": self.current_language,
            "is_default_page": False,
            "sort_on": "getObjPositionInParent",
        }

        if not self.settings["nonfolderish_tabs"]:
            query["is_folderish"] = True

        if self.settings["filter_on_workflow"]:
            query["review_state"] = list(
                self.settings["workflow_states_to_show"] or ())

        if not self.settings["show_excluded_items"]:
            query["exclude_from_nav"] = False

        context_path = "/".join(self.context.getPhysicalPath())
        portal_catalog = getToolByName(self.context, "portal_catalog")
        brains = portal_catalog.searchResults(**query)

        registry = getUtility(IRegistry)
        types_using_view = registry.get(
            "plone.types_use_view_action_in_listings", [])

        for brain in brains:
            brain_path = brain.getPath()
            brain_parent_path = brain_path.rpartition("/")[0]
            if brain_parent_path == navtree_path:
                # This should be already provided by the portal_tabs_view
                continue
            if brain.exclude_from_nav and not context_path.startswith(
                    brain_path):
                # skip excluded items if they're not in our context path
                continue
            url = brain.getURL()
            entry = {
                "path":
                brain_path,
                "@id":
                url,
                "title":
                safe_unicode(brain.Title),
                "description":
                safe_unicode(brain.Description),
                "review_state":
                json_compatible(brain.review_state),
                "use_view_action_in_listings":
                brain.portal_type in types_using_view,
            }
            if "nav_title" in brain and brain.nav_title:
                entry.update({"title": brain.nav_title})

            self.customize_entry(entry, brain)
            ret[brain_parent_path].append(entry)
        return ret
Пример #39
0
 def __call__(self, source_string):
     return translate(source_string,
                      domain=self.domain,
                      context=self.context)
Пример #40
0
 def test_pm_ChangeItemOrderMoveAtGivenNumber(self):
     '''Test the ChangeItemOrderView :
        - we can change an item to a given p_moveNumber.'''
     # create a meetingWithItems and play
     self.changeUser('pmManager')
     meeting, item1, item2, item3, item4, item5, item6, item7 = self._setupOrderedItems(
     )
     self.assertEquals(item1.getItemNumber(), 100)
     self.assertEquals(item2.getItemNumber(), 200)
     self.assertEquals(item3.getItemNumber(), 300)
     self.assertEquals(item4.getItemNumber(), 400)
     self.assertEquals(item5.getItemNumber(), 500)
     view = item2.restrictedTraverse('@@change-item-order')
     # move the item2 to position 3
     view('number', '3')
     self.assertEquals(item2.getItemNumber(), 300)
     # and other items position are adapted
     self.assertEquals(item1.getItemNumber(), 100)
     self.assertEquals(item3.getItemNumber(), 200)
     self.assertEquals(item4.getItemNumber(), 400)
     self.assertEquals(item5.getItemNumber(), 500)
     # put the item2 back to position 2
     view('up')
     self.assertEquals(item2.getItemNumber(), 200)
     # and other items position are adapted
     self.assertEquals(item1.getItemNumber(), 100)
     self.assertEquals(item3.getItemNumber(), 300)
     self.assertEquals(item4.getItemNumber(), 400)
     self.assertEquals(item5.getItemNumber(), 500)
     # no valid number does not cause crash
     view('number', '0')
     # nothing changed
     self.assertEquals(item2.getItemNumber(), 200)
     view('number', '-4')
     # nothing changed
     self.assertEquals(item2.getItemNumber(), 200)
     view('number', '99')
     # nothing changed
     self.assertEquals(item2.getItemNumber(), 200)
     view('number', None)
     # nothing changed
     self.assertEquals(item2.getItemNumber(), 200)
     # move 2 positions to far
     self.assertEqual(len(meeting.get_items()), 7)
     view('number', '9')
     # nothing changed
     self.assertEquals(item2.getItemNumber(), 200)
     # move one of the last items upper
     view = item4.restrictedTraverse('@@change-item-order')
     view('number', '1')
     self.assertEquals(item4.getItemNumber(), 100)
     # and other items position are adapted
     self.assertEquals(item1.getItemNumber(), 200)
     self.assertEquals(item2.getItemNumber(), 300)
     self.assertEquals(item3.getItemNumber(), 400)
     self.assertEquals(item5.getItemNumber(), 500)
     # change the item to the same place, a message is displayed
     messages = IStatusMessage(self.request)
     view('number', _storedItemNumber_to_itemNumber(item4.getItemNumber()))
     self.assertEquals(messages.show()[-1].message,
                       translate('item_did_not_move', 'PloneMeeting'))
Пример #41
0
    def add_new_person(self,
                       companyid,
                       username,
                       email,
                       fullname,
                       password,
                       selectnewvalue,
                       disable=False,
                       notify=False):
        # create a user from the input

        notify = not disable and notify

        portalObj = getToolByName(self.context, 'portal_url').getPortalObject()
        company = getattr(portalObj.companies, companyid)
        result = company.check_id(id=username, contained_by=company)
        if result:
            self.getCommandSet('plone').issuePortalMessage(result, 'error')
            return

        # portal_registration = getUtility(IRegistrationTool)
        # if not portal_registration.isMemberIdAllowed(username):
        #     self.getCommandSet('portalmessage').issuePortalMessage(
        #             'illegal member id', 'portalWarningMessage')
        #     return self.render()

        if valid_id(username) is None:
            self.getCommandSet('plone').issuePortalMessage(
                translate(_(u'illegal_member_id',
                            default='Member Id is valid'),
                          context=self.request),
                translate(_(u'error'), context=self.request))
            return

        membership = getToolByName(self.context, 'portal_membership')
        if membership.getMemberById(username) is not None:
            self.getCommandSet('plone').issuePortalMessage(
                translate(_(
                    u'exisits_in_portal',
                    default='Exisits in portal, please change person username.'
                ),
                          context=self.request),
                translate(_(u'error'), context=self.request))
            return

        # company.invokeFactory(type_name='Person', id=username)
        _createObjectByType('Person', company, username)
        person = getattr(company, username)
        person.setEmail(email)
        person.setTitle(fullname)
        person.setPassword(password)
        person.reindexObject()

        # 手动调用,以便设置权限
        person.unmarkCreationFlag()

        event.notify(ObjectEditedEvent(person))
        person.at_post_create_script()

        if disable:
            wf_tool = getToolByName(person, 'portal_workflow')
            wf_tool.doActionFor(person, 'deactivate')

        team_id = selectnewvalue
        team = getattr(self.context, team_id)
        team.setMembers(team.getMembers() + [person])

        self._update_company(companyid)

        if notify:
            person.sendAccountInfoEmail(password)
Пример #42
0
 def translate(self, msgid, domain=None, mapping=None, default=None):
     context = self.contexts.get('request')
     return translate(
         msgid, domain=domain, mapping=mapping,
         context=context, default=default)
Пример #43
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.label = translate(self.label,
                            domain='PloneMeeting',
                            context=self.request)
Пример #44
0
 def dialog_title(self):
     title = _(u'Delete ${schoolyear}',
               mapping={'schoolyear': self.context.title})
     return translate(title, context=self.request)
Пример #45
0
 def translate(self, msgid, domain='plone'):
     """Let's translate a given msgid in given domain."""
     return translate(msgid, domain, context=self.request)
Пример #46
0
def t(i18n_msg):
    """Safely translate and convert to UTF8, any zope i18n msgid returned from
    a bikaMessageFactory _
    """
    return to_utf8(translate(i18n_msg))
Пример #47
0
 def contextual_title(self):
     parent = self.aq_parent
     if parent == self.bika_setup.bika_analysisspecs:
         return self.title + " (" + translate(_("Lab")) + ")"
     else:
         return self.title + " (" + translate(_("Client")) + ")"
Пример #48
0
 def context_provider(context):
     value = translate(msgstring, context=getRequest())
     if replacements:
         value = value.format(**replacements)
     return value
Пример #49
0
 def __call__(self):
     return u'<a href="%s/download"> %s </a>' \
         % (url.absoluteURL(self.__parent__.context, self.request),
             translate(_("download"), context=self.request),
         )
Пример #50
0
 def sectionName(term, section):
     return '%s in %s' % (translate(section.label), term.title)
Пример #51
0
def jupload__call__(self):
    authenticator = getMultiAdapter((self.context, self.request),
                                    name=u"authenticator")
    if not authenticator.verify() or \
            self.request['REQUEST_METHOD'] != 'POST':
        raise Unauthorized
    filedata = self.request.form.get("files[]", None)
    if filedata is None:
        return
    filename = filedata.filename
    content_type = mimetypes.guess_type(filename)[0] or ""

    if not filedata:
        return

    ctr = getToolByName(self.context, 'content_type_registry')
    type_ = ctr.findTypeName(filename.lower(), '', '') or 'File'

    # Determine if the default file/image types are DX or AT based
    DX_BASED = False
    context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state')
    if HAS_DEXTERITY:
        pt = getToolByName(self.context, 'portal_types')
        if IDexterityFTI.providedBy(getattr(pt, type_)):
            factory = IDXFileFactory(self.context)
            DX_BASED = True
        else:
            factory = IATCTFileFactory(self.context)
        # if the container is a DX type, get the available types from the behavior
        if IDexterityFTI.providedBy(getattr(pt, self.context.portal_type)):
            addable_types = ISelectableConstrainTypes(
                self.context).getLocallyAllowedTypes()
        elif context_state.is_portal_root():
            allowed_types = _allowedTypes(self.request, self.context)
            addable_types = [fti.getId() for fti in allowed_types]
        else:
            addable_types = self.context.getLocallyAllowedTypes()
    else:
        factory = IATCTFileFactory(self.context)
        if context_state.is_portal_root():
            allowed_types = _allowedTypes(self.request, self.context)
            addable_types = [fti.getId() for fti in allowed_types]
        else:
            addable_types = self.context.getLocallyAllowedTypes()

    # if the type_ is disallowed in this folder, return an error
    if type_ not in addable_types:
        msg = translate(
            _WF('disallowed_type_error',
                default='${filename}: adding of "${type}" \
                         type is disabled in this folder',
                mapping={'filename': filename, 'type': type_}),
            context=self.request
        )
        return json.dumps({'files': [{'error': msg}]})

    obj = factory(filename, content_type, filedata)

    if DX_BASED:
        if 'File' in obj.portal_type:
            size = obj.file.getSize()
            content_type = obj.file.contentType
        elif 'Image' in obj.portal_type:
            size = obj.image.getSize()
            content_type = obj.image.contentType

        result = {
            "url": obj.absolute_url(),
            "name": obj.getId(),
            "type": content_type,
            "size": size
        }
    else:
        try:
            size = obj.getSize()
        except AttributeError:
            size = obj.getObjSize()

        result = {
            "url": obj.absolute_url(),
            "name": obj.getId(),
            "type": obj.getContentType(),
            "size": size
        }

    if 'Image' in obj.portal_type:
        result['thumbnail_url'] = result['url'] + '/@@images/image/tile'

    return json.dumps({
        'files': [result]
    })
Пример #52
0
def title_helper(item, value):
    return translate(item['action'].get('title'), context=getRequest())
Пример #53
0
 def get_js(self):
     pagedate = datetime.date.today()
     if self.maxDate < pagedate:
         pagedate = self.maxDate
     if ((type(self._data) == datetime.date)
             or (type(self._data) == datetime.datetime)):
         pagedate = self._data
     calendar = self.request.locale.dates.calendars["gregorian"]
     month = _(u"Choose Month")
     year = _(u"Enter Year")
     submit = _("OK")
     cancel = _(u"Cancel")
     invalidYear = _(u"Please enter a valid year")
     months_short = self.jstr(calendar.getMonthAbbreviations())
     months_long = self.jstr(calendar.getMonthNames())
     w_day_1char = self.jstr(
         [dn[:1] for dn in calendar.getDayAbbreviations()])
     w_day_short = self.jstr(
         [dn[:2] for dn in calendar.getDayAbbreviations()])
     w_day_medium = self.jstr(calendar.getDayAbbreviations())
     w_day_long = self.jstr(calendar.getDayNames())
     return self.js_template % {
         "name":
         self.field_name,
         "sel_day":
         self._day_name,
         "sel_month":
         self._month_name,
         "sel_year":
         self._year_name,
         "txt_date":
         self.date_name,
         "mindate":
         self.minDate.strftime("%m/%d/%Y"),
         "maxdate":
         self.maxDate.strftime("%m/%d/%Y"),
         "pagedate":
         pagedate.strftime("%m/%Y"),
         "months_short":
         months_short,
         "months_long":
         months_long,
         "w_day_1char":
         w_day_1char,
         "w_day_short":
         w_day_short,
         "w_day_medium":
         w_day_medium,
         "w_day_long":
         w_day_long,
         "month":
         translate(str(month), domain="bungeni", context=self.request),
         "year":
         translate(str(year), domain="bungeni", context=self.request),
         "submit":
         translate(str(submit), domain="bungeni", context=self.request),
         "cancel":
         translate(str(cancel), domain="bungeni", context=self.request),
         "invalidYear":
         translate(str(invalidYear), domain="bungeni", context=self.request)
     }
Пример #54
0
    def date_format(self, time, formatstring):
        # This is a simplified version of
        # Products.CMFPlone.i18nl10n.ulocalized_time
        # that can take any format string.

        # ${a}        Locale's abbreviated weekday name.
        # ${A}        Locale's full weekday name.
        # ${b}        Locale's abbreviated month name.
        # ${B}        Locale's full month name.
        # ${d}        Day of the month as a decimal number [01,31].
        # ${H}        Hour (24-hour clock) as a decimal number [00,23].
        # ${I}        Hour (12-hour clock) as a decimal number [01,12].
        # ${m}        Month as a decimal number [01,12].
        # ${M}        Minute as a decimal number [00,59].
        # ${p}        Locale's equivalent of either AM or PM.
        # ${S}        Second as a decimal number [00,61].
        # ${y}        Year without century as a decimal number [00,99].
        # ${Y}        Year with century as a decimal number.
        # ${Z}        Time zone name (no characters if no time zone exists).

        # get the format elements used in the formatstring
        mapping = {}
        formatelements = _interp_regex.findall(formatstring)
        # reformat the ${foo} to foo
        formatelements = [el[2:-1] for el in formatelements]

        # add used elements to mapping
        elements = [e for e in formatelements if e in datetime_formatvariables]

        # add weekday name, abbr. weekday name, month name, abbr month name
        week_included = True
        month_included = True

        name_elements = [
            e for e in formatelements if e in name_formatvariables
        ]
        if not ('a' in name_elements or 'A' in name_elements):
            week_included = False
        if not ('b' in name_elements or 'B' in name_elements):
            month_included = False

        for key in elements:
            mapping[key] = time.strftime('%' + key)

        if week_included:
            weekday = int(time.strftime('%w'))  # weekday, sunday = 0
            if 'a' in name_elements:
                mapping['a'] = weekdayname_msgid_abbr(weekday)
            if 'A' in name_elements:
                mapping['A'] = weekdayname_msgid(weekday)
        if month_included:
            monthday = int(time.strftime('%m'))  # month, january = 1
            if 'b' in name_elements:
                mapping['b'] = monthname_msgid_abbr(monthday)
            if 'B' in name_elements:
                mapping['B'] = monthname_msgid(monthday)

        # translate translateable elements
        for key in name_elements:
            mapping[key] = translate(mapping[key],
                                     'plonelocales',
                                     context=self.request,
                                     default=mapping[key])

        # Apply the data to the format string:
        return interpolate(formatstring, mapping)
Пример #55
0
    def generate(self,
                 contents,
                 columns,
                 sortable=False,
                 selected=(None, None),
                 css_mapping={},
                 translations=[],
                 template=None,
                 options={},
                 output='html',
                 meta_data=None):
        """We make sure to use thread local data as a single instance of this
        object is shared between threads (see comment on utilities at the
        beginning of this file).
        """
        self.reset_data()
        self.set_data("sortable", sortable)
        self.set_data("selected", selected)
        self.set_data("columns", self.process_columns(columns))
        self.set_data("contents", contents)
        self.set_data("options", options)
        self.set_data("grouping_enabled", False)

        if output == 'html':
            # XXX
            # NOT WORK, WHEN WE USED THE TRANSFERRED TEMPLATE
            if template is not None:
                template = ViewPageTemplateFile(template.filename)
            else:
                template = self.template

            css = self._css_mapping.copy()
            css.update(css_mapping)
            self.css_mapping = css
            #if template is not None:
            #    #XXX dirty
            #    return template(**self.__dict__)
            return template(self)
        elif output == 'json':

            msgids = set(self._translations + translations)

            table = dict(totalCount=len(self.contents), rows=[])

            for content in self.contents:
                row = {}
                if isinstance(content, tuple):
                    # group is enabled.
                    # when group is enabled, the rows should be tuples
                    # containg the group label
                    if not isinstance(content, tuple):
                        raise ValueError('Expected row to be a tuple since '
                                         'grouping is activated.')
                    self.set_data("grouping_enabled", True)
                    content, row['groupBy'] = content

                for column in self.columns:
                    key = (column.get('sort_index', None) or column['attr']
                           or column['title'] or column['transform'].__name__)

                    value = self.get_value(content, column)
                    if value == Missing.Value:
                        value = ''
                    if isinstance(value, Message):
                        value = translate(value,
                                          domain='ftw.table',
                                          context=self.context)
                    row[key] = value
                    try:
                        row['id'] = content.id
                    except AttributeError:
                        pass
                table['rows'].append(row)

            if meta_data is None:
                #create metadata for oldstyle column definition
                meta_data = deepcopy(METADATA)
                for column in self.columns:

                    key = (column.get('sort_index', None) or column['attr']
                           or column['title'] or column['transform'].__name__)

                    field = deepcopy(FIELD)
                    field['name'] = key
                    col = deepcopy(COLUMN)
                    col['dataIndex'] = key
                    if isinstance(column['title'], Message):
                        col['header'] = translate(column['title'],
                                                  column['title'].domain,
                                                  context=self.request)
                    else:
                        col['header'] = column['title']

                    col['id'] = key
                    col['sortable'] = column.get('sortable', True)
                    col['hidden'] = column.get('hidden', False)
                    col['groupable'] = column.get('groupable', True)

                    if not column['title']:
                        if key == 'draggable':
                            col['menuDisabled'] = False
                            col['header'] = '&nbsp;'
                            col['sortable'] = True
                        else:
                            col['menuDisabled'] = True
                        col['width'] = column.get('width', 30)
                        col['hideable'] = False
                        col['resizable'] = False
                        col['fixed'] = True
                    else:
                        if column.get('width', None):
                            col['width'] = column['width']

                    meta_data['fields'].append(field)
                    meta_data['columns'].append(col)

                meta_data['config'] = {}
                # if grouping is enabled add additional column
                if self.grouping_enabled:
                    col = deepcopy(COLUMN)
                    field = deepcopy(FIELD)
                    meta_data['config']['group'] = field['name'] = \
                        col['dataIndex'] = col['header'] = \
                        col['id'] = 'groupBy'
                    col['sortable'] = False
                    col['hideable'] = False
                    meta_data['fields'].append(field)
                    meta_data['columns'].append(col)

                meta_data['config']['gridstate'] = options.get(
                    'gridstate', None)
                meta_data['config']['sort'] = selected[0]
                sort_order = selected[1]
                if sort_order is None:
                    sort_order = 'asc'
                elif sort_order == 'reverse':
                    sort_order = 'desc'
                meta_data['config']['dir'] = sort_order.upper()
                if self.options and 'auto_expand_column' in self.options:
                    aecolumn = self.options['auto_expand_column']
                    meta_data['config']['auto_expand_column'] = aecolumn

            #add static html snippets. Eg batching, buttons, etc
            if 'static' in self.options:
                meta_data['static'] = deepcopy(self.options['static'])

            #add translations for the table
            meta_data['translations'] = {}
            for msgid in msgids:
                meta_data['translations'][msgid] = translate(
                    msgid, domain='ftw.table', context=self.request)
            if meta_data:
                table['metaData'] = meta_data
            jsonstr = json.dumps(table)
            return jsonstr
        else:
            return 'unsupported output format'
Пример #56
0
 def next(self, request):
     message = translate(_('changes_saved', default=u'Changes Saved'),
                         context=self.request)
     continuation = [AjaxMessage(message, 'info', None)]
     ajax_continue(self.request, continuation)
     return False
Пример #57
0
    def get_translated_validation_messages(self):
        context = aq_inner(self.context)
        request = context.REQUEST
        fieldnames = {
            'organisation': translate(_('Company/Organisation')),
            'address': translate(_('Address')),
            'postal_code': translate(_('Postal Code')),
            'city': translate(_('City')),
            'country': translate(_('Country')),
            'firstname': translate(_('Firstname')),
            'lastname': translate(_('Lastname')),
            'sector': translate(_('Sector')),
            'email': translate(_('Email')),
            'telephone': translate(_('Telephone')),
            'privacy': translate(_(u'Privacy')),
        }
        messages = {}

        for field_id in fieldnames:
            fieldname = fieldnames[field_id]
            err_msgs = {
                'required': translate(
                    _(u'error_required',
                      default=u'${name} is required, please correct.',
                      mapping={'name': fieldname}),
                    context=request,
                ),

                'email': translate(
                    _(u"You entered an invalid email address."),
                    context=request,
                ),
            }

            messages[field_id] = err_msgs

        return {'messages': messages}
Пример #58
0
    def __call__(self, form=None, errors={}):
        self.form = form
        self.errors = errors
        request = self.context.REQUEST
        if 'form.submitted' not in request.form:
            return super(
                NationalPartnerForm, self).__call__(self.context, self.request)

        language = self.context.portal_languages.getPreferredLanguage()
        messages = IStatusMessage(request)
        portal = getToolByName(self, 'portal_url').getPortalObject()
        from_address = portal.getProperty('email_from_address', '')

        url = "/%s/get-involved/get-your-certificate/feedback" % language

        organisation = request.get('organisation', '')
        address = request.get('address', '')
        postal_code = request.get('postal_code', '')
        city = request.get('city', '')
        country = request.get('country', '')
        firstname = request.get('firstname', '')
        lastname = request.get('lastname', '')
        sector = request.get('sector', '')
        email = request.get('email', '')
        telephone = request.get('telephone', '')
        checkboxlist = request.get('checkboxlist', [])
        other = request.get('other_activities_text', '')
        privacy = request.get('privacy', False)

        required_fields = {
            "organisation": organisation,
            "address": address,
            "postal_code": postal_code,
            "city": city,
            "country": country,
            "firstname": firstname,
            "lastname": lastname,
            "sector": sector,
            "email": email,
            "telephone": telephone,
            "privacy": privacy,
        }

        error_messages = self.get_translated_validation_messages()["messages"]
        has_errors = False
        errors = {}
        for required_field in required_fields.keys():
            if required_field == "email":
                try:
                    checkEmailAddress(required_fields.get(required_field, ""))
                except EmailAddressInvalid:
                    has_errors = True
                    messages.add(
                        error_messages[required_field]["email"],
                        type=u"error")
                    errors[required_field] = error_messages[required_field]["email"]
            elif required_field == 'privacy':
                if not required_fields.get(required_field, False):
                    has_errors = True
                    messages.add(
                        error_messages[required_field]["required"],
                        type=u"error")
                    errors[required_field] = error_messages[required_field]["required"]
            elif required_fields[required_field].strip() == "":
                has_errors = True
                messages.add(
                    error_messages[required_field]["required"],
                    type=u"error")
                errors[required_field] = error_messages[required_field]["required"]
        if has_errors:
            if 'form.submitted' in request.form:
                del request.form['form.submitted']
            form_path = (
                "%s/@@get-campaign-certificate"
                % "/".join(self.context.getPhysicalPath()))
            return self.context.restrictedTraverse(
                form_path)(form=request.form, errors=errors)

        checkboxes = {}
        for c in checkboxlist:
            args = c.split('_', 1)
            if args[1] == 'other':
                args[1] = other
            checkboxes[int(args[0])] = args[1]

        checkbox_keys = [
            'seminars',
            'competitions',
            'audiovisual',
            'advertising',
            'partnerships',
            'good_neighbour',
            'hazard_spotting',
            'inspections',
            'initiatives',
        ]
        checkbox_options = {}
        for i, key in enumerate(checkbox_keys):
            checkbox_options[key] = checkboxes.get(i, '')

        participant_details = {
            'organisation': organisation,
            'address': address,
            'postal_code': postal_code,
            'city': city,
            'country': country,
            'firstname': firstname,
            'lastname': lastname,
            'sector': sector,
            'email': email,
            'telephone': telephone,
            'other': other,
        }
        participant_details.update(checkbox_options)
        self.store_participant_details(participant_details)

        try:
            logit(" ... calling generatePDF, language: %s" % language)
            logit(" ... calling generatePDF")
            pdf = generatePDF(
                self.context,
                company=organisation,
                language=language,
                firstname=firstname,
                lastname=lastname,
                checkboxes=checkboxes,
                usePDFTK=0
            )

            logit(" ... generatePDF called!")
            send_charter_email(
                self.context,
                pdf=pdf,
                to=email,
                sender="Healthy Workplaces <%s>" % from_address,
                body=translate(email_template, target_language=language,).encode('utf-8'),
                language=language,
            )
        #XXX Too many things could possibly go wrong. So we catch all.
        except Exception, e:
            exception = self.context.plone_utils.exceptionString()
            logit("Exception: " + exception)
            raise
            return request.RESPONSE.redirect(
                url + '?portal_status_message=' + str(e))
Пример #59
0
    def create_mail(self, text='', objs=[], only_links=''):
        """Create the mail and attach the the files.

        For object without a file it include a Link to the Object in to the
        message.
        """
        attachment_parts = []
        msg = MIMEMultipart()
        msg['Date'] = formatdate(localtime=True)

        # iterate over object list (which can include documents and mails),
        # create attachement parts for them and prepare docs_links
        docs_links = '%s:\r\n' % (translate(
                _('label_documents', default=u'Attachments'),
                context=self.request))

        for obj in objs:

            if IMail.providedBy(obj):
                obj_file = obj.message
            else:
                obj_file = obj.file

            if only_links or not obj_file:
                # rewrite the url with current adminunit's public url
                url = '%s/%s' % (
                    get_current_admin_unit().public_url,
                    '/'.join(obj.getPhysicalPath()[2:]))

                docs_links = '%s\r\n - %s (%s)' % (
                    docs_links, obj.title, url)
                continue

            docs_links = '%s\r\n - %s (%s)' % (
                docs_links,
                obj.title,
                translate(
                    _('label_see_attachment', default=u'see attachment'),
                    context=self.request))

            mimetype = obj_file.contentType
            if not mimetype:
                mimetype = 'application/octet-stream'
            maintype, subtype = obj_file.contentType.split('/', 1)
            part = MIMEBase(maintype, subtype)
            part.set_payload(obj_file.data)
            if mimetype != 'message/rfc822':
                Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                            % obj_file.filename)
            attachment_parts.append(part)

        # First, create the text part and attach it to the message ...
        text = '%s\r\n\r\n%s\r\n' % (
            text.encode(CHARSET, 'ignore'),
            docs_links.encode(CHARSET))

        if not isinstance(text, unicode):
            text = text.decode('utf8')
        msg.attach(MIMEText(text, 'plain', CHARSET))

        # ... then attach all the attachment parts
        for part in attachment_parts:
            msg.attach(part)

        return msg
Пример #60
0
def element_importer(parent, identifier, title, data, children, vocabulary,
                     treating_groups_titles):
    """Format an element for import"""
    if parent:
        existing_elements = api.content.find(context=parent,
                                             internal_reference_no=identifier)
    else:
        existing_elements = []

    exist = False
    has_change = False
    element = {}
    existing_element = None
    portal_type = get_portal_type(parent)
    csv_line = data.pop('_ln', 0)
    if len(existing_elements) >= 1:
        existing_element = parent[existing_elements[0].id]
        exist = True
    else:
        element["@type"] = portal_type
        element["internal_reference_no"] = identifier
    # if not exist:
    #     print(u"{}: '{}', '{}'".format(csv_line, identifier, title))

    if not existing_element or existing_element.title != title:
        element["title"] = title
        has_change = True

    key = "treating_groups"
    # we include treating_groups only if defined
    if data.get(key) and (not existing_element
                          or getattr(existing_element, key) != data.get(key)):
        element[key] = data.get(key)
        has_change = True
    if data.get('treating_groups_title'):
        value = treating_groups_titles.get(data.get('treating_groups_title'))
        if value is None:
            sp = api.portal.get().portal_properties.site_properties
            raise Invalid(
                translate(u"Cannot find treating_groups title '${title}'",
                          domain='collective.classification.folder',
                          target_language=sp.getProperty(
                              'default_language', 'fr'),
                          mapping={
                              'title': data.get('treating_groups_title')
                          }).encode('utf8'))
        elif not existing_element or getattr(existing_element, key) != value:
            element[key] = value
            has_change = True

    key = "classification_informations"
    if not existing_element or getattr(existing_element, key) != data.get(key):
        element[key] = data.get(key)
        has_change = True

    key = "classification_categories"
    if not existing_element:
        values = [vocabulary.getTerm(e).title for e in data.get(key)]
        element[key] = values
        has_change = True
    else:
        values = [vocabulary.getTerm(e).title for e in data.get(key)]
        if getattr(existing_element, key) != values:
            element[key] = values
            has_change = True

    key = "archived"
    if not existing_element or getattr(existing_element, key) != data.get(
            key, False):
        element[key] = data.get(key, False)
        has_change = True

    elements = []
    if exist is True and has_change is True:
        element["internal_reference_no"] = identifier

    if portal_type == "ClassificationFolder":
        element = (exist, element)

    if exist is True and has_change is True:
        elements.append(element)
    elif exist is False:
        elements.append(element)
    elif portal_type == "ClassificationFolder":
        elements.append(element)

    if children:
        for child in children:
            args = (
                exist and existing_element or None,
                child["internal_reference_no"],
                child["title"],
                child["data"],
                child.get("_children"),
                vocabulary,
                treating_groups_titles,
            )
            elements.extend(element_importer(*args))
    return elements