コード例 #1
0
 def getSignupMessage(self):
     """ returns signup message for signupsheet_view """
     if self.getSignupStatus(nextstatus=1)=='open':
         msg = utranslate(msgid='sign_up', default='Sign up!', context=self, domain="signupsheet")
     else:
         msg = utranslate(msgid='sign_up_for_waitinglist', default='Signup for waiting list', context=self, domain="signupsheet")        
     return msg
コード例 #2
0
ファイル: __init__.py プロジェクト: doun/Bika-LIMS
    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 = utranslate(_("From ${start_date} to ${end_date}",
                               mapping={"start":from_date, "end":to_date}))
        elif from_date:
            parms = utranslate(_("Before ${start_date}",
                               mapping={"start":from_date}))
        elif to_date:
            parms = utranslate(_("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
コード例 #3
0
 def initialize(self):
     data = self.getContent()
     if 'subject' not in data:
         data['subject'] = utranslate(DOMAIN,
             _(u'Dear ${recip_honorific} ${recip_first} ${recip_last}'),
             context=self.request)
     if 'template' not in data:
         data['template'] = utranslate(DOMAIN, DEFAULT_LETTER_TEMPLATE, context=self.request)
     self.wizard.sync()
コード例 #4
0
 def initialize(self):
     data = self.getContent()
     if 'subject' not in data:
         data['subject'] = utranslate(DOMAIN,
             _(u'Thanks for your participation, ${sender_first}'),
             context=self.request)
     if 'template' not in data:
         data['template'] = utranslate(DOMAIN, DEFAULT_THANKYOU_TEMPLATE, context=self.request)
     if 'thankyou_text' not in data:
         data['thankyou_text'] = utranslate(DOMAIN,
             _(u'Thank you for participating.'),
             context=self.request)
     self.wizard.sync()
コード例 #5
0
ファイル: i18n.py プロジェクト: socialplanning/opencore
def translate(msgid, domain=i18n_domain, mapping=None, context=None, target_language=None, default=None):
    """
    Wrapper around Plone's utranslate method that defaults to the
    our standard domain.  Returns instance of unicode type. 
    """
    kw = dict(mapping=mapping, context=context, target_language=target_language, default=default)

    # if no translation is available in the desired language,
    # and no default is specified, use the english translation
    # as a fallback; better that than "email_to_pending_user"
    if default is None and getattr(msgid, "default", None) is None:
        try:
            translator = getUtility(ITranslationDomain, i18n_domain)
        except ComponentLookupError:
            # in a fresh build, MO files will not yet have been compiled,
            # so it's possible that we won't find an ITranslationDomain
            # (notably in buildbot builds!). there's no reason to *force*
            # the existence of an English PO file so in that case we'll
            # revert to the default behavior for defaults.
            # http://www.coactivate.org/projects/opencore/lists/opencore-dev/archive/2009/06/1245964042046/forum_view#1246051875766
            return utranslate(domain, msgid, **kw)

        default_kw = dict(kw)
        default_kw["target_language"] = "en"

        if isinstance(msgid, zope.i18nmessageid.Message):
            # Messages have a read-only mapping; we can make a copy to stuff
            # our mapping in there.

            # msgid.domain may return None; if it does, TranslationDomain.translate
            # will clobber its own translation domain with None from the msgid object,
            # and then we'll get a component lookup error (luckily we have a test in
            # opencore/utility/email-sender.txt L39 that managed to trip this wire)
            msgid = zope.i18nmessageid.Message(msgid, domain=i18n_domain)

        default = translator.translate(msgid, **default_kw)
        # zope.i18n.translationdomain:TranslationDomain.translate says
        # that MessageID attributes override arguments, so it's safe to
        # just stuff these all in, i think
        kw["default"] = default

        # Products.Five.i18n @L38 clobbers kw['default'] with msgid.default
        # so we need to trick it.
        if isinstance(msgid, zope.i18nmessageid.Message):
            # Messages have a read-only mapping; we can make a copy to stuff
            # our mapping in there.
            msgid = zope.i18nmessageid.Message(msgid, default=default)

    return utranslate(domain, msgid, **kw)
コード例 #6
0
    def apply(self, pfg, initial_finish=True):
        """
        Apply changes to the underlying PloneFormGen form based on the submitted values.
        """
        data = self.getContent()
        existing_ids = pfg.objectIds()
        annotation = IAnnotations(pfg).setdefault(ANNOTATION_KEY, PersistentDict())

        # store the recipient info in an annotation on the form
        annotation['recipients'] = data['recipients']
        
        # create the multiplexing mailer
        if RECIPIENT_MAILER_ID not in existing_ids:
            pfg.invokeFactory(id=RECIPIENT_MAILER_ID, type_name='LetterRecipientMailerAdapter')
            adapters = list(pfg.actionAdapter)
            adapters.remove(RECIPIENT_MAILER_ID)
            pfg.setActionAdapter(adapters)
            mailer = getattr(pfg, RECIPIENT_MAILER_ID)
            mailer.setTitle(utranslate(DOMAIN, _(u'Emails to decision maker(s)'), context=self.request))
        else:
            mailer = getattr(pfg, RECIPIENT_MAILER_ID)
        if mailer.getExecCondition != 'request/form/recip_email|nothing':
            mailer.setExecCondition('request/form/recip_email|nothing')
        if not mailer.getRawRecipientOverride():
            mailer.setRecipientOverride('request/form/recip_email|nothing')
        formgen_tool = getToolByName(pfg, 'formgen_tool')
        if mailer.getRawBody_pt() == formgen_tool.getDefaultMailTemplateBody():
            mailer.setBody_pt(LETTER_MAILTEMPLATE_BODY)
        execCondition = mailer.getRawExecCondition()
        if not execCondition or execCondition in ('request/form/recip_email|nothing', 'python:False'):
            mailer.setExecCondition(data['send_email'] and 'request/form/recip_email|nothing' or 'python:False')
コード例 #7
0
    def listing(self):
        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)

        columns = self.columns
        values = self.manager.get('orders-search').results
        if not values:
            message = _(u'No orders found for your filter.')
            return self.context.utranslate(msgid=message,
                                           default=message,
                                           domain='plonegetpaid')

        formatter = BatchingFormatter(
            self.context,
            self.request,
            values,
            prefix="form",
            batch_size=10,
            visible_column_names=[c.name for c in columns],
            #sort_on = ( ('name', False)
            columns=columns)

        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #8
0
    def apply(self, pfg, initial_finish=True):
        data = self.getContent()
        if THANK_YOU_EMAIL_ID not in pfg.objectIds():
            pfg.invokeFactory(id=THANK_YOU_EMAIL_ID, type_name="FormMailerAdapter")
            mailer = getattr(pfg, THANK_YOU_EMAIL_ID)
            mailer.setTitle(utranslate(DOMAIN, _(u"Thank you email to activist"), context=self.request))
        else:
            mailer = getattr(pfg, THANK_YOU_EMAIL_ID)

        action_adapters = list(pfg.getActionAdapter())
        if data['email'] and mailer.getId() not in action_adapters:
            action_adapters.append(mailer.getId())
        elif not data['email'] and mailer.getId() in action_adapters:
            action_adapters.remove(mailer.getId())
        pfg.setActionAdapter(action_adapters)

        if data.get("from_addr", None):
            mailer.setSenderOverride('string:' + data['from_addr'])
        if mailer.getTo_field() == '#NONE#':
            mailer.setTo_field('email')
        mailer.setMsg_subject(data['subject'])
        annotation = IAnnotations(pfg).setdefault(ANNOTATION_KEY, PersistentDict())
        annotation['thankyou_template'] = data['template']
        # replace default mail template body with our own version, unless its been customized
        formgen_tool = getToolByName(pfg, 'formgen_tool')
        if mailer.getRawBody_pt() == formgen_tool.getDefaultMailTemplateBody():
            mailer.setBody_pt(THANKYOU_MAILTEMPLATE_BODY)
        if not mailer.getRawSubjectOverride():
            mailer.setSubjectOverride('here/@@letter-mailer-renderer/render_subject')
        
        thankyou = getattr(pfg, 'thank-you', None)
        if thankyou is not None:
            thankyou.setThanksPrologue(data['thankyou_text'])
        if data['thankyou_url']:
            pfg.setThanksPageOverride('redirect_to:string:' + data['thankyou_url'])
コード例 #9
0
    def renderCart(self):
        cart = component.getUtility(IShoppingCartUtility).get(self.context)
        if not cart:
            return _(u"N/A")

        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.name,
                                          context=self.request)

        # create an order so that tax/shipping utilities have full order information
        # to determine costs (ie. billing/shipping address ).
        order = self.createTransientOrder()
        formatter = OrderFormatter(
            order,
            self.request,
            cart.values(),
            prefix=self.prefix,
            visible_column_names=[c.name for c in self.columns],
            #sort_on = ( ('name', False)
            columns=self.columns)

        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #10
