本文整理汇总了Python中Mailman.i18n.get_translation函数的典型用法代码示例。如果您正苦于以下问题:Python get_translation函数的具体用法?Python get_translation怎么用?Python get_translation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_translation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: html_foot
def html_foot(self):
# avoid i18n side-effects
mlist = self.maillist
otrans = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
# Convenience
def quotetime(s):
return html_quote(i18n.ctime(s), self.lang)
try:
d = {"lastdate": quotetime(self.lastdate),
"archivedate": quotetime(self.archivedate),
"listinfo": mlist.GetScriptURL('listinfo', absolute=1),
"version": self.version,
"listname": html_quote(mlist.real_name, self.lang),
}
i = {"thread": _("thread"),
"subject": _("subject"),
"author": _("author"),
"date": _("date")
}
finally:
i18n.set_translation(otrans)
for t in i.keys():
cap = t[0].upper() + t[1:]
if self.type == cap:
d["%s_ref" % (t)] = ""
else:
d["%s_ref" % (t)] = ('<a href="%s.html#start">[ %s ]</a>'
% (t, i[t]))
return quick_maketext(
'archidxfoot.html', d,
mlist=mlist)
示例2: __refuse
def __refuse(self, request, recip, comment, origmsg=None, lang=None):
# As this message is going to the requestor, try to set the language
# to his/her language choice, if they are a member. Otherwise use the
# list's preferred language.
realname = self.real_name
if lang is None:
lang = self.getMemberLanguage(recip)
text = Utils.maketext(
'refuse.txt',
{'listname' : realname,
'request' : request,
'reason' : comment,
'adminaddr': self.GetOwnerEmail(),
}, lang=lang, mlist=self)
otrans = i18n.get_translation()
i18n.set_language(lang)
try:
# add in original message, but not wrap/filled
if origmsg:
text = NL.join(
[text,
'---------- ' + _('Original Message') + ' ----------',
str(origmsg)
])
subject = _('Request to mailing list %(realname)s rejected')
finally:
i18n.set_translation(otrans)
msg = Message.UserNotification(recip, self.GetOwnerEmail(),
subject, text, lang)
msg.send(self)
示例3: decode_headers
def decode_headers(self):
"""MIME-decode headers.
If the email, subject, or author attributes contain non-ASCII
characters using the encoded-word syntax of RFC 2047, decoded versions
of those attributes are placed in the self.decoded (a dictionary).
If the list's charset differs from the header charset, an attempt is
made to decode the headers as Unicode. If that fails, they are left
undecoded.
"""
author = self.decode_charset(self.author)
subject = self.decode_charset(self.subject)
if author:
self.decoded['author'] = author
email = self.decode_charset(self.email)
if email:
self.decoded['email'] = email
if subject:
if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
otrans = i18n.get_translation()
try:
i18n.set_language(self._lang)
atmark = unicode(_(' at '), Utils.GetCharSet(self._lang))
subject = re.sub(r'([-+,.\w]+)@([-+.\w]+)',
'\g<1>' + atmark + '\g<2>', subject)
finally:
i18n.set_translation(otrans)
self.decoded['subject'] = subject
self.decoded['stripped'] = self.strip_subject(subject or self.subject)
示例4: sendProbe
def sendProbe(self, member, msg):
listname = self.real_name
# Put together the substitution dictionary.
d = {
"listname": listname,
"address": member,
"optionsurl": self.GetOptionsURL(member, absolute=True),
"owneraddr": self.GetOwnerEmail(),
}
text = Utils.maketext("probe.txt", d, lang=self.getMemberLanguage(member), mlist=self)
# Calculate the VERP'd sender address for bounce processing of the
# probe message.
token = self.pend_new(Pending.PROBE_BOUNCE, member, msg)
probedict = {"bounces": self.internal_name() + "-bounces", "token": token}
probeaddr = "%[email protected]%s" % ((mm_cfg.VERP_PROBE_FORMAT % probedict), self.host_name)
# Calculate the Subject header, in the member's preferred language
ulang = self.getMemberLanguage(member)
otrans = i18n.get_translation()
i18n.set_language(ulang)
try:
subject = _("%(listname)s mailing list probe message")
finally:
i18n.set_translation(otrans)
outer = Message.UserNotification(member, probeaddr, subject, lang=ulang)
outer.set_type("multipart/mixed")
text = MIMEText(text, _charset=Utils.GetCharSet(ulang))
outer.attach(text)
outer.attach(MIMEMessage(msg))
# Turn off further VERP'ing in the final delivery step. We set
# probe_token for the OutgoingRunner to more easily handling local
# rejects of probe messages.
outer.send(self, envsender=probeaddr, verp=False, probe_token=token)
示例5: Format
def Format(self, indent=0):
charset = get_translation().charset() or 'us-ascii'
output = ['<INPUT name="%s" type="%s" value="%s"' %
(self.name, self.type, self.value)]
for item in self.kws.items():
output.append('%s="%s"' % item)
if self.checked:
output.append('CHECKED')
output.append('>')
ret = SPACE.join(output)
if self.type == 'TEXT' and isinstance(ret, unicode):
ret = ret.encode(charset, 'replace')
return ret
示例6: as_html
def as_html(self):
"""Different attributes that can be used when generating a html file from a template for the archives."""
d = self.__dict__.copy()
# avoid i18n side-effects
otrans = i18n.get_translation()
i18n.set_language(self._lang)
try:
d["prev"], d["prev_wsubj"] = self._get_prev()
d["next"], d["next_wsubj"] = self._get_next()
d["email_html"] = self.quote(self.email)
d["title"] = self.quote(self.subject)
d["subject_html"] = self.quote(self.subject)
# TK: These two _url variables are used to compose a response
# from the archive web page. So, ...
# Possibly remove since not used??
d["subject_url"] = url_quote('Re: ' + self.subject)
d["in_reply_to_url"] = url_quote(self._message_id)
if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
# Point the mailto url back to the list
author = re.sub('@', _(' at '), self.author)
emailurl = self._mlist.GetListEmail()
else:
author = self.author
emailurl = self.email
d["author_html"] = self.quote(author)
d["email_url"] = url_quote(emailurl)
d["datestr_html"] = self.quote(i18n.ctime(int(self.date)))
d["body"] = self._get_body()
d['listurl'] = self._mlist.GetScriptURL('listinfo', absolute=1)
d['listname'] = self._mlist.real_name
d['encoding'] = ''
try:
# This should work after a couple of emails has been send and the thread
# address has been set, but to not get an error in the beginning the error
# is caught and an already existing address is provided. Is for dlists.
d['thread_addr'] = self.thread_addr
d['thread_addr_at'] = re.sub('@', _(' at '), self.thread_addr)
except:
d['thread_addr'] = d["email_url"]
d['thread_addr_at'] = d["email_url"]
finally:
i18n.set_translation(otrans)
charset = Utils.GetCharSet(self._lang)
d["encoding"] = html_charset % charset
self._add_decoded(d)
return quick_maketext(
'article.html', d,
lang=self._lang, mlist=self._mlist)
示例7: SendHostileSubscriptionNotice
def SendHostileSubscriptionNotice(self, listname, address):
# Some one was invited to one list but tried to confirm to a different
# list. We inform both list owners of the bogosity, but be careful
# not to reveal too much information.
selfname = self.internal_name()
syslog("mischief", "%s was invited to %s but confirmed to %s", address, listname, selfname)
# First send a notice to the attacked list
msg = Message.OwnerNotification(
self,
_("Hostile subscription attempt detected"),
Utils.wrap(
_(
"""%(address)s was invited to a different mailing
list, but in a deliberate malicious attempt they tried to confirm the
invitation to your list. We just thought you'd like to know. No further
action by you is required."""
)
),
)
msg.send(self)
# Now send a notice to the invitee list
try:
# Avoid import loops
from Mailman.MailList import MailList
mlist = MailList(listname, lock=False)
except Errors.MMListError:
# Oh well
return
otrans = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
try:
msg = Message.OwnerNotification(
mlist,
_("Hostile subscription attempt detected"),
Utils.wrap(
_(
"""You invited %(address)s to your list, but in a
deliberate malicious attempt, they tried to confirm the invitation to a
different list. We just thought you'd like to know. No further action by you
is required."""
)
),
)
msg.send(mlist)
finally:
i18n.set_translation(otrans)
示例8: _onefile
def _onefile(self, msg, msgdata):
# Do some common sanity checking on the message metadata. It's got to
# be destined for a particular mailing list. This switchboard is used
# to shunt off badly formatted messages. We don't want to just trash
# them because they may be fixable with human intervention. Just get
# them out of our site though.
#
# Find out which mailing list this message is destined for.
listname = msgdata.get('listname')
if not listname:
listname = mm_cfg.MAILMAN_SITE_LIST
mlist = self._open_list(listname)
if not mlist:
syslog('error',
'Dequeuing message destined for missing list: %s',
listname)
self._shunt.enqueue(msg, msgdata)
return
# Now process this message, keeping track of any subprocesses that may
# have been spawned. We'll reap those later.
#
# We also want to set up the language context for this message. The
# context will be the preferred language for the user if a member of
# the list, or the list's preferred language. However, we must take
# special care to reset the defaults, otherwise subsequent messages
# may be translated incorrectly. BAW: I'm not sure I like this
# approach, but I can't think of anything better right now.
otranslation = i18n.get_translation()
sender = msg.get_sender()
if mlist:
lang = mlist.getMemberLanguage(sender)
else:
lang = mm_cfg.DEFAULT_SERVER_LANGUAGE
i18n.set_language(lang)
msgdata['lang'] = lang
try:
keepqueued = self._dispose(mlist, msg, msgdata)
finally:
i18n.set_translation(otranslation)
# Keep tabs on any child processes that got spawned.
kids = msgdata.get('_kids')
if kids:
self._kids.update(kids)
if keepqueued:
self._switchboard.enqueue(msg, msgdata)
示例9: html_TOC
def html_TOC(self):
mlist = self.maillist
listname = mlist.internal_name()
mbox = os.path.join(mlist.archive_dir()+'.mbox', listname+'.mbox')
d = {"listname": mlist.real_name,
"listinfo": mlist.GetScriptURL('listinfo', absolute=1),
"fullarch": '../%s.mbox/%s.mbox' % (listname, listname),
"size": sizeof(mbox, mlist.preferred_language),
'meta': '',
}
# Avoid i18n side-effects
otrans = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
try:
if not self.archives:
d["noarchive_msg"] = _(
'<P>Currently, there are no archives. </P>')
d["archive_listing_start"] = ""
d["archive_listing_end"] = ""
d["archive_listing"] = ""
else:
d["noarchive_msg"] = ""
d["archive_listing_start"] = quick_maketext(
'archliststart.html',
lang=mlist.preferred_language,
mlist=mlist)
d["archive_listing_end"] = quick_maketext(
'archlistend.html',
mlist=mlist)
accum = []
for a in self.archives:
accum.append(self.html_TOC_entry(a))
d["archive_listing"] = EMPTYSTRING.join(accum)
finally:
i18n.set_translation(otrans)
# The TOC is always in the charset of the list's preferred language
d['meta'] += html_charset % Utils.GetCharSet(mlist.preferred_language)
# The site can disable public access to the mbox file.
if mm_cfg.PUBLIC_MBOX:
template = 'archtoc.html'
else:
template = 'archtocnombox.html'
return quick_maketext(template, d, mlist=mlist)
示例10: as_html
def as_html(self):
d = self.__dict__.copy()
# avoid i18n side-effects
otrans = i18n.get_translation()
i18n.set_language(self._lang)
try:
d["prev"], d["prev_wsubj"] = self._get_prev()
d["next"], d["next_wsubj"] = self._get_next()
d["email_html"] = self.quote(self.email)
d["title"] = self.quote(self.subject)
d["subject_html"] = self.quote(self.subject)
d["message_id"] = self.quote(self._message_id)
# TK: These two _url variables are used to compose a response
# from the archive web page. So, ...
d["subject_url"] = url_quote('Re: ' + self.subject)
d["in_reply_to_url"] = url_quote(self._message_id)
if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
# Point the mailto url back to the list
author = re.sub('@', _(' at '), self.author)
emailurl = self._mlist.GetListEmail()
else:
author = self.author
emailurl = self.email
d["author_html"] = self.quote(author)
d["email_url"] = url_quote(emailurl)
d["datestr_html"] = self.quote(i18n.ctime(int(self.date)))
d["body"] = self._get_body()
d['listurl'] = self._mlist.GetScriptURL('listinfo', absolute=1)
d['listname'] = self._mlist.real_name
d['encoding'] = ''
finally:
i18n.set_translation(otrans)
charset = Utils.GetCharSet(self._lang)
d["encoding"] = html_charset % charset
self._add_decoded(d)
return quick_maketext(
'article.html', d,
lang=self._lang, mlist=self._mlist)
示例11: html_head
def html_head(self):
# avoid i18n side-effects
mlist = self.maillist
otrans = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
# Convenience
def quotetime(s):
return html_quote(i18n.ctime(s), self.lang)
try:
d = {"listname": html_quote(mlist.real_name, self.lang),
"archtype": self.type,
"archive": self.volNameToDesc(self.archive),
"listinfo": mlist.GetScriptURL('listinfo', absolute=1),
"firstdate": quotetime(self.firstdate),
"lastdate": quotetime(self.lastdate),
"size": self.size,
}
i = {"thread": _("thread"),
"subject": _("subject"),
"author": _("author"),
"date": _("date"),
}
finally:
i18n.set_translation(otrans)
for t in i.keys():
cap = t[0].upper() + t[1:]
if self.type == cap:
d["%s_ref" % (t)] = ""
d["archtype"] = i[t]
else:
d["%s_ref" % (t)] = ('<a href="%s.html#start">[ %s ]</a>'
% (t, i[t]))
if self.charset:
d["encoding"] = html_charset % self.charset
else:
d["encoding"] = ""
return quick_maketext(
'archidxhead.html', d,
mlist=mlist)
示例12: send_digests
def send_digests(mlist, mboxfp):
# Set the digest volume and time
if mlist.digest_last_sent_at:
bump = False
# See if we should bump the digest volume number
timetup = time.localtime(mlist.digest_last_sent_at)
now = time.localtime(time.time())
freq = mlist.digest_volume_frequency
if freq == 0 and timetup[0] < now[0]:
# Yearly
bump = True
elif freq == 1 and timetup[1] <> now[1]:
# Monthly, but we take a cheap way to calculate this. We assume
# that the clock isn't going to be reset backwards.
bump = True
elif freq == 2 and (timetup[1] % 4 <> now[1] % 4):
# Quarterly, same caveat
bump = True
elif freq == 3:
# Once again, take a cheap way of calculating this
weeknum_last = int(time.strftime('%W', timetup))
weeknum_now = int(time.strftime('%W', now))
if weeknum_now > weeknum_last or timetup[0] > now[0]:
bump = True
elif freq == 4 and timetup[7] <> now[7]:
# Daily
bump = True
if bump:
mlist.bump_digest_volume()
mlist.digest_last_sent_at = time.time()
# Wrapper around actually digest crafter to set up the language context
# properly. All digests are translated to the list's preferred language.
otranslation = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
try:
send_i18n_digests(mlist, mboxfp)
finally:
i18n.set_translation(otranslation)
示例13: as_text
def as_text(self):
d = self.__dict__.copy()
# We need to guarantee a valid From_ line, even if there are
# bososities in the headers.
if not d.get('fromdate', '').strip():
d['fromdate'] = time.ctime(time.time())
if not d.get('email', '').strip():
d['email'] = '[email protected]'
if not d.get('datestr', '').strip():
d['datestr'] = time.ctime(time.time())
#
headers = ['From %(email)s %(fromdate)s',
'From: %(email)s (%(author)s)',
'Date: %(datestr)s',
'Subject: %(subject)s']
if d['_in_reply_to']:
headers.append('In-Reply-To: %(_in_reply_to)s')
if d['_references']:
headers.append('References: %(_references)s')
if d['_message_id']:
headers.append('Message-ID: %(_message_id)s')
body = EMPTYSTRING.join(self.body)
cset = Utils.GetCharSet(self._lang)
# Coerce the body to Unicode and replace any invalid characters.
if not isinstance(body, types.UnicodeType):
body = unicode(body, cset, 'replace')
if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
otrans = i18n.get_translation()
try:
i18n.set_language(self._lang)
atmark = unicode(_(' at '), cset)
body = re.sub(r'([-+,.\w]+)@([-+.\w]+)',
'\g<1>' + atmark + '\g<2>', body)
finally:
i18n.set_translation(otrans)
# Return body to character set of article.
body = body.encode(cset, 'replace')
return NL.join(headers) % d + '\n\n' + body + '\n'
示例14: __init__
def __init__(self, message=None, sequence=0, keepHeaders=[],
lang=mm_cfg.DEFAULT_SERVER_LANGUAGE, mlist=None):
self.__super_init(message, sequence, keepHeaders)
self.prev = None
self.next = None
# Trim Re: from the subject line
i = 0
while i != -1:
result = REpat.match(self.subject)
if result:
i = result.end(0)
self.subject = self.subject[i:]
else:
i = -1
# Useful to keep around
self._lang = lang
self._mlist = mlist
if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
# Avoid i18n side-effects. Note that the language for this
# article (for this list) could be different from the site-wide
# preferred language, so we need to ensure no side-effects will
# occur. Think what happens when executing bin/arch.
otrans = i18n.get_translation()
try:
i18n.set_language(lang)
if self.author == self.email:
self.author = self.email = re.sub('@', _(' at '),
self.email)
else:
self.email = re.sub('@', _(' at '), self.email)
finally:
i18n.set_translation(otrans)
# Snag the content-* headers. RFC 1521 states that their values are
# case insensitive.
ctype = message.get('Content-Type', 'text/plain')
cenc = message.get('Content-Transfer-Encoding', '')
self.ctype = ctype.lower()
self.cenc = cenc.lower()
self.decoded = {}
cset = Utils.GetCharSet(mlist.preferred_language)
cset_out = Charset(cset).output_charset or cset
if isinstance(cset_out, unicode):
# email 3.0.1 (python 2.4) doesn't like unicode
cset_out = cset_out.encode('us-ascii')
charset = message.get_content_charset(cset_out)
if charset:
charset = charset.lower().strip()
if charset[0]=='"' and charset[-1]=='"':
charset = charset[1:-1]
if charset[0]=="'" and charset[-1]=="'":
charset = charset[1:-1]
try:
body = message.get_payload(decode=True)
except binascii.Error:
body = None
if body and charset != Utils.GetCharSet(self._lang):
# decode body
try:
body = unicode(body, charset)
except (UnicodeError, LookupError):
body = None
if body:
self.body = [l + "\n" for l in body.splitlines()]
self.decode_headers()
示例15: hold_for_approval
def hold_for_approval(mlist, msg, msgdata, exc):
# BAW: This should really be tied into the email confirmation system so
# that the message can be approved or denied via email as well as the
# web.
#
# XXX We use the weird type(type) construct below because in Python 2.1,
# type is a function not a type and so can't be used as the second
# argument in isinstance(). However, in Python 2.5, exceptions are
# new-style classes and so are not of ClassType.
if isinstance(exc, ClassType) or isinstance(exc, type(type)):
# Go ahead and instantiate it now.
exc = exc()
listname = mlist.real_name
sender = msgdata.get('sender', msg.get_sender())
usersubject = msg.get('subject')
charset = Utils.GetCharSet(mlist.preferred_language)
if usersubject:
usersubject = Utils.oneline(usersubject, charset)
else:
usersubject = _('(no subject)')
message_id = msg.get('message-id', 'n/a')
owneraddr = mlist.GetOwnerEmail()
adminaddr = mlist.GetBouncesEmail()
requestaddr = mlist.GetRequestEmail()
# We need to send both the reason and the rejection notice through the
# translator again, because of the games we play above
reason = Utils.wrap(exc.reason_notice())
msgdata['rejection_notice'] = Utils.wrap(exc.rejection_notice(mlist))
id = mlist.HoldMessage(msg, reason, msgdata)
# Now we need to craft and send a message to the list admin so they can
# deal with the held message.
d = {'listname' : listname,
'hostname' : mlist.host_name,
'reason' : _(reason),
'sender' : sender,
'subject' : usersubject,
'admindb_url': mlist.GetScriptURL('admindb', absolute=1),
}
# We may want to send a notification to the original sender too
fromusenet = msgdata.get('fromusenet')
# Since we're sending two messages, which may potentially be in different
# languages (the user's preferred and the list's preferred for the admin),
# we need to play some i18n games here. Since the current language
# context ought to be set up for the user, let's craft his message first.
cookie = mlist.pend_new(Pending.HELD_MESSAGE, id)
if not fromusenet and ackp(msg) and mlist.respond_to_post_requests and \
mlist.autorespondToSender(sender, mlist.getMemberLanguage(sender)):
# Get a confirmation cookie
d['confirmurl'] = '%s/%s' % (mlist.GetScriptURL('confirm', absolute=1),
cookie)
lang = msgdata.get('lang', mlist.getMemberLanguage(sender))
subject = _('Your message to %(listname)s awaits moderator approval')
text = Utils.maketext('postheld.txt', d, lang=lang, mlist=mlist)
nmsg = Message.UserNotification(sender, owneraddr, subject, text, lang)
nmsg.send(mlist)
# Now the message for the list owners. Be sure to include the list
# moderators in this message. This one should appear to come from
# <list>-owner since we really don't need to do bounce processing on it.
if mlist.admin_immed_notify:
# Now let's temporarily set the language context to that which the
# admin is expecting.
otranslation = i18n.get_translation()
i18n.set_language(mlist.preferred_language)
try:
lang = mlist.preferred_language
charset = Utils.GetCharSet(lang)
# We need to regenerate or re-translate a few values in d
d['reason'] = _(reason)
d['subject'] = usersubject
# craft the admin notification message and deliver it
subject = _('%(listname)s post from %(sender)s requires approval')
nmsg = Message.UserNotification(owneraddr, owneraddr, subject,
lang=lang)
nmsg.set_type('multipart/mixed')
text = MIMEText(
Utils.maketext('postauth.txt', d, raw=1, mlist=mlist),
_charset=charset)
dmsg = MIMEText(Utils.wrap(_("""\
If you reply to this message, keeping the Subject: header intact, Mailman will
discard the held message. Do this if the message is spam. If you reply to
this message and include an Approved: header with the list password in it, the
message will be approved for posting to the list. The Approved: header can
also appear in the first line of the body of the reply.""")),
_charset=Utils.GetCharSet(lang))
dmsg['Subject'] = 'confirm ' + cookie
dmsg['Sender'] = requestaddr
dmsg['From'] = requestaddr
dmsg['Date'] = email.Utils.formatdate(localtime=True)
dmsg['Message-ID'] = Utils.unique_message_id(mlist)
nmsg.attach(text)
nmsg.attach(MIMEMessage(msg))
nmsg.attach(MIMEMessage(dmsg))
nmsg.send(mlist, **{'tomoderators': 1})
finally:
i18n.set_translation(otranslation)
# Log the held message
syslog('vette', '%s post from %s held, message-id=%s: %s',
listname, sender, message_id, reason)
# raise the specific MessageHeld exception to exit out of the message
# delivery pipeline
#.........这里部分代码省略.........