Code

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