0
    def __init__(self,
                 context,
                 request,
                 items,
                 visible_column_names=None,
                 batch_start=None,
                 batch_size=None,
                 prefix=None,
                 columns=None):
        """ override method to set some stuff we want on this class
        """
        super(CartFormatter,
              self).__init__(context, request, items, visible_column_names,
                             batch_start, batch_size, prefix, columns)

        totals = self.getTotals()

        self.tax_list = totals.getTaxCost()
        for tax in self.tax_list:
            tax['value'] = '%0.2f' % tax['value']
        self.shipping_price = '%0.2f' % totals.getShippingCost()
        self.subtotal_price = '%0.2f' % totals.getSubTotalPrice()
        self.total_price = '%0.2f' % totals.getTotalPrice()
        self.extra = super(CartFormatter, self).renderExtra()
        self.translate = lambda msg: utranslate(
            domain='plonegetpaid', msgid=msg, context=self.request)
        self.has_items = bool(len(self.context))
        if self.is_recurring():
            firstitem = self.items[0]
            self.interval = firstitem.interval
            self.unit = firstitem.unit
            self.total_occurrences = firstitem.total_occurrences
コード例 #11
0
    def renderCart(self):
        cart = component.getUtility(
            interfaces.IShoppingCartUtility).get(self.context)
        if not cart:
            return _(u"N/A")

        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)

        # create an order so that tax/shipping utilities have full order
        # information to determine costs (ie. billing/shipping address).
        order = self.createTransientOrder()
        formatter = OrderFormatter(
            order,
            self.request,
            cart.values(),
            prefix=self.prefix,
            visible_column_names=[c.name for c in self.columns],
            #sort_on = (('name', False)
            columns=self.columns
        )

        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #12
0
ファイル: cart.py プロジェクト: gitesdewallonie/gites.shop
 def update(self):
     for column in self.columns:
         if column.name == "selection":
             continue
         if hasattr(column, "title"):
             column.title = utranslate(domain="plonegetpaid", msgid=column.name, context=self.request)
     super(ShoppingCartListing, self).update()
コード例 #13
0
    def renderExtra( self ):

        translate = lambda msg: utranslate(domain='plonegetpaid',
                                           msgid=msg,
                                           context=self.request)

        if not len( self.context ):
            return super( CartFormatter, self).renderExtra()
        
        totals = self.getTotals()

        tax_list = totals.getTaxCost()
        shipping_price = totals.getShippingCost()
        subtotal_price = totals.getSubTotalPrice()
        total_price = totals.getTotalPrice()
        
        buffer = [ u'<div class="getpaid-totals"><table class="listing">']
        buffer.append('<tr><th>')
        buffer.append( translate(_(u"SubTotal")) )
        buffer.append( '</th><td style="border-top:1px solid #8CACBB;">%0.2f</td></tr>'%( subtotal_price ) )

