1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
4 # This module is free software, and you may redistribute it and/or modify
5 # under the same terms as Python, so long as this copyright message and
6 # disclaimer are retained in their original form.
7 #
8 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
9 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
10 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
11 # POSSIBILITY OF SUCH DAMAGE.
12 #
13 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
14 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
15 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
16 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
17 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
18 #
20 """An e-mail gateway for Roundup.
22 Incoming messages are examined for multiple parts:
23 . In a multipart/mixed message or part, each subpart is extracted and
24 examined. The text/plain subparts are assembled to form the textual
25 body of the message, to be stored in the file associated with a "msg"
26 class node. Any parts of other types are each stored in separate files
27 and given "file" class nodes that are linked to the "msg" node.
28 . In a multipart/alternative message or part, we look for a text/plain
29 subpart and ignore the other parts.
31 Summary
32 -------
33 The "summary" property on message nodes is taken from the first non-quoting
34 section in the message body. The message body is divided into sections by
35 blank lines. Sections where the second and all subsequent lines begin with
36 a ">" or "|" character are considered "quoting sections". The first line of
37 the first non-quoting section becomes the summary of the message.
39 Addresses
40 ---------
41 All of the addresses in the To: and Cc: headers of the incoming message are
42 looked up among the user nodes, and the corresponding users are placed in
43 the "recipients" property on the new "msg" node. The address in the From:
44 header similarly determines the "author" property of the new "msg"
45 node. The default handling for addresses that don't have corresponding
46 users is to create new users with no passwords and a username equal to the
47 address. (The web interface does not permit logins for users with no
48 passwords.) If we prefer to reject mail from outside sources, we can simply
49 register an auditor on the "user" class that prevents the creation of user
50 nodes with no passwords.
52 Actions
53 -------
54 The subject line of the incoming message is examined to determine whether
55 the message is an attempt to create a new item or to discuss an existing
56 item. A designator enclosed in square brackets is sought as the first thing
57 on the subject line (after skipping any "Fwd:" or "Re:" prefixes).
59 If an item designator (class name and id number) is found there, the newly
60 created "msg" node is added to the "messages" property for that item, and
61 any new "file" nodes are added to the "files" property for the item.
63 If just an item class name is found there, we attempt to create a new item
64 of that class with its "messages" property initialized to contain the new
65 "msg" node and its "files" property initialized to contain any new "file"
66 nodes.
68 Triggers
69 --------
70 Both cases may trigger detectors (in the first case we are calling the
71 set() method to add the message to the item's spool; in the second case we
72 are calling the create() method to create a new node). If an auditor raises
73 an exception, the original message is bounced back to the sender with the
74 explanatory message given in the exception.
76 $Id: mailgw.py,v 1.196 2008-07-23 03:04:44 richard Exp $
77 """
78 __docformat__ = 'restructuredtext'
80 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
81 import time, random, sys, logging
82 import traceback, rfc822
84 from email.Header import decode_header
86 from roundup import configuration, hyperdb, date, password, rfc2822, exceptions
87 from roundup.mailer import Mailer, MessageSendError
88 from roundup.i18n import _
89 from roundup.hyperdb import iter_roles
91 try:
92 import pyme, pyme.core, pyme.gpgme
93 except ImportError:
94 pyme = None
96 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
98 class MailGWError(ValueError):
99 pass
101 class MailUsageError(ValueError):
102 pass
104 class MailUsageHelp(Exception):
105 """ We need to send the help message to the user. """
106 pass
108 class Unauthorized(Exception):
109 """ Access denied """
110 pass
112 class IgnoreMessage(Exception):
113 """ A general class of message that we should ignore. """
114 pass
115 class IgnoreBulk(IgnoreMessage):
116 """ This is email from a mailing list or from a vacation program. """
117 pass
118 class IgnoreLoop(IgnoreMessage):
119 """ We've seen this message before... """
120 pass
122 def initialiseSecurity(security):
123 ''' Create some Permissions and Roles on the security object
125 This function is directly invoked by security.Security.__init__()
126 as a part of the Security object instantiation.
127 '''
128 p = security.addPermission(name="Email Access",
129 description="User may use the email interface")
130 security.addPermissionToRole('Admin', p)
132 def getparam(str, param):
133 ''' From the rfc822 "header" string, extract "param" if it appears.
134 '''
135 if ';' not in str:
136 return None
137 str = str[str.index(';'):]
138 while str[:1] == ';':
139 str = str[1:]
140 if ';' in str:
141 # XXX Should parse quotes!
142 end = str.index(';')
143 else:
144 end = len(str)
145 f = str[:end]
146 if '=' in f:
147 i = f.index('=')
148 if f[:i].strip().lower() == param:
149 return rfc822.unquote(f[i+1:].strip())
150 return None
152 def gpgh_key_getall(key, attr):
153 ''' return list of given attribute for all uids in
154 a key
155 '''
156 u = key.uids
157 while u:
158 yield getattr(u, attr)
159 u = u.next
161 def gpgh_sigs(sig):
162 ''' more pythonic iteration over GPG signatures '''
163 while sig:
164 yield sig
165 sig = sig.next
167 def check_pgp_sigs(sig, gpgctx, author):
168 ''' Theoretically a PGP message can have several signatures. GPGME
169 returns status on all signatures in a linked list. Walk that
170 linked list looking for the author's signature
171 '''
172 for sig in gpgh_sigs(sig):
173 key = gpgctx.get_key(sig.fpr, False)
174 # we really only care about the signature of the user who
175 # submitted the email
176 if key and (author in gpgh_key_getall(key, 'email')):
177 if sig.summary & pyme.gpgme.GPGME_SIGSUM_VALID:
178 return True
179 else:
180 # try to narrow down the actual problem to give a more useful
181 # message in our bounce
182 if sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_MISSING:
183 raise MailUsageError, \
184 _("Message signed with unknown key: %s") % sig.fpr
185 elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_EXPIRED:
186 raise MailUsageError, \
187 _("Message signed with an expired key: %s") % sig.fpr
188 elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_REVOKED:
189 raise MailUsageError, \
190 _("Message signed with a revoked key: %s") % sig.fpr
191 else:
192 raise MailUsageError, \
193 _("Invalid PGP signature detected.")
195 # we couldn't find a key belonging to the author of the email
196 raise MailUsageError, _("Message signed with unknown key: %s") % sig.fpr
198 class Message(mimetools.Message):
199 ''' subclass mimetools.Message so we can retrieve the parts of the
200 message...
201 '''
202 def getpart(self):
203 ''' Get a single part of a multipart message and return it as a new
204 Message instance.
205 '''
206 boundary = self.getparam('boundary')
207 mid, end = '--'+boundary, '--'+boundary+'--'
208 s = cStringIO.StringIO()
209 while 1:
210 line = self.fp.readline()
211 if not line:
212 break
213 if line.strip() in (mid, end):
214 # according to rfc 1431 the preceding line ending is part of
215 # the boundary so we need to strip that
216 length = s.tell()
217 s.seek(-2, 1)
218 lineending = s.read(2)
219 if lineending == '\r\n':
220 s.truncate(length - 2)
221 elif lineending[1] in ('\r', '\n'):
222 s.truncate(length - 1)
223 else:
224 raise ValueError('Unknown line ending in message.')
225 break
226 s.write(line)
227 if not s.getvalue().strip():
228 return None
229 s.seek(0)
230 return Message(s)
232 def getparts(self):
233 """Get all parts of this multipart message."""
234 # skip over the intro to the first boundary
235 self.fp.seek(0)
236 self.getpart()
238 # accumulate the other parts
239 parts = []
240 while 1:
241 part = self.getpart()
242 if part is None:
243 break
244 parts.append(part)
245 return parts
247 def getheader(self, name, default=None):
248 hdr = mimetools.Message.getheader(self, name, default)
249 if not hdr:
250 return ''
251 if hdr:
252 hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders
253 # historically this method has returned utf-8 encoded string
254 l = []
255 for part, encoding in decode_header(hdr):
256 if encoding:
257 part = part.decode(encoding)
258 l.append(part)
259 return ''.join([s.encode('utf-8') for s in l])
261 def getaddrlist(self, name):
262 # overload to decode the name part of the address
263 l = []
264 for (name, addr) in mimetools.Message.getaddrlist(self, name):
265 p = []
266 for part, encoding in decode_header(name):
267 if encoding:
268 part = part.decode(encoding)
269 p.append(part)
270 name = ''.join([s.encode('utf-8') for s in p])
271 l.append((name, addr))
272 return l
274 def getname(self):
275 """Find an appropriate name for this message."""
276 if self.gettype() == 'message/rfc822':
277 # handle message/rfc822 specially - the name should be
278 # the subject of the actual e-mail embedded here
279 self.fp.seek(0)
280 name = Message(self.fp).getheader('subject')
281 else:
282 # try name on Content-Type
283 name = self.getparam('name')
284 if not name:
285 disp = self.getheader('content-disposition', None)
286 if disp:
287 name = getparam(disp, 'filename')
289 if name:
290 return name.strip()
292 def getbody(self):
293 """Get the decoded message body."""
294 self.rewindbody()
295 encoding = self.getencoding()
296 data = None
297 if encoding == 'base64':
298 # BUG: is base64 really used for text encoding or
299 # are we inserting zip files here.
300 data = binascii.a2b_base64(self.fp.read())
301 elif encoding == 'quoted-printable':
302 # the quopri module wants to work with files
303 decoded = cStringIO.StringIO()
304 quopri.decode(self.fp, decoded)
305 data = decoded.getvalue()
306 elif encoding == 'uuencoded':
307 data = binascii.a2b_uu(self.fp.read())
308 else:
309 # take it as text
310 data = self.fp.read()
312 # Encode message to unicode
313 charset = rfc2822.unaliasCharset(self.getparam("charset"))
314 if charset:
315 # Do conversion only if charset specified - handle
316 # badly-specified charsets
317 edata = unicode(data, charset, 'replace').encode('utf-8')
318 # Convert from dos eol to unix
319 edata = edata.replace('\r\n', '\n')
320 else:
321 # Leave message content as is
322 edata = data
324 return edata
326 # General multipart handling:
327 # Take the first text/plain part, anything else is considered an
328 # attachment.
329 # multipart/mixed:
330 # Multiple "unrelated" parts.
331 # multipart/Alternative (rfc 1521):
332 # Like multipart/mixed, except that we'd only want one of the
333 # alternatives. Generally a top-level part from MUAs sending HTML
334 # mail - there will be a text/plain version.
335 # multipart/signed (rfc 1847):
336 # The control information is carried in the second of the two
337 # required body parts.
338 # ACTION: Default, so if content is text/plain we get it.
339 # multipart/encrypted (rfc 1847):
340 # The control information is carried in the first of the two
341 # required body parts.
342 # ACTION: Not handleable as the content is encrypted.
343 # multipart/related (rfc 1872, 2112, 2387):
344 # The Multipart/Related content-type addresses the MIME
345 # representation of compound objects, usually HTML mail with embedded
346 # images. Usually appears as an alternative.
347 # ACTION: Default, if we must.
348 # multipart/report (rfc 1892):
349 # e.g. mail system delivery status reports.
350 # ACTION: Default. Could be ignored or used for Delivery Notification
351 # flagging.
352 # multipart/form-data:
353 # For web forms only.
355 def extract_content(self, parent_type=None, ignore_alternatives = False):
356 """Extract the body and the attachments recursively.
358 If the content is hidden inside a multipart/alternative part,
359 we use the *last* text/plain part of the *first*
360 multipart/alternative in the whole message.
361 """
362 content_type = self.gettype()
363 content = None
364 attachments = []
366 if content_type == 'text/plain':
367 content = self.getbody()
368 elif content_type[:10] == 'multipart/':
369 content_found = bool (content)
370 ig = ignore_alternatives and not content_found
371 for part in self.getparts():
372 new_content, new_attach = part.extract_content(content_type,
373 not content and ig)
375 # If we haven't found a text/plain part yet, take this one,
376 # otherwise make it an attachment.
377 if not content:
378 content = new_content
379 cpart = part
380 elif new_content:
381 if content_found or content_type != 'multipart/alternative':
382 attachments.append(part.text_as_attachment())
383 else:
384 # if we have found a text/plain in the current
385 # multipart/alternative and find another one, we
386 # use the first as an attachment (if configured)
387 # and use the second one because rfc 2046, sec.
388 # 5.1.4. specifies that later parts are better
389 # (thanks to Philipp Gortan for pointing this
390 # out)
391 attachments.append(cpart.text_as_attachment())
392 content = new_content
393 cpart = part
395 attachments.extend(new_attach)
396 if ig and content_type == 'multipart/alternative' and content:
397 attachments = []
398 elif (parent_type == 'multipart/signed' and
399 content_type == 'application/pgp-signature'):
400 # ignore it so it won't be saved as an attachment
401 pass
402 else:
403 attachments.append(self.as_attachment())
404 return content, attachments
406 def text_as_attachment(self):
407 """Return first text/plain part as Message"""
408 if not self.gettype().startswith ('multipart/'):
409 return self.as_attachment()
410 for part in self.getparts():
411 content_type = part.gettype()
412 if content_type == 'text/plain':
413 return part.as_attachment()
414 elif content_type.startswith ('multipart/'):
415 p = part.text_as_attachment()
416 if p:
417 return p
418 return None
420 def as_attachment(self):
421 """Return this message as an attachment."""
422 return (self.getname(), self.gettype(), self.getbody())
424 def pgp_signed(self):
425 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
426 '''
427 return self.gettype() == 'multipart/signed' \
428 and self.typeheader.find('protocol="application/pgp-signature"') != -1
430 def pgp_encrypted(self):
431 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
432 '''
433 return self.gettype() == 'multipart/encrypted' \
434 and self.typeheader.find('protocol="application/pgp-encrypted"') != -1
436 def decrypt(self, author):
437 ''' decrypt an OpenPGP MIME message
438 This message must be signed as well as encrypted using the "combined"
439 method. The decrypted contents are returned as a new message.
440 '''
441 (hdr, msg) = self.getparts()
442 # According to the RFC 3156 encrypted mail must have exactly two parts.
443 # The first part contains the control information. Let's verify that
444 # the message meets the RFC before we try to decrypt it.
445 if hdr.getbody() != 'Version: 1' or hdr.gettype() != 'application/pgp-encrypted':
446 raise MailUsageError, \
447 _("Unknown multipart/encrypted version.")
449 context = pyme.core.Context()
450 ciphertext = pyme.core.Data(msg.getbody())
451 plaintext = pyme.core.Data()
453 result = context.op_decrypt_verify(ciphertext, plaintext)
455 if result:
456 raise MailUsageError, _("Unable to decrypt your message.")
458 # we've decrypted it but that just means they used our public
459 # key to send it to us. now check the signatures to see if it
460 # was signed by someone we trust
461 result = context.op_verify_result()
462 check_pgp_sigs(result.signatures, context, author)
464 plaintext.seek(0,0)
465 # pyme.core.Data implements a seek method with a different signature
466 # than roundup can handle. So we'll put the data in a container that
467 # the Message class can work with.
468 c = cStringIO.StringIO()
469 c.write(plaintext.read())
470 c.seek(0)
471 return Message(c)
473 def verify_signature(self, author):
474 ''' verify the signature of an OpenPGP MIME message
475 This only handles detached signatures. Old style
476 PGP mail (i.e. '-----BEGIN PGP SIGNED MESSAGE----')
477 is archaic and not supported :)
478 '''
479 # we don't check the micalg parameter...gpgme seems to
480 # figure things out on its own
481 (msg, sig) = self.getparts()
483 if sig.gettype() != 'application/pgp-signature':
484 raise MailUsageError, \
485 _("No PGP signature found in message.")
487 context = pyme.core.Context()
488 # msg.getbody() is skipping over some headers that are
489 # required to be present for verification to succeed so
490 # we'll do this by hand
491 msg.fp.seek(0)
492 # according to rfc 3156 the data "MUST first be converted
493 # to its content-type specific canonical form. For
494 # text/plain this means conversion to an appropriate
495 # character set and conversion of line endings to the
496 # canonical <CR><LF> sequence."
497 # TODO: what about character set conversion?
498 canonical_msg = re.sub('(?<!\r)\n', '\r\n', msg.fp.read())
499 msg_data = pyme.core.Data(canonical_msg)
500 sig_data = pyme.core.Data(sig.getbody())
502 context.op_verify(sig_data, msg_data, None)
504 # check all signatures for validity
505 result = context.op_verify_result()
506 check_pgp_sigs(result.signatures, context, author)
508 class MailGW:
510 def __init__(self, instance, arguments=()):
511 self.instance = instance
512 self.arguments = arguments
513 self.default_class = None
514 for option, value in self.arguments:
515 if option == '-c':
516 self.default_class = value.strip()
518 self.mailer = Mailer(instance.config)
519 self.logger = logging.getLogger('mailgw')
521 # should we trap exceptions (normal usage) or pass them through
522 # (for testing)
523 self.trapExceptions = 1
525 def do_pipe(self):
526 """ Read a message from standard input and pass it to the mail handler.
528 Read into an internal structure that we can seek on (in case
529 there's an error).
531 XXX: we may want to read this into a temporary file instead...
532 """
533 s = cStringIO.StringIO()
534 s.write(sys.stdin.read())
535 s.seek(0)
536 self.main(s)
537 return 0
539 def do_mailbox(self, filename):
540 """ Read a series of messages from the specified unix mailbox file and
541 pass each to the mail handler.
542 """
543 # open the spool file and lock it
544 import fcntl
545 # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
546 if hasattr(fcntl, 'LOCK_EX'):
547 FCNTL = fcntl
548 else:
549 import FCNTL
550 f = open(filename, 'r+')
551 fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
553 # handle and clear the mailbox
554 try:
555 from mailbox import UnixMailbox
556 mailbox = UnixMailbox(f, factory=Message)
557 # grab one message
558 message = mailbox.next()
559 while message:
560 # handle this message
561 self.handle_Message(message)
562 message = mailbox.next()
563 # nuke the file contents
564 os.ftruncate(f.fileno(), 0)
565 except:
566 import traceback
567 traceback.print_exc()
568 return 1
569 fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
570 return 0
572 def do_imap(self, server, user='', password='', mailbox='', ssl=0,
573 cram=0):
574 ''' Do an IMAP connection
575 '''
576 import getpass, imaplib, socket
577 try:
578 if not user:
579 user = raw_input('User: ')
580 if not password:
581 password = getpass.getpass()
582 except (KeyboardInterrupt, EOFError):
583 # Ctrl C or D maybe also Ctrl Z under Windows.
584 print "\nAborted by user."
585 return 1
586 # open a connection to the server and retrieve all messages
587 try:
588 if ssl:
589 self.logger.debug('Trying server %r with ssl'%server)
590 server = imaplib.IMAP4_SSL(server)
591 else:
592 self.logger.debug('Trying server %r without ssl'%server)
593 server = imaplib.IMAP4(server)
594 except (imaplib.IMAP4.error, socket.error, socket.sslerror):
595 self.logger.exception('IMAP server error')
596 return 1
598 try:
599 if cram:
600 server.login_cram_md5(user, password)
601 else:
602 server.login(user, password)
603 except imaplib.IMAP4.error, e:
604 self.logger.exception('IMAP login failure')
605 return 1
607 try:
608 if not mailbox:
609 (typ, data) = server.select()
610 else:
611 (typ, data) = server.select(mailbox=mailbox)
612 if typ != 'OK':
613 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
614 data))
615 return 1
616 try:
617 numMessages = int(data[0])
618 except ValueError, value:
619 self.logger.error('Invalid message count from mailbox %r'%
620 data[0])
621 return 1
622 for i in range(1, numMessages+1):
623 (typ, data) = server.fetch(str(i), '(RFC822)')
625 # mark the message as deleted.
626 server.store(str(i), '+FLAGS', r'(\Deleted)')
628 # process the message
629 s = cStringIO.StringIO(data[0][1])
630 s.seek(0)
631 self.handle_Message(Message(s))
632 server.close()
633 finally:
634 try:
635 server.expunge()
636 except:
637 pass
638 server.logout()
640 return 0
643 def do_apop(self, server, user='', password='', ssl=False):
644 ''' Do authentication POP
645 '''
646 self._do_pop(server, user, password, True, ssl)
648 def do_pop(self, server, user='', password='', ssl=False):
649 ''' Do plain POP
650 '''
651 self._do_pop(server, user, password, False, ssl)
653 def _do_pop(self, server, user, password, apop, ssl):
654 '''Read a series of messages from the specified POP server.
655 '''
656 import getpass, poplib, socket
657 try:
658 if not user:
659 user = raw_input('User: ')
660 if not password:
661 password = getpass.getpass()
662 except (KeyboardInterrupt, EOFError):
663 # Ctrl C or D maybe also Ctrl Z under Windows.
664 print "\nAborted by user."
665 return 1
667 # open a connection to the server and retrieve all messages
668 try:
669 if ssl:
670 klass = poplib.POP3_SSL
671 else:
672 klass = poplib.POP3
673 server = klass(server)
674 except socket.error:
675 self.logger.exception('POP server error')
676 return 1
677 if apop:
678 server.apop(user, password)
679 else:
680 server.user(user)
681 server.pass_(password)
682 numMessages = len(server.list()[1])
683 for i in range(1, numMessages+1):
684 # retr: returns
685 # [ pop response e.g. '+OK 459 octets',
686 # [ array of message lines ],
687 # number of octets ]
688 lines = server.retr(i)[1]
689 s = cStringIO.StringIO('\n'.join(lines))
690 s.seek(0)
691 self.handle_Message(Message(s))
692 # delete the message
693 server.dele(i)
695 # quit the server to commit changes.
696 server.quit()
697 return 0
699 def main(self, fp):
700 ''' fp - the file from which to read the Message.
701 '''
702 return self.handle_Message(Message(fp))
704 def handle_Message(self, message):
705 """Handle an RFC822 Message
707 Handle the Message object by calling handle_message() and then cope
708 with any errors raised by handle_message.
709 This method's job is to make that call and handle any
710 errors in a sane manner. It should be replaced if you wish to
711 handle errors in a different manner.
712 """
713 # in some rare cases, a particularly stuffed-up e-mail will make
714 # its way into here... try to handle it gracefully
716 sendto = message.getaddrlist('resent-from')
717 if not sendto:
718 sendto = message.getaddrlist('from')
719 if not sendto:
720 # very bad-looking message - we don't even know who sent it
721 msg = ['Badly formed message from mail gateway. Headers:']
722 msg.extend(message.headers)
723 msg = '\n'.join(map(str, msg))
724 self.logger.error(msg)
725 return
727 msg = 'Handling message'
728 if message.getheader('message-id'):
729 msg += ' (Message-id=%r)'%message.getheader('message-id')
730 self.logger.info(msg)
732 # try normal message-handling
733 if not self.trapExceptions:
734 return self.handle_message(message)
736 # no, we want to trap exceptions
737 try:
738 return self.handle_message(message)
739 except MailUsageHelp:
740 # bounce the message back to the sender with the usage message
741 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
742 m = ['']
743 m.append('\n\nMail Gateway Help\n=================')
744 m.append(fulldoc)
745 self.mailer.bounce_message(message, [sendto[0][1]], m,
746 subject="Mail Gateway Help")
747 except MailUsageError, value:
748 # bounce the message back to the sender with the usage message
749 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
750 m = ['']
751 m.append(str(value))
752 m.append('\n\nMail Gateway Help\n=================')
753 m.append(fulldoc)
754 self.mailer.bounce_message(message, [sendto[0][1]], m)
755 except Unauthorized, value:
756 # just inform the user that he is not authorized
757 m = ['']
758 m.append(str(value))
759 self.mailer.bounce_message(message, [sendto[0][1]], m)
760 except IgnoreMessage:
761 # do not take any action
762 # this exception is thrown when email should be ignored
763 msg = 'IgnoreMessage raised'
764 if message.getheader('message-id'):
765 msg += ' (Message-id=%r)'%message.getheader('message-id')
766 self.logger.info(msg)
767 return
768 except:
769 msg = 'Exception handling message'
770 if message.getheader('message-id'):
771 msg += ' (Message-id=%r)'%message.getheader('message-id')
772 self.logger.exception(msg)
774 # bounce the message back to the sender with the error message
775 # let the admin know that something very bad is happening
776 m = ['']
777 m.append('An unexpected error occurred during the processing')
778 m.append('of your message. The tracker administrator is being')
779 m.append('notified.\n')
780 self.mailer.bounce_message(message, [sendto[0][1]], m)
782 m.append('----------------')
783 m.append(traceback.format_exc())
784 self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
786 def handle_message(self, message):
787 ''' message - a Message instance
789 Parse the message as per the module docstring.
790 '''
791 # get database handle for handling one email
792 self.db = self.instance.open ('admin')
793 try:
794 return self._handle_message (message)
795 finally:
796 self.db.close()
798 def _handle_message(self, message):
799 ''' message - a Message instance
801 Parse the message as per the module docstring.
803 The implementation expects an opened database and a try/finally
804 that closes the database.
805 '''
806 # detect loops
807 if message.getheader('x-roundup-loop', ''):
808 raise IgnoreLoop
810 # handle the subject line
811 subject = message.getheader('subject', '')
812 if not subject:
813 raise MailUsageError, _("""
814 Emails to Roundup trackers must include a Subject: line!
815 """)
817 # detect Precedence: Bulk, or Microsoft Outlook autoreplies
818 if (message.getheader('precedence', '') == 'bulk'
819 or subject.lower().find("autoreply") > 0):
820 raise IgnoreBulk
822 if subject.strip().lower() == 'help':
823 raise MailUsageHelp
825 # config is used many times in this method.
826 # make local variable for easier access
827 config = self.instance.config
829 # determine the sender's address
830 from_list = message.getaddrlist('resent-from')
831 if not from_list:
832 from_list = message.getaddrlist('from')
834 # XXX Don't enable. This doesn't work yet.
835 # "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
836 # handle delivery to addresses like:tracker+issue25@some.dom.ain
837 # use the embedded issue number as our issue
838 # issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
839 # if issue_re:
840 # for header in ['to', 'cc', 'bcc']:
841 # addresses = message.getheader(header, '')
842 # if addresses:
843 # # FIXME, this only finds the first match in the addresses.
844 # issue = re.search(issue_re, addresses, 'i')
845 # if issue:
846 # classname = issue.group('classname')
847 # nodeid = issue.group('nodeid')
848 # break
850 # Matches subjects like:
851 # Re: "[issue1234] title of issue [status=resolved]"
853 # Alias since we need a reference to the original subject for
854 # later use in error messages
855 tmpsubject = subject
857 sd_open, sd_close = config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
858 delim_open = re.escape(sd_open)
859 if delim_open in '[(': delim_open = '\\' + delim_open
860 delim_close = re.escape(sd_close)
861 if delim_close in '[(': delim_close = '\\' + delim_close
863 matches = dict.fromkeys(['refwd', 'quote', 'classname',
864 'nodeid', 'title', 'args',
865 'argswhole'])
867 # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
868 re_re = r"(?P<refwd>%s)\s*" % config["MAILGW_REFWD_RE"].pattern
869 m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
870 if m:
871 m = m.groupdict()
872 if m['refwd']:
873 matches.update(m)
874 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
876 # Look for Leading "
877 m = re.match(r'(?P<quote>\s*")', tmpsubject,
878 re.IGNORECASE)
879 if m:
880 matches.update(m.groupdict())
881 tmpsubject = tmpsubject[len(matches['quote']):] # Consume quote
883 has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
884 delim_close), tmpsubject.strip())
886 class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
887 "|".join(self.db.getclasses()), delim_close)
888 # Note: re.search, not re.match as there might be garbage
889 # (mailing list prefix, etc.) before the class identifier
890 m = re.search(class_re, tmpsubject, re.IGNORECASE)
891 if m:
892 matches.update(m.groupdict())
893 # Skip to the end of the class identifier, including any
894 # garbage before it.
896 tmpsubject = tmpsubject[m.end():]
898 # if we've not found a valid classname prefix then force the
899 # scanning to handle there being a leading delimiter
900 title_re = r'(?P<title>%s[^%s]+)'%(
901 not matches['classname'] and '.' or '', delim_open)
902 m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
903 if m:
904 matches.update(m.groupdict())
905 tmpsubject = tmpsubject[len(matches['title']):] # Consume title
907 args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
908 delim_close)
909 m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
910 if m:
911 matches.update(m.groupdict())
913 # figure subject line parsing modes
914 pfxmode = config['MAILGW_SUBJECT_PREFIX_PARSING']
915 sfxmode = config['MAILGW_SUBJECT_SUFFIX_PARSING']
917 # check for registration OTK
918 # or fallback on the default class
919 if self.db.config['EMAIL_REGISTRATION_CONFIRMATION']:
920 otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
921 otk = otk_re.search(matches['title'] or '')
922 if otk:
923 self.db.confirm_registration(otk.group('otk'))
924 subject = 'Your registration to %s is complete' % \
925 config['TRACKER_NAME']
926 sendto = [from_list[0][1]]
927 self.mailer.standard_message(sendto, subject, '')
928 return
930 # get the classname
931 if pfxmode == 'none':
932 classname = None
933 else:
934 classname = matches['classname']
936 if not classname and has_prefix and pfxmode == 'strict':
937 raise MailUsageError, _("""
938 The message you sent to roundup did not contain a properly formed subject
939 line. The subject must contain a class name or designator to indicate the
940 'topic' of the message. For example:
941 Subject: [issue] This is a new issue
942 - this will create a new issue in the tracker with the title 'This is
943 a new issue'.
944 Subject: [issue1234] This is a followup to issue 1234
945 - this will append the message's contents to the existing issue 1234
946 in the tracker.
948 Subject was: '%(subject)s'
949 """) % locals()
951 # try to get the class specified - if "loose" or "none" then fall
952 # back on the default
953 attempts = []
954 if classname:
955 attempts.append(classname)
957 if self.default_class:
958 attempts.append(self.default_class)
959 else:
960 attempts.append(config['MAILGW_DEFAULT_CLASS'])
962 # first valid class name wins
963 cl = None
964 for trycl in attempts:
965 try:
966 cl = self.db.getclass(trycl)
967 classname = trycl
968 break
969 except KeyError:
970 pass
972 if not cl:
973 validname = ', '.join(self.db.getclasses())
974 if classname:
975 raise MailUsageError, _("""
976 The class name you identified in the subject line ("%(classname)s") does
977 not exist in the database.
979 Valid class names are: %(validname)s
980 Subject was: "%(subject)s"
981 """) % locals()
982 else:
983 raise MailUsageError, _("""
984 You did not identify a class name in the subject line and there is no
985 default set for this tracker. The subject must contain a class name or
986 designator to indicate the 'topic' of the message. For example:
987 Subject: [issue] This is a new issue
988 - this will create a new issue in the tracker with the title 'This is
989 a new issue'.
990 Subject: [issue1234] This is a followup to issue 1234
991 - this will append the message's contents to the existing issue 1234
992 in the tracker.
994 Subject was: '%(subject)s'
995 """) % locals()
997 # get the optional nodeid
998 if pfxmode == 'none':
999 nodeid = None
1000 else:
1001 nodeid = matches['nodeid']
1003 # try in-reply-to to match the message if there's no nodeid
1004 inreplyto = message.getheader('in-reply-to') or ''
1005 if nodeid is None and inreplyto:
1006 l = self.db.getclass('msg').stringFind(messageid=inreplyto)
1007 if l:
1008 nodeid = cl.filter(None, {'messages':l})[0]
1010 # title is optional too
1011 title = matches['title']
1012 if title:
1013 title = title.strip()
1014 else:
1015 title = ''
1017 # strip off the quotes that dumb emailers put around the subject, like
1018 # Re: "[issue1] bla blah"
1019 if matches['quote'] and title.endswith('"'):
1020 title = title[:-1]
1022 # but we do need either a title or a nodeid...
1023 if nodeid is None and not title:
1024 raise MailUsageError, _("""
1025 I cannot match your message to a node in the database - you need to either
1026 supply a full designator (with number, eg "[issue123]") or keep the
1027 previous subject title intact so I can match that.
1029 Subject was: "%(subject)s"
1030 """) % locals()
1032 # If there's no nodeid, check to see if this is a followup and
1033 # maybe someone's responded to the initial mail that created an
1034 # entry. Try to find the matching nodes with the same title, and
1035 # use the _last_ one matched (since that'll _usually_ be the most
1036 # recent...). The subject_content_match config may specify an
1037 # additional restriction based on the matched node's creation or
1038 # activity.
1039 tmatch_mode = config['MAILGW_SUBJECT_CONTENT_MATCH']
1040 if tmatch_mode != 'never' and nodeid is None and matches['refwd']:
1041 l = cl.stringFind(title=title)
1042 limit = None
1043 if (tmatch_mode.startswith('creation') or
1044 tmatch_mode.startswith('activity')):
1045 limit, interval = tmatch_mode.split(' ', 1)
1046 threshold = date.Date('.') - date.Interval(interval)
1047 for id in l:
1048 if limit:
1049 if threshold < cl.get(id, limit):
1050 nodeid = id
1051 else:
1052 nodeid = id
1054 # if a nodeid was specified, make sure it's valid
1055 if nodeid is not None and not cl.hasnode(nodeid):
1056 if pfxmode == 'strict':
1057 raise MailUsageError, _("""
1058 The node specified by the designator in the subject of your message
1059 ("%(nodeid)s") does not exist.
1061 Subject was: "%(subject)s"
1062 """) % locals()
1063 else:
1064 title = subject
1065 nodeid = None
1067 # Handle the arguments specified by the email gateway command line.
1068 # We do this by looping over the list of self.arguments looking for
1069 # a -C to tell us what class then the -S setting string.
1070 msg_props = {}
1071 user_props = {}
1072 file_props = {}
1073 issue_props = {}
1074 # so, if we have any arguments, use them
1075 if self.arguments:
1076 current_class = 'msg'
1077 for option, propstring in self.arguments:
1078 if option in ( '-C', '--class'):
1079 current_class = propstring.strip()
1080 # XXX this is not flexible enough.
1081 # we should chect for subclasses of these classes,
1082 # not for the class name...
1083 if current_class not in ('msg', 'file', 'user', 'issue'):
1084 mailadmin = config['ADMIN_EMAIL']
1085 raise MailUsageError, _("""
1086 The mail gateway is not properly set up. Please contact
1087 %(mailadmin)s and have them fix the incorrect class specified as:
1088 %(current_class)s
1089 """) % locals()
1090 if option in ('-S', '--set'):
1091 if current_class == 'issue' :
1092 errors, issue_props = setPropArrayFromString(self,
1093 cl, propstring.strip(), nodeid)
1094 elif current_class == 'file' :
1095 temp_cl = self.db.getclass('file')
1096 errors, file_props = setPropArrayFromString(self,
1097 temp_cl, propstring.strip())
1098 elif current_class == 'msg' :
1099 temp_cl = self.db.getclass('msg')
1100 errors, msg_props = setPropArrayFromString(self,
1101 temp_cl, propstring.strip())
1102 elif current_class == 'user' :
1103 temp_cl = self.db.getclass('user')
1104 errors, user_props = setPropArrayFromString(self,
1105 temp_cl, propstring.strip())
1106 if errors:
1107 mailadmin = config['ADMIN_EMAIL']
1108 raise MailUsageError, _("""
1109 The mail gateway is not properly set up. Please contact
1110 %(mailadmin)s and have them fix the incorrect properties:
1111 %(errors)s
1112 """) % locals()
1114 #
1115 # handle the users
1116 #
1117 # Don't create users if anonymous isn't allowed to register
1118 create = 1
1119 anonid = self.db.user.lookup('anonymous')
1120 if not (self.db.security.hasPermission('Register', anonid, 'user')
1121 and self.db.security.hasPermission('Email Access', anonid)):
1122 create = 0
1124 # ok, now figure out who the author is - create a new user if the
1125 # "create" flag is true
1126 author = uidFromAddress(self.db, from_list[0], create=create)
1128 # if we're not recognised, and we don't get added as a user, then we
1129 # must be anonymous
1130 if not author:
1131 author = anonid
1133 # make sure the author has permission to use the email interface
1134 if not self.db.security.hasPermission('Email Access', author):
1135 if author == anonid:
1136 # we're anonymous and we need to be a registered user
1137 from_address = from_list[0][1]
1138 registration_info = ""
1139 if self.db.security.hasPermission('Web Access', author) and \
1140 self.db.security.hasPermission('Register', anonid, 'user'):
1141 tracker_web = self.instance.config.TRACKER_WEB
1142 registration_info = """ Please register at:
1144 %(tracker_web)suser?template=register
1146 ...before sending mail to the tracker.""" % locals()
1148 raise Unauthorized, _("""
1149 You are not a registered user.%(registration_info)s
1151 Unknown address: %(from_address)s
1152 """) % locals()
1153 else:
1154 # we're registered and we're _still_ not allowed access
1155 raise Unauthorized, _(
1156 'You are not permitted to access this tracker.')
1158 # make sure they're allowed to edit or create this class of information
1159 if nodeid:
1160 if not self.db.security.hasPermission('Edit', author, classname,
1161 itemid=nodeid):
1162 raise Unauthorized, _(
1163 'You are not permitted to edit %(classname)s.') % locals()
1164 else:
1165 if not self.db.security.hasPermission('Create', author, classname):
1166 raise Unauthorized, _(
1167 'You are not permitted to create %(classname)s.'
1168 ) % locals()
1170 # the author may have been created - make sure the change is
1171 # committed before we reopen the database
1172 self.db.commit()
1174 # set the database user as the author
1175 username = self.db.user.get(author, 'username')
1176 self.db.setCurrentUser(username)
1178 # re-get the class with the new database connection
1179 cl = self.db.getclass(classname)
1181 # now update the recipients list
1182 recipients = []
1183 tracker_email = config['TRACKER_EMAIL'].lower()
1184 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
1185 r = recipient[1].strip().lower()
1186 if r == tracker_email or not r:
1187 continue
1189 # look up the recipient - create if necessary (and we're
1190 # allowed to)
1191 recipient = uidFromAddress(self.db, recipient, create, **user_props)
1193 # if all's well, add the recipient to the list
1194 if recipient:
1195 recipients.append(recipient)
1197 #
1198 # handle the subject argument list
1199 #
1200 # figure what the properties of this Class are
1201 properties = cl.getprops()
1202 props = {}
1203 args = matches['args']
1204 argswhole = matches['argswhole']
1205 if args:
1206 if sfxmode == 'none':
1207 title += ' ' + argswhole
1208 else:
1209 errors, props = setPropArrayFromString(self, cl, args, nodeid)
1210 # handle any errors parsing the argument list
1211 if errors:
1212 if sfxmode == 'strict':
1213 errors = '\n- '.join(map(str, errors))
1214 raise MailUsageError, _("""
1215 There were problems handling your subject line argument list:
1216 - %(errors)s
1218 Subject was: "%(subject)s"
1219 """) % locals()
1220 else:
1221 title += ' ' + argswhole
1224 # set the issue title to the subject
1225 title = title.strip()
1226 if (title and properties.has_key('title') and not
1227 issue_props.has_key('title')):
1228 issue_props['title'] = title
1230 #
1231 # handle message-id and in-reply-to
1232 #
1233 messageid = message.getheader('message-id')
1234 # generate a messageid if there isn't one
1235 if not messageid:
1236 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1237 classname, nodeid, config['MAIL_DOMAIN'])
1239 # if they've enabled PGP processing then verify the signature
1240 # or decrypt the message
1242 # if PGP_ROLES is specified the user must have a Role in the list
1243 # or we will skip PGP processing
1244 def pgp_role():
1245 if self.instance.config.PGP_ROLES:
1246 return self.db.user.has_role(author,
1247 iter_roles(self.instance.config.PGP_ROLES))
1248 else:
1249 return True
1251 if self.instance.config.PGP_ENABLE and pgp_role():
1252 assert pyme, 'pyme is not installed'
1253 # signed/encrypted mail must come from the primary address
1254 author_address = self.db.user.get(author, 'address')
1255 if self.instance.config.PGP_HOMEDIR:
1256 os.environ['GNUPGHOME'] = self.instance.config.PGP_HOMEDIR
1257 if message.pgp_signed():
1258 message.verify_signature(author_address)
1259 elif message.pgp_encrypted():
1260 # replace message with the contents of the decrypted
1261 # message for content extraction
1262 # TODO: encrypted message handling is far from perfect
1263 # bounces probably include the decrypted message, for
1264 # instance :(
1265 message = message.decrypt(author_address)
1266 else:
1267 raise MailUsageError, _("""
1268 This tracker has been configured to require all email be PGP signed or
1269 encrypted.""")
1270 # now handle the body - find the message
1271 ig = self.instance.config.MAILGW_IGNORE_ALTERNATIVES
1272 content, attachments = message.extract_content(ignore_alternatives = ig)
1273 if content is None:
1274 raise MailUsageError, _("""
1275 Roundup requires the submission to be plain text. The message parser could
1276 not find a text/plain part to use.
1277 """)
1279 # parse the body of the message, stripping out bits as appropriate
1280 summary, content = parseContent(content, config=config)
1281 content = content.strip()
1283 #
1284 # handle the attachments
1285 #
1286 files = []
1287 if attachments and properties.has_key('files'):
1288 for (name, mime_type, data) in attachments:
1289 if not self.db.security.hasPermission('Create', author, 'file'):
1290 raise Unauthorized, _(
1291 'You are not permitted to create files.')
1292 if not name:
1293 name = "unnamed"
1294 try:
1295 fileid = self.db.file.create(type=mime_type, name=name,
1296 content=data, **file_props)
1297 except exceptions.Reject:
1298 pass
1299 else:
1300 files.append(fileid)
1301 # allowed to attach the files to an existing node?
1302 if nodeid and not self.db.security.hasPermission('Edit', author,
1303 classname, 'files'):
1304 raise Unauthorized, _(
1305 'You are not permitted to add files to %(classname)s.'
1306 ) % locals()
1308 if nodeid:
1309 # extend the existing files list
1310 fileprop = cl.get(nodeid, 'files')
1311 fileprop.extend(files)
1312 props['files'] = fileprop
1313 else:
1314 # pre-load the files list
1315 props['files'] = files
1317 #
1318 # create the message if there's a message body (content)
1319 #
1320 if (content and properties.has_key('messages')):
1321 if not self.db.security.hasPermission('Create', author, 'msg'):
1322 raise Unauthorized, _(
1323 'You are not permitted to create messages.')
1325 try:
1326 message_id = self.db.msg.create(author=author,
1327 recipients=recipients, date=date.Date('.'),
1328 summary=summary, content=content, files=files,
1329 messageid=messageid, inreplyto=inreplyto, **msg_props)
1330 except exceptions.Reject, error:
1331 raise MailUsageError, _("""
1332 Mail message was rejected by a detector.
1333 %(error)s
1334 """) % locals()
1335 # allowed to attach the message to the existing node?
1336 if nodeid and not self.db.security.hasPermission('Edit', author,
1337 classname, 'messages'):
1338 raise Unauthorized, _(
1339 'You are not permitted to add messages to %(classname)s.'
1340 ) % locals()
1342 if nodeid:
1343 # add the message to the node's list
1344 messages = cl.get(nodeid, 'messages')
1345 messages.append(message_id)
1346 props['messages'] = messages
1347 else:
1348 # pre-load the messages list
1349 props['messages'] = [message_id]
1351 #
1352 # perform the node change / create
1353 #
1354 try:
1355 # merge the command line props defined in issue_props into
1356 # the props dictionary because function(**props, **issue_props)
1357 # is a syntax error.
1358 for prop in issue_props.keys() :
1359 if not props.has_key(prop) :
1360 props[prop] = issue_props[prop]
1362 if nodeid:
1363 # Check permissions for each property
1364 for prop in props.keys():
1365 if not self.db.security.hasPermission('Edit', author,
1366 classname, prop):
1367 raise Unauthorized, _('You are not permitted to edit '
1368 'property %(prop)s of class %(classname)s.') % locals()
1369 cl.set(nodeid, **props)
1370 else:
1371 # Check permissions for each property
1372 for prop in props.keys():
1373 if not self.db.security.hasPermission('Create', author,
1374 classname, prop):
1375 raise Unauthorized, _('You are not permitted to set '
1376 'property %(prop)s of class %(classname)s.') % locals()
1377 nodeid = cl.create(**props)
1378 except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1379 raise MailUsageError, _("""
1380 There was a problem with the message you sent:
1381 %(message)s
1382 """) % locals()
1384 # commit the changes to the DB
1385 self.db.commit()
1387 return nodeid
1390 def setPropArrayFromString(self, cl, propString, nodeid=None):
1391 ''' takes string of form prop=value,value;prop2=value
1392 and returns (error, prop[..])
1393 '''
1394 props = {}
1395 errors = []
1396 for prop in string.split(propString, ';'):
1397 # extract the property name and value
1398 try:
1399 propname, value = prop.split('=')
1400 except ValueError, message:
1401 errors.append(_('not of form [arg=value,value,...;'
1402 'arg=value,value,...]'))
1403 return (errors, props)
1404 # convert the value to a hyperdb-usable value
1405 propname = propname.strip()
1406 try:
1407 props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1408 propname, value)
1409 except hyperdb.HyperdbValueError, message:
1410 errors.append(str(message))
1411 return errors, props
1414 def extractUserFromList(userClass, users):
1415 '''Given a list of users, try to extract the first non-anonymous user
1416 and return that user, otherwise return None
1417 '''
1418 if len(users) > 1:
1419 for user in users:
1420 # make sure we don't match the anonymous or admin user
1421 if userClass.get(user, 'username') in ('admin', 'anonymous'):
1422 continue
1423 # first valid match will do
1424 return user
1425 # well, I guess we have no choice
1426 return user[0]
1427 elif users:
1428 return users[0]
1429 return None
1432 def uidFromAddress(db, address, create=1, **user_props):
1433 ''' address is from the rfc822 module, and therefore is (name, addr)
1435 user is created if they don't exist in the db already
1436 user_props may supply additional user information
1437 '''
1438 (realname, address) = address
1440 # try a straight match of the address
1441 user = extractUserFromList(db.user, db.user.stringFind(address=address))
1442 if user is not None:
1443 return user
1445 # try the user alternate addresses if possible
1446 props = db.user.getprops()
1447 if props.has_key('alternate_addresses'):
1448 users = db.user.filter(None, {'alternate_addresses': address})
1449 user = extractUserFromList(db.user, users)
1450 if user is not None:
1451 return user
1453 # try to match the username to the address (for local
1454 # submissions where the address is empty)
1455 user = extractUserFromList(db.user, db.user.stringFind(username=address))
1457 # couldn't match address or username, so create a new user
1458 if create:
1459 # generate a username
1460 if '@' in address:
1461 username = address.split('@')[0]
1462 else:
1463 username = address
1464 trying = username
1465 n = 0
1466 while 1:
1467 try:
1468 # does this username exist already?
1469 db.user.lookup(trying)
1470 except KeyError:
1471 break
1472 n += 1
1473 trying = username + str(n)
1475 # create!
1476 try:
1477 return db.user.create(username=trying, address=address,
1478 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1479 password=password.Password(password.generatePassword()),
1480 **user_props)
1481 except exceptions.Reject:
1482 return 0
1483 else:
1484 return 0
1486 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1487 """Parse mail message; return message summary and stripped content
1489 The message body is divided into sections by blank lines.
1490 Sections where the second and all subsequent lines begin with a ">"
1491 or "|" character are considered "quoting sections". The first line of
1492 the first non-quoting section becomes the summary of the message.
1494 Arguments:
1496 keep_citations: declared for backward compatibility.
1497 If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1499 keep_body: declared for backward compatibility.
1500 If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1502 config: tracker configuration object.
1503 If omitted or None, use default configuration.
1505 """
1506 if config is None:
1507 config = configuration.CoreConfig()
1508 if keep_citations is None:
1509 keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1510 if keep_body is None:
1511 keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1512 eol = config["MAILGW_EOL_RE"]
1513 signature = config["MAILGW_SIGN_RE"]
1514 original_msg = config["MAILGW_ORIGMSG_RE"]
1516 # strip off leading carriage-returns / newlines
1517 i = 0
1518 for i in range(len(content)):
1519 if content[i] not in '\r\n':
1520 break
1521 if i > 0:
1522 sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1523 else:
1524 sections = config["MAILGW_BLANKLINE_RE"].split(content)
1526 # extract out the summary from the message
1527 summary = ''
1528 l = []
1529 for section in sections:
1530 #section = section.strip()
1531 if not section:
1532 continue
1533 lines = eol.split(section)
1534 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1535 lines[1] and lines[1][0] in '>|'):
1536 # see if there's a response somewhere inside this section (ie.
1537 # no blank line between quoted message and response)
1538 for line in lines[1:]:
1539 if line and line[0] not in '>|':
1540 break
1541 else:
1542 # we keep quoted bits if specified in the config
1543 if keep_citations:
1544 l.append(section)
1545 continue
1546 # keep this section - it has reponse stuff in it
1547 lines = lines[lines.index(line):]
1548 section = '\n'.join(lines)
1549 # and while we're at it, use the first non-quoted bit as
1550 # our summary
1551 summary = section
1553 if not summary:
1554 # if we don't have our summary yet use the first line of this
1555 # section
1556 summary = section
1557 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1558 # lose any signature
1559 break
1560 elif original_msg.match(lines[0]):
1561 # ditch the stupid Outlook quoting of the entire original message
1562 break
1564 # and add the section to the output
1565 l.append(section)
1567 # figure the summary - find the first sentence-ending punctuation or the
1568 # first whole line, whichever is longest
1569 sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1570 if sentence:
1571 sentence = sentence.group(1)
1572 else:
1573 sentence = ''
1574 first = eol.split(summary)[0]
1575 summary = max(sentence, first)
1577 # Now reconstitute the message content minus the bits we don't care
1578 # about.
1579 if not keep_body:
1580 content = '\n\n'.join(l)
1582 return summary, content
1584 # vim: set filetype=python sts=4 sw=4 et si :