Code

- fix explicit python version description and mention the password for
[roundup.git] / roundup / mailgw.py
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         ''' Do an IMAP connection
574         '''
575         import getpass, imaplib, socket
576         try:
577             if not user:
578                 user = raw_input('User: ')
579             if not password:
580                 password = getpass.getpass()
581         except (KeyboardInterrupt, EOFError):
582             # Ctrl C or D maybe also Ctrl Z under Windows.
583             print "\nAborted by user."
584             return 1
585         # open a connection to the server and retrieve all messages
586         try:
587             if ssl:
588                 self.logger.debug('Trying server %r with ssl'%server)
589                 server = imaplib.IMAP4_SSL(server)
590             else:
591                 self.logger.debug('Trying server %r without ssl'%server)
592                 server = imaplib.IMAP4(server)
593         except (imaplib.IMAP4.error, socket.error, socket.sslerror):
594             self.logger.exception('IMAP server error')
595             return 1
597         try:
598             server.login(user, password)
599         except imaplib.IMAP4.error, e:
600             self.logger.exception('IMAP login failure')
601             return 1
603         try:
604             if not mailbox:
605                 (typ, data) = server.select()
606             else:
607                 (typ, data) = server.select(mailbox=mailbox)
608             if typ != 'OK':
609                 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
610                     data))
611                 return 1
612             try:
613                 numMessages = int(data[0])
614             except ValueError, value:
615                 self.logger.error('Invalid message count from mailbox %r'%
616                     data[0])
617                 return 1
618             for i in range(1, numMessages+1):
619                 (typ, data) = server.fetch(str(i), '(RFC822)')
621                 # mark the message as deleted.
622                 server.store(str(i), '+FLAGS', r'(\Deleted)')
624                 # process the message
625                 s = cStringIO.StringIO(data[0][1])
626                 s.seek(0)
627                 self.handle_Message(Message(s))
628             server.close()
629         finally:
630             try:
631                 server.expunge()
632             except:
633                 pass
634             server.logout()
636         return 0
639     def do_apop(self, server, user='', password='', ssl=False):
640         ''' Do authentication POP
641         '''
642         self._do_pop(server, user, password, True, ssl)
644     def do_pop(self, server, user='', password='', ssl=False):
645         ''' Do plain POP
646         '''
647         self._do_pop(server, user, password, False, ssl)
649     def _do_pop(self, server, user, password, apop, ssl):
650         '''Read a series of messages from the specified POP server.
651         '''
652         import getpass, poplib, socket
653         try:
654             if not user:
655                 user = raw_input('User: ')
656             if not password:
657                 password = getpass.getpass()
658         except (KeyboardInterrupt, EOFError):
659             # Ctrl C or D maybe also Ctrl Z under Windows.
660             print "\nAborted by user."
661             return 1
663         # open a connection to the server and retrieve all messages
664         try:
665             if ssl:
666                 klass = poplib.POP3_SSL
667             else:
668                 klass = poplib.POP3
669             server = klass(server)
670         except socket.error:
671             self.logger.exception('POP server error')
672             return 1
673         if apop:
674             server.apop(user, password)
675         else:
676             server.user(user)
677             server.pass_(password)
678         numMessages = len(server.list()[1])
679         for i in range(1, numMessages+1):
680             # retr: returns
681             # [ pop response e.g. '+OK 459 octets',
682             #   [ array of message lines ],
683             #   number of octets ]
684             lines = server.retr(i)[1]
685             s = cStringIO.StringIO('\n'.join(lines))
686             s.seek(0)
687             self.handle_Message(Message(s))
688             # delete the message
689             server.dele(i)
691         # quit the server to commit changes.
692         server.quit()
693         return 0
695     def main(self, fp):
696         ''' fp - the file from which to read the Message.
697         '''
698         return self.handle_Message(Message(fp))
700     def handle_Message(self, message):
701         """Handle an RFC822 Message
703         Handle the Message object by calling handle_message() and then cope
704         with any errors raised by handle_message.
705         This method's job is to make that call and handle any
706         errors in a sane manner. It should be replaced if you wish to
707         handle errors in a different manner.
708         """
709         # in some rare cases, a particularly stuffed-up e-mail will make
710         # its way into here... try to handle it gracefully
712         sendto = message.getaddrlist('resent-from')
713         if not sendto:
714             sendto = message.getaddrlist('from')
715         if not sendto:
716             # very bad-looking message - we don't even know who sent it
717             msg = ['Badly formed message from mail gateway. Headers:']
718             msg.extend(message.headers)
719             msg = '\n'.join(map(str, msg))
720             self.logger.error(msg)
721             return
723         msg = 'Handling message'
724         if message.getheader('message-id'):
725             msg += ' (Message-id=%r)'%message.getheader('message-id')
726         self.logger.info(msg)
728         # try normal message-handling
729         if not self.trapExceptions:
730             return self.handle_message(message)
732         # no, we want to trap exceptions
733         try:
734             return self.handle_message(message)
735         except MailUsageHelp:
736             # bounce the message back to the sender with the usage message
737             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
738             m = ['']
739             m.append('\n\nMail Gateway Help\n=================')
740             m.append(fulldoc)
741             self.mailer.bounce_message(message, [sendto[0][1]], m,
742                 subject="Mail Gateway Help")
743         except MailUsageError, value:
744             # bounce the message back to the sender with the usage message
745             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
746             m = ['']
747             m.append(str(value))
748             m.append('\n\nMail Gateway Help\n=================')
749             m.append(fulldoc)
750             self.mailer.bounce_message(message, [sendto[0][1]], m)
751         except Unauthorized, value:
752             # just inform the user that he is not authorized
753             m = ['']
754             m.append(str(value))
755             self.mailer.bounce_message(message, [sendto[0][1]], m)
756         except IgnoreMessage:
757             # do not take any action
758             # this exception is thrown when email should be ignored
759             msg = 'IgnoreMessage raised'
760             if message.getheader('message-id'):
761                 msg += ' (Message-id=%r)'%message.getheader('message-id')
762             self.logger.info(msg)
763             return
764         except:
765             msg = 'Exception handling message'
766             if message.getheader('message-id'):
767                 msg += ' (Message-id=%r)'%message.getheader('message-id')
768             self.logger.exception(msg)
770             # bounce the message back to the sender with the error message
771             # let the admin know that something very bad is happening
772             m = ['']
773             m.append('An unexpected error occurred during the processing')
774             m.append('of your message. The tracker administrator is being')
775             m.append('notified.\n')
776             self.mailer.bounce_message(message, [sendto[0][1]], m)
778             m.append('----------------')
779             m.append(traceback.format_exc())
780             self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
782     def handle_message(self, message):
783         ''' message - a Message instance
785         Parse the message as per the module docstring.
786         '''
787         # get database handle for handling one email
788         self.db = self.instance.open ('admin')
789         try:
790             return self._handle_message (message)
791         finally:
792             self.db.close()
794     def _handle_message(self, message):
795         ''' message - a Message instance
797         Parse the message as per the module docstring.
799         The implementation expects an opened database and a try/finally
800         that closes the database.
801         '''
802         # detect loops
803         if message.getheader('x-roundup-loop', ''):
804             raise IgnoreLoop
806         # handle the subject line
807         subject = message.getheader('subject', '')
808         if not subject:
809             raise MailUsageError, _("""
810 Emails to Roundup trackers must include a Subject: line!
811 """)
813         # detect Precedence: Bulk, or Microsoft Outlook autoreplies
814         if (message.getheader('precedence', '') == 'bulk'
815                 or subject.lower().find("autoreply") > 0):
816             raise IgnoreBulk
818         if subject.strip().lower() == 'help':
819             raise MailUsageHelp
821         # config is used many times in this method.
822         # make local variable for easier access
823         config = self.instance.config
825         # determine the sender's address
826         from_list = message.getaddrlist('resent-from')
827         if not from_list:
828             from_list = message.getaddrlist('from')
830         # XXX Don't enable. This doesn't work yet.
831 #  "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
832         # handle delivery to addresses like:tracker+issue25@some.dom.ain
833         # use the embedded issue number as our issue
834 #        issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
835 #        if issue_re:
836 #            for header in ['to', 'cc', 'bcc']:
837 #                addresses = message.getheader(header, '')
838 #            if addresses:
839 #              # FIXME, this only finds the first match in the addresses.
840 #                issue = re.search(issue_re, addresses, 'i')
841 #                if issue:
842 #                    classname = issue.group('classname')
843 #                    nodeid = issue.group('nodeid')
844 #                    break
846         # Matches subjects like:
847         # Re: "[issue1234] title of issue [status=resolved]"
849         # Alias since we need a reference to the original subject for
850         # later use in error messages
851         tmpsubject = subject
853         sd_open, sd_close = config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
854         delim_open = re.escape(sd_open)
855         if delim_open in '[(': delim_open = '\\' + delim_open
856         delim_close = re.escape(sd_close)
857         if delim_close in '[(': delim_close = '\\' + delim_close
859         matches = dict.fromkeys(['refwd', 'quote', 'classname',
860                                  'nodeid', 'title', 'args',
861                                  'argswhole'])
863         # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
864         re_re = r"(?P<refwd>%s)\s*" % config["MAILGW_REFWD_RE"].pattern
865         m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
866         if m:
867             m = m.groupdict()
868             if m['refwd']:
869                 matches.update(m)
870                 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
872         # Look for Leading "
873         m = re.match(r'(?P<quote>\s*")', tmpsubject,
874                      re.IGNORECASE)
875         if m:
876             matches.update(m.groupdict())
877             tmpsubject = tmpsubject[len(matches['quote']):] # Consume quote
879         has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
880             delim_close), tmpsubject.strip())
882         class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
883             "|".join(self.db.getclasses()), delim_close)
884         # Note: re.search, not re.match as there might be garbage
885         # (mailing list prefix, etc.) before the class identifier
886         m = re.search(class_re, tmpsubject, re.IGNORECASE)
887         if m:
888             matches.update(m.groupdict())
889             # Skip to the end of the class identifier, including any
890             # garbage before it.
892             tmpsubject = tmpsubject[m.end():]
894         # if we've not found a valid classname prefix then force the
895         # scanning to handle there being a leading delimiter
896         title_re = r'(?P<title>%s[^%s]+)'%(
897             not matches['classname'] and '.' or '', delim_open)
898         m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
899         if m:
900             matches.update(m.groupdict())
901             tmpsubject = tmpsubject[len(matches['title']):] # Consume title
903         args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
904             delim_close)
905         m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
906         if m:
907             matches.update(m.groupdict())
909         # figure subject line parsing modes
910         pfxmode = config['MAILGW_SUBJECT_PREFIX_PARSING']
911         sfxmode = config['MAILGW_SUBJECT_SUFFIX_PARSING']
913         # check for registration OTK
914         # or fallback on the default class
915         if self.db.config['EMAIL_REGISTRATION_CONFIRMATION']:
916             otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
917             otk = otk_re.search(matches['title'] or '')
918             if otk:
919                 self.db.confirm_registration(otk.group('otk'))
920                 subject = 'Your registration to %s is complete' % \
921                           config['TRACKER_NAME']
922                 sendto = [from_list[0][1]]
923                 self.mailer.standard_message(sendto, subject, '')
924                 return
926         # get the classname
927         if pfxmode == 'none':
928             classname = None
929         else:
930             classname = matches['classname']
932         if not classname and has_prefix and pfxmode == 'strict':
933             raise MailUsageError, _("""
934 The message you sent to roundup did not contain a properly formed subject
935 line. The subject must contain a class name or designator to indicate the
936 'topic' of the message. For example:
937     Subject: [issue] This is a new issue
938       - this will create a new issue in the tracker with the title 'This is
939         a new issue'.
940     Subject: [issue1234] This is a followup to issue 1234
941       - this will append the message's contents to the existing issue 1234
942         in the tracker.
944 Subject was: '%(subject)s'
945 """) % locals()
947         # try to get the class specified - if "loose" or "none" then fall
948         # back on the default
949         attempts = []
950         if classname:
951             attempts.append(classname)
953         if self.default_class:
954             attempts.append(self.default_class)
955         else:
956             attempts.append(config['MAILGW_DEFAULT_CLASS'])
958         # first valid class name wins
959         cl = None
960         for trycl in attempts:
961             try:
962                 cl = self.db.getclass(trycl)
963                 classname = trycl
964                 break
965             except KeyError:
966                 pass
968         if not cl:
969             validname = ', '.join(self.db.getclasses())
970             if classname:
971                 raise MailUsageError, _("""
972 The class name you identified in the subject line ("%(classname)s") does
973 not exist in the database.
975 Valid class names are: %(validname)s
976 Subject was: "%(subject)s"
977 """) % locals()
978             else:
979                 raise MailUsageError, _("""
980 You did not identify a class name in the subject line and there is no
981 default set for this tracker. The subject must contain a class name or
982 designator to indicate the 'topic' of the message. For example:
983     Subject: [issue] This is a new issue
984       - this will create a new issue in the tracker with the title 'This is
985         a new issue'.
986     Subject: [issue1234] This is a followup to issue 1234
987       - this will append the message's contents to the existing issue 1234
988         in the tracker.
990 Subject was: '%(subject)s'
991 """) % locals()
993         # get the optional nodeid
994         if pfxmode == 'none':
995             nodeid = None
996         else:
997             nodeid = matches['nodeid']
999         # try in-reply-to to match the message if there's no nodeid
1000         inreplyto = message.getheader('in-reply-to') or ''
1001         if nodeid is None and inreplyto:
1002             l = self.db.getclass('msg').stringFind(messageid=inreplyto)
1003             if l:
1004                 nodeid = cl.filter(None, {'messages':l})[0]
1006         # title is optional too
1007         title = matches['title']
1008         if title:
1009             title = title.strip()
1010         else:
1011             title = ''
1013         # strip off the quotes that dumb emailers put around the subject, like
1014         #      Re: "[issue1] bla blah"
1015         if matches['quote'] and title.endswith('"'):
1016             title = title[:-1]
1018         # but we do need either a title or a nodeid...
1019         if nodeid is None and not title:
1020             raise MailUsageError, _("""
1021 I cannot match your message to a node in the database - you need to either
1022 supply a full designator (with number, eg "[issue123]") or keep the
1023 previous subject title intact so I can match that.
1025 Subject was: "%(subject)s"
1026 """) % locals()
1028         # If there's no nodeid, check to see if this is a followup and
1029         # maybe someone's responded to the initial mail that created an
1030         # entry. Try to find the matching nodes with the same title, and
1031         # use the _last_ one matched (since that'll _usually_ be the most
1032         # recent...). The subject_content_match config may specify an
1033         # additional restriction based on the matched node's creation or
1034         # activity.
1035         tmatch_mode = config['MAILGW_SUBJECT_CONTENT_MATCH']
1036         if tmatch_mode != 'never' and nodeid is None and matches['refwd']:
1037             l = cl.stringFind(title=title)
1038             limit = None
1039             if (tmatch_mode.startswith('creation') or
1040                     tmatch_mode.startswith('activity')):
1041                 limit, interval = tmatch_mode.split(' ', 1)
1042                 threshold = date.Date('.') - date.Interval(interval)
1043             for id in l:
1044                 if limit:
1045                     if threshold < cl.get(id, limit):
1046                         nodeid = id
1047                 else:
1048                     nodeid = id
1050         # if a nodeid was specified, make sure it's valid
1051         if nodeid is not None and not cl.hasnode(nodeid):
1052             if pfxmode == 'strict':
1053                 raise MailUsageError, _("""
1054 The node specified by the designator in the subject of your message
1055 ("%(nodeid)s") does not exist.
1057 Subject was: "%(subject)s"
1058 """) % locals()
1059             else:
1060                 title = subject
1061                 nodeid = None
1063         # Handle the arguments specified by the email gateway command line.
1064         # We do this by looping over the list of self.arguments looking for
1065         # a -C to tell us what class then the -S setting string.
1066         msg_props = {}
1067         user_props = {}
1068         file_props = {}
1069         issue_props = {}
1070         # so, if we have any arguments, use them
1071         if self.arguments:
1072             current_class = 'msg'
1073             for option, propstring in self.arguments:
1074                 if option in ( '-C', '--class'):
1075                     current_class = propstring.strip()
1076                     # XXX this is not flexible enough.
1077                     #   we should chect for subclasses of these classes,
1078                     #   not for the class name...
1079                     if current_class not in ('msg', 'file', 'user', 'issue'):
1080                         mailadmin = config['ADMIN_EMAIL']
1081                         raise MailUsageError, _("""
1082 The mail gateway is not properly set up. Please contact
1083 %(mailadmin)s and have them fix the incorrect class specified as:
1084   %(current_class)s
1085 """) % locals()
1086                 if option in ('-S', '--set'):
1087                     if current_class == 'issue' :
1088                         errors, issue_props = setPropArrayFromString(self,
1089                             cl, propstring.strip(), nodeid)
1090                     elif current_class == 'file' :
1091                         temp_cl = self.db.getclass('file')
1092                         errors, file_props = setPropArrayFromString(self,
1093                             temp_cl, propstring.strip())
1094                     elif current_class == 'msg' :
1095                         temp_cl = self.db.getclass('msg')
1096                         errors, msg_props = setPropArrayFromString(self,
1097                             temp_cl, propstring.strip())
1098                     elif current_class == 'user' :
1099                         temp_cl = self.db.getclass('user')
1100                         errors, user_props = setPropArrayFromString(self,
1101                             temp_cl, propstring.strip())
1102                     if errors:
1103                         mailadmin = config['ADMIN_EMAIL']
1104                         raise MailUsageError, _("""
1105 The mail gateway is not properly set up. Please contact
1106 %(mailadmin)s and have them fix the incorrect properties:
1107   %(errors)s
1108 """) % locals()
1110         #
1111         # handle the users
1112         #
1113         # Don't create users if anonymous isn't allowed to register
1114         create = 1
1115         anonid = self.db.user.lookup('anonymous')
1116         if not (self.db.security.hasPermission('Register', anonid, 'user')
1117                 and self.db.security.hasPermission('Email Access', anonid)):
1118             create = 0
1120         # ok, now figure out who the author is - create a new user if the
1121         # "create" flag is true
1122         author = uidFromAddress(self.db, from_list[0], create=create)
1124         # if we're not recognised, and we don't get added as a user, then we
1125         # must be anonymous
1126         if not author:
1127             author = anonid
1129         # make sure the author has permission to use the email interface
1130         if not self.db.security.hasPermission('Email Access', author):
1131             if author == anonid:
1132                 # we're anonymous and we need to be a registered user
1133                 from_address = from_list[0][1]
1134                 registration_info = ""
1135                 if self.db.security.hasPermission('Web Access', author) and \
1136                    self.db.security.hasPermission('Register', anonid, 'user'):
1137                     tracker_web = self.instance.config.TRACKER_WEB
1138                     registration_info = """ Please register at:
1140 %(tracker_web)suser?template=register
1142 ...before sending mail to the tracker.""" % locals()
1144                 raise Unauthorized, _("""
1145 You are not a registered user.%(registration_info)s
1147 Unknown address: %(from_address)s
1148 """) % locals()
1149             else:
1150                 # we're registered and we're _still_ not allowed access
1151                 raise Unauthorized, _(
1152                     'You are not permitted to access this tracker.')
1154         # make sure they're allowed to edit or create this class of information
1155         if nodeid:
1156             if not self.db.security.hasPermission('Edit', author, classname,
1157                     itemid=nodeid):
1158                 raise Unauthorized, _(
1159                     'You are not permitted to edit %(classname)s.') % locals()
1160         else:
1161             if not self.db.security.hasPermission('Create', author, classname):
1162                 raise Unauthorized, _(
1163                     'You are not permitted to create %(classname)s.'
1164                     ) % locals()
1166         # the author may have been created - make sure the change is
1167         # committed before we reopen the database
1168         self.db.commit()
1170         # set the database user as the author
1171         username = self.db.user.get(author, 'username')
1172         self.db.setCurrentUser(username)
1174         # re-get the class with the new database connection
1175         cl = self.db.getclass(classname)
1177         # now update the recipients list
1178         recipients = []
1179         tracker_email = config['TRACKER_EMAIL'].lower()
1180         for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
1181             r = recipient[1].strip().lower()
1182             if r == tracker_email or not r:
1183                 continue
1185             # look up the recipient - create if necessary (and we're
1186             # allowed to)
1187             recipient = uidFromAddress(self.db, recipient, create, **user_props)
1189             # if all's well, add the recipient to the list
1190             if recipient:
1191                 recipients.append(recipient)
1193         #
1194         # handle the subject argument list
1195         #
1196         # figure what the properties of this Class are
1197         properties = cl.getprops()
1198         props = {}
1199         args = matches['args']
1200         argswhole = matches['argswhole']
1201         if args:
1202             if sfxmode == 'none':
1203                 title += ' ' + argswhole
1204             else:
1205                 errors, props = setPropArrayFromString(self, cl, args, nodeid)
1206                 # handle any errors parsing the argument list
1207                 if errors:
1208                     if sfxmode == 'strict':
1209                         errors = '\n- '.join(map(str, errors))
1210                         raise MailUsageError, _("""
1211 There were problems handling your subject line argument list:
1212 - %(errors)s
1214 Subject was: "%(subject)s"
1215 """) % locals()
1216                     else:
1217                         title += ' ' + argswhole
1220         # set the issue title to the subject
1221         title = title.strip()
1222         if (title and properties.has_key('title') and not
1223                 issue_props.has_key('title')):
1224             issue_props['title'] = title
1226         #
1227         # handle message-id and in-reply-to
1228         #
1229         messageid = message.getheader('message-id')
1230         # generate a messageid if there isn't one
1231         if not messageid:
1232             messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1233                 classname, nodeid, config['MAIL_DOMAIN'])
1235         # if they've enabled PGP processing then verify the signature
1236         # or decrypt the message
1238         # if PGP_ROLES is specified the user must have a Role in the list
1239         # or we will skip PGP processing
1240         def pgp_role():
1241             if self.instance.config.PGP_ROLES:
1242                 return self.db.user.has_role(author,
1243                     iter_roles(self.instance.config.PGP_ROLES))
1244             else:
1245                 return True
1247         if self.instance.config.PGP_ENABLE and pgp_role():
1248             assert pyme, 'pyme is not installed'
1249             # signed/encrypted mail must come from the primary address
1250             author_address = self.db.user.get(author, 'address')
1251             if self.instance.config.PGP_HOMEDIR:
1252                 os.environ['GNUPGHOME'] = self.instance.config.PGP_HOMEDIR
1253             if message.pgp_signed():
1254                 message.verify_signature(author_address)
1255             elif message.pgp_encrypted():
1256                 # replace message with the contents of the decrypted
1257                 # message for content extraction
1258                 # TODO: encrypted message handling is far from perfect
1259                 # bounces probably include the decrypted message, for
1260                 # instance :(
1261                 message = message.decrypt(author_address)
1262             else:
1263                 raise MailUsageError, _("""
1264 This tracker has been configured to require all email be PGP signed or
1265 encrypted.""")
1266         # now handle the body - find the message
1267         ig = self.instance.config.MAILGW_IGNORE_ALTERNATIVES
1268         content, attachments = message.extract_content(ignore_alternatives = ig)
1269         if content is None:
1270             raise MailUsageError, _("""
1271 Roundup requires the submission to be plain text. The message parser could
1272 not find a text/plain part to use.
1273 """)
1275         # parse the body of the message, stripping out bits as appropriate
1276         summary, content = parseContent(content, config=config)
1277         content = content.strip()
1279         #
1280         # handle the attachments
1281         #
1282         files = []
1283         if attachments and properties.has_key('files'):
1284             for (name, mime_type, data) in attachments:
1285                 if not self.db.security.hasPermission('Create', author, 'file'):
1286                     raise Unauthorized, _(
1287                         'You are not permitted to create files.')
1288                 if not name:
1289                     name = "unnamed"
1290                 try:
1291                     fileid = self.db.file.create(type=mime_type, name=name,
1292                          content=data, **file_props)
1293                 except exceptions.Reject:
1294                     pass
1295                 else:
1296                     files.append(fileid)
1297             # allowed to attach the files to an existing node?
1298             if nodeid and not self.db.security.hasPermission('Edit', author,
1299                     classname, 'files'):
1300                 raise Unauthorized, _(
1301                     'You are not permitted to add files to %(classname)s.'
1302                     ) % locals()
1304             if nodeid:
1305                 # extend the existing files list
1306                 fileprop = cl.get(nodeid, 'files')
1307                 fileprop.extend(files)
1308                 props['files'] = fileprop
1309             else:
1310                 # pre-load the files list
1311                 props['files'] = files
1313         #
1314         # create the message if there's a message body (content)
1315         #
1316         if (content and properties.has_key('messages')):
1317             if not self.db.security.hasPermission('Create', author, 'msg'):
1318                 raise Unauthorized, _(
1319                     'You are not permitted to create messages.')
1321             try:
1322                 message_id = self.db.msg.create(author=author,
1323                     recipients=recipients, date=date.Date('.'),
1324                     summary=summary, content=content, files=files,
1325                     messageid=messageid, inreplyto=inreplyto, **msg_props)
1326             except exceptions.Reject, error:
1327                 raise MailUsageError, _("""
1328 Mail message was rejected by a detector.
1329 %(error)s
1330 """) % locals()
1331             # allowed to attach the message to the existing node?
1332             if nodeid and not self.db.security.hasPermission('Edit', author,
1333                     classname, 'messages'):
1334                 raise Unauthorized, _(
1335                     'You are not permitted to add messages to %(classname)s.'
1336                     ) % locals()
1338             if nodeid:
1339                 # add the message to the node's list
1340                 messages = cl.get(nodeid, 'messages')
1341                 messages.append(message_id)
1342                 props['messages'] = messages
1343             else:
1344                 # pre-load the messages list
1345                 props['messages'] = [message_id]
1347         #
1348         # perform the node change / create
1349         #
1350         try:
1351             # merge the command line props defined in issue_props into
1352             # the props dictionary because function(**props, **issue_props)
1353             # is a syntax error.
1354             for prop in issue_props.keys() :
1355                 if not props.has_key(prop) :
1356                     props[prop] = issue_props[prop]
1358             if nodeid:
1359                 # Check permissions for each property
1360                 for prop in props.keys():
1361                     if not self.db.security.hasPermission('Edit', author,
1362                             classname, prop):
1363                         raise Unauthorized, _('You are not permitted to edit '
1364                             'property %(prop)s of class %(classname)s.') % locals()
1365                 cl.set(nodeid, **props)
1366             else:
1367                 # Check permissions for each property
1368                 for prop in props.keys():
1369                     if not self.db.security.hasPermission('Create', author,
1370                             classname, prop):
1371                         raise Unauthorized, _('You are not permitted to set '
1372                             'property %(prop)s of class %(classname)s.') % locals()
1373                 nodeid = cl.create(**props)
1374         except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1375             raise MailUsageError, _("""
1376 There was a problem with the message you sent:
1377    %(message)s
1378 """) % locals()
1380         # commit the changes to the DB
1381         self.db.commit()
1383         return nodeid
1386 def setPropArrayFromString(self, cl, propString, nodeid=None):
1387     ''' takes string of form prop=value,value;prop2=value
1388         and returns (error, prop[..])
1389     '''
1390     props = {}
1391     errors = []
1392     for prop in string.split(propString, ';'):
1393         # extract the property name and value
1394         try:
1395             propname, value = prop.split('=')
1396         except ValueError, message:
1397             errors.append(_('not of form [arg=value,value,...;'
1398                 'arg=value,value,...]'))
1399             return (errors, props)
1400         # convert the value to a hyperdb-usable value
1401         propname = propname.strip()
1402         try:
1403             props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1404                 propname, value)
1405         except hyperdb.HyperdbValueError, message:
1406             errors.append(str(message))
1407     return errors, props
1410 def extractUserFromList(userClass, users):
1411     '''Given a list of users, try to extract the first non-anonymous user
1412        and return that user, otherwise return None
1413     '''
1414     if len(users) > 1:
1415         for user in users:
1416             # make sure we don't match the anonymous or admin user
1417             if userClass.get(user, 'username') in ('admin', 'anonymous'):
1418                 continue
1419             # first valid match will do
1420             return user
1421         # well, I guess we have no choice
1422         return user[0]
1423     elif users:
1424         return users[0]
1425     return None
1428 def uidFromAddress(db, address, create=1, **user_props):
1429     ''' address is from the rfc822 module, and therefore is (name, addr)
1431         user is created if they don't exist in the db already
1432         user_props may supply additional user information
1433     '''
1434     (realname, address) = address
1436     # try a straight match of the address
1437     user = extractUserFromList(db.user, db.user.stringFind(address=address))
1438     if user is not None:
1439         return user
1441     # try the user alternate addresses if possible
1442     props = db.user.getprops()
1443     if props.has_key('alternate_addresses'):
1444         users = db.user.filter(None, {'alternate_addresses': address})
1445         user = extractUserFromList(db.user, users)
1446         if user is not None:
1447             return user
1449     # try to match the username to the address (for local
1450     # submissions where the address is empty)
1451     user = extractUserFromList(db.user, db.user.stringFind(username=address))
1453     # couldn't match address or username, so create a new user
1454     if create:
1455         # generate a username
1456         if '@' in address:
1457             username = address.split('@')[0]
1458         else:
1459             username = address
1460         trying = username
1461         n = 0
1462         while 1:
1463             try:
1464                 # does this username exist already?
1465                 db.user.lookup(trying)
1466             except KeyError:
1467                 break
1468             n += 1
1469             trying = username + str(n)
1471         # create!
1472         try:
1473             return db.user.create(username=trying, address=address,
1474                 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1475                 password=password.Password(password.generatePassword()),
1476                 **user_props)
1477         except exceptions.Reject:
1478             return 0
1479     else:
1480         return 0
1482 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1483     """Parse mail message; return message summary and stripped content
1485     The message body is divided into sections by blank lines.
1486     Sections where the second and all subsequent lines begin with a ">"
1487     or "|" character are considered "quoting sections". The first line of
1488     the first non-quoting section becomes the summary of the message.
1490     Arguments:
1492         keep_citations: declared for backward compatibility.
1493             If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1495         keep_body: declared for backward compatibility.
1496             If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1498         config: tracker configuration object.
1499             If omitted or None, use default configuration.
1501     """
1502     if config is None:
1503         config = configuration.CoreConfig()
1504     if keep_citations is None:
1505         keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1506     if keep_body is None:
1507         keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1508     eol = config["MAILGW_EOL_RE"]
1509     signature = config["MAILGW_SIGN_RE"]
1510     original_msg = config["MAILGW_ORIGMSG_RE"]
1512     # strip off leading carriage-returns / newlines
1513     i = 0
1514     for i in range(len(content)):
1515         if content[i] not in '\r\n':
1516             break
1517     if i > 0:
1518         sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1519     else:
1520         sections = config["MAILGW_BLANKLINE_RE"].split(content)
1522     # extract out the summary from the message
1523     summary = ''
1524     l = []
1525     for section in sections:
1526         #section = section.strip()
1527         if not section:
1528             continue
1529         lines = eol.split(section)
1530         if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1531                 lines[1] and lines[1][0] in '>|'):
1532             # see if there's a response somewhere inside this section (ie.
1533             # no blank line between quoted message and response)
1534             for line in lines[1:]:
1535                 if line and line[0] not in '>|':
1536                     break
1537             else:
1538                 # we keep quoted bits if specified in the config
1539                 if keep_citations:
1540                     l.append(section)
1541                 continue
1542             # keep this section - it has reponse stuff in it
1543             lines = lines[lines.index(line):]
1544             section = '\n'.join(lines)
1545             # and while we're at it, use the first non-quoted bit as
1546             # our summary
1547             summary = section
1549         if not summary:
1550             # if we don't have our summary yet use the first line of this
1551             # section
1552             summary = section
1553         elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1554             # lose any signature
1555             break
1556         elif original_msg.match(lines[0]):
1557             # ditch the stupid Outlook quoting of the entire original message
1558             break
1560         # and add the section to the output
1561         l.append(section)
1563     # figure the summary - find the first sentence-ending punctuation or the
1564     # first whole line, whichever is longest
1565     sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1566     if sentence:
1567         sentence = sentence.group(1)
1568     else:
1569         sentence = ''
1570     first = eol.split(summary)[0]
1571     summary = max(sentence, first)
1573     # Now reconstitute the message content minus the bits we don't care
1574     # about.
1575     if not keep_body:
1576         content = '\n\n'.join(l)
1578     return summary, content
1580 # vim: set filetype=python sts=4 sw=4 et si :