#        buffer.append( "<tr><th>" )
#        buffer.append( translate(_(u"Shipping")) )
#        buffer.append( "</th><td>%0.2f</td></tr>"%( shipping_price ) )

        for tax in tax_list:
            buffer.append( "<tr><th>%s</th><td>%0.2f</td></tr>"%( tax['name'], tax['value'] ) )
        buffer.append( "<tr><th>" )
        buffer.append( translate(_(u"Total")) )
        buffer.append( "</th><td>%0.2f</td></tr>"%( total_price ) )
        buffer.append('</table></div>')
        
        return u''.join( buffer) + super( CartFormatter, self).renderExtra()
コード例 #14
0
    def __init__(self, context, request, items, visible_column_names=None,
                 batch_start=None, batch_size=None, prefix=None, columns=None):
        """ override method to set some stuff we want on this class
        """
        super(CartFormatter, self).__init__(context, request, items,
            visible_column_names, batch_start, batch_size,
            prefix, columns)

        totals = self.getTotals()

        self.tax_list = totals.getTaxCost()
        for tax in self.tax_list:
            tax['value'] = '%0.2f' % tax['value']
        self.shipping_price = '%0.2f' % totals.getShippingCost()
        self.subtotal_price = '%0.2f' % totals.getSubTotalPrice()
        self.total_price = '%0.2f' % totals.getTotalPrice()
        self.extra = super(CartFormatter, self).renderExtra()
        self.translate = lambda msg: utranslate(domain='plonegetpaid',
                                           msgid=msg,
                                           context=self.request)
        self.has_items = bool(len(self.context))
        if self.is_recurring():
            firstitem = self.items[0]
            self.interval = firstitem.interval
            self.unit = firstitem.unit
            self.total_occurrences = firstitem.total_occurrences
コード例 #15
0
    def __init__( self, *args, **kw):
        super( ShoppingCartListing, self ).__init__( *args, **kw )

        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)
コード例 #16
0
    def __init__( self, *args, **kw):
        super( ShoppingCartListing, self ).__init__( *args, **kw )

        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)
コード例 #17
0
 def update(self):
     for column in self.columns:
         if column.name == 'selection':
             continue
         if hasattr(column, 'title'):
             column.title = utranslate(domain='plonegetpaid',
                                       msgid=column.name,
                                       context=self.request)
     super(ShoppingCartListing, self).update()
コード例 #18
0
 def _getFieldMap(self, sfobj_type):
     """
     Returns the field mapping that gets set with setFieldMap.
     """
     
     if sfobj_type == u'Contact':
         field_source = SF_CONTACT_FIELDMAPPING
     else:
         field_source = SF_LEAD_FIELDMAPPING
         
     return tuple([dict(field_path=p, form_field=utranslate(DOMAIN, _(l),
         context=self.request), sf_field=s) for (p, s, l) in field_source])
コード例 #19
0
ファイル: __init__.py プロジェクト: Adam-Brown/Bika-LIMS
    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 = utranslate(_("From ${start_date} to ${end_date}", mapping={"start": from_date, "end": to_date}))
        elif from_date:
            parms = utranslate(_("Before ${start_date}", mapping={"start": from_date}))
        elif to_date:
            parms = utranslate(_("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
コード例 #20
0
ファイル: viewlets.py プロジェクト: OpenBfS/dokpool-plone
    def portal_tabs(self):
        tabs = []

        # fetch actions-based tabs?
        if show_actions_tabs:
            tabs.extend(self._actions_tabs())

        # fetch content structure-based tabs?
        if show_content_tabs:
            # put content-based actions before content structure-based ones?
            if content_before_actions_tabs:
                tabs = self._content_tabs() + tabs
            else:
                tabs.extend(self._content_tabs())
        
        
        for tab in tabs:
            if tab['id'].find('config') != -1:
                tab['item_class'] = "config"
            elif tab['id'] == 'content':
                tab['item_class'] = "hide"

        apds = getApplicationDocPoolsForCurrentUser(self.context)
        if apds:
            apds.extend(tabs)
            tabs = apds

        
        if not self.context.isArchive():
            ffu = getFoldersForCurrentUser(self.context)
            if ffu:
                for f in ffu:
                    if not f.has_key('item_class'):
                        f['item_class'] = "personal"
                tabs.append(
                    {'id': 'content',
                     'Title': utranslate("docpool.base", "Content Area", context=self.context),
                     'Description': '',
                     'getURL': '',
                     'show_children': True,
                     'children': ffu,
                     'currentItem': False,
                     'item_class': 'contentarea',
                     'currentParent': self.context.isPersonal(),
                     'normalized_review_state': 'visible'}
                            )
        return tabs
コード例 #21
0
    def listing( self ):
        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)

        columns = self.columns
        formatter = table.StandaloneFullFormatter( self.context,
                                                   self.request,
                                                   self.line_items,
                                                   prefix=self.prefix,
                                                   visible_column_names = [c.name for c in columns],
                                                   #sort_on = ( ('name', False)
                                                   columns = columns )
        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #22
0
    def __call__(self, context):
        gsm = getGlobalSiteManager()
        interfaces = gsm.getUtilitiesFor(ITaskMarkerInterface)
        items = []

        for interface_name, marker_interface in interfaces:
            items.append(
                SimpleTerm(
                    interface_name, marker_interface.__doc__,
                    utranslate(msgid=marker_interface.__doc__,
                               domain='imio.schedule',
                               context=context,
                               default=marker_interface.__doc__)))

        # sort elements by title
        items.sort(lambda a, b: cmp(a.title, b.title))

        return SimpleVocabulary(items)
コード例 #23
0
    def listing(self):
        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)

        columns = self.columns
        formatter = table.StandaloneFullFormatter(
            self.context,
            self.request,
            self.line_items,
            prefix=self.prefix,
            visible_column_names=[c.name for c in columns],
            #sort_on = ( ('name', False)
            columns=columns)
        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #24
