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