示例#1
0
    def toCalendarLocalizedTime(self, time):
        """Convert a date in the calendar date format"""
        time = DateTime(time.strftime("%Y-%m-%d"))

        mapping = {}
        formatstring = translate('date_format_long',
                                 'monet.calendar.extensions',
                                 mapping,
                                 self.request,
                                 default="${A} ${B} ${d} ${Y}")

        # get the format elements used in the formatstring
        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])

        # translate the time string
        return translate('date_format_long',
                         'monet.calendar.extensions',
                         mapping,
                         self.request,
                         default="${A} ${B} ${d} ${Y}")
    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)
示例#3
0
    def publication_date(self, format=None):
        """Return the periodical publication date localized and in the format
        specified. For more information on format codes see:
        http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
        """
        periodical = self.periodical()
        if periodical.publication_date:
            day = periodical.publication_date.weekday()
            month = periodical.publication_date.month

            # let's map and translate the directives we care about
            # an example of what we get for Friday, April 26, 2013:
            # {'%a': 'Fri', '%A': 'Friday', '%b': 'Apr', '%A': 'April'}
            codes = {
                '%a': self._translate(weekdayname_msgid_abbr(day)),
                '%A': self._translate(weekdayname_msgid(day)),
                '%b': self._translate(monthname_msgid_abbr(month)),
                '%B': self._translate(monthname_msgid(month)),
            }

            # replace occurrences of directives with our translated strings
            prog = re.compile('|'.join(codes.keys()))
            result = prog.sub(lambda m: codes[m.group(0)], format)
            # process the remaining format codes normally
            return periodical.publication_date.strftime(result)
def zLocalizedTime(request, time, long_format=False):
    """Convert time to localized time
    """
    month_msgid = monthname_msgid(time.strftime('%m'))
    month = translate(month_msgid, domain='plonelocales',
                      context=request)

    return month.encode('utf-8')
示例#5
0
def zLocalizedTime(request, time, long_format=False):
    """Convert time to localized time
    """
    month_msgid = monthname_msgid(time.strftime("%m"))
    month = translate(month_msgid, domain='plonelocales',
                      context=request)

    return u"%s %s" % (month, time.strftime('%Y'))
示例#6
0
def zLocalizedTime(request, time, long_format=False):
    """Convert time to localized time
    """
    month_msgid = monthname_msgid(time.strftime("%m"))
    month = translate(month_msgid, domain='plonelocales',
                      context=request)

    return u"%s" % (month)
示例#7
0
 def hr_date(self):
     date = self.json_data.get("date", "").split("-")
     if not date:
         return ""
     try:
         date[1] = api.portal.translate(monthname_msgid(date[1]),
                                        domain="plonelocales")
     except Exception:
         logger.error("Not a valid date %r", date)
     return " ".join(reversed(date))
示例#8
0
    def update(self):
        super(HeaderTimeViewlet, self).update()

        date = DateTime()
        self.day = date.day()
        self.month = _pl(monthname_msgid(int(date.strftime('%m'))),
            default=safe_unicode(date.Month()))
        self.dayname = _pl(weekdayname_msgid(int(date.strftime('%w'))),
            default=safe_unicode(date.DayOfWeek()))
        self.datetime = self.toLocalizedTime(date, long_format=True)
    def toCalendarLocalizedTime(self, time):
        """Convert a date in the calendar date format"""
        time = DateTime(time.strftime("%Y-%m-%d"))

        mapping = {}
        formatstring = translate('date_format_long', 'monet.calendar.extensions', mapping,
                                 self.request, default="${A} ${B} ${d} ${Y}")
        
        # get the format elements used in the formatstring
        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])
    
        # translate the time string
        return translate('date_format_long', 'monet.calendar.extensions', mapping,
                         self.request, default="${A} ${B} ${d} ${Y}")
