Code

d96d5edaaba08cc65563173a4e7a82db2feff63b
[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         # TODO are there any other False values possible?
250         # TODO if not hdr: return hdr
251         if hdr is None:
252             return None
253         if not hdr:
254             return ''
255         if hdr:
256             hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders
257         # historically this method has returned utf-8 encoded string
258         l = []
259         for part, encoding in decode_header(hdr):
260             if encoding:
261                 part = part.decode(encoding)
262             l.append(part)
263         return ''.join([s.encode('utf-8') for s in l])
265     def getaddrlist(self, name):
266         # overload to decode the name part of the address
267         l = []
268         for (name, addr) in mimetools.Message.getaddrlist(self, name):
269             p = []
270             for part, encoding in decode_header(name):
271                 if encoding:
272                     part = part.decode(encoding)
273                 p.append(part)
274             name = ''.join([s.encode('utf-8') for s in p])
275             l.append((name, addr))
276         return l
278     def getname(self):
279         """Find an appropriate name for this message."""
280         if self.gettype() == 'message/rfc822':
281             # handle message/rfc822 specially - the name should be
282             # the subject of the actual e-mail embedded here
283             self.fp.seek(0)
284             name = Message(self.fp).getheader('subject')
285         else:
286             # try name on Content-Type
287             name = self.getparam('name')
288             if not name:
289                 disp = self.getheader('content-disposition', None)
290                 if disp:
291                     name = getparam(disp, 'filename')
293         if name:
294             return name.strip()
296     def getbody(self):
297         """Get the decoded message body."""
298         self.rewindbody()
299         encoding = self.getencoding()
300         data = None
301         if encoding == 'base64':
302             # BUG: is base64 really used for text encoding or
303             # are we inserting zip files here.
304             data = binascii.a2b_base64(self.fp.read())
305         elif encoding == 'quoted-printable':
306             # the quopri module wants to work with files
307             decoded = cStringIO.StringIO()
308             quopri.decode(self.fp, decoded)
309             data = decoded.getvalue()
310         elif encoding == 'uuencoded':
311             data = binascii.a2b_uu(self.fp.read())
312         else:
313             # take it as text
314             data = self.fp.read()
316         # Encode message to unicode
317         charset = rfc2822.unaliasCharset(self.getparam("charset"))
318         if charset:
319             # Do conversion only if charset specified - handle
320             # badly-specified charsets
321             edata = unicode(data, charset, 'replace').encode('utf-8')
322             # Convert from dos eol to unix
323             edata = edata.replace('\r\n', '\n')
324         else:
325             # Leave message content as is
326             edata = data
328         return edata
330     # General multipart handling:
331     #   Take the first text/plain part, anything else is considered an
332     #   attachment.
333     # multipart/mixed:
334     #   Multiple "unrelated" parts.
335     # multipart/Alternative (rfc 1521):
336     #   Like multipart/mixed, except that we'd only want one of the
337     #   alternatives. Generally a top-level part from MUAs sending HTML
338     #   mail - there will be a text/plain version.
339     # multipart/signed (rfc 1847):
340     #   The control information is carried in the second of the two
341     #   required body parts.
342     #   ACTION: Default, so if content is text/plain we get it.
343     # multipart/encrypted (rfc 1847):
344     #   The control information is carried in the first of the two
345     #   required body parts.
346     #   ACTION: Not handleable as the content is encrypted.
347     # multipart/related (rfc 1872, 2112, 2387):
348     #   The Multipart/Related content-type addresses the MIME
349     #   representation of compound objects, usually HTML mail with embedded
350     #   images. Usually appears as an alternative.
351     #   ACTION: Default, if we must.
352     # multipart/report (rfc 1892):
353     #   e.g. mail system delivery status reports.
354     #   ACTION: Default. Could be ignored or used for Delivery Notification
355     #   flagging.
356     # multipart/form-data:
357     #   For web forms only.
359     def extract_content(self, parent_type=None, ignore_alternatives = False):
360         """Extract the body and the attachments recursively.
362            If the content is hidden inside a multipart/alternative part,
363            we use the *last* text/plain part of the *first*
364            multipart/alternative in the whole message.
365         """
366         content_type = self.gettype()
367         content = None
368         attachments = []
370         if content_type == 'text/plain':
371             content = self.getbody()
372         elif content_type[:10] == 'multipart/':
373             content_found = bool (content)
374             ig = ignore_alternatives and not content_found
375             for part in self.getparts():
376                 new_content, new_attach = part.extract_content(content_type,
377                     not content and ig)
379                 # If we haven't found a text/plain part yet, take this one,
380                 # otherwise make it an attachment.
381                 if not content:
382                     content = new_content
383                     cpart   = part
384                 elif new_content:
385                     if content_found or content_type != 'multipart/alternative':
386                         attachments.append(part.text_as_attachment())
387                     else:
388                         # if we have found a text/plain in the current
389                         # multipart/alternative and find another one, we
390                         # use the first as an attachment (if configured)
391                         # and use the second one because rfc 2046, sec.
392                         # 5.1.4. specifies that later parts are better
393                         # (thanks to Philipp Gortan for pointing this
394                         # out)
395                         attachments.append(cpart.text_as_attachment())
396                         content = new_content
397                         cpart   = part
399                 attachments.extend(new_attach)
400             if ig and content_type == 'multipart/alternative' and content:
401                 attachments = []
402         elif (parent_type == 'multipart/signed' and
403               content_type == 'application/pgp-signature'):
404             # ignore it so it won't be saved as an attachment
405             pass
406         else:
407             attachments.append(self.as_attachment())
408         return content, attachments
410     def text_as_attachment(self):
411         """Return first text/plain part as Message"""
412         if not self.gettype().startswith ('multipart/'):
413             return self.as_attachment()
414         for part in self.getparts():
415             content_type = part.gettype()
416             if content_type == 'text/plain':
417                 return part.as_attachment()
418             elif content_type.startswith ('multipart/'):
419                 p = part.text_as_attachment()
420                 if p:
421                     return p
422         return None
424     def as_attachment(self):
425         """Return this message as an attachment."""
426         return (self.getname(), self.gettype(), self.getbody())
428     def pgp_signed(self):
429         ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
430         '''
431         return self.gettype() == 'multipart/signed' \
432             and self.typeheader.find('protocol="application/pgp-signature"') != -1
434     def pgp_encrypted(self):
435         ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
436         '''
437         return self.gettype() == 'multipart/encrypted' \
438             and self.typeheader.find('protocol="application/pgp-encrypted"') != -1
440     def decrypt(self, author):
441         ''' decrypt an OpenPGP MIME message
442             This message must be signed as well as encrypted using the "combined"
443             method. The decrypted contents are returned as a new message.
444         '''
445         (hdr, msg) = self.getparts()
446         # According to the RFC 3156 encrypted mail must have exactly two parts.
447         # The first part contains the control information. Let's verify that
448         # the message meets the RFC before we try to decrypt it.
449         if hdr.getbody() != 'Version: 1' or hdr.gettype() != 'application/pgp-encrypted':
450             raise MailUsageError, \
451                 _("Unknown multipart/encrypted version.")
453         context = pyme.core.Context()
454         ciphertext = pyme.core.Data(msg.getbody())
455         plaintext = pyme.core.Data()
457         result = context.op_decrypt_verify(ciphertext, plaintext)
459         if result:
460             raise MailUsageError, _("Unable to decrypt your message.")
462         # we've decrypted it but that just means they used our public
463         # key to send it to us. now check the signatures to see if it
464         # was signed by someone we trust
465         result = context.op_verify_result()
466         check_pgp_sigs(result.signatures, context, author)
468         plaintext.seek(0,0)
469         # pyme.core.Data implements a seek method with a different signature
470         # than roundup can handle. So we'll put the data in a container that
471         # the Message class can work with.
472         c = cStringIO.StringIO()
473         c.write(plaintext.read())
474         c.seek(0)
475         return Message(c)
477     def verify_signature(self, author):
478         ''' verify the signature of an OpenPGP MIME message
479             This only handles detached signatures. Old style
480             PGP mail (i.e. '-----BEGIN PGP SIGNED MESSAGE----')
481             is archaic and not supported :)
482         '''
483         # we don't check the micalg parameter...gpgme seems to
484         # figure things out on its own
485         (msg, sig) = self.getparts()
487         if sig.gettype() != 'application/pgp-signature':
488             raise MailUsageError, \
489                 _("No PGP signature found in message.")
491         context = pyme.core.Context()
492         # msg.getbody() is skipping over some headers that are
493         # required to be present for verification to succeed so
494         # we'll do this by hand
495         msg.fp.seek(0)
496         # according to rfc 3156 the data "MUST first be converted
497         # to its content-type specific canonical form. For
498         # text/plain this means conversion to an appropriate
499         # character set and conversion of line endings to the
500         # canonical <CR><LF> sequence."
501         # TODO: what about character set conversion?
502         canonical_msg = re.sub('(?<!\r)\n', '\r\n', msg.fp.read())
503         msg_data = pyme.core.Data(canonical_msg)
504         sig_data = pyme.core.Data(sig.getbody())
506         context.op_verify(sig_data, msg_data, None)
508         # check all signatures for validity
509         result = context.op_verify_result()
510         check_pgp_sigs(result.signatures, context, author)
512 class MailGW:
514     def __init__(self, instance, arguments=()):
515         self.instance = instance
516         self.arguments = arguments
517         self.default_class = None
518         for option, value in self.arguments:
519             if option == '-c':
520                 self.default_class = value.strip()
522         self.mailer = Mailer(instance.config)
523         self.logger = logging.getLogger('roundup.mailgw')
525         # should we trap exceptions (normal usage) or pass them through
526         # (for testing)
527         self.trapExceptions = 1
529     def do_pipe(self):
530         """ Read a message from standard input and pass it to the mail handler.
532             Read into an internal structure that we can seek on (in case
533             there's an error).
535             XXX: we may want to read this into a temporary file instead...
536         """
537         s = cStringIO.StringIO()
538         s.write(sys.stdin.read())
539         s.seek(0)
540         self.main(s)
541         return 0
543     def do_mailbox(self, filename):
544         """ Read a series of messages from the specified unix mailbox file and
545             pass each to the mail handler.
546         """
547         # open the spool file and lock it
548         import fcntl
549         # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
550         if hasattr(fcntl, 'LOCK_EX'):
551             FCNTL = fcntl
552         else:
553             import FCNTL
554         f = open(filename, 'r+')
555         fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
557         # handle and clear the mailbox
558         try:
559             from mailbox import UnixMailbox
560             mailbox = UnixMailbox(f, factory=Message)
561             # grab one message
562             message = mailbox.next()
563             while message:
564                 # handle this message
565                 self.handle_Message(message)
566                 message = mailbox.next()
567             # nuke the file contents
568             os.ftruncate(f.fileno(), 0)
569         except:
570             import traceback
571             traceback.print_exc()
572             return 1
573         fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
574         return 0
576     def do_imap(self, server, user='', password='', mailbox='', ssl=0,
577             cram=0):
578         ''' Do an IMAP connection
579         '''
580         import getpass, imaplib, socket
581         try:
582             if not user:
583                 user = raw_input('User: ')
584             if not password:
585                 password = getpass.getpass()
586         except (KeyboardInterrupt, EOFError):
587             # Ctrl C or D maybe also Ctrl Z under Windows.
588             print "\nAborted by user."
589             return 1
590         # open a connection to the server and retrieve all messages
591         try:
592             if ssl:
593                 self.logger.debug('Trying server %r with ssl'%server)
594                 server = imaplib.IMAP4_SSL(server)
595             else:
596                 self.logger.debug('Trying server %r without ssl'%server)
597                 server = imaplib.IMAP4(server)
598         except (imaplib.IMAP4.error, socket.error, socket.sslerror):
599             self.logger.exception('IMAP server error')
600             return 1
602         try:
603             if cram:
604                 server.login_cram_md5(user, password)
605             else:
606                 server.login(user, password)
607         except imaplib.IMAP4.error, e:
608             self.logger.exception('IMAP login failure')
609             return 1
611         try:
612             if not mailbox:
613                 (typ, data) = server.select()
614             else:
615                 (typ, data) = server.select(mailbox=mailbox)
616             if typ != 'OK':
617                 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
618                     data))
619                 return 1
620             try:
621                 numMessages = int(data[0])
622             except ValueError, value:
623                 self.logger.error('Invalid message count from mailbox %r'%
624                     data[0])
625                 return 1
626             for i in range(1, numMessages+1):
627                 (typ, data) = server.fetch(str(i), '(RFC822)')
629                 # mark the message as deleted.
630                 server.store(str(i), '+FLAGS', r'(\Deleted)')
632                 # process the message
633                 s = cStringIO.StringIO(data[0][1])
634                 s.seek(0)
635                 self.handle_Message(Message(s))
636             server.close()
637         finally:
638             try:
639                 server.expunge()
640             except:
641                 pass
642             server.logout()
644         return 0
647     def do_apop(self, server, user='', password='', ssl=False):
648         ''' Do authentication POP
649         '''
650         self._do_pop(server, user, password, True, ssl)
652     def do_pop(self, server, user='', password='', ssl=False):
653         ''' Do plain POP
654         '''
655         self._do_pop(server, user, password, False, ssl)
657     def _do_pop(self, server, user, password, apop, ssl):
658         '''Read a series of messages from the specified POP server.
659         '''
660         import getpass, poplib, socket
661         try:
662             if not user:
663                 user = raw_input('User: ')
664             if not password:
665                 password = getpass.getpass()
666         except (KeyboardInterrupt, EOFError):
667             # Ctrl C or D maybe also Ctrl Z under Windows.
668             print "\nAborted by user."
669             return 1
671         # open a connection to the server and retrieve all messages
672         try:
673             if ssl:
674                 klass = poplib.POP3_SSL
675             else:
676                 klass = poplib.POP3
677             server = klass(server)
678         except socket.error:
679             self.logger.exception('POP server error')
680             return 1
681         if apop:
682             server.apop(user, password)
683         else:
684             server.user(user)
685             server.pass_(password)
686         numMessages = len(server.list()[1])
687         for i in range(1, numMessages+1):
688             # retr: returns
689             # [ pop response e.g. '+OK 459 octets',
690             #   [ array of message lines ],
691             #   number of octets ]
692             lines = server.retr(i)[1]
693             s = cStringIO.StringIO('\n'.join(lines))
694             s.seek(0)
695             self.handle_Message(Message(s))
696             # delete the message
697             server.dele(i)
699         # quit the server to commit changes.
700         server.quit()
701         return 0
703     def main(self, fp):
704         ''' fp - the file from which to read the Message.
705         '''
706         return self.handle_Message(Message(fp))
708     def handle_Message(self, message):
709         """Handle an RFC822 Message
711         Handle the Message object by calling handle_message() and then cope
712         with any errors raised by handle_message.
713         This method's job is to make that call and handle any
714         errors in a sane manner. It should be replaced if you wish to
715         handle errors in a different manner.
716         """
717         # in some rare cases, a particularly stuffed-up e-mail will make
718         # its way into here... try to handle it gracefully
720         sendto = message.getaddrlist('resent-from')
721         if not sendto:
722             sendto = message.getaddrlist('from')
723         if not sendto:
724             # very bad-looking message - we don't even know who sent it
725             msg = ['Badly formed message from mail gateway. Headers:']
726             msg.extend(message.headers)
727             msg = '\n'.join(map(str, msg))
728             self.logger.error(msg)
729             return
731         msg = 'Handling message'
732         if message.getheader('message-id'):
733             msg += ' (Message-id=%r)'%message.getheader('message-id')
734         self.logger.info(msg)
736         # try normal message-handling
737         if not self.trapExceptions:
738             return self.handle_message(message)
740         # no, we want to trap exceptions
741         try:
742             return self.handle_message(message)
743         except MailUsageHelp:
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('\n\nMail Gateway Help\n=================')
748             m.append(fulldoc)
749             self.mailer.bounce_message(message, [sendto[0][1]], m,
750                 subject="Mail Gateway Help")
751         except MailUsageError, value:
752             # bounce the message back to the sender with the usage message
753             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
754             m = ['']
755             m.append(str(value))
756             m.append('\n\nMail Gateway Help\n=================')
757             m.append(fulldoc)
758             self.mailer.bounce_message(message, [sendto[0][1]], m)
759         except Unauthorized, value:
760             # just inform the user that he is not authorized
761             m = ['']
762             m.append(str(value))
763             self.mailer.bounce_message(message, [sendto[0][1]], m)
764         except IgnoreMessage:
765             # do not take any action
766             # this exception is thrown when email should be ignored
767             msg = 'IgnoreMessage raised'
768             if message.getheader('message-id'):
769                 msg += ' (Message-id=%r)'%message.getheader('message-id')
770             self.logger.info(msg)
771             return
772         except:
773             msg = 'Exception handling message'
774             if message.getheader('message-id'):
775                 msg += ' (Message-id=%r)'%message.getheader('message-id')
776             self.logger.exception(msg)
778             # bounce the message back to the sender with the error message
779             # let the admin know that something very bad is happening
780             m = ['']
781             m.append('An unexpected error occurred during the processing')
782             m.append('of your message. The tracker administrator is being')
783             m.append('notified.\n')
784             self.mailer.bounce_message(message, [sendto[0][1]], m)
786             m.append('----------------')
787             m.append(traceback.format_exc())
788             self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
790     def handle_message(self, message):
791         ''' message - a Message instance
793         Parse the message as per the module docstring.
794         '''
795         # get database handle for handling one email
796         self.db = self.instance.open ('admin')
797         try:
798             return self._handle_message (message)
799         finally:
800             self.db.close()
802     def _handle_message(self, message):
803         ''' message - a Message instance
805         Parse the message as per the module docstring.
807         The implementation expects an opened database and a try/finally
808         that closes the database.
809         '''
810         # detect loops
811         if message.getheader('x-roundup-loop', ''):
812             raise IgnoreLoop
814         # handle the subject line
815         subject = message.getheader('subject', '')
816         if not subject:
817             raise MailUsageError, _("""
818 Emails to Roundup trackers must include a Subject: line!
819 """)
821         # detect Precedence: Bulk, or Microsoft Outlook autoreplies
822         if (message.getheader('precedence', '') == 'bulk'
823                 or subject.lower().find("autoreply") > 0):
824             raise IgnoreBulk
826         if subject.strip().lower() == 'help':
827             raise MailUsageHelp
829         # config is used many times in this method.
830         # make local variable for easier access
831         config = self.instance.config
833         # determine the sender's address
834         from_list = message.getaddrlist('resent-from')
835         if not from_list:
836             from_list = message.getaddrlist('from')
838         # XXX Don't enable. This doesn't work yet.
839 #  "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
840         # handle delivery to addresses like:tracker+issue25@some.dom.ain
841         # use the embedded issue number as our issue
842 #        issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
843 #        if issue_re:
844 #            for header in ['to', 'cc', 'bcc']:
845 #                addresses = message.getheader(header, '')
846 #            if addresses:
847 #              # FIXME, this only finds the first match in the addresses.
848 #                issue = re.search(issue_re, addresses, 'i')
849 #                if issue:
850 #                    classname = issue.group('classname')
851 #                    nodeid = issue.group('nodeid')
852 #                    break
854         # Matches subjects like:
855         # Re: "[issue1234] title of issue [status=resolved]"
857         # Alias since we need a reference to the original subject for
858         # later use in error messages
859         tmpsubject = subject
861         sd_open, sd_close = config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
862         delim_open = re.escape(sd_open)
863         if delim_open in '[(': delim_open = '\\' + delim_open
864         delim_close = re.escape(sd_close)
865         if delim_close in '[(': delim_close = '\\' + delim_close
867         matches = dict.fromkeys(['refwd', 'quote', 'classname',
868                                  'nodeid', 'title', 'args',
869                                  'argswhole'])
871         # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
872         re_re = r"(?P<refwd>%s)\s*" % config["MAILGW_REFWD_RE"].pattern
873         m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
874         if m:
875             m = m.groupdict()
876             if m['refwd']:
877                 matches.update(m)
878                 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
880         # Look for Leading "
881         m = re.match(r'(?P<quote>\s*")', tmpsubject,
882                      re.IGNORECASE)
883         if m:
884             matches.update(m.groupdict())
885             tmpsubject = tmpsubject[len(matches['quote']):] # Consume quote
887         has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
888             delim_close), tmpsubject.strip())
890         class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
891             "|".join(self.db.getclasses()), delim_close)
892         # Note: re.search, not re.match as there might be garbage
893         # (mailing list prefix, etc.) before the class identifier
894         m = re.search(class_re, tmpsubject, re.IGNORECASE)
895         if m:
896             matches.update(m.groupdict())
897             # Skip to the end of the class identifier, including any
898             # garbage before it.
900             tmpsubject = tmpsubject[m.end():]
902         # if we've not found a valid classname prefix then force the
903         # scanning to handle there being a leading delimiter
904         title_re = r'(?P<title>%s[^%s]*)'%(
905             not matches['classname'] and '.' or '', delim_open)
906         m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
907         if m:
908             matches.update(m.groupdict())
909             tmpsubject = tmpsubject[len(matches['title']):] # Consume title
911         args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
912             delim_close)
913         m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
914         if m:
915             matches.update(m.groupdict())
917         # figure subject line parsing modes
918         pfxmode = config['MAILGW_SUBJECT_PREFIX_PARSING']
919         sfxmode = config['MAILGW_SUBJECT_SUFFIX_PARSING']
921         # check for registration OTK
922         # or fallback on the default class
923         if self.db.config['EMAIL_REGISTRATION_CONFIRMATION']:
924             otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
925             otk = otk_re.search(matches['title'] or '')
926             if otk:
927                 self.db.confirm_registration(otk.group('otk'))
928                 subject = 'Your registration to %s is complete' % \
929                           config['TRACKER_NAME']
930                 sendto = [from_list[0][1]]
931                 self.mailer.standard_message(sendto, subject, '')
932                 return
934         # get the classname
935         if pfxmode == 'none':
936             classname = None
937         else:
938             classname = matches['classname']
940         if not classname and has_prefix and pfxmode == 'strict':
941             raise MailUsageError, _("""
942 The message you sent to roundup did not contain a properly formed subject
943 line. The subject must contain a class name or designator to indicate the
944 'topic' of the message. For example:
945     Subject: [issue] This is a new issue
946       - this will create a new issue in the tracker with the title 'This is
947         a new issue'.
948     Subject: [issue1234] This is a followup to issue 1234
949       - this will append the message's contents to the existing issue 1234
950         in the tracker.
952 Subject was: '%(subject)s'
953 """) % locals()
955         # try to get the class specified - if "loose" or "none" then fall
956         # back on the default
957         attempts = []
958         if classname:
959             attempts.append(classname)
961         if self.default_class:
962             attempts.append(self.default_class)
963         else:
964             attempts.append(config['MAILGW_DEFAULT_CLASS'])
966         # first valid class name wins
967         cl = None
968         for trycl in attempts:
969             try:
970                 cl = self.db.getclass(trycl)
971                 classname = trycl
972                 break
973             except KeyError:
974                 pass
976         if not cl:
977             validname = ', '.join(self.db.getclasses())
978             if classname:
979                 raise MailUsageError, _("""
980 The class name you identified in the subject line ("%(classname)s") does
981 not exist in the database.
983 Valid class names are: %(validname)s
984 Subject was: "%(subject)s"
985 """) % locals()
986             else:
987                 raise MailUsageError, _("""
988 You did not identify a class name in the subject line and there is no
989 default set for this tracker. The subject must contain a class name or
990 designator to indicate the 'topic' of the message. For example:
991     Subject: [issue] This is a new issue
992       - this will create a new issue in the tracker with the title 'This is
993         a new issue'.
994     Subject: [issue1234] This is a followup to issue 1234
995       - this will append the message's contents to the existing issue 1234
996         in the tracker.
998 Subject was: '%(subject)s'
999 """) % locals()
1001         # get the optional nodeid
1002         if pfxmode == 'none':
1003             nodeid = None
1004         else:
1005             nodeid = matches['nodeid']
1007         # try in-reply-to to match the message if there's no nodeid
1008         inreplyto = message.getheader('in-reply-to') or ''
1009         if nodeid is None and inreplyto:
1010             l = self.db.getclass('msg').stringFind(messageid=inreplyto)
1011             if l:
1012                 nodeid = cl.filter(None, {'messages':l})[0]
1014         # title is optional too
1015         title = matches['title']
1016         if title:
1017             title = title.strip()
1018         else:
1019             title = ''
1021         # strip off the quotes that dumb emailers put around the subject, like
1022         #      Re: "[issue1] bla blah"
1023         if matches['quote'] and title.endswith('"'):
1024             title = title[:-1]
1026         # but we do need either a title or a nodeid...
1027         if nodeid is None and not title:
1028             raise MailUsageError, _("""
1029 I cannot match your message to a node in the database - you need to either
1030 supply a full designator (with number, eg "[issue123]") or keep the
1031 previous subject title intact so I can match that.
1033 Subject was: "%(subject)s"
1034 """) % locals()
1036         # If there's no nodeid, check to see if this is a followup and
1037         # maybe someone's responded to the initial mail that created an
1038         # entry. Try to find the matching nodes with the same title, and
1039         # use the _last_ one matched (since that'll _usually_ be the most
1040         # recent...). The subject_content_match config may specify an
1041         # additional restriction based on the matched node's creation or
1042         # activity.
1043         tmatch_mode = config['MAILGW_SUBJECT_CONTENT_MATCH']
1044         if tmatch_mode != 'never' and nodeid is None and matches['refwd']:
1045             l = cl.stringFind(title=title)
1046             limit = None
1047             if (tmatch_mode.startswith('creation') or
1048                     tmatch_mode.startswith('activity')):
1049                 limit, interval = tmatch_mode.split(' ', 1)
1050                 threshold = date.Date('.') - date.Interval(interval)
1051             for id in l:
1052                 if limit:
1053                     if threshold < cl.get(id, limit):
1054                         nodeid = id
1055                 else:
1056                     nodeid = id
1058         # if a nodeid was specified, make sure it's valid
1059         if nodeid is not None and not cl.hasnode(nodeid):
1060             if pfxmode == 'strict':
1061                 raise MailUsageError, _("""
1062 The node specified by the designator in the subject of your message
1063 ("%(nodeid)s") does not exist.
1065 Subject was: "%(subject)s"
1066 """) % locals()
1067             else:
1068                 title = subject
1069                 nodeid = None
1071         # Handle the arguments specified by the email gateway command line.
1072         # We do this by looping over the list of self.arguments looking for
1073         # a -C to tell us what class then the -S setting string.
1074         msg_props = {}
1075         user_props = {}
1076         file_props = {}
1077         issue_props = {}
1078         # so, if we have any arguments, use them
1079         if self.arguments:
1080             current_class = 'msg'
1081             for option, propstring in self.arguments:
1082                 if option in ( '-C', '--class'):
1083                     current_class = propstring.strip()
1084                     # XXX this is not flexible enough.
1085                     #   we should chect for subclasses of these classes,
1086                     #   not for the class name...
1087                     if current_class not in ('msg', 'file', 'user', 'issue'):
1088                         mailadmin = config['ADMIN_EMAIL']
1089                         raise MailUsageError, _("""
1090 The mail gateway is not properly set up. Please contact
1091 %(mailadmin)s and have them fix the incorrect class specified as:
1092   %(current_class)s
1093 """) % locals()
1094                 if option in ('-S', '--set'):
1095                     if current_class == 'issue' :
1096                         errors, issue_props = setPropArrayFromString(self,
1097                             cl, propstring.strip(), nodeid)
1098                     elif current_class == 'file' :
1099                         temp_cl = self.db.getclass('file')
1100                         errors, file_props = setPropArrayFromString(self,
1101                             temp_cl, propstring.strip())
1102                     elif current_class == 'msg' :
1103                         temp_cl = self.db.getclass('msg')
1104                         errors, msg_props = setPropArrayFromString(self,
1105                             temp_cl, propstring.strip())
1106                     elif current_class == 'user' :
1107                         temp_cl = self.db.getclass('user')
1108                         errors, user_props = setPropArrayFromString(self,
1109                             temp_cl, propstring.strip())
1110                     if errors:
1111                         mailadmin = config['ADMIN_EMAIL']
1112                         raise MailUsageError, _("""
1113 The mail gateway is not properly set up. Please contact
1114 %(mailadmin)s and have them fix the incorrect properties:
1115   %(errors)s
1116 """) % locals()
1118         #
1119         # handle the users
1120         #
1121         # Don't create users if anonymous isn't allowed to register
1122         create = 1
1123         anonid = self.db.user.lookup('anonymous')
1124         if not (self.db.security.hasPermission('Register', anonid, 'user')
1125                 and self.db.security.hasPermission('Email Access', anonid)):
1126             create = 0
1128         # ok, now figure out who the author is - create a new user if the
1129         # "create" flag is true
1130         author = uidFromAddress(self.db, from_list[0], create=create)
1132         # if we're not recognised, and we don't get added as a user, then we
1133         # must be anonymous
1134         if not author:
1135             author = anonid
1137         # make sure the author has permission to use the email interface
1138         if not self.db.security.hasPermission('Email Access', author):
1139             if author == anonid:
1140                 # we're anonymous and we need to be a registered user
1141                 from_address = from_list[0][1]
1142                 registration_info = ""
1143                 if self.db.security.hasPermission('Web Access', author) and \
1144                    self.db.security.hasPermission('Register', anonid, 'user'):
1145                     tracker_web = self.instance.config.TRACKER_WEB
1146                     registration_info = """ Please register at:
1148 %(tracker_web)suser?template=register
1150 ...before sending mail to the tracker.""" % locals()
1152                 raise Unauthorized, _("""
1153 You are not a registered user.%(registration_info)s
1155 Unknown address: %(from_address)s
1156 """) % locals()
1157             else:
1158                 # we're registered and we're _still_ not allowed access
1159                 raise Unauthorized, _(
1160                     'You are not permitted to access this tracker.')
1162         # make sure they're allowed to edit or create this class of information
1163         if nodeid:
1164             if not self.db.security.hasPermission('Edit', author, classname,
1165                     itemid=nodeid):
1166                 raise Unauthorized, _(
1167                     'You are not permitted to edit %(classname)s.') % locals()
1168         else:
1169             if not self.db.security.hasPermission('Create', author, classname):
1170                 raise Unauthorized, _(
1171                     'You are not permitted to create %(classname)s.'
1172                     ) % locals()
1174         # the author may have been created - make sure the change is
1175         # committed before we reopen the database
1176         self.db.commit()
1178         # set the database user as the author
1179         username = self.db.user.get(author, 'username')
1180         self.db.setCurrentUser(username)
1182         # re-get the class with the new database connection
1183         cl = self.db.getclass(classname)
1185         # now update the recipients list
1186         recipients = []
1187         tracker_email = config['TRACKER_EMAIL'].lower()
1188         for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
1189             r = recipient[1].strip().lower()
1190             if r == tracker_email or not r:
1191                 continue
1193             # look up the recipient - create if necessary (and we're
1194             # allowed to)
1195             recipient = uidFromAddress(self.db, recipient, create, **user_props)
1197             # if all's well, add the recipient to the list
1198             if recipient:
1199                 recipients.append(recipient)
1201         #
1202         # handle the subject argument list
1203         #
1204         # figure what the properties of this Class are
1205         properties = cl.getprops()
1206         props = {}
1207         args = matches['args']
1208         argswhole = matches['argswhole']
1209         if args:
1210             if sfxmode == 'none':
1211                 title += ' ' + argswhole
1212             else:
1213                 errors, props = setPropArrayFromString(self, cl, args, nodeid)
1214                 # handle any errors parsing the argument list
1215                 if errors:
1216                     if sfxmode == 'strict':
1217                         errors = '\n- '.join(map(str, errors))
1218                         raise MailUsageError, _("""
1219 There were problems handling your subject line argument list:
1220 - %(errors)s
1222 Subject was: "%(subject)s"
1223 """) % locals()
1224                     else:
1225                         title += ' ' + argswhole
1228         # set the issue title to the subject
1229         title = title.strip()
1230         if (title and properties.has_key('title') and not
1231                 issue_props.has_key('title')):
1232             issue_props['title'] = title
1233         if (nodeid and properties.has_key('title') and not
1234                 config['MAILGW_SUBJECT_UPDATES_TITLE']):
1235             issue_props['title'] = cl.get(nodeid,'title')
1237         #
1238         # handle message-id and in-reply-to
1239         #
1240         messageid = message.getheader('message-id')
1241         # generate a messageid if there isn't one
1242         if not messageid:
1243             messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1244                 classname, nodeid, config['MAIL_DOMAIN'])
1246         # if they've enabled PGP processing then verify the signature
1247         # or decrypt the message
1249         # if PGP_ROLES is specified the user must have a Role in the list
1250         # or we will skip PGP processing
1251         def pgp_role():
1252             if self.instance.config.PGP_ROLES:
1253                 return self.db.user.has_role(author,
1254                     iter_roles(self.instance.config.PGP_ROLES))
1255             else:
1256                 return True
1258         if self.instance.config.PGP_ENABLE and pgp_role():
1259             assert pyme, 'pyme is not installed'
1260             # signed/encrypted mail must come from the primary address
1261             author_address = self.db.user.get(author, 'address')
1262             if self.instance.config.PGP_HOMEDIR:
1263                 os.environ['GNUPGHOME'] = self.instance.config.PGP_HOMEDIR
1264             if message.pgp_signed():
1265                 message.verify_signature(author_address)
1266             elif message.pgp_encrypted():
1267                 # replace message with the contents of the decrypted
1268                 # message for content extraction
1269                 # TODO: encrypted message handling is far from perfect
1270                 # bounces probably include the decrypted message, for
1271                 # instance :(
1272                 message = message.decrypt(author_address)
1273             else:
1274                 raise MailUsageError, _("""
1275 This tracker has been configured to require all email be PGP signed or
1276 encrypted.""")
1277         # now handle the body - find the message
1278         ig = self.instance.config.MAILGW_IGNORE_ALTERNATIVES
1279         content, attachments = message.extract_content(ignore_alternatives = ig)
1280         if content is None:
1281             raise MailUsageError, _("""
1282 Roundup requires the submission to be plain text. The message parser could
1283 not find a text/plain part to use.
1284 """)
1286         # parse the body of the message, stripping out bits as appropriate
1287         summary, content = parseContent(content, config=config)
1288         content = content.strip()
1290         #
1291         # handle the attachments
1292         #
1293         files = []
1294         if attachments and properties.has_key('files'):
1295             for (name, mime_type, data) in attachments:
1296                 if not self.db.security.hasPermission('Create', author, 'file'):
1297                     raise Unauthorized, _(
1298                         'You are not permitted to create files.')
1299                 if not name:
1300                     name = "unnamed"
1301                 try:
1302                     fileid = self.db.file.create(type=mime_type, name=name,
1303                          content=data, **file_props)
1304                 except exceptions.Reject:
1305                     pass
1306                 else:
1307                     files.append(fileid)
1308             # allowed to attach the files to an existing node?
1309             if nodeid and not self.db.security.hasPermission('Edit', author,
1310                     classname, 'files'):
1311                 raise Unauthorized, _(
1312                     'You are not permitted to add files to %(classname)s.'
1313                     ) % locals()
1315             if nodeid:
1316                 # extend the existing files list
1317                 fileprop = cl.get(nodeid, 'files')
1318                 fileprop.extend(files)
1319                 props['files'] = fileprop
1320             else:
1321                 # pre-load the files list
1322                 props['files'] = files
1324         #
1325         # create the message if there's a message body (content)
1326         #
1327         if (content and properties.has_key('messages')):
1328             if not self.db.security.hasPermission('Create', author, 'msg'):
1329                 raise Unauthorized, _(
1330                     'You are not permitted to create messages.')
1332             try:
1333                 message_id = self.db.msg.create(author=author,
1334                     recipients=recipients, date=date.Date('.'),
1335                     summary=summary, content=content, files=files,
1336                     messageid=messageid, inreplyto=inreplyto, **msg_props)
1337             except exceptions.Reject, error:
1338                 raise MailUsageError, _("""
1339 Mail message was rejected by a detector.
1340 %(error)s
1341 """) % locals()
1342             # allowed to attach the message to the existing node?
1343             if nodeid and not self.db.security.hasPermission('Edit', author,
1344                     classname, 'messages'):
1345                 raise Unauthorized, _(
1346                     'You are not permitted to add messages to %(classname)s.'
1347                     ) % locals()
1349             if nodeid:
1350                 # add the message to the node's list
1351                 messages = cl.get(nodeid, 'messages')
1352                 messages.append(message_id)
1353                 props['messages'] = messages
1354             else:
1355                 # pre-load the messages list
1356                 props['messages'] = [message_id]
1358         #
1359         # perform the node change / create
1360         #
1361         try:
1362             # merge the command line props defined in issue_props into
1363             # the props dictionary because function(**props, **issue_props)
1364             # is a syntax error.
1365             for prop in issue_props.keys() :
1366                 if not props.has_key(prop) :
1367                     props[prop] = issue_props[prop]
1369             if nodeid:
1370                 # Check permissions for each property
1371                 for prop in props.keys():
1372                     if not self.db.security.hasPermission('Edit', author,
1373                             classname, prop):
1374                         raise Unauthorized, _('You are not permitted to edit '
1375                             'property %(prop)s of class %(classname)s.') % locals()
1376                 cl.set(nodeid, **props)
1377             else:
1378                 # Check permissions for each property
1379                 for prop in props.keys():
1380                     if not self.db.security.hasPermission('Create', author,
1381                             classname, prop):
1382                         raise Unauthorized, _('You are not permitted to set '
1383                             'property %(prop)s of class %(classname)s.') % locals()
1384                 nodeid = cl.create(**props)
1385         except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1386             raise MailUsageError, _("""
1387 There was a problem with the message you sent:
1388    %(message)s
1389 """) % locals()
1391         # commit the changes to the DB
1392         self.db.commit()
1394         return nodeid
1397 def setPropArrayFromString(self, cl, propString, nodeid=None):
1398     ''' takes string of form prop=value,value;prop2=value
1399         and returns (error, prop[..])
1400     '''
1401     props = {}
1402     errors = []
1403     for prop in string.split(propString, ';'):
1404         # extract the property name and value
1405         try:
1406             propname, value = prop.split('=')
1407         except ValueError, message:
1408             errors.append(_('not of form [arg=value,value,...;'
1409                 'arg=value,value,...]'))
1410             return (errors, props)
1411         # convert the value to a hyperdb-usable value
1412         propname = propname.strip()
1413         try:
1414             props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1415                 propname, value)
1416         except hyperdb.HyperdbValueError, message:
1417             errors.append(str(message))
1418     return errors, props
1421 def extractUserFromList(userClass, users):
1422     '''Given a list of users, try to extract the first non-anonymous user
1423        and return that user, otherwise return None
1424     '''
1425     if len(users) > 1:
1426         for user in users:
1427             # make sure we don't match the anonymous or admin user
1428             if userClass.get(user, 'username') in ('admin', 'anonymous'):
1429                 continue
1430             # first valid match will do
1431             return user
1432         # well, I guess we have no choice
1433         return user[0]
1434     elif users:
1435         return users[0]
1436     return None
1439 def uidFromAddress(db, address, create=1, **user_props):
1440     ''' address is from the rfc822 module, and therefore is (name, addr)
1442         user is created if they don't exist in the db already
1443         user_props may supply additional user information
1444     '''
1445     (realname, address) = address
1447     # try a straight match of the address
1448     user = extractUserFromList(db.user, db.user.stringFind(address=address))
1449     if user is not None:
1450         return user
1452     # try the user alternate addresses if possible
1453     props = db.user.getprops()
1454     if props.has_key('alternate_addresses'):
1455         users = db.user.filter(None, {'alternate_addresses': address})
1456         user = extractUserFromList(db.user, users)
1457         if user is not None:
1458             return user
1460     # try to match the username to the address (for local
1461     # submissions where the address is empty)
1462     user = extractUserFromList(db.user, db.user.stringFind(username=address))
1464     # couldn't match address or username, so create a new user
1465     if create:
1466         # generate a username
1467         if '@' in address:
1468             username = address.split('@')[0]
1469         else:
1470             username = address
1471         trying = username
1472         n = 0
1473         while 1:
1474             try:
1475                 # does this username exist already?
1476                 db.user.lookup(trying)
1477             except KeyError:
1478                 break
1479             n += 1
1480             trying = username + str(n)
1482         # create!
1483         try:
1484             return db.user.create(username=trying, address=address,
1485                 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1486                 password=password.Password(password.generatePassword()),
1487                 **user_props)
1488         except exceptions.Reject:
1489             return 0
1490     else:
1491         return 0
1493 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1494     """Parse mail message; return message summary and stripped content
1496     The message body is divided into sections by blank lines.
1497     Sections where the second and all subsequent lines begin with a ">"
1498     or "|" character are considered "quoting sections". The first line of
1499     the first non-quoting section becomes the summary of the message.
1501     Arguments:
1503         keep_citations: declared for backward compatibility.
1504             If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1506         keep_body: declared for backward compatibility.
1507             If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1509         config: tracker configuration object.
1510             If omitted or None, use default configuration.
1512     """
1513     if config is None:
1514         config = configuration.CoreConfig()
1515     if keep_citations is None:
1516         keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1517     if keep_body is None:
1518         keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1519     eol = config["MAILGW_EOL_RE"]
1520     signature = config["MAILGW_SIGN_RE"]
1521     original_msg = config["MAILGW_ORIGMSG_RE"]
1523     # strip off leading carriage-returns / newlines
1524     i = 0
1525     for i in range(len(content)):
1526         if content[i] not in '\r\n':
1527             break
1528     if i > 0:
1529         sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1530     else:
1531         sections = config["MAILGW_BLANKLINE_RE"].split(content)
1533     # extract out the summary from the message
1534     summary = ''
1535     l = []
1536     for section in sections:
1537         #section = section.strip()
1538         if not section:
1539             continue
1540         lines = eol.split(section)
1541         if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1542                 lines[1] and lines[1][0] in '>|'):
1543             # see if there's a response somewhere inside this section (ie.
1544             # no blank line between quoted message and response)
1545             for line in lines[1:]:
1546                 if line and line[0] not in '>|':
1547                     break
1548             else:
1549                 # we keep quoted bits if specified in the config
1550                 if keep_citations:
1551                     l.append(section)
1552                 continue
1553             # keep this section - it has reponse stuff in it
1554             lines = lines[lines.index(line):]
1555             section = '\n'.join(lines)
1556             # and while we're at it, use the first non-quoted bit as
1557             # our summary
1558             summary = section
1560         if not summary:
1561             # if we don't have our summary yet use the first line of this
1562             # section
1563             summary = section
1564         elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1565             # lose any signature
1566             break
1567         elif original_msg.match(lines[0]):
1568             # ditch the stupid Outlook quoting of the entire original message
1569             break
1571         # and add the section to the output
1572         l.append(section)
1574     # figure the summary - find the first sentence-ending punctuation or the
1575     # first whole line, whichever is longest
1576     sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1577     if sentence:
1578         sentence = sentence.group(1)
1579     else:
1580         sentence = ''
1581     first = eol.split(summary)[0]
1582     summary = max(sentence, first)
1584     # Now reconstitute the message content minus the bits we don't care
1585     # about.
1586     if not keep_body:
1587         content = '\n\n'.join(l)
1589     return summary, content
1591 # vim: set filetype=python sts=4 sw=4 et si :