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.77 2002-07-18 11:17:31 gmcm 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 # should we trap exceptions (normal usage) or pass them through
132 # (for testing)
133 self.trapExceptions = 1
135 def main(self, fp):
136 ''' fp - the file from which to read the Message.
137 '''
138 return self.handle_Message(Message(fp))
140 def handle_Message(self, message):
141 '''Handle an RFC822 Message
143 Handle the Message object by calling handle_message() and then cope
144 with any errors raised by handle_message.
145 This method's job is to make that call and handle any
146 errors in a sane manner. It should be replaced if you wish to
147 handle errors in a different manner.
148 '''
149 # in some rare cases, a particularly stuffed-up e-mail will make
150 # its way into here... try to handle it gracefully
151 sendto = message.getaddrlist('from')
152 if sendto:
153 if not self.trapExceptions:
154 return self.handle_message(message)
155 try:
156 return self.handle_message(message)
157 except MailUsageHelp:
158 # bounce the message back to the sender with the usage message
159 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
160 sendto = [sendto[0][1]]
161 m = ['']
162 m.append('\n\nMail Gateway Help\n=================')
163 m.append(fulldoc)
164 m = self.bounce_message(message, sendto, m,
165 subject="Mail Gateway Help")
166 except MailUsageError, value:
167 # bounce the message back to the sender with the usage message
168 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
169 sendto = [sendto[0][1]]
170 m = ['']
171 m.append(str(value))
172 m.append('\n\nMail Gateway Help\n=================')
173 m.append(fulldoc)
174 m = self.bounce_message(message, sendto, m)
175 except UnAuthorized, value:
176 # just inform the user that he is not authorized
177 sendto = [sendto[0][1]]
178 m = ['']
179 m.append(str(value))
180 m = self.bounce_message(message, sendto, m)
181 except:
182 # bounce the message back to the sender with the error message
183 sendto = [sendto[0][1], self.instance.ADMIN_EMAIL]
184 m = ['']
185 m.append('An unexpected error occurred during the processing')
186 m.append('of your message. The tracker administrator is being')
187 m.append('notified.\n')
188 m.append('---- traceback of failure ----')
189 s = cStringIO.StringIO()
190 import traceback
191 traceback.print_exc(None, s)
192 m.append(s.getvalue())
193 m = self.bounce_message(message, sendto, m)
194 else:
195 # very bad-looking message - we don't even know who sent it
196 sendto = [self.instance.ADMIN_EMAIL]
197 m = ['Subject: badly formed message from mail gateway']
198 m.append('')
199 m.append('The mail gateway retrieved a message which has no From:')
200 m.append('line, indicating that it is corrupt. Please check your')
201 m.append('mail gateway source. Failed message is attached.')
202 m.append('')
203 m = self.bounce_message(message, sendto, m,
204 subject='Badly formed message from mail gateway')
206 # now send the message
207 if SENDMAILDEBUG:
208 open(SENDMAILDEBUG, 'w').write('From: %s\nTo: %s\n%s\n'%(
209 self.instance.ADMIN_EMAIL, ', '.join(sendto), m.getvalue()))
210 else:
211 try:
212 smtp = smtplib.SMTP(self.instance.MAILHOST)
213 smtp.sendmail(self.instance.ADMIN_EMAIL, sendto, m.getvalue())
214 except socket.error, value:
215 raise MailGWError, "Couldn't send error email: "\
216 "mailhost %s"%value
217 except smtplib.SMTPException, value:
218 raise MailGWError, "Couldn't send error email: %s"%value
220 def bounce_message(self, message, sendto, error,
221 subject='Failed issue tracker submission'):
222 ''' create a message that explains the reason for the failed
223 issue submission to the author and attach the original
224 message.
225 '''
226 msg = cStringIO.StringIO()
227 writer = MimeWriter.MimeWriter(msg)
228 writer.addheader('Subject', subject)
229 writer.addheader('From', '%s <%s>'% (self.instance.INSTANCE_NAME,
230 self.instance.ISSUE_TRACKER_EMAIL))
231 writer.addheader('To', ','.join(sendto))
232 writer.addheader('MIME-Version', '1.0')
233 part = writer.startmultipartbody('mixed')
234 part = writer.nextpart()
235 body = part.startbody('text/plain')
236 body.write('\n'.join(error))
238 # reconstruct the original message
239 m = cStringIO.StringIO()
240 w = MimeWriter.MimeWriter(m)
241 # default the content_type, just in case...
242 content_type = 'text/plain'
243 # add the headers except the content-type
244 for header in message.headers:
245 header_name = header.split(':')[0]
246 if header_name.lower() == 'content-type':
247 content_type = message.getheader(header_name)
248 elif message.getheader(header_name):
249 w.addheader(header_name, message.getheader(header_name))
250 # now attach the message body
251 body = w.startbody(content_type)
252 try:
253 message.rewindbody()
254 except IOError:
255 body.write("*** couldn't include message body: read from pipe ***")
256 else:
257 body.write(message.fp.read())
259 # attach the original message to the returned message
260 part = writer.nextpart()
261 part.addheader('Content-Disposition','attachment')
262 part.addheader('Content-Description','Message you sent')
263 part.addheader('Content-Transfer-Encoding', '7bit')
264 body = part.startbody('message/rfc822')
265 body.write(m.getvalue())
267 writer.lastpart()
268 return msg
270 def get_part_data_decoded(self,part):
271 encoding = part.getencoding()
272 data = None
273 if encoding == 'base64':
274 # BUG: is base64 really used for text encoding or
275 # are we inserting zip files here.
276 data = binascii.a2b_base64(part.fp.read())
277 elif encoding == 'quoted-printable':
278 # the quopri module wants to work with files
279 decoded = cStringIO.StringIO()
280 quopri.decode(part.fp, decoded)
281 data = decoded.getvalue()
282 elif encoding == 'uuencoded':
283 data = binascii.a2b_uu(part.fp.read())
284 else:
285 # take it as text
286 data = part.fp.read()
287 return data
289 def handle_message(self, message):
290 ''' message - a Message instance
292 Parse the message as per the module docstring.
293 '''
294 # handle the subject line
295 subject = message.getheader('subject', '')
297 if subject.strip() == 'help':
298 raise MailUsageHelp
300 m = subject_re.match(subject)
302 # check for well-formed subject line
303 if m:
304 # get the classname
305 classname = m.group('classname')
306 if classname is None:
307 # no classname, fallback on the default
308 if hasattr(self.instance, 'MAIL_DEFAULT_CLASS') and \
309 self.instance.MAIL_DEFAULT_CLASS:
310 classname = self.instance.MAIL_DEFAULT_CLASS
311 else:
312 # fail
313 m = None
315 if not m:
316 raise MailUsageError, '''
317 The message you sent to roundup did not contain a properly formed subject
318 line. The subject must contain a class name or designator to indicate the
319 "topic" of the message. For example:
320 Subject: [issue] This is a new issue
321 - this will create a new issue in the tracker with the title "This is
322 a new issue".
323 Subject: [issue1234] This is a followup to issue 1234
324 - this will append the message's contents to the existing issue 1234
325 in the tracker.
327 Subject was: "%s"
328 '''%subject
330 # get the class
331 try:
332 cl = self.db.getclass(classname)
333 except KeyError:
334 raise MailUsageError, '''
335 The class name you identified in the subject line ("%s") does not exist in the
336 database.
338 Valid class names are: %s
339 Subject was: "%s"
340 '''%(classname, ', '.join(self.db.getclasses()), subject)
342 # get the optional nodeid
343 nodeid = m.group('nodeid')
345 # title is optional too
346 title = m.group('title')
347 if title:
348 title = title.strip()
349 else:
350 title = ''
352 # but we do need either a title or a nodeid...
353 if nodeid is None and not title:
354 raise MailUsageError, '''
355 I cannot match your message to a node in the database - you need to either
356 supply a full node identifier (with number, eg "[issue123]" or keep the
357 previous subject title intact so I can match that.
359 Subject was: "%s"
360 '''%subject
362 # If there's no nodeid, check to see if this is a followup and
363 # maybe someone's responded to the initial mail that created an
364 # entry. Try to find the matching nodes with the same title, and
365 # use the _last_ one matched (since that'll _usually_ be the most
366 # recent...)
367 if nodeid is None and m.group('refwd'):
368 l = cl.stringFind(title=title)
369 if l:
370 nodeid = l[-1]
372 # if a nodeid was specified, make sure it's valid
373 if nodeid is not None and not cl.hasnode(nodeid):
374 raise MailUsageError, '''
375 The node specified by the designator in the subject of your message ("%s")
376 does not exist.
378 Subject was: "%s"
379 '''%(nodeid, subject)
381 #
382 # extract the args
383 #
384 subject_args = m.group('args')
386 #
387 # handle the subject argument list
388 #
389 # figure what the properties of this Class are
390 properties = cl.getprops()
391 props = {}
392 args = m.group('args')
393 if args:
394 errors = []
395 for prop in string.split(args, ';'):
396 # extract the property name and value
397 try:
398 propname, value = prop.split('=')
399 except ValueError, message:
400 errors.append('not of form [arg=value,'
401 'value,...;arg=value,value...]')
402 break
404 # ensure it's a valid property name
405 propname = propname.strip()
406 try:
407 proptype = properties[propname]
408 except KeyError:
409 errors.append('refers to an invalid property: '
410 '"%s"'%propname)
411 continue
413 # convert the string value to a real property value
414 if isinstance(proptype, hyperdb.String):
415 props[propname] = value.strip()
416 if isinstance(proptype, hyperdb.Password):
417 props[propname] = password.Password(value.strip())
418 elif isinstance(proptype, hyperdb.Date):
419 try:
420 props[propname] = date.Date(value.strip())
421 except ValueError, message:
422 errors.append('contains an invalid date for '
423 '%s.'%propname)
424 elif isinstance(proptype, hyperdb.Interval):
425 try:
426 props[propname] = date.Interval(value)
427 except ValueError, message:
428 errors.append('contains an invalid date interval'
429 'for %s.'%propname)
430 elif isinstance(proptype, hyperdb.Link):
431 linkcl = self.db.classes[proptype.classname]
432 propkey = linkcl.labelprop(default_to_id=1)
433 try:
434 props[propname] = linkcl.lookup(value)
435 except KeyError, message:
436 errors.append('"%s" is not a value for %s.'%(value,
437 propname))
438 elif isinstance(proptype, hyperdb.Multilink):
439 # get the linked class
440 linkcl = self.db.classes[proptype.classname]
441 propkey = linkcl.labelprop(default_to_id=1)
442 if nodeid:
443 curvalue = cl.get(nodeid, propname)
444 else:
445 curvalue = []
447 # handle each add/remove in turn
448 # keep an extra list for all items that are
449 # definitely in the new list (in case of e.g.
450 # <propname>=A,+B, which should replace the old
451 # list with A,B)
452 set = 0
453 newvalue = []
454 for item in value.split(','):
455 item = item.strip()
457 # handle +/-
458 remove = 0
459 if item.startswith('-'):
460 remove = 1
461 item = item[1:]
462 elif item.startswith('+'):
463 item = item[1:]
464 else:
465 set = 1
467 # look up the value
468 try:
469 item = linkcl.lookup(item)
470 except KeyError, message:
471 errors.append('"%s" is not a value for %s.'%(item,
472 propname))
473 continue
475 # perform the add/remove
476 if remove:
477 try:
478 curvalue.remove(item)
479 except ValueError:
480 errors.append('"%s" is not currently in '
481 'for %s.'%(item, propname))
482 continue
483 else:
484 newvalue.append(item)
485 if item not in curvalue:
486 curvalue.append(item)
488 # that's it, set the new Multilink property value,
489 # or overwrite it completely
490 if set:
491 props[propname] = newvalue
492 else:
493 props[propname] = curvalue
494 elif isinstance(proptype, hyperdb.Boolean):
495 value = value.strip()
496 props[propname] = value.lower() in ('yes', 'true', 'on', '1')
497 elif isinstance(proptype, hyperdb.Number):
498 value = value.strip()
499 props[propname] = int(value)
501 # handle any errors parsing the argument list
502 if errors:
503 errors = '\n- '.join(errors)
504 raise MailUsageError, '''
505 There were problems handling your subject line argument list:
506 - %s
508 Subject was: "%s"
509 '''%(errors, subject)
511 #
512 # handle the users
513 #
515 # Don't create users if ANONYMOUS_REGISTER_MAIL is denied
516 # ... fall back on ANONYMOUS_REGISTER if the other doesn't exist
517 create = 1
518 if hasattr(self.instance, 'ANONYMOUS_REGISTER_MAIL'):
519 if self.instance.ANONYMOUS_REGISTER_MAIL == 'deny':
520 create = 0
521 elif self.instance.ANONYMOUS_REGISTER == 'deny':
522 create = 0
524 author = self.db.uidFromAddress(message.getaddrlist('from')[0],
525 create=create)
526 if not author:
527 raise UnAuthorized, '''
528 You are not a registered user.
530 Unknown address: %s
531 '''%message.getaddrlist('from')[0][1]
533 # the author may have been created - make sure the change is
534 # committed before we reopen the database
535 self.db.commit()
537 # reopen the database as the author
538 username = self.db.user.get(author, 'username')
539 self.db = self.instance.open(username)
541 # re-get the class with the new database connection
542 cl = self.db.getclass(classname)
544 # now update the recipients list
545 recipients = []
546 tracker_email = self.instance.ISSUE_TRACKER_EMAIL.lower()
547 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
548 r = recipient[1].strip().lower()
549 if r == tracker_email or not r:
550 continue
552 # look up the recipient - create if necessary (and we're
553 # allowed to)
554 recipient = self.db.uidFromAddress(recipient, create)
556 # if all's well, add the recipient to the list
557 if recipient:
558 recipients.append(recipient)
560 #
561 # handle message-id and in-reply-to
562 #
563 messageid = message.getheader('message-id')
564 inreplyto = message.getheader('in-reply-to') or ''
565 # generate a messageid if there isn't one
566 if not messageid:
567 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
568 classname, nodeid, self.instance.MAIL_DOMAIN)
570 #
571 # now handle the body - find the message
572 #
573 content_type = message.gettype()
574 attachments = []
575 # General multipart handling:
576 # Take the first text/plain part, anything else is considered an
577 # attachment.
578 # multipart/mixed: multiple "unrelated" parts.
579 # multipart/signed (rfc 1847):
580 # The control information is carried in the second of the two
581 # required body parts.
582 # ACTION: Default, so if content is text/plain we get it.
583 # multipart/encrypted (rfc 1847):
584 # The control information is carried in the first of the two
585 # required body parts.
586 # ACTION: Not handleable as the content is encrypted.
587 # multipart/related (rfc 1872, 2112, 2387):
588 # The Multipart/Related content-type addresses the MIME
589 # representation of compound objects.
590 # ACTION: Default. If we are lucky there is a text/plain.
591 # TODO: One should use the start part and look for an Alternative
592 # that is text/plain.
593 # multipart/Alternative (rfc 1872, 1892):
594 # only in "related" ?
595 # multipart/report (rfc 1892):
596 # e.g. mail system delivery status reports.
597 # ACTION: Default. Could be ignored or used for Delivery Notification
598 # flagging.
599 # multipart/form-data:
600 # For web forms only.
601 if content_type == 'multipart/mixed':
602 # skip over the intro to the first boundary
603 part = message.getPart()
604 content = None
605 while 1:
606 # get the next part
607 part = message.getPart()
608 if part is None:
609 break
610 # parse it
611 subtype = part.gettype()
612 if subtype == 'text/plain' and not content:
613 # The first text/plain part is the message content.
614 content = self.get_part_data_decoded(part)
615 elif subtype == 'message/rfc822':
616 # handle message/rfc822 specially - the name should be
617 # the subject of the actual e-mail embedded here
618 i = part.fp.tell()
619 mailmess = Message(part.fp)
620 name = mailmess.getheader('subject')
621 part.fp.seek(i)
622 attachments.append((name, 'message/rfc822', part.fp.read()))
623 else:
624 # try name on Content-Type
625 name = part.getparam('name')
626 # this is just an attachment
627 data = self.get_part_data_decoded(part)
628 attachments.append((name, part.gettype(), data))
629 if content is None:
630 raise MailUsageError, '''
631 Roundup requires the submission to be plain text. The message parser could
632 not find a text/plain part to use.
633 '''
635 elif content_type[:10] == 'multipart/':
636 # skip over the intro to the first boundary
637 message.getPart()
638 content = None
639 while 1:
640 # get the next part
641 part = message.getPart()
642 if part is None:
643 break
644 # parse it
645 if part.gettype() == 'text/plain' and not content:
646 content = self.get_part_data_decoded(part)
647 if content is None:
648 raise MailUsageError, '''
649 Roundup requires the submission to be plain text. The message parser could
650 not find a text/plain part to use.
651 '''
653 elif content_type != 'text/plain':
654 raise MailUsageError, '''
655 Roundup requires the submission to be plain text. The message parser could
656 not find a text/plain part to use.
657 '''
659 else:
660 content = self.get_part_data_decoded(message)
662 # figure how much we should muck around with the email body
663 keep_citations = getattr(self.instance, 'EMAIL_KEEP_QUOTED_TEXT',
664 'no') == 'yes'
665 keep_body = getattr(self.instance, 'EMAIL_LEAVE_BODY_UNCHANGED',
666 'no') == 'yes'
668 # parse the body of the message, stripping out bits as appropriate
669 summary, content = parseContent(content, keep_citations,
670 keep_body)
672 #
673 # handle the attachments
674 #
675 files = []
676 for (name, mime_type, data) in attachments:
677 if not name:
678 name = "unnamed"
679 files.append(self.db.file.create(type=mime_type, name=name,
680 content=data))
682 #
683 # create the message if there's a message body (content)
684 #
685 if content:
686 message_id = self.db.msg.create(author=author,
687 recipients=recipients, date=date.Date('.'), summary=summary,
688 content=content, files=files, messageid=messageid,
689 inreplyto=inreplyto)
691 # attach the message to the node
692 if nodeid:
693 # add the message to the node's list
694 messages = cl.get(nodeid, 'messages')
695 messages.append(message_id)
696 props['messages'] = messages
697 else:
698 # pre-load the messages list
699 props['messages'] = [message_id]
701 # set the title to the subject
702 if properties.has_key('title') and not props.has_key('title'):
703 props['title'] = title
705 #
706 # perform the node change / create
707 #
708 try:
709 if nodeid:
710 cl.set(nodeid, **props)
711 else:
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 changes to the DB
720 self.db.commit()
722 return nodeid
724 def parseContent(content, keep_citations, keep_body,
725 blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
726 eol=re.compile(r'[\r\n]+'),
727 signature=re.compile(r'^[>|\s]*[-_]+\s*$'),
728 original_message=re.compile(r'^[>|\s]*-----Original Message-----$')):
729 ''' The message body is divided into sections by blank lines.
730 Sections where the second and all subsequent lines begin with a ">" or "|"
731 character are considered "quoting sections". The first line of the first
732 non-quoting section becomes the summary of the message.
733 '''
734 # strip off leading carriage-returns / newlines
735 i = 0
736 for i in range(len(content)):
737 if content[i] not in '\r\n':
738 break
739 if i > 0:
740 sections = blank_line.split(content[i:])
741 else:
742 sections = blank_line.split(content)
744 # extract out the summary from the message
745 summary = ''
746 l = []
747 for section in sections:
748 #section = section.strip()
749 if not section:
750 continue
751 lines = eol.split(section)
752 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
753 lines[1] and lines[1][0] in '>|'):
754 # see if there's a response somewhere inside this section (ie.
755 # no blank line between quoted message and response)
756 for line in lines[1:]:
757 if line[0] not in '>|':
758 break
759 else:
760 # we keep quoted bits if specified in the config
761 if keep_citations:
762 l.append(section)
763 continue
764 # keep this section - it has reponse stuff in it
765 if not summary:
766 # and while we're at it, use the first non-quoted bit as
767 # our summary
768 summary = line
769 lines = lines[lines.index(line):]
770 section = '\n'.join(lines)
772 if not summary:
773 # if we don't have our summary yet use the first line of this
774 # section
775 summary = lines[0]
776 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
777 # lose any signature
778 break
779 elif original_message.match(lines[0]):
780 # ditch the stupid Outlook quoting of the entire original message
781 break
783 # and add the section to the output
784 l.append(section)
785 # we only set content for those who want to delete cruft from the
786 # message body, otherwise the body is left untouched.
787 if not keep_body:
788 content = '\n\n'.join(l)
789 return summary, content
791 #
792 # $Log: not supported by cvs2svn $
793 # Revision 1.76 2002/07/10 06:39:37 richard
794 # . made mailgw handle set and modify operations on multilinks (bug #579094)
795 #
796 # Revision 1.75 2002/07/09 01:21:24 richard
797 # Added ability for unit tests to turn off exception handling in mailgw so
798 # that exceptions are reported earlier (and hence make sense).
799 #
800 # Revision 1.74 2002/05/29 01:16:17 richard
801 # Sorry about this huge checkin! It's fixing a lot of related stuff in one go
802 # though.
803 #
804 # . #541941 ] changing multilink properties by mail
805 # . #526730 ] search for messages capability
806 # . #505180 ] split MailGW.handle_Message
807 # - also changed cgi client since it was duplicating the functionality
808 # . build htmlbase if tests are run using CVS checkout (removed note from
809 # installation.txt)
810 # . don't create an empty message on email issue creation if the email is empty
811 #
812 # Revision 1.73 2002/05/22 04:12:05 richard
813 # . applied patch #558876 ] cgi client customization
814 # ... with significant additions and modifications ;)
815 # - extended handling of ML assignedto to all places it's handled
816 # - added more NotFound info
817 #
818 # Revision 1.72 2002/05/22 01:24:51 richard
819 # Added note to MIGRATION about new config vars. Also made us more resilient
820 # for upgraders. Reinstated list header style (oops)
821 #
822 # Revision 1.71 2002/05/08 02:40:55 richard
823 # grr
824 #
825 # Revision 1.70 2002/05/06 23:40:07 richard
826 # hrm
827 #
828 # Revision 1.69 2002/05/06 23:37:21 richard
829 # Tweaking the signature deletion from mail messages.
830 # Added nuking of the "-----Original Message-----" crap from Outlook.
831 #
832 # Revision 1.68 2002/05/02 07:56:34 richard
833 # . added option to automatically add the authors and recipients of messages
834 # to the nosy lists with the options ADD_AUTHOR_TO_NOSY (default 'new') and
835 # ADD_RECIPIENTS_TO_NOSY (default 'new'). These settings emulate the current
836 # behaviour. Setting them to 'yes' will add the author/recipients to the nosy
837 # on messages that create issues and followup messages.
838 # . added missing documentation for a few of the config option values
839 #
840 # Revision 1.67 2002/04/23 15:46:49 rochecompaan
841 # . stripping of the email message body can now be controlled through
842 # the config variables EMAIL_KEEP_QUOTED_TEST and
843 # EMAIL_LEAVE_BODY_UNCHANGED.
844 #
845 # Revision 1.66 2002/03/14 23:59:24 richard
846 # . #517734 ] web header customisation is obscure
847 #
848 # Revision 1.65 2002/02/15 00:13:38 richard
849 # . #503204 ] mailgw needs a default class
850 # - partially done - the setting of additional properties can wait for a
851 # better configuration system.
852 #
853 # Revision 1.64 2002/02/14 23:46:02 richard
854 # . #516883 ] mail interface + ANONYMOUS_REGISTER
855 #
856 # Revision 1.63 2002/02/12 08:08:55 grubert
857 # . Clean up mail handling, multipart handling.
858 #
859 # Revision 1.62 2002/02/05 14:15:29 grubert
860 # . respect encodings in non multipart messages.
861 #
862 # Revision 1.61 2002/02/04 09:40:21 grubert
863 # . add test for multipart messages with first part being encoded.
864 #
865 # Revision 1.60 2002/02/01 07:43:12 grubert
866 # . mailgw checks encoding on first part too.
867 #
868 # Revision 1.59 2002/01/23 21:43:23 richard
869 # tabnuke
870 #
871 # Revision 1.58 2002/01/23 21:41:56 richard
872 # . mailgw failures (unexpected ones) are forwarded to the roundup admin
873 #
874 # Revision 1.57 2002/01/22 22:27:43 richard
875 # . handle stripping of "AW:" from subject line
876 #
877 # Revision 1.56 2002/01/22 11:54:45 rochecompaan
878 # Fixed status change in mail gateway.
879 #
880 # Revision 1.55 2002/01/21 10:05:47 rochecompaan
881 # Feature:
882 # . the mail gateway now responds with an error message when invalid
883 # values for arguments are specified for link or multilink properties
884 # . modified unit test to check nosy and assignedto when specified as
885 # arguments
886 #
887 # Fixed:
888 # . fixed setting nosy as argument in subject line
889 #
890 # Revision 1.54 2002/01/16 09:14:45 grubert
891 # . if the attachment has no name, name it unnamed, happens with tnefs.
892 #
893 # Revision 1.53 2002/01/16 07:20:54 richard
894 # simple help command for mailgw
895 #
896 # Revision 1.52 2002/01/15 00:12:40 richard
897 # #503340 ] creating issue with [asignedto=p.ohly]
898 #
899 # Revision 1.51 2002/01/14 02:20:15 richard
900 # . changed all config accesses so they access either the instance or the
901 # config attriubute on the db. This means that all config is obtained from
902 # instance_config instead of the mish-mash of classes. This will make
903 # switching to a ConfigParser setup easier too, I hope.
904 #
905 # At a minimum, this makes migration a _little_ easier (a lot easier in the
906 # 0.5.0 switch, I hope!)
907 #
908 # Revision 1.50 2002/01/11 22:59:01 richard
909 # . #502342 ] pipe interface
910 #
911 # Revision 1.49 2002/01/10 06:19:18 richard
912 # followup lines directly after a quoted section were being eaten.
913 #
914 # Revision 1.48 2002/01/08 04:12:05 richard
915 # Changed message-id format to "<%s.%s.%s%s@%s>" so it complies with RFC822
916 #
917 # Revision 1.47 2002/01/02 02:32:38 richard
918 # ANONYMOUS_ACCESS -> ANONYMOUS_REGISTER
919 #
920 # Revision 1.46 2002/01/02 02:31:38 richard
921 # Sorry for the huge checkin message - I was only intending to implement #496356
922 # but I found a number of places where things had been broken by transactions:
923 # . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
924 # for _all_ roundup-generated smtp messages to be sent to.
925 # . the transaction cache had broken the roundupdb.Class set() reactors
926 # . newly-created author users in the mailgw weren't being committed to the db
927 #
928 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
929 # on when I found that stuff :):
930 # . #496356 ] Use threading in messages
931 # . detectors were being registered multiple times
932 # . added tests for mailgw
933 # . much better attaching of erroneous messages in the mail gateway
934 #
935 # Revision 1.45 2001/12/20 15:43:01 rochecompaan
936 # Features added:
937 # . Multilink properties are now displayed as comma separated values in
938 # a textbox
939 # . The add user link is now only visible to the admin user
940 # . Modified the mail gateway to reject submissions from unknown
941 # addresses if ANONYMOUS_ACCESS is denied
942 #
943 # Revision 1.44 2001/12/18 15:30:34 rochecompaan
944 # Fixed bugs:
945 # . Fixed file creation and retrieval in same transaction in anydbm
946 # backend
947 # . Cgi interface now renders new issue after issue creation
948 # . Could not set issue status to resolved through cgi interface
949 # . Mail gateway was changing status back to 'chatting' if status was
950 # omitted as an argument
951 #
952 # Revision 1.43 2001/12/15 19:39:01 rochecompaan
953 # Oops.
954 #
955 # Revision 1.42 2001/12/15 19:24:39 rochecompaan
956 # . Modified cgi interface to change properties only once all changes are
957 # collected, files created and messages generated.
958 # . Moved generation of change note to nosyreactors.
959 # . We now check for changes to "assignedto" to ensure it's added to the
960 # nosy list.
961 #
962 # Revision 1.41 2001/12/10 00:57:38 richard
963 # From CHANGES:
964 # . Added the "display" command to the admin tool - displays a node's values
965 # . #489760 ] [issue] only subject
966 # . fixed the doc/index.html to include the quoting in the mail alias.
967 #
968 # Also:
969 # . fixed roundup-admin so it works with transactions
970 # . disabled the back_anydbm module if anydbm tries to use dumbdbm
971 #
972 # Revision 1.40 2001/12/05 14:26:44 rochecompaan
973 # Removed generation of change note from "sendmessage" in roundupdb.py.
974 # The change note is now generated when the message is created.
975 #
976 # Revision 1.39 2001/12/02 05:06:16 richard
977 # . We now use weakrefs in the Classes to keep the database reference, so
978 # the close() method on the database is no longer needed.
979 # I bumped the minimum python requirement up to 2.1 accordingly.
980 # . #487480 ] roundup-server
981 # . #487476 ] INSTALL.txt
982 #
983 # I also cleaned up the change message / post-edit stuff in the cgi client.
984 # There's now a clearly marked "TODO: append the change note" where I believe
985 # the change note should be added there. The "changes" list will obviously
986 # have to be modified to be a dict of the changes, or somesuch.
987 #
988 # More testing needed.
989 #
990 # Revision 1.38 2001/12/01 07:17:50 richard
991 # . We now have basic transaction support! Information is only written to
992 # the database when the commit() method is called. Only the anydbm
993 # backend is modified in this way - neither of the bsddb backends have been.
994 # The mail, admin and cgi interfaces all use commit (except the admin tool
995 # doesn't have a commit command, so interactive users can't commit...)
996 # . Fixed login/registration forwarding the user to the right page (or not,
997 # on a failure)
998 #
999 # Revision 1.37 2001/11/28 21:55:35 richard
1000 # . login_action and newuser_action return values were being ignored
1001 # . Woohoo! Found that bloody re-login bug that was killing the mail
1002 # gateway.
1003 # (also a minor cleanup in hyperdb)
1004 #
1005 # Revision 1.36 2001/11/26 22:55:56 richard
1006 # Feature:
1007 # . Added INSTANCE_NAME to configuration - used in web and email to identify
1008 # the instance.
1009 # . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
1010 # signature info in e-mails.
1011 # . Some more flexibility in the mail gateway and more error handling.
1012 # . Login now takes you to the page you back to the were denied access to.
1013 #
1014 # Fixed:
1015 # . Lots of bugs, thanks Roché and others on the devel mailing list!
1016 #
1017 # Revision 1.35 2001/11/22 15:46:42 jhermann
1018 # Added module docstrings to all modules.
1019 #
1020 # Revision 1.34 2001/11/15 10:24:27 richard
1021 # handle the case where there is no file attached
1022 #
1023 # Revision 1.33 2001/11/13 21:44:44 richard
1024 # . re-open the database as the author in mail handling
1025 #
1026 # Revision 1.32 2001/11/12 22:04:29 richard
1027 # oops, left debug in there
1028 #
1029 # Revision 1.31 2001/11/12 22:01:06 richard
1030 # Fixed issues with nosy reaction and author copies.
1031 #
1032 # Revision 1.30 2001/11/09 22:33:28 richard
1033 # More error handling fixes.
1034 #
1035 # Revision 1.29 2001/11/07 05:29:26 richard
1036 # Modified roundup-mailgw so it can read e-mails from a local mail spool
1037 # file. Truncates the spool file after parsing.
1038 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
1039 # the popgw.
1040 #
1041 # Revision 1.28 2001/11/01 22:04:37 richard
1042 # Started work on supporting a pop3-fetching server
1043 # Fixed bugs:
1044 # . bug #477104 ] HTML tag error in roundup-server
1045 # . bug #477107 ] HTTP header problem
1046 #
1047 # Revision 1.27 2001/10/30 11:26:10 richard
1048 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
1049 #
1050 # Revision 1.26 2001/10/30 00:54:45 richard
1051 # Features:
1052 # . #467129 ] Lossage when username=e-mail-address
1053 # . #473123 ] Change message generation for author
1054 # . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
1055 #
1056 # Revision 1.25 2001/10/28 23:22:28 richard
1057 # fixed bug #474749 ] Indentations lost
1058 #
1059 # Revision 1.24 2001/10/23 22:57:52 richard
1060 # Fix unread->chatting auto transition, thanks Roch'e
1061 #
1062 # Revision 1.23 2001/10/21 04:00:20 richard
1063 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
1064 #
1065 # Revision 1.22 2001/10/21 03:35:13 richard
1066 # bug #473125: Paragraph in e-mails
1067 #
1068 # Revision 1.21 2001/10/21 00:53:42 richard
1069 # bug #473130: Nosy list not set correctly
1070 #
1071 # Revision 1.20 2001/10/17 23:13:19 richard
1072 # Did a fair bit of work on the admin tool. Now has an extra command "table"
1073 # which displays node information in a tabular format. Also fixed import and
1074 # export so they work. Removed freshen.
1075 # Fixed quopri usage in mailgw from bug reports.
1076 #
1077 # Revision 1.19 2001/10/11 23:43:04 richard
1078 # Implemented the comma-separated printing option in the admin tool.
1079 # Fixed a typo (more of a vim-o actually :) in mailgw.
1080 #
1081 # Revision 1.18 2001/10/11 06:38:57 richard
1082 # Initial cut at trying to handle people responding to CC'ed messages that
1083 # create an issue.
1084 #
1085 # Revision 1.17 2001/10/09 07:25:59 richard
1086 # Added the Password property type. See "pydoc roundup.password" for
1087 # implementation details. Have updated some of the documentation too.
1088 #
1089 # Revision 1.16 2001/10/05 02:23:24 richard
1090 # . roundup-admin create now prompts for property info if none is supplied
1091 # on the command-line.
1092 # . hyperdb Class getprops() method may now return only the mutable
1093 # properties.
1094 # . Login now uses cookies, which makes it a whole lot more flexible. We can
1095 # now support anonymous user access (read-only, unless there's an
1096 # "anonymous" user, in which case write access is permitted). Login
1097 # handling has been moved into cgi_client.Client.main()
1098 # . The "extended" schema is now the default in roundup init.
1099 # . The schemas have had their page headings modified to cope with the new
1100 # login handling. Existing installations should copy the interfaces.py
1101 # file from the roundup lib directory to their instance home.
1102 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1103 # Ping - has been removed.
1104 # . Fixed a whole bunch of places in the CGI interface where we should have
1105 # been returning Not Found instead of throwing an exception.
1106 # . Fixed a deviation from the spec: trying to modify the 'id' property of
1107 # an item now throws an exception.
1108 #
1109 # Revision 1.15 2001/08/30 06:01:17 richard
1110 # Fixed missing import in mailgw :(
1111 #
1112 # Revision 1.14 2001/08/13 23:02:54 richard
1113 # Make the mail parser a little more robust.
1114 #
1115 # Revision 1.13 2001/08/12 06:32:36 richard
1116 # using isinstance(blah, Foo) now instead of isFooType
1117 #
1118 # Revision 1.12 2001/08/08 01:27:00 richard
1119 # Added better error handling to mailgw.
1120 #
1121 # Revision 1.11 2001/08/08 00:08:03 richard
1122 # oops ;)
1123 #
1124 # Revision 1.10 2001/08/07 00:24:42 richard
1125 # stupid typo
1126 #
1127 # Revision 1.9 2001/08/07 00:15:51 richard
1128 # Added the copyright/license notice to (nearly) all files at request of
1129 # Bizar Software.
1130 #
1131 # Revision 1.8 2001/08/05 07:06:07 richard
1132 # removed some print statements
1133 #
1134 # Revision 1.7 2001/08/03 07:18:22 richard
1135 # Implemented correct mail splitting (was taking a shortcut). Added unit
1136 # tests. Also snips signatures now too.
1137 #
1138 # Revision 1.6 2001/08/01 04:24:21 richard
1139 # mailgw was assuming certain properties existed on the issues being created.
1140 #
1141 # Revision 1.5 2001/07/29 07:01:39 richard
1142 # Added vim command to all source so that we don't get no steenkin' tabs :)
1143 #
1144 # Revision 1.4 2001/07/28 06:43:02 richard
1145 # Multipart message class has the getPart method now. Added some tests for it.
1146 #
1147 # Revision 1.3 2001/07/28 00:34:34 richard
1148 # Fixed some non-string node ids.
1149 #
1150 # Revision 1.2 2001/07/22 12:09:32 richard
1151 # Final commit of Grande Splite
1152 #
1153 #
1154 # vim: set filetype=python ts=4 sw=4 et si