Code

. add test for multipart messages with first part being encoded.
[roundup.git] / roundup / mailgw.py
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
19 __doc__ = '''
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.61 2002-02-04 09:40:21 grubert Exp $
77 '''
80 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
81 import time, random
82 import traceback, MimeWriter
83 import hyperdb, date, password
85 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
87 class MailGWError(ValueError):
88     pass
90 class MailUsageError(ValueError):
91     pass
93 class MailUsageHelp(Exception):
94     pass
96 class UnAuthorized(Exception):
97     """ Access denied """
99 class Message(mimetools.Message):
100     ''' subclass mimetools.Message so we can retrieve the parts of the
101         message...
102     '''
103     def getPart(self):
104         ''' Get a single part of a multipart message and return it as a new
105             Message instance.
106         '''
107         boundary = self.getparam('boundary')
108         mid, end = '--'+boundary, '--'+boundary+'--'
109         s = cStringIO.StringIO()
110         while 1:
111             line = self.fp.readline()
112             if not line:
113                 break
114             if line.strip() in (mid, end):
115                 break
116             s.write(line)
117         if not s.getvalue().strip():
118             return None
119         s.seek(0)
120         return Message(s)
122 subject_re = re.compile(r'(?P<refwd>\s*\W?\s*(fwd|re|aw)\s*\W?\s*)*'
123     r'\s*(\[(?P<classname>[^\d\s]+)(?P<nodeid>\d+)?\])'
124     r'\s*(?P<title>[^[]+)?(\[(?P<args>.+?)\])?', re.I)
126 class MailGW:
127     def __init__(self, instance, db):
128         self.instance = instance
129         self.db = db
131     def main(self, fp):
132         ''' fp - the file from which to read the Message.
133         '''
134         self.handle_Message(Message(fp))
136     def handle_Message(self, message):
137         '''Handle an RFC822 Message
139         Handle the Message object by calling handle_message() and then cope
140         with any errors raised by handle_message.
141         This method's job is to make that call and handle any
142         errors in a sane manner. It should be replaced if you wish to
143         handle errors in a different manner.
144         '''
145         # in some rare cases, a particularly stuffed-up e-mail will make
146         # its way into here... try to handle it gracefully
147         sendto = message.getaddrlist('from')
148         if sendto:
149             try:
150                 return self.handle_message(message)
151             except MailUsageHelp:
152                 # bounce the message back to the sender with the usage message
153                 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
154                 sendto = [sendto[0][1]]
155                 m = ['']
156                 m.append('\n\nMail Gateway Help\n=================')
157                 m.append(fulldoc)
158                 m = self.bounce_message(message, sendto, m,
159                     subject="Mail Gateway Help")
160             except MailUsageError, value:
161                 # bounce the message back to the sender with the usage message
162                 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
163                 sendto = [sendto[0][1]]
164                 m = ['']
165                 m.append(str(value))
166                 m.append('\n\nMail Gateway Help\n=================')
167                 m.append(fulldoc)
168                 m = self.bounce_message(message, sendto, m)
169             except UnAuthorized, value:
170                 # just inform the user that he is not authorized
171                 sendto = [sendto[0][1]]
172                 m = ['']
173                 m.append(str(value))
174                 m = self.bounce_message(message, sendto, m)
175             except:
176                 # bounce the message back to the sender with the error message
177                 sendto = [sendto[0][1], self.instance.ADMIN_EMAIL]
178                 m = ['']
179                 m.append('An unexpected error occurred during the processing')
180                 m.append('of your message. The tracker administrator is being')
181                 m.append('notified.\n')
182                 m.append('----  traceback of failure  ----')
183                 s = cStringIO.StringIO()
184                 import traceback
185                 traceback.print_exc(None, s)
186                 m.append(s.getvalue())
187                 m = self.bounce_message(message, sendto, m)
188         else:
189             # very bad-looking message - we don't even know who sent it
190             sendto = [self.instance.ADMIN_EMAIL]
191             m = ['Subject: badly formed message from mail gateway']
192             m.append('')
193             m.append('The mail gateway retrieved a message which has no From:')
194             m.append('line, indicating that it is corrupt. Please check your')
195             m.append('mail gateway source. Failed message is attached.')
196             m.append('')
197             m = self.bounce_message(message, sendto, m,
198                 subject='Badly formed message from mail gateway')
200         # now send the message
201         if SENDMAILDEBUG:
202             open(SENDMAILDEBUG, 'w').write('From: %s\nTo: %s\n%s\n'%(
203                 self.instance.ADMIN_EMAIL, ', '.join(sendto), m.getvalue()))
204         else:
205             try:
206                 smtp = smtplib.SMTP(self.instance.MAILHOST)
207                 smtp.sendmail(self.instance.ADMIN_EMAIL, sendto, m.getvalue())
208             except socket.error, value:
209                 raise MailGWError, "Couldn't send error email: "\
210                     "mailhost %s"%value
211             except smtplib.SMTPException, value:
212                 raise MailGWError, "Couldn't send error email: %s"%value
214     def bounce_message(self, message, sendto, error,
215             subject='Failed issue tracker submission'):
216         ''' create a message that explains the reason for the failed
217             issue submission to the author and attach the original
218             message.
219         '''
220         msg = cStringIO.StringIO()
221         writer = MimeWriter.MimeWriter(msg)
222         writer.addheader('Subject', subject)
223         writer.addheader('From', '%s <%s>'% (self.instance.INSTANCE_NAME,
224                                             self.instance.ISSUE_TRACKER_EMAIL))
225         writer.addheader('To', ','.join(sendto))
226         writer.addheader('MIME-Version', '1.0')
227         part = writer.startmultipartbody('mixed')
228         part = writer.nextpart()
229         body = part.startbody('text/plain')
230         body.write('\n'.join(error))
232         # reconstruct the original message
233         m = cStringIO.StringIO()
234         w = MimeWriter.MimeWriter(m)
235         # default the content_type, just in case...
236         content_type = 'text/plain'
237         # add the headers except the content-type
238         for header in message.headers:
239             header_name = header.split(':')[0]
240             if header_name.lower() == 'content-type':
241                 content_type = message.getheader(header_name)
242             elif message.getheader(header_name):
243                 w.addheader(header_name, message.getheader(header_name))
244         # now attach the message body
245         body = w.startbody(content_type)
246         try:
247             message.rewindbody()
248         except IOError:
249             body.write("*** couldn't include message body: read from pipe ***")
250         else:
251             body.write(message.fp.read())
253         # attach the original message to the returned message
254         part = writer.nextpart()
255         part.addheader('Content-Disposition','attachment')
256         part.addheader('Content-Description','Message you sent')
257         part.addheader('Content-Transfer-Encoding', '7bit')
258         body = part.startbody('message/rfc822')
259         body.write(m.getvalue())
261         writer.lastpart()
262         return msg
264     def handle_message(self, message):
265         ''' message - a Message instance
267         Parse the message as per the module docstring.
268         '''
269         # handle the subject line
270         subject = message.getheader('subject', '')
272         if subject.strip() == 'help':
273             raise MailUsageHelp
275         m = subject_re.match(subject)
276         if not m:
277             raise MailUsageError, '''
278 The message you sent to roundup did not contain a properly formed subject
279 line. The subject must contain a class name or designator to indicate the
280 "topic" of the message. For example:
281     Subject: [issue] This is a new issue
282       - this will create a new issue in the tracker with the title "This is
283         a new issue".
284     Subject: [issue1234] This is a followup to issue 1234
285       - this will append the message's contents to the existing issue 1234
286         in the tracker.
288 Subject was: "%s"
289 '''%subject
291         # get the classname
292         classname = m.group('classname')
293         try:
294             cl = self.db.getclass(classname)
295         except KeyError:
296             raise MailUsageError, '''
297 The class name you identified in the subject line ("%s") does not exist in the
298 database.
300 Valid class names are: %s
301 Subject was: "%s"
302 '''%(classname, ', '.join(self.db.getclasses()), subject)
304         # get the optional nodeid
305         nodeid = m.group('nodeid')
307         # title is optional too
308         title = m.group('title')
309         if title:
310             title = title.strip()
311         else:
312             title = ''
314         # but we do need either a title or a nodeid...
315         if not nodeid and not title:
316             raise MailUsageError, '''
317 I cannot match your message to a node in the database - you need to either
318 supply a full node identifier (with number, eg "[issue123]" or keep the
319 previous subject title intact so I can match that.
321 Subject was: "%s"
322 '''%subject
324         # extract the args
325         subject_args = m.group('args')
327         # If there's no nodeid, check to see if this is a followup and
328         # maybe someone's responded to the initial mail that created an
329         # entry. Try to find the matching nodes with the same title, and
330         # use the _last_ one matched (since that'll _usually_ be the most
331         # recent...)
332         if not nodeid and m.group('refwd'):
333             l = cl.stringFind(title=title)
334             if l:
335                 nodeid = l[-1]
337         # start of the props
338         properties = cl.getprops()
339         props = {}
341         # handle the args
342         args = m.group('args')
343         if args:
344             for prop in string.split(args, ';'):
345                 # extract the property name and value
346                 try:
347                     key, value = prop.split('=')
348                 except ValueError, message:
349                     raise MailUsageError, '''
350 Subject argument list not of form [arg=value,value,...;arg=value,value...]
351    (specific exception message was "%s")
353 Subject was: "%s"
354 '''%(message, subject)
356                 # ensure it's a valid property name
357                 key = key.strip()
358                 try:
359                     proptype =  properties[key]
360                 except KeyError:
361                     raise MailUsageError, '''
362 Subject argument list refers to an invalid property: "%s"
364 Subject was: "%s"
365 '''%(key, subject)
367                 # convert the string value to a real property value
368                 if isinstance(proptype, hyperdb.String):
369                     props[key] = value.strip()
370                 if isinstance(proptype, hyperdb.Password):
371                     props[key] = password.Password(value.strip())
372                 elif isinstance(proptype, hyperdb.Date):
373                     try:
374                         props[key] = date.Date(value.strip())
375                     except ValueError, message:
376                         raise UsageError, '''
377 Subject argument list contains an invalid date for %s.
379 Error was: %s
380 Subject was: "%s"
381 '''%(key, message, subject)
382                 elif isinstance(proptype, hyperdb.Interval):
383                     try:
384                         props[key] = date.Interval(value) # no strip needed
385                     except ValueError, message:
386                         raise UsageError, '''
387 Subject argument list contains an invalid date interval for %s.
389 Error was: %s
390 Subject was: "%s"
391 '''%(key, message, subject)
392                 elif isinstance(proptype, hyperdb.Link):
393                     linkcl = self.db.classes[proptype.classname]
394                     propkey = linkcl.labelprop(default_to_id=1)
395                     try:
396                         props[key] = linkcl.lookup(value)
397                     except KeyError, message:
398                         raise MailUsageError, '''
399 Subject argument list contains an invalid value for %s.
401 Error was: %s
402 Subject was: "%s"
403 '''%(key, message, subject)
404                 elif isinstance(proptype, hyperdb.Multilink):
405                     # get the linked class
406                     linkcl = self.db.classes[proptype.classname]
407                     propkey = linkcl.labelprop(default_to_id=1)
408                     for item in value.split(','):
409                         item = item.strip()
410                         try:
411                             item = linkcl.lookup(item)
412                         except KeyError, message:
413                             raise MailUsageError, '''
414 Subject argument list contains an invalid value for %s.
416 Error was: %s
417 Subject was: "%s"
418 '''%(key, message, subject)
419                         if props.has_key(key):
420                             props[key].append(item)
421                         else:
422                             props[key] = [item]
424         #
425         # handle the users
426         #
428         # Don't create users if ANONYMOUS_REGISTER is denied
429         if self.instance.ANONYMOUS_REGISTER == 'deny':
430             create = 0
431         else:
432             create = 1
433         author = self.db.uidFromAddress(message.getaddrlist('from')[0],
434             create=create)
435         if not author:
436             raise UnAuthorized, '''
437 You are not a registered user.
439 Unknown address: %s
440 '''%message.getaddrlist('from')[0][1]
442         # the author may have been created - make sure the change is
443         # committed before we reopen the database
444         self.db.commit()
445             
446         # reopen the database as the author
447         username = self.db.user.get(author, 'username')
448         self.db = self.instance.open(username)
450         # re-get the class with the new database connection
451         cl = self.db.getclass(classname)
453         # now update the recipients list
454         recipients = []
455         tracker_email = self.instance.ISSUE_TRACKER_EMAIL.lower()
456         for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
457             r = recipient[1].strip().lower()
458             if r == tracker_email or not r:
459                 continue
460             recipients.append(self.db.uidFromAddress(recipient))
462         #
463         # handle message-id and in-reply-to
464         #
465         messageid = message.getheader('message-id')
466         inreplyto = message.getheader('in-reply-to') or ''
467         # generate a messageid if there isn't one
468         if not messageid:
469             messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
470                 classname, nodeid, self.instance.MAIL_DOMAIN)
472         #
473         # now handle the body - find the message
474         #
475         content_type =  message.gettype()
476         attachments = []
477         if content_type == 'multipart/mixed':
478             # skip over the intro to the first boundary
479             part = message.getPart()
480             content = None
481             while 1:
482                 # get the next part
483                 part = message.getPart()
484                 if part is None:
485                     break
486                 # parse it
487                 subtype = part.gettype()
488                 if subtype == 'text/plain' and not content:
489                     # add all text/plain parts to the message content
490                     # BUG (in code or comment) only add the first one. 
491                     if content is None:
492                         # try name on Content-Type
493                         # maybe add name to non text content ?
494                         name = part.getparam('name')
495                         # assume first part is the mail
496                         encoding = part.getencoding()
497                         if encoding == 'base64':
498                             # BUG: is base64 really used for text encoding or
499                             # are we inserting zip files here. 
500                             data = binascii.a2b_base64(part.fp.read())
501                         elif encoding == 'quoted-printable':
502                             # the quopri module wants to work with files
503                             decoded = cStringIO.StringIO()
504                             quopri.decode(part.fp, decoded)
505                             data = decoded.getvalue()
506                         elif encoding == 'uuencoded':
507                             data = binascii.a2b_uu(part.fp.read())
508                             attachments.append((name, part.gettype(), data))
509                         else:
510                             # take it as text
511                             data = part.fp.read()
512                         content = data
513                     else:
514                         content = content + part.fp.read()
516                 elif subtype == 'message/rfc822':
517                     # handle message/rfc822 specially - the name should be
518                     # the subject of the actual e-mail embedded here
519                     i = part.fp.tell()
520                     mailmess = Message(part.fp)
521                     name = mailmess.getheader('subject')
522                     part.fp.seek(i)
523                     attachments.append((name, 'message/rfc822', part.fp.read()))
525                 else:
526                     # try name on Content-Type
527                     name = part.getparam('name')
528                     # this is just an attachment
529                     encoding = part.getencoding()
530                     if encoding == 'base64':
531                         data = binascii.a2b_base64(part.fp.read())
532                     elif encoding == 'quoted-printable':
533                         # the quopri module wants to work with files
534                         decoded = cStringIO.StringIO()
535                         quopri.decode(part.fp, decoded)
536                         data = decoded.getvalue()
537                     elif encoding == 'uuencoded':
538                         data = binascii.a2b_uu(part.fp.read())
539                     attachments.append((name, part.gettype(), data))
540             if content is None:
541                 raise MailUsageError, '''
542 Roundup requires the submission to be plain text. The message parser could
543 not find a text/plain part to use.
544 '''
546         elif content_type[:10] == 'multipart/':
547             # skip over the intro to the first boundary
548             message.getPart()
549             content = None
550             while 1:
551                 # get the next part
552                 part = message.getPart()
553                 if part is None:
554                     break
555                 # parse it
556                 if part.gettype() == 'text/plain' and not content:
557                     # this one's our content
558                     content = part.fp.read()
559             if content is None:
560                 raise MailUsageError, '''
561 Roundup requires the submission to be plain text. The message parser could
562 not find a text/plain part to use.
563 '''
565         elif content_type != 'text/plain':
566             raise MailUsageError, '''
567 Roundup requires the submission to be plain text. The message parser could
568 not find a text/plain part to use.
569 '''
571         else:
572             content = message.fp.read()
574         summary, content = parseContent(content)
576         # 
577         # handle the attachments
578         #
579         files = []
580         for (name, mime_type, data) in attachments:
581             if not name:
582                 name = "unnamed"
583             files.append(self.db.file.create(type=mime_type, name=name,
584                 content=data))
586         #
587         # now handle the db stuff
588         #
589         if nodeid:
590             # If an item designator (class name and id number) is found there,
591             # the newly created "msg" node is added to the "messages" property
592             # for that item, and any new "file" nodes are added to the "files" 
593             # property for the item. 
595             # if the message is currently 'unread' or 'resolved', then set
596             # it to 'chatting'
597             if properties.has_key('status'):
598                 try:
599                     # determine the id of 'unread', 'resolved' and 'chatting'
600                     unread_id = self.db.status.lookup('unread')
601                     resolved_id = self.db.status.lookup('resolved')
602                     chatting_id = self.db.status.lookup('chatting')
603                 except KeyError:
604                     pass
605                 else:
606                     current_status = cl.get(nodeid, 'status')
607                     if (not props.has_key('status') and
608                             current_status == unread_id or
609                             current_status == resolved_id):
610                         props['status'] = chatting_id
612             # add nosy in arguments to issue's nosy list
613             if not props.has_key('nosy'): props['nosy'] = []
614             n = {}
615             for nid in cl.get(nodeid, 'nosy'):
616                 n[nid] = 1
617             for value in props['nosy']:
618                 if self.db.hasnode('user', value):
619                     nid = value
620                 else: 
621                     continue
622                 if n.has_key(nid): continue
623                 n[nid] = 1
624             props['nosy'] = n.keys()
625             # add assignedto to the nosy list
626             if props.has_key('assignedto'):
627                 assignedto = props['assignedto']
628                 if assignedto not in props['nosy']:
629                     props['nosy'].append(assignedto)
631             message_id = self.db.msg.create(author=author,
632                 recipients=recipients, date=date.Date('.'), summary=summary,
633                 content=content, files=files, messageid=messageid,
634                 inreplyto=inreplyto)
635             try:
636                 messages = cl.get(nodeid, 'messages')
637             except IndexError:
638                 raise MailUsageError, '''
639 The node specified by the designator in the subject of your message ("%s")
640 does not exist.
642 Subject was: "%s"
643 '''%(nodeid, subject)
644             messages.append(message_id)
645             props['messages'] = messages
647             # now apply the changes
648             try:
649                 cl.set(nodeid, **props)
650             except (TypeError, IndexError, ValueError), message:
651                 raise MailUsageError, '''
652 There was a problem with the message you sent:
653    %s
654 '''%message
655             # commit the changes to the DB
656             self.db.commit()
657         else:
658             # If just an item class name is found there, we attempt to create a
659             # new item of that class with its "messages" property initialized to
660             # contain the new "msg" node and its "files" property initialized to
661             # contain any new "file" nodes. 
662             message_id = self.db.msg.create(author=author,
663                 recipients=recipients, date=date.Date('.'), summary=summary,
664                 content=content, files=files, messageid=messageid,
665                 inreplyto=inreplyto)
667             # pre-set the issue to unread
668             if properties.has_key('status') and not props.has_key('status'):
669                 try:
670                     # determine the id of 'unread'
671                     unread_id = self.db.status.lookup('unread')
672                 except KeyError:
673                     pass
674                 else:
675                     props['status'] = '1'
677             # set the title to the subject
678             if properties.has_key('title') and not props.has_key('title'):
679                 props['title'] = title
681             # pre-load the messages list
682             props['messages'] = [message_id]
684             # set up (clean) the nosy list
685             nosy = props.get('nosy', [])
686             n = {}
687             for value in nosy:
688                 nid = value
689                 if n.has_key(nid): continue
690                 n[nid] = 1
691             props['nosy'] = n.keys()
692             # add on the recipients of the message
693             for recipient in recipients:
694                 if not n.has_key(recipient):
695                     props['nosy'].append(recipient)
696                     n[recipient] = 1
698             # add the author to the nosy list
699             if not n.has_key(author):
700                 props['nosy'].append(author)
701                 n[author] = 1
703             # add assignedto to the nosy list
704             if properties.has_key('assignedto') and props.has_key('assignedto'):
705                 assignedto = props['assignedto']
706                 if not n.has_key(assignedto):
707                     props['nosy'].append(assignedto)
708                     n[assignedto] = 1
710             # and attempt to create the new node
711             try:
712                 nodeid = cl.create(**props)
713             except (TypeError, IndexError, ValueError), message:
714                 raise MailUsageError, '''
715 There was a problem with the message you sent:
716    %s
717 '''%message
719             # commit the new node(s) to the DB
720             self.db.commit()
722 def parseContent(content, blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
723         eol=re.compile(r'[\r\n]+'), signature=re.compile(r'^[>|\s]*[-_]+\s*$')):
724     ''' The message body is divided into sections by blank lines.
725     Sections where the second and all subsequent lines begin with a ">" or "|"
726     character are considered "quoting sections". The first line of the first
727     non-quoting section becomes the summary of the message. 
728     '''
729     # strip off leading carriage-returns / newlines
730     i = 0
731     for i in range(len(content)):
732         if content[i] not in '\r\n':
733             break
734     if i > 0:
735         sections = blank_line.split(content[i:])
736     else:
737         sections = blank_line.split(content)
739     # extract out the summary from the message
740     summary = ''
741     l = []
742     for section in sections:
743         #section = section.strip()
744         if not section:
745             continue
746         lines = eol.split(section)
747         if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
748                 lines[1] and lines[1][0] in '>|'):
749             # see if there's a response somewhere inside this section (ie.
750             # no blank line between quoted message and response)
751             for line in lines[1:]:
752                 if line[0] not in '>|':
753                     break
754             else:
755                 # TODO: people who want to keep quoted bits will want the
756                 # next line...
757                 # l.append(section)
758                 continue
759             # keep this section - it has reponse stuff in it
760             if not summary:
761                 # and while we're at it, use the first non-quoted bit as
762                 # our summary
763                 summary = line
764             lines = lines[lines.index(line):]
765             section = '\n'.join(lines)
767         if not summary:
768             # if we don't have our summary yet use the first line of this
769             # section
770             summary = lines[0]
771         elif signature.match(lines[0]):
772             break
774         # and add the section to the output
775         l.append(section)
776     return summary, '\n\n'.join(l)
779 # $Log: not supported by cvs2svn $
780 # Revision 1.60  2002/02/01 07:43:12  grubert
781 #  . mailgw checks encoding on first part too.
783 # Revision 1.59  2002/01/23 21:43:23  richard
784 # tabnuke
786 # Revision 1.58  2002/01/23 21:41:56  richard
787 #  . mailgw failures (unexpected ones) are forwarded to the roundup admin
789 # Revision 1.57  2002/01/22 22:27:43  richard
790 #  . handle stripping of "AW:" from subject line
792 # Revision 1.56  2002/01/22 11:54:45  rochecompaan
793 # Fixed status change in mail gateway.
795 # Revision 1.55  2002/01/21 10:05:47  rochecompaan
796 # Feature:
797 #  . the mail gateway now responds with an error message when invalid
798 #    values for arguments are specified for link or multilink properties
799 #  . modified unit test to check nosy and assignedto when specified as
800 #    arguments
802 # Fixed:
803 #  . fixed setting nosy as argument in subject line
805 # Revision 1.54  2002/01/16 09:14:45  grubert
806 #  . if the attachment has no name, name it unnamed, happens with tnefs.
808 # Revision 1.53  2002/01/16 07:20:54  richard
809 # simple help command for mailgw
811 # Revision 1.52  2002/01/15 00:12:40  richard
812 # #503340 ] creating issue with [asignedto=p.ohly]
814 # Revision 1.51  2002/01/14 02:20:15  richard
815 #  . changed all config accesses so they access either the instance or the
816 #    config attriubute on the db. This means that all config is obtained from
817 #    instance_config instead of the mish-mash of classes. This will make
818 #    switching to a ConfigParser setup easier too, I hope.
820 # At a minimum, this makes migration a _little_ easier (a lot easier in the
821 # 0.5.0 switch, I hope!)
823 # Revision 1.50  2002/01/11 22:59:01  richard
824 #  . #502342 ] pipe interface
826 # Revision 1.49  2002/01/10 06:19:18  richard
827 # followup lines directly after a quoted section were being eaten.
829 # Revision 1.48  2002/01/08 04:12:05  richard
830 # Changed message-id format to "<%s.%s.%s%s@%s>" so it complies with RFC822
832 # Revision 1.47  2002/01/02 02:32:38  richard
833 # ANONYMOUS_ACCESS -> ANONYMOUS_REGISTER
835 # Revision 1.46  2002/01/02 02:31:38  richard
836 # Sorry for the huge checkin message - I was only intending to implement #496356
837 # but I found a number of places where things had been broken by transactions:
838 #  . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
839 #    for _all_ roundup-generated smtp messages to be sent to.
840 #  . the transaction cache had broken the roundupdb.Class set() reactors
841 #  . newly-created author users in the mailgw weren't being committed to the db
843 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
844 # on when I found that stuff :):
845 #  . #496356 ] Use threading in messages
846 #  . detectors were being registered multiple times
847 #  . added tests for mailgw
848 #  . much better attaching of erroneous messages in the mail gateway
850 # Revision 1.45  2001/12/20 15:43:01  rochecompaan
851 # Features added:
852 #  .  Multilink properties are now displayed as comma separated values in
853 #     a textbox
854 #  .  The add user link is now only visible to the admin user
855 #  .  Modified the mail gateway to reject submissions from unknown
856 #     addresses if ANONYMOUS_ACCESS is denied
858 # Revision 1.44  2001/12/18 15:30:34  rochecompaan
859 # Fixed bugs:
860 #  .  Fixed file creation and retrieval in same transaction in anydbm
861 #     backend
862 #  .  Cgi interface now renders new issue after issue creation
863 #  .  Could not set issue status to resolved through cgi interface
864 #  .  Mail gateway was changing status back to 'chatting' if status was
865 #     omitted as an argument
867 # Revision 1.43  2001/12/15 19:39:01  rochecompaan
868 # Oops.
870 # Revision 1.42  2001/12/15 19:24:39  rochecompaan
871 #  . Modified cgi interface to change properties only once all changes are
872 #    collected, files created and messages generated.
873 #  . Moved generation of change note to nosyreactors.
874 #  . We now check for changes to "assignedto" to ensure it's added to the
875 #    nosy list.
877 # Revision 1.41  2001/12/10 00:57:38  richard
878 # From CHANGES:
879 #  . Added the "display" command to the admin tool - displays a node's values
880 #  . #489760 ] [issue] only subject
881 #  . fixed the doc/index.html to include the quoting in the mail alias.
883 # Also:
884 #  . fixed roundup-admin so it works with transactions
885 #  . disabled the back_anydbm module if anydbm tries to use dumbdbm
887 # Revision 1.40  2001/12/05 14:26:44  rochecompaan
888 # Removed generation of change note from "sendmessage" in roundupdb.py.
889 # The change note is now generated when the message is created.
891 # Revision 1.39  2001/12/02 05:06:16  richard
892 # . We now use weakrefs in the Classes to keep the database reference, so
893 #   the close() method on the database is no longer needed.
894 #   I bumped the minimum python requirement up to 2.1 accordingly.
895 # . #487480 ] roundup-server
896 # . #487476 ] INSTALL.txt
898 # I also cleaned up the change message / post-edit stuff in the cgi client.
899 # There's now a clearly marked "TODO: append the change note" where I believe
900 # the change note should be added there. The "changes" list will obviously
901 # have to be modified to be a dict of the changes, or somesuch.
903 # More testing needed.
905 # Revision 1.38  2001/12/01 07:17:50  richard
906 # . We now have basic transaction support! Information is only written to
907 #   the database when the commit() method is called. Only the anydbm
908 #   backend is modified in this way - neither of the bsddb backends have been.
909 #   The mail, admin and cgi interfaces all use commit (except the admin tool
910 #   doesn't have a commit command, so interactive users can't commit...)
911 # . Fixed login/registration forwarding the user to the right page (or not,
912 #   on a failure)
914 # Revision 1.37  2001/11/28 21:55:35  richard
915 #  . login_action and newuser_action return values were being ignored
916 #  . Woohoo! Found that bloody re-login bug that was killing the mail
917 #    gateway.
918 #  (also a minor cleanup in hyperdb)
920 # Revision 1.36  2001/11/26 22:55:56  richard
921 # Feature:
922 #  . Added INSTANCE_NAME to configuration - used in web and email to identify
923 #    the instance.
924 #  . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
925 #    signature info in e-mails.
926 #  . Some more flexibility in the mail gateway and more error handling.
927 #  . Login now takes you to the page you back to the were denied access to.
929 # Fixed:
930 #  . Lots of bugs, thanks Roché and others on the devel mailing list!
932 # Revision 1.35  2001/11/22 15:46:42  jhermann
933 # Added module docstrings to all modules.
935 # Revision 1.34  2001/11/15 10:24:27  richard
936 # handle the case where there is no file attached
938 # Revision 1.33  2001/11/13 21:44:44  richard
939 #  . re-open the database as the author in mail handling
941 # Revision 1.32  2001/11/12 22:04:29  richard
942 # oops, left debug in there
944 # Revision 1.31  2001/11/12 22:01:06  richard
945 # Fixed issues with nosy reaction and author copies.
947 # Revision 1.30  2001/11/09 22:33:28  richard
948 # More error handling fixes.
950 # Revision 1.29  2001/11/07 05:29:26  richard
951 # Modified roundup-mailgw so it can read e-mails from a local mail spool
952 # file. Truncates the spool file after parsing.
953 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
954 # the popgw.
956 # Revision 1.28  2001/11/01 22:04:37  richard
957 # Started work on supporting a pop3-fetching server
958 # Fixed bugs:
959 #  . bug #477104 ] HTML tag error in roundup-server
960 #  . bug #477107 ] HTTP header problem
962 # Revision 1.27  2001/10/30 11:26:10  richard
963 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
965 # Revision 1.26  2001/10/30 00:54:45  richard
966 # Features:
967 #  . #467129 ] Lossage when username=e-mail-address
968 #  . #473123 ] Change message generation for author
969 #  . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
971 # Revision 1.25  2001/10/28 23:22:28  richard
972 # fixed bug #474749 ] Indentations lost
974 # Revision 1.24  2001/10/23 22:57:52  richard
975 # Fix unread->chatting auto transition, thanks Roch'e
977 # Revision 1.23  2001/10/21 04:00:20  richard
978 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
980 # Revision 1.22  2001/10/21 03:35:13  richard
981 # bug #473125: Paragraph in e-mails
983 # Revision 1.21  2001/10/21 00:53:42  richard
984 # bug #473130: Nosy list not set correctly
986 # Revision 1.20  2001/10/17 23:13:19  richard
987 # Did a fair bit of work on the admin tool. Now has an extra command "table"
988 # which displays node information in a tabular format. Also fixed import and
989 # export so they work. Removed freshen.
990 # Fixed quopri usage in mailgw from bug reports.
992 # Revision 1.19  2001/10/11 23:43:04  richard
993 # Implemented the comma-separated printing option in the admin tool.
994 # Fixed a typo (more of a vim-o actually :) in mailgw.
996 # Revision 1.18  2001/10/11 06:38:57  richard
997 # Initial cut at trying to handle people responding to CC'ed messages that
998 # create an issue.
1000 # Revision 1.17  2001/10/09 07:25:59  richard
1001 # Added the Password property type. See "pydoc roundup.password" for
1002 # implementation details. Have updated some of the documentation too.
1004 # Revision 1.16  2001/10/05 02:23:24  richard
1005 #  . roundup-admin create now prompts for property info if none is supplied
1006 #    on the command-line.
1007 #  . hyperdb Class getprops() method may now return only the mutable
1008 #    properties.
1009 #  . Login now uses cookies, which makes it a whole lot more flexible. We can
1010 #    now support anonymous user access (read-only, unless there's an
1011 #    "anonymous" user, in which case write access is permitted). Login
1012 #    handling has been moved into cgi_client.Client.main()
1013 #  . The "extended" schema is now the default in roundup init.
1014 #  . The schemas have had their page headings modified to cope with the new
1015 #    login handling. Existing installations should copy the interfaces.py
1016 #    file from the roundup lib directory to their instance home.
1017 #  . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1018 #    Ping - has been removed.
1019 #  . Fixed a whole bunch of places in the CGI interface where we should have
1020 #    been returning Not Found instead of throwing an exception.
1021 #  . Fixed a deviation from the spec: trying to modify the 'id' property of
1022 #    an item now throws an exception.
1024 # Revision 1.15  2001/08/30 06:01:17  richard
1025 # Fixed missing import in mailgw :(
1027 # Revision 1.14  2001/08/13 23:02:54  richard
1028 # Make the mail parser a little more robust.
1030 # Revision 1.13  2001/08/12 06:32:36  richard
1031 # using isinstance(blah, Foo) now instead of isFooType
1033 # Revision 1.12  2001/08/08 01:27:00  richard
1034 # Added better error handling to mailgw.
1036 # Revision 1.11  2001/08/08 00:08:03  richard
1037 # oops ;)
1039 # Revision 1.10  2001/08/07 00:24:42  richard
1040 # stupid typo
1042 # Revision 1.9  2001/08/07 00:15:51  richard
1043 # Added the copyright/license notice to (nearly) all files at request of
1044 # Bizar Software.
1046 # Revision 1.8  2001/08/05 07:06:07  richard
1047 # removed some print statements
1049 # Revision 1.7  2001/08/03 07:18:22  richard
1050 # Implemented correct mail splitting (was taking a shortcut). Added unit
1051 # tests. Also snips signatures now too.
1053 # Revision 1.6  2001/08/01 04:24:21  richard
1054 # mailgw was assuming certain properties existed on the issues being created.
1056 # Revision 1.5  2001/07/29 07:01:39  richard
1057 # Added vim command to all source so that we don't get no steenkin' tabs :)
1059 # Revision 1.4  2001/07/28 06:43:02  richard
1060 # Multipart message class has the getPart method now. Added some tests for it.
1062 # Revision 1.3  2001/07/28 00:34:34  richard
1063 # Fixed some non-string node ids.
1065 # Revision 1.2  2001/07/22 12:09:32  richard
1066 # Final commit of Grande Splite
1069 # vim: set filetype=python ts=4 sw=4 et si