示例#10
0
    def test_HeaderTimeViewlet(self):
        request = self.app.REQUEST
        viewlet = HeaderTimeViewlet(self.portal, request, None, None)
        viewlet.update()

        date = DateTime()
        self.assertEqual(viewlet.day, date.day())

        month = _pl(monthname_msgid(int(date.strftime('%m'))),
            default=safe_unicode(date.Month()))
        dayname = _pl(weekdayname_msgid(int(date.strftime('%w'))),
            default=safe_unicode(date.DayOfWeek()))
        datetime = viewlet.toLocalizedTime(date, long_format=True)
        self.assertEqual(viewlet.month, month)
        self.assertEqual(viewlet.dayname, dayname)
        self.assertEqual(viewlet.datetime, datetime)
 def monthname(self, month):
     return monthname_msgid(month)
示例#12
0
def ulocalized_time(time,
                    long_format=None,
                    time_only=False,
                    context=None,
                    domain='plonelocales',
                    formatstring_domain='plonelocales',
                    request=None,
                    target_language=None):
    """Unicode aware localized time method (l10n), extended from CMFPlone
        The ONLY change versus CMFPlone is the extra parameter
        `formatstring_domain`.
        This allows us to define a different date_format_long in ploneintranet,
        while still being able to use the default translations provided by
        plonelocales, e.g. for the month names.
    """

    if time_only:
        msgid = 'time_format'
    elif long_format:
        msgid = 'date_format_long'
    else:
        msgid = 'date_format_short'

    # NOTE: this requires the presence of three msgids inside the translation
    #       catalog date_format_long, date_format_short, and time_format
    #       These msgids are translated using interpolation.
    #       The variables used here are the same as used in the strftime
    #       formating.
    #       Supported are:
    #           %A, %a, %B, %b, %H, %I, %m, %d, %M, %p, %S, %Y, %y, %Z
    #       Each used as variable in the msgstr without the %.
    #       For example: "${A} ${d}. ${B} ${Y}, ${H}:${M} ${Z}"
    #       Each language dependend part is translated itself as well.

    # From http://docs.python.org/lib/module-time.html
    #
    # %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).

    mapping = {}
    # convert to DateTime instances. Either a date string or
    # a DateTime instance needs to be passed.
    if not IDateTime.providedBy(time):
        try:
            time = DateTime(time)
        except:
            log('Failed to convert %s to a DateTime object' % time,
                severity=logging.DEBUG)
            return None

    if context is None:
        # when without context, we cannot do very much.
        return time.ISO8601()

    if request is None:
        request = aq_acquire(context, 'REQUEST')

    # 1. if our Enabled flag in the configuration registry is set,
    # the format string there should override the translation machinery
    formatstring = get_formatstring_from_registry(msgid)
    if formatstring is not None:
        return time.strftime(formatstring)

    # 2. the normal case: translation machinery,
    # that is the ".../LC_MESSAGES/plonelocales.po" files
    # XXX: here, we pass `formatstring_domain` instead of `domain`
    formatstring = translate(msgid,
                             formatstring_domain,
                             mapping,
                             request,
                             target_language=target_language)

    # 3. if both failed, fall back to hardcoded ISO style
    if formatstring == msgid:
        if msgid == 'date_format_long':
            formatstring = '%Y-%m-%d %H:%M'  # 2038-01-19 03:14
        elif msgid == 'date_format_short':
            formatstring = '%Y-%m-%d'  # 2038-01-19
        elif msgid == 'time_format':
            formatstring = '%H:%M'  # 03:14
        else:
            formatstring = '[INTERNAL ERROR]'
        return time.strftime(formatstring)

    # get the format elements used in the formatstring
    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
    # Note: Here, the normal `domain` is used
    for key in name_elements:
        mapping[key] = translate(mapping[key],
                                 domain,
                                 context=request,
                                 default=mapping[key],
                                 target_language=target_language)

    # translate the time string
    # XXX: here, we pass `formatstring_domain` instead of `domain`
    return translate(msgid,
                     formatstring_domain,
                     mapping,
                     request,
                     target_language=target_language)
示例#13
0
def month_name(context, request, month):
    """Returns the text for the given month (1-12)."""
    assert (1 <= month and month <= 12)
    msgid = monthname_msgid(month)
    return translate(context, request, msgid, 'plonelocales')