0
ファイル: vocabulary.py プロジェクト: IMIO/imio.schedule
    def __call__(self, context):
        gsm = getGlobalSiteManager()
        interfaces = gsm.getUtilitiesFor(ITaskMarkerInterface)
        items = []

        for interface_name, marker_interface in interfaces:
            items.append(
                SimpleTerm(
                    interface_name,
                    marker_interface.__doc__,
                    utranslate(
                        msgid=marker_interface.__doc__,
                        domain='imio.schedule',
                        context=context,
                        default=marker_interface.__doc__
                    )
                )
            )

        #sort elements by title
        items.sort(lambda a, b: cmp(a.title, b.title))

        return SimpleVocabulary(items)
コード例 #25
0
    def renderCart(self):
        cart = getCart(self.context)
        if not cart:
            return _(u"N/A")

        for column in self.columns:
            if hasattr(column, "title"):
                column.title = utranslate(domain="plonegetpaid", msgid=column.title, context=self.request)

        # create an order so that tax/shipping utilities have full order
        # information to determine costs (ie. billing/shipping address ).
        order = self.createTransientOrder()
        formatter = OrderFormatter(
            order,
            self.request,
            cart.values(),
            prefix=self.prefix,
            visible_column_names=[c.name for c in self.columns],
            columns=self.columns,
        )

        formatter.cssClasses["table"] = "listing"
        return formatter()
コード例 #26
0
    def listing( self ):
        for column in self.columns:
            if hasattr(column, 'title'):
                column.title = utranslate(domain='plonegetpaid',
                                          msgid=column.title,
                                          context=self.request)

        columns = self.columns
        values = self.manager.get('orders-search').results
        if not values:
            message = _(u'No orders found for your filter.')
            return self.context.utranslate(msgid=message, default=message, domain='plonegetpaid')

        formatter = BatchingFormatter( self.context,
                                      self.request,
                                      values,
                                      prefix="form",
                                      batch_size=10,
                                      visible_column_names = [c.name for c in columns],
                                      #sort_on = ( ('name', False)
                                      columns = columns )

        formatter.cssClasses['table'] = 'listing'
        return formatter()
コード例 #27
0
ファイル: content.py プロジェクト: kamon/collective.newsroom
    def _createSubObjects(self):
        """ """

        if 'press-releases' not in self.objectIds():
            self.invokeFactory("Folder", 'press-releases')
            obj = self['press-releases']

            # FIXME on the way utranslate() is used...
            obj.setTitle(utranslate('newsroom', 'Press Releases', context=self))
            obj.setDescription(utranslate('pressroom', 'Our press releases', context=self))
            
            addCollectionAsListingPage(obj, obj.Title(), ['PressRelease'])
            _setup_constrains(obj, ['PressRelease'])

            _publish(obj)
            obj.reindexObject()

        if 'press-clips' not in self.objectIds():
            self.invokeFactory("Folder", 'press-clips')
            obj = self['press-clips']

            # FIXME on the way utranslate() is used...
            obj.setTitle(utranslate('newsroom', 'Press Clips', context=self))
            obj.setDescription(utranslate('pressroom', 'Our press clips', context=self))

            addCollectionAsListingPage(obj, obj.Title(), ['PressClip'])
            _setup_constrains(obj, ['PressClip'])

            _publish(obj)
            obj.reindexObject()

        if 'press-contacts' not in self.objectIds():
            self.invokeFactory("Folder", 'press-contacts')
            obj = self['press-contacts']

            # FIXME on the way utranslate() is used...
            obj.setTitle(utranslate('newsroom', 'Press Contacts', context=self))
            obj.setDescription(utranslate('pressroom', 'Our press contacts', context=self))

            addCollectionAsListingPage(obj, obj.Title(), ['PressContact'])
            _setup_constrains(obj, ['PressContact'])

            _publish(obj)
            obj.reindexObject()


#         if 'press-contacts' not in self.objectIds():
# 
#             # The Press Contacts directory settings...
#             # FIXME: Look for the conventional position types...
#             position_types = [{'name': u'Journalist', 'token': u'journalist'},
#                               {'name': u'Communication Officer', 'token': u'communication_officer'},
#                               {'name': u'Principal', 'token': u'principal'},
#                              ]
# 
#             # FIXME: Look for the conventional organization types...
#             organization_types = [{'name': u'Media House', 'token': u'media_house'},
#                                   {'name': u'PR Agency', 'token': u'pr_agency'},
#                                   {'name': u'Internal Marketing Department', 'token': u'internal_marketing_department'},
#                                  ]
# 
#             # FIXME: Do we need this ? Make it optional or find a meaningful org level ?
#             organization_levels = [{'name': u'Any', 'token': u'any'},
#                                   ]
# 
#             params = {'title': u"Press Contacts",
#               'position_types': position_types,
#               'organization_types': organization_types,
#               'organization_levels': organization_levels,
#               }
#         
#             self.invokeFactory('directory', 'press-contacts', **params)
#             directory = self['press-contacts']
# 
#             _publish(directory)

        transaction.savepoint()
コード例 #28
0
ファイル: dpevent.py プロジェクト: OpenBfS/dokpool-plone
 def purgeConfirmMsg(self):
     """
     Do you really want to remove all documents from this scenario?
     """
     return utranslate("docpool.event", "purge_confirm_msg", context=self)