示例#14
0
def ulocalized_time(time, formatstring, request, target_language=None):
    """time localization method copied from Products.CMFPlone.i18nl10n.
    The method was modified to allow for a custom formatstring in the
    normal python format.

    From http://docs.python.org/lib/module-time.html

    %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).
    """

    domain = 'plonelocales'
    # map to a message string, to make easier reuse of original
    # method and _interp_regex.
    formatstring = format_string_to_message_string(formatstring)

    mapping = {}
    # convert to DateTime instances. Either a date string or
    # a DateTime instance needs to be passed.
    if not IDateTime.providedBy(time):
        try:
            time = DateTime(time)
        except Exception:
            log('Failed to convert %s to a DateTime object' % time,
                severity=logging.DEBUG)
            return None

    # get the format elements used in the formatstring
    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], domain,
                                 context=request, default=mapping[key],
                                 target_language=target_language)

    # translate the time string
    return formatstring.replace("${", "{").format(**mapping)
 def monthname(self, month):
     return monthname_msgid(month)
示例#16
0
    def testI18Ngenerator(self):
        '''Runs the i18ngenerator'''

        ctl = {}
        ctl['plone'] = catalog.MessageCatalog(domain='plone')

        # global actions
        for provider in self.action_tool.listActionProviders():
            provider_tool = getToolByName(self.portal, provider, None)
            for action in provider_tool.listActions():
                title = norm(action.title)
                if action.visible:
                    ctl['plone'].add(title, msgstr=title, references=['action defined in %s' % provider])

        # description of action icons
        for icon in self.ai_tool.listActionIcons():
            title= icon.getTitle()
            ctl['plone'].add(title, msgstr=title, references=['action_icon id %s - category %s' % (icon.getIconURL(), icon.getCategory())])


        # workflow states and worflow transitions
        for workflow in self.wf_tool.listWorkflows():
            wf = self.wf_tool.getWorkflowById(workflow)
            for obj in wf.objectValues():
                if isinstance(obj, States.States):
                    for state in obj.objectValues():
                        ctl['plone'].add(state.getId(), msgstr=state.getId(), references=['workflow state defined in %s - title %s' % (workflow, state.title)])
                        ctl['plone'].add(state.title, msgstr=state.title, references=['workflow state defined in %s - id %s' % (workflow, state.getId())])
                elif isinstance(obj, Transitions.Transitions):
                    for transition in obj.objectValues():
                        ctl['plone'].add(transition.getId(), msgstr=transition.getId(), references=['workflow transition defined in %s - title %s new state %s' % (workflow, transition.title, transition.new_state_id)])
                        ctl['plone'].add(transition.title, msgstr=transition.title, references=['workflow transition defined in %s - id %s new state %s' % (workflow, transition.getId(), transition.new_state_id)])
                        ctl['plone'].add(transition.actbox_name, msgstr=transition.actbox_name, references=['workflow action defined in %s - title %s new state %s' % (workflow, transition.title, transition.new_state_id)])


        # portal types and types actions
        types = [t for t in self.types_tool.listContentTypes() if not t.startswith('CMF ')] # filter out CMF types

        for type in types:
            typeObj = self.types_tool.getTypeInfo(type)

            methods = []
            try:
                methods = typeObj.view_methods
            except AttributeError:
                # this type doesn't support the DynamicViewFTI
                pass

            for method in methods:
                mid = getattr(typeObj, method, None)
                title = mid.aq_inner.aq_explicit.title_or_id()
                if type.endswith('Folder') or type == 'Topic': # XXX Need a better way to filter out unused views
                    ctl['plone'].add(title, msgstr=title, references=['dynamic view name template %s on type %s' % (method, type)])

            title = norm(typeObj.Title())
            desc = norm(typeObj.Description())
            ctl['plone'].add(title, msgstr=title, references=['portal type title of type with description %s' % desc])
            ctl['plone'].add(desc, msgstr=desc, references=['portal type description of type with title %s' % title])

            # don't show actions definied on criteria
            if title.lower().find('criteri') == -1:
                for action in typeObj.listActions():
                    actionTitle = norm(action.title)
                    ctl['plone'].add(actionTitle, msgstr=actionTitle, references=['type action defined on %s' % title])

        # portal_controlpanel categories
        for group in self.cp_tool.getGroups():
            id = group.get('id')
            title = group.get('title')
            ctl['plone'].add(title, msgstr=title, references=['controlpanel category-id %s' % id])

        # day and monthnames
        for num in range(7):
            day = weekdayname_english(num) # Monday, Tuesday...
            ctl['plone'].add(weekdayname_msgid(num), msgstr=day, references=['datetime name of a day, format %A'])
            day = weekdayname_english(num, 'a') # Mon, Tue, ...
            ctl['plone'].add(weekdayname_msgid_abbr(num), msgstr=day, references=['datetime abbreviation of a day, format %a'])
            day = weekdayname_english(num, 'a')[:2] # Mo, Tu, ...
            ctl['plone'].add(weekdayname_msgid_short(num), msgstr=day, references=['datetime two letter abbreviation of a day used in the portlet_calendar'])
        for num in range(1,13):
            month = monthname_english(num) # January, February...
            ctl['plone'].add(monthname_msgid(num), msgstr=month, references=['datetime name of a month, format %B'])
            month = monthname_english(num, 'a') # Jan, Feb...
            ctl['plone'].add(monthname_msgid_abbr(num), msgstr=month, references=['datetime name of a month, format %b'])

        # indexes and metadata and smart folder options
        domain = 'plone'
        for index in self.atct_tool.getIndexes():
            index = self.atct_tool.getIndex(index)
            id = index.index
            title = index.friendlyName
            desc = index.description
            if title:
                ctl[domain].add(title, msgstr=title, references=['index friendly name of index %s' % id])
            if desc:
                ctl[domain].add(desc, msgstr=desc, references=['index description of index %s' % id])
            # add in criterions
            for criterion in self.atct_tool.getCriteriaForIndex(id, as_dict= True):
                name = criterion['name']
                desc = criterion['description']
                ctl[domain].add(desc, msgstr=desc, references=['criterion description of criterion %s' % name])
        for meta in self.atct_tool.getAllMetadata(enabledOnly=1):
            meta = self.atct_tool.getMetadata(meta)
            id = meta.index
            title = meta.friendlyName
            desc = meta.description
            if title:
                ctl[domain].add(title, msgstr=title, references=['metadata friendly name of metadata %s' % id])
            if desc:
                ctl[domain].add(desc, msgstr=desc, references=['metadata description of metadata %s' % id])

        # DisplayList properties XXX This takes only static DisplayLists for now. Need to look at dynamically generated ones (which need a content object to be present)

        for attype in self.at_tool.listRegisteredTypes():
            # typename = attype['name']
            schema = attype['schema']
            for field in schema.fields():
                if not isinstance(field, ReferenceField):
                    domain = field.widget.__dict__.get('i18n_domain')
                    vocab = field.Vocabulary()
                    if isinstance(vocab, DisplayList):
                        for key in vocab:
                            value = vocab.getValue(key)
                            if len(value) > 1:
                                msgid = vocab.getMsgId(key)
                                if domain == None:
                                    domain = 'plone'
                                if not domain in ctl.keys():
                                    ctl[domain] = catalog.MessageCatalog(domain=domain)
                                ctl[domain].add(msgid, msgstr=value, references=['DisplayList entry for field %s' % field.getName()])

        # archetypes widgets XXX Should be merged with the DisplayList stuff

        for widget in self.at_tool.getWidgets():
            w = widget._args.get('widget')
            dict = w.__dict__
            domain = dict.get('i18n_domain')
            if domain:
                if not domain in ctl.keys():
                    ctl[domain] = catalog.MessageCatalog(domain=domain)
                label = dict.get('label')
                label_msgid = dict.get('label_msgid')
                desc = norm(dict.get('description'))
                desc_msgid = dict.get('description_msgid')

                if label_msgid and label:
                    ctl[domain].add(label_msgid, label, references=['widget label of %s - description \"%s\"' % (w.getName(), desc)])
                if desc_msgid and desc:
                    ctl[domain].add(desc_msgid, desc, references=['widget description of %s for label %s' % (w.getName(), label)])

        domains = ctl.keys()

        for domain in domains:
            file = open('%s-generated.pot' % domain, 'w')
            writer = catalog.POWriter(file, ctl[domain])
            writer.write(sort=True, msgstrToComment=True)