コード例 #29
0
ファイル: dpevent.py プロジェクト: OpenBfS/dokpool-plone
 def archiveConfirmMsg(self):
     """
     Do you really want to archive this scenario?
     """
     return utranslate("docpool.event", "archive_confirm_msg", context=self)
コード例 #30
0
 def _get_fields(self):
     data = self.getContent()
     if 'fields' in data:
         return data['fields']
     
     # initialize fields
     fields = {
         'body': {
             'field_type': 'text',
             'title': utranslate(DOMAIN, _(u'Letter Body'), context=self.request),
             'description': utranslate(DOMAIN, _(u'A salutation and signature will be added automatically.'), context=self.request),
             'default': utranslate(DOMAIN, _(u'Enter the body of your letter here.  A salutation and signature will be added automatically.'), context=self.request),
             'required': True,
             'order': 0,
             },
         'sincerely': {
             'field_type': 'label',
             'title': utranslate(DOMAIN, _(u'Sincerely,'), context=self.request),
             'description': u'',
             'required': False,
             'order': 1,
             },
         'first': {
             'title': utranslate(DOMAIN, _(u'First Name'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': True,
             'order': 2,
             },
         'last': {
             'title': utranslate(DOMAIN, _(u'Last Name'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': True,
             'order': 3,
             },
         'email': {
             'title': utranslate(DOMAIN, _(u'E-mail Address'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': True,
             'validator': 'isEmail',
             'order': 4,
             },
         'street': {
             'title': utranslate(DOMAIN, _(u'Street Address'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': False,
             'order': 5,
             },
         'city': {
             'title': utranslate(DOMAIN, _(u'City'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': False,
             'order': 6,
             },
         'state': {
             'field_type': 'selection',
             'title': utranslate(DOMAIN, _(u'State'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': False,
             'vocab': STATES,
             'order': 7,
             },
         'zip': {
             'title': utranslate(DOMAIN, _(u'Postal Code'), context=self.request),
             'description': utranslate(DOMAIN, _(u''), context=self.request),
             'required': False,
             'validator': 'isZipCode',
             'order': 8,
             'size': 10,
             },
         }
     if HAS_CAPTCHA:
         fields['captcha'] = {
             'field_type': 'captcha',
             'title': utranslate(DOMAIN, _(u'Please enter this text.'), context=self.request),
             'description': utranslate(DOMAIN, _(u'This helps prevent spammers from using this form.'), context=self.request),
             'required': True,
             'order': 9,
             }
     if 'intro' in self.wizard.session.keys() and self.wizard.session['intro']['megaphone_type'] == 'petition':
         del fields['sincerely']
         fields['body']['title'] = utranslate(DOMAIN, _(u'Additional Comment'), context=self.request)
         fields['body']['description'] = u''
         fields['body']['default'] = u''
     return self.getContent().setdefault('fields', fields)
コード例 #31
0
    def _createSubFolders(self, use_large_folders=True):
        """We're splitting this out and giving the optional arg just
        to facilitate testing."""

        folder_type = "Folder"
        if HAS_PLONE40:
            use_large_folders = False
        elif use_large_folders:
            folder_type = "Large Plone Folder"
            # enable the addition of LPFs momentarily
            large_folders_addable = True
            portal_types = getToolByName(self, "portal_types")
            lpf = getattr(portal_types, folder_type)
            if not lpf.global_allow:
                large_folders_addable = False
                lpf.manage_changeProperties(global_allow = True)

        if 'press-releases' not in self.objectIds():
            self.invokeFactory(folder_type, 'press-releases')
            obj = self['press-releases']
            obj.setConstrainTypesMode(1)
            obj.setImmediatelyAddableTypes(["PressRelease",])
            obj.setLocallyAllowedTypes(["Topic","PressRelease",])

            obj.setTitle(utranslate('pressroom', 'Press Releases', context=self))
            obj.setDescription(utranslate('pressroom', 'These are our press releases', context=self))
            obj.reindexObject()

            # create Smart Folder to be this folder's default page
            obj.invokeFactory('Topic','all-press-releases')
            obj.setDefaultPage('all-press-releases')

            smart_obj = obj['all-press-releases']
            smart_obj.setTitle(utranslate('pressroom', u'Press Releases', context=self))
            smart_obj.setDescription(utranslate('pressroom', u'These are our press releases', context=self))
            smart_obj.setLayout('folder_listing_pressroom')
            smart_obj.reindexObject()

            state_crit = smart_obj.addCriterion('review_state',
                                                'ATSimpleStringCriterion')
            state_crit.setValue('published')

            type_crit = smart_obj.addCriterion('Type',
                                               'ATPortalTypeCriterion')
            type_crit.setValue('Press Release')

            path_crit = smart_obj.addCriterion('path',
                                               'ATPathCriterion')
            path_crit.setValue(self.UID())
            path_crit.setRecurse(True)

            smart_obj.addCriterion('getReleaseDate','ATSortCriterion')
            smart_obj.getSortCriterion().setReversed(True)

            # Update Smart Folder settings  
            smart_folder_tool = getToolByName(self, 'portal_atct') 
            if 'getReleaseDate' not in smart_folder_tool.getIndexes(enabledOnly=True):     
                smart_folder_tool.addIndex("getReleaseDate", "Release Date", "The date of the press release", enabled=True) 
            elif 'getReleaseDate' not in smart_folder_tool.getIndexes():
                # index exists, but is disabled 
                smart_folder_tool.updateIndex('getReleaseDate', enabled=True)
            if 'getReleaseDate' not in smart_folder_tool.getAllMetadata(enabledOnly=True):
                smart_folder_tool.addMetadata("getReleaseDate", "Release Date", "The date of the press release", enabled=True)
            elif 'getReleaseDate' not in smart_folder_tool.getAllMetadata():     
                # metadata exist, but are disabled     
                smart_folder_tool.updateMetadata('getReleaseDate', enabled=True) 

        if 'press-clips' not in self.objectIds():
            self.invokeFactory(folder_type, 'press-clips')
            obj = self['press-clips']
            obj.setConstrainTypesMode(1)
            obj.setImmediatelyAddableTypes(["PressClip",])
            obj.setLocallyAllowedTypes(["Topic","PressClip",])

            obj.setTitle(utranslate('pressroom', u'Press Clips', context=self))
            obj.setDescription(utranslate('pressroom', u'See us in the news!', context=self))
            obj.reindexObject()

            # create Smart Folder to be this folder's default page
            obj.invokeFactory('Topic','all-press-clips')
            obj.setDefaultPage('all-press-clips')

            smart_obj = obj['all-press-clips']
            smart_obj.setTitle(utranslate('pressroom', u'Press Clips', context=self))
            smart_obj.setDescription(utranslate('pressroom', u'See us in the news!', context=self))
            smart_obj.setLayout('folder_listing_pressroom')
            smart_obj.reindexObject()

            state_crit = smart_obj.addCriterion('review_state',
                                                'ATSimpleStringCriterion')
            state_crit.setValue('published')
            type_crit = smart_obj.addCriterion('Type',
                                               'ATPortalTypeCriterion')
            type_crit.setValue('Press Clip')
            smart_obj.addCriterion('getStorydate','ATSortCriterion')
            path_crit = smart_obj.addCriterion('path',
                                               'ATPathCriterion')
            path_crit.setValue(self.UID())
            path_crit.setRecurse(True)
            smart_obj.getSortCriterion().setReversed(True)

            # Update Smart Folder settings  
            if 'getStorydate' not in smart_folder_tool.getIndexes(enabledOnly=True):     
                smart_folder_tool.addIndex("getStorydate", "Story Date", "The date of the press clip", enabled=True) 
            elif 'getStorydate' not in smart_folder_tool.getIndexes():
                # index exists, but is disabled 
                smart_folder_tool.updateIndex('getStorydate', enabled=True)
            if 'getStorydate' not in smart_folder_tool.getAllMetadata(enabledOnly=True):
                smart_folder_tool.addMetadata("getStorydate", "Release Date", "The date of the press clip", enabled=True)
            elif 'getStorydate' not in smart_folder_tool.getAllMetadata(): 
                # metadata exist, but are disabled     
                smart_folder_tool.updateMetadata('getStorydate', enabled=True)     



        if 'press-contacts' not in self.objectIds():
            self.invokeFactory("Folder", 'press-contacts')
            obj = self['press-contacts']
            obj.setConstrainTypesMode(1)
            obj.setImmediatelyAddableTypes(["PressContact",])
            obj.setLocallyAllowedTypes(["Topic","PressContact",])
            obj.setTitle(utranslate('pressroom', u'Press Contacts', context=self))
            obj.setDescription(utranslate('pressroom', u'Contact these people for more information', context=self))
            obj.reindexObject()

            # create Smart Folder to be this folder's default page
            obj.invokeFactory('Topic','press-contacts')
            obj.setDefaultPage('press-contacts')

            smart_obj = obj['press-contacts']
            smart_obj.setTitle(utranslate('pressroom', u'Press Contacts', context=self))
            smart_obj.setDescription(utranslate('pressroom', u'Contact these people for more information', context=self))
            smart_obj.setLayout('folder_listing_pressroom')
            smart_obj.reindexObject()

            # set the criteria published, type, public, and ordering
            state_crit = smart_obj.addCriterion('review_state',
                                                'ATSimpleStringCriterion')
            state_crit.setValue('published')
            type_crit = smart_obj.addCriterion('Type',
                                               'ATPortalTypeCriterion')
            type_crit.setValue('Press Contact')
            path_crit = smart_obj.addCriterion('path',
                                               'ATPathCriterion')
            path_crit.setValue(self.UID())
            path_crit.setRecurse(True)
            smart_obj.addCriterion('getObjPositionInParent','ATSortCriterion')

        if use_large_folders and not large_folders_addable:
            lpf.manage_changeProperties(global_allow = False)

        transaction.savepoint()
コード例 #32
0
ファイル: utils.py プロジェクト: OpenBfS/dokpool-plone
def getApplicationDocPoolsForCurrentUser(self, user=None):
    """
    Determine all accessible DocPools an their applications, that the user has access to.
    """
    if not user:
        if api.user.is_anonymous():
            return None
        user = api.user.get_current()
    
    portal = getSite()

    dps = [ dp.getObject() for dp in queryForObjects(self, path = "/".join(portal.getPhysicalPath()), portal_type='DocumentPool') ]

    #dps = _folderTree(self, "%s" % ("/".join(portal.getPhysicalPath())), {'portal_type': ('PloneSite', 'DocumentPool')})['children']
    request = self.REQUEST
    dp_app_state = getMultiAdapter((self, request), name=u'dp_app_state')
    active_apps = dp_app_state.appsActivatedByCurrentUser()
    current_app = None
    if len(active_apps) > 0:
        current_app = appName(active_apps[0])
    current_dp = None
    if shasattr(self, "myDocumentPool", True):
        current_dp = self.myDocumentPool()
    root_title = current_dp is None and utranslate("docpool.menu", "Docpools", context=self) or "%s: %s" % (current_dp.Title(), current_app)
    apps_root = [ 
                    {'id': 'apps',
                     'Title': root_title,
                     'Description': '',
                     'getURL': '',
                     'show_children': True,
                     'children': None,
                     'currentItem': False,
                     'currentParent': True,
                     'item_class': 'applications',
                     'normalized_review_state': 'visible'}
            
             ]
    pools = []
    for dp in dps:
        apps = [] # determine locally available apps
        dp_app_state = getMultiAdapter((dp, request), name=u'dp_app_state') # need to get fresh adapter for each pool
        app_names = dp_app_state.appsAvailableToCurrentUser()
        app_names.insert(0, BASE_APP)
        for app_name in app_names:
            if app_name == 'base':
                if self.isAdmin():
                    app_title = utranslate("docpool.menu", "Docpool Base", context=self)
                else:
                    continue
            else:
                app_title = appName(app_name)

            if dp.getId() in self.absolute_url():
               pools.append({'id': dp.getId() + "-" + app_name,
                        'Title': dp.Title() + ": " + app_title,
                        'Description': '',
                        'getURL': "%s/setActiveApp?app=%s" % (self.absolute_url(), app_name),
                        'show_children': False,
                        'children': [],
                        'currentItem': False,
                        'currentParent': False,
                        'item_class': app_title,
                        'normalized_review_state': 'visible'})
            else:
               pools.append({'id': dp.getId() + "-" + app_name,
                        'Title': dp.Title() + ": " + app_title,
                        'Description': '',
                        'getURL': "%s/setActiveApp?app=%s" % (dp.absolute_url(), app_name),
                        'show_children': False,
                        'children': [],
                        'currentItem': False,
                        'currentParent': False,
                        'item_class': app_title,
                        'normalized_review_state': 'visible'})


    apps_root[0]['children'] = pools
    return apps_root
コード例 #33
0
    def apply(self, pfg, initial_finish=True):
        data = self.getContent()
        existing_ids = pfg.objectIds()
        sfobj_type = data['sfobj_type']
        obj_adapter_title = u'Salesforce.com %s Adapter' % sfobj_type
        lead_source = data['lead_source'] or u'Web'
        
        if salesforce_is_configured() and data['save_lead']:
            if ORG_FIELD_ID not in existing_ids:
                pfg.invokeFactory(id=ORG_FIELD_ID, type_name='FormStringField')
                f = getattr(pfg, ORG_FIELD_ID)
                f.setTitle(utranslate(DOMAIN, _(u'Organization'), context=self.request))
                f.setDescription(utranslate(DOMAIN, _(u"This field is used internally to provide the required 'Company' value to Salesforce.com"), context=self.request))
                f.setServerSide(True)
                if not f.getFgDefault():
                    f.setFgDefault(utranslate(DOMAIN, _(u'[not provided]'), context=self.request))
                f.reindexObject()

            if SF_LEAD_ID not in existing_ids:
                pfg.invokeFactory(id=SF_LEAD_ID, type_name='SalesforcePFGAdapter')
                a = getattr(pfg, SF_LEAD_ID)
                new_adapter = True
            else:
                a = getattr(pfg, SF_LEAD_ID)
                new_adapter = False
            if new_adapter or not a.getSFObjectType() == sfobj_type:
                a.setTitle(utranslate(DOMAIN, _(obj_adapter_title), context=self.request))
                a.setSFObjectType(sfobj_type)
                a.setFieldMap(self._getFieldMap(sfobj_type))
                a.reindexObject()
            if hasattr(a, 'setPresetValueMap'): # BBB for salesforcepfgadapter < 1.6b2
                preset_map = list(a.getPresetValueMap())
                found = False
                for entry in preset_map:
                    if entry['sf_field'] == 'LeadSource':
                        entry['value'] = lead_source
                        found = True
                if not found:
                    preset_map.append({'value': lead_source, 'sf_field': 'LeadSource'})
                a.setPresetValueMap(tuple(preset_map))

            if data['campaign_id']:
                if CAMPAIGN_ID_FIELD_ID not in existing_ids:
                    pfg.invokeFactory(id=CAMPAIGN_ID_FIELD_ID, type_name='FormStringField')
                    f = getattr(pfg, CAMPAIGN_ID_FIELD_ID)
                    f.setTitle(utranslate(DOMAIN, _(u'Salesforce.com Campaign ID'), context=self.request))
                    f.setDescription(utranslate(DOMAIN, _(u'This field is used to supply the ID of a Salesforce.com Campaign to the CampaignMember adapter.'), context=self.request))
                    f.setServerSide(True)
                    f.reindexObject()
                else:
                    f = getattr(pfg, CAMPAIGN_ID_FIELD_ID)
                f.setFgDefault(data['campaign_id'])

                if SF_CAMPAIGNMEMBER_ID not in existing_ids:
                    pfg.invokeFactory(id=SF_CAMPAIGNMEMBER_ID, type_name='SalesforcePFGAdapter')
                    a = getattr(pfg, SF_CAMPAIGNMEMBER_ID)
                    a.setTitle(utranslate(DOMAIN, _(u'Salesforce.com CampaignMember Adapter'), context=self.request))
                    a.setSFObjectType('CampaignMember')
                    a.setFieldMap((
                        dict(field_path=CAMPAIGN_ID_FIELD_ID, form_field=utranslate(DOMAIN, _(u'Campaign ID'), context=self.request), sf_field='CampaignId'),
                        ))
                    a.reindexObject()
                else:
                    a = getattr(pfg, SF_CAMPAIGNMEMBER_ID)
                a.setDependencyMap((
                    dict(adapter_id=SF_LEAD_ID, adapter_name=utranslate(DOMAIN, _(obj_adapter_title), context=self.request), sf_field='%sId' % sfobj_type),
                    ))
            else:
                objs_to_delete = []
                if SF_CAMPAIGNMEMBER_ID in existing_ids:
                    objs_to_delete.append(SF_CAMPAIGNMEMBER_ID)
                if CAMPAIGN_ID_FIELD_ID in existing_ids:
                    objs_to_delete.append(CAMPAIGN_ID_FIELD_ID)
                pfg.manage_delObjects(objs_to_delete)
            
            if data['campaign_status']:
                a = getattr(pfg, SF_CAMPAIGNMEMBER_ID, None)
                if a is not None:
                    preset_map = list(a.getPresetValueMap())
                    found = False
                    for entry in preset_map:
                        if entry['sf_field'] == 'Status':
                            entry['value'] = data['campaign_status']
                            found = True
                    if not found:
                        preset_map.append({'value': data['campaign_status'], 'sf_field': 'Status'})
                    a.setPresetValueMap(tuple(preset_map))
            else:
                a = getattr(pfg, SF_CAMPAIGNMEMBER_ID, None)
                if a is not None:
                    preset_map = a.getPresetValueMap()
                    preset_map = [entry for entry in preset_map if entry['sf_field'] != 'Status']
                    a.setPresetValueMap(tuple(preset_map))
        else:
            objs_to_delete = []
            if SF_LEAD_ID in existing_ids:
                objs_to_delete.append(SF_LEAD_ID)
            if SF_CAMPAIGNMEMBER_ID in existing_ids:
                objs_to_delete.append(SF_CAMPAIGNMEMBER_ID)
            if CAMPAIGN_ID_FIELD_ID in existing_ids:
                objs_to_delete.append(CAMPAIGN_ID_FIELD_ID)
            if objs_to_delete:
                pfg.manage_delObjects(objs_to_delete)
                adapters = list(pfg.actionAdapter)
                for id in objs_to_delete:
                    if id in adapters:
                        adapters.remove(id)
                pfg.actionAdapter = adapters
コード例 #34
0
_ = zope.i18nmessageid.MessageFactory('opencore')


portal = context.portal_url.getPortalObject()
request = context.REQUEST

# if cookie crumbler did a traverse instead of a redirect,
# this would be the way to get the value of came_from
#url = portal.getCurrentUrl()
#context.REQUEST.set('came_from', url)

referer = request.environ.get('HTTP_REFERER')

if context.portal_membership.isAnonymousUser():
    msg = _(u'psm_please_sign_in', u'Please sign in to continue.')
    msg = utranslate('opencore', msg, context=context)
    plone_utils = getToolByName(portal, 'plone_utils')
    plone_utils.addPortalMessage(msg)
    if referer is not None:
        request.form['referer'] = referer
    return portal.restrictedTraverse(login)()
else:
    # We're already logged in.
    if request.form.get('came_from'):
        referer = referer or ''
        if request.form['came_from'].split('?')[0] == referer.split('?')[0]:
            # AFAICT, the HTTP referer and the came_from value are equal when
            # Flunc (and possibly other clients) update the referer on
            # every redirect, which causes an infinite redirect loop
            # in our login code.  Break the loop by redirecting
            # somewhere innocuous. Firefox doesn't seem to have this
コード例 #35
0
    def finish(self):
        data = self.session
        if IAdding.providedBy(self.context):
            # creating a new letter
            container = self.context.context
            id = container.generateUniqueId("form-folder")
            
            # this is based on the createObject.py script from plone_scripts
            container.invokeFactory(id=id, type_name='FormFolder')
            obj=getattr(container, id, None)
            
            obj.portal_type = 'Megaphone Action'
            obj.setTitle(data['general']['title'])

            # enable preview if the type is letter
            if data.get('intro', {}).get('megaphone_type', 'letter') == 'letter':
                submit_label = _(u'Preview')
            else:
                submit_label = _(u'Send')
            obj.setSubmitLabel(utranslate(DOMAIN, submit_label, context=self.request))
            
            # delete the default form fields that come w/ PFG
            existing_ids = obj.objectIds()
            deleters = ("mailer", "replyto", "topic", "comments")
            deleters = [d for d in deleters if d in existing_ids]
            obj.manage_delObjects(deleters)
            obj.setActionAdapter(())
            if obj._at_rename_after_creation:
                obj._renameAfterCreation()
            alsoProvides(obj, IMegaphone)
            
            if not obj.getRawAfterValidationOverride():
                obj.setAfterValidationOverride('here/@@recipient_multiplexer')
            
            obj['thank-you'].setShowAll(0)
            
            self.request.response.redirect("%s/@@summary?new=1" % (obj.absolute_url()))
            self.applySteps(obj, initial_finish=True)

        else:
            # existing letter
            obj = self.context
            self.request.response.redirect("%s/@@summary" % (obj.absolute_url()))
            self.applySteps(obj, initial_finish=False)

        # make sure the saved data adapter is configured properly
        existing_ids = obj.objectIds()
        if SAVEDATA_ID not in existing_ids:
            obj.invokeFactory(id=SAVEDATA_ID, type_name="FormSaveDataAdapter")
            sda = getattr(obj, SAVEDATA_ID)
            alsoProvides(sda, IMultiplexedActionAdapter)
            sda.setTitle(utranslate(DOMAIN, _(u'Saved Signatures'), context=self.request))
        sda = getattr(obj, SAVEDATA_ID)
        adapters = list(obj.actionAdapter)
        if SAVEDATA_ID in adapters:
            adapters.remove(SAVEDATA_ID)
            obj.setActionAdapter(adapters)
        execCondition = sda.getRawExecCondition()
        if not execCondition or execCondition in ('python:True', 'python:False'):
            sda.setExecCondition('python:True')

        if RENDERED_LETTER_ID not in existing_ids:
            obj.invokeFactory(id=RENDERED_LETTER_ID, type_name='FormStringField')
            f = getattr(obj, RENDERED_LETTER_ID)
            f.setServerSide(True)
            f.setTitle(utranslate(DOMAIN, _(u'Rendered Letter'), context=self.request))
            f.setDescription(utranslate(DOMAIN, _(u'This hidden field is used to provide the rendered letter to the mailer and save data adapters.'), context=self.request))

        obj.reindexObject()
        
        if IAdding.providedBy(self.context):
            notify(ObjectInitializedEvent(obj))
        else:
            notify(ObjectEditedEvent(obj))