示例#17
0
 def Title(self):
     # Get utranslate script from context...
     return getToolByName(self, 'utranslate')(msgid=monthname_msgid(self.month), default=monthname_english(self.month), domain='plonelocales').capitalize()
 def month_name(self, month_no):
     return translate(monthname_msgid(str(month_no)),
                      'plonelocales',
                       context=self.request,
                       default=monthname_english(month_no))
示例#19
0
def month_name(context, request, month):
    """Returns the text for the given month (1-12)."""
    assert (1 <= month and month <= 12)
    msgid = monthname_msgid(month)
    return translate(context, request, msgid, 'plonelocales')
def i18nl10n_ulocalized_time(time, long_format=None, time_only=None, context=None,
                             domain='plonelocales', request=None):
    """This patched version change the behaviour and the meaning of long_format parameter.

    This trick is quite ugly, but is the only way to keep compatibility with basic use case of this method
    all around Plone code.
    
    The format must be given using the .po format, so not if for example you want to translate this:
        '%a %d %b %Y'
    you need to change it to:
        '${a} ${d} ${b} ${Y}'
    """
    
    # get msgid
    if not long_format or (type(long_format)!=str and type(long_format)!=unicode):
        msgid = long_format and 'date_format_long' or 'date_format_short'
        if time_only is not None:
            msgid = 'time_format'
    else:
        msgid = long_format

    # NOTE: this requires the presence of three msgids inside the translation catalog
    #       date_format_long, date_format_short, and time_format
    #       These msgids are translated using interpolation.
    #       The variables used here are the same as used in the strftime formating.
    #       Supported are %A, %a, %B, %b, %H, %I, %m, %d, %M, %p, %S, %Y, %y, %Z, each used as
    #       variable in the msgstr without the %.
    #       For example: "${A} ${d}. ${B} ${Y}, ${H}:${M} ${Z}"
    #       Each language dependend part is translated itself as well.

    # From http://docs.python.org/lib/module-time.html
    #
    # %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).     

    mapping = {}
    # convert to DateTime instances. Either a date string or 
    # a DateTime instance needs to be passed.
    if not IDateTime.providedBy(time):
        try:
            time = DateTime(time)
        except:
            log('Failed to convert %s to a DateTime object' % time,
                severity=logging.DEBUG)
            return None

    if context is None:
        # when without context, we cannot do very much.
        return time.ISO()

    if request is None:
        request = aq_acquire(context, 'REQUEST')

    # get the formatstring
    formatstring = translate(msgid, domain, mapping, request)

    if formatstring is None or formatstring.startswith('date_') or formatstring.startswith('time_'):
        # msg catalog was not able to translate this msgids
        # use default setting

        properties=getToolByName(context, 'portal_properties').site_properties
        if long_format:
            format=properties.localLongTimeFormat
        else:
            if time_only:
                format=properties.localTimeOnlyFormat
            else:
                format=properties.localTimeFormat

        return time.strftime(format)
    
    # get the format elements used in the formatstring
    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], domain, context=request, default=mapping[key])

    # translate the time string
    return translate(msgid, domain, mapping, request)
示例#21
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)
示例#22
0
def translate_month(month_index, language): 
    month_id = i18nl10n.monthname_msgid(month_index)
#    ts = getGlobalTranslationService()
#    return ts.translate(domain='plonelocales', msgid=month_id, target_language=language)
    return translate(domain='plonelocales', msgid=month_id, target_language=language)