Code

*** empty log message ***
[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 """
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.141 2004-01-17 13:49:06 jlgijsbers Exp $
77 """
79 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
80 import time, random, sys
81 import traceback, MimeWriter, rfc822
83 from roundup import hyperdb, date, password, rfc2822
84 from roundup.mailer import Mailer
86 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
88 class MailGWError(ValueError):
89     pass
91 class MailUsageError(ValueError):
92     pass
94 class MailUsageHelp(Exception):
95     """ We need to send the help message to the user. """
96     pass
98 class Unauthorized(Exception):
99     """ Access denied """
100     pass
102 class IgnoreMessage(Exception):
103     """ A general class of message that we should ignore. """
104     pass
105 class IgnoreBulk(IgnoreMessage):
106         """ This is email from a mailing list or from a vacation program. """
107         pass
108 class IgnoreLoop(IgnoreMessage):
109         """ We've seen this message before... """
110         pass
112 def initialiseSecurity(security):
113     ''' Create some Permissions and Roles on the security object
115         This function is directly invoked by security.Security.__init__()
116         as a part of the Security object instantiation.
117     '''
118     security.addPermission(name="Email Registration",
119         description="Anonymous may register through e-mail")
120     p = security.addPermission(name="Email Access",
121         description="User may use the email interface")
122     security.addPermissionToRole('Admin', p)
124 def getparam(str, param):
125     ''' From the rfc822 "header" string, extract "param" if it appears.
126     '''
127     if ';' not in str:
128         return None
129     str = str[str.index(';'):]
130     while str[:1] == ';':
131         str = str[1:]
132         if ';' in str:
133             # XXX Should parse quotes!
134             end = str.index(';')
135         else:
136             end = len(str)
137         f = str[:end]
138         if '=' in f:
139             i = f.index('=')
140             if f[:i].strip().lower() == param:
141                 return rfc822.unquote(f[i+1:].strip())
142     return None
144 class Message(mimetools.Message):
145     ''' subclass mimetools.Message so we can retrieve the parts of the
146         message...
147     '''
148     def getpart(self):
149         ''' Get a single part of a multipart message and return it as a new
150             Message instance.
151         '''
152         boundary = self.getparam('boundary')
153         mid, end = '--'+boundary, '--'+boundary+'--'
154         s = cStringIO.StringIO()
155         while 1:
156             line = self.fp.readline()
157             if not line:
158                 break
159             if line.strip() in (mid, end):
160                 break
161             s.write(line)
162         if not s.getvalue().strip():
163             return None
164         s.seek(0)
165         return Message(s)
167     def getparts(self):
168         """Get all parts of this multipart message."""
169         # skip over the intro to the first boundary
170         self.getpart()
172         # accumulate the other parts
173         parts = []
174         while 1:
175             part = self.getpart()
176             if part is None:
177                 break
178             parts.append(part)
179         return parts
181     def getheader(self, name, default=None):
182         hdr = mimetools.Message.getheader(self, name, default)
183         if hdr:
184             hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders
185         return rfc2822.decode_header(hdr)
187     def getname(self):
188         """Find an appropriate name for this message."""
189         if self.gettype() == 'message/rfc822':
190             # handle message/rfc822 specially - the name should be
191             # the subject of the actual e-mail embedded here
192             self.fp.seek(0)
193             name = Message(self.fp).getheader('subject')
194         else:
195             # try name on Content-Type
196             name = self.getparam('name')
197             if not name:
198                 disp = self.getheader('content-disposition', None)
199                 if disp:
200                     name = getparam(disp, 'filename')
202         if name:
203             return name.strip()
205     def getbody(self):
206         """Get the decoded message body."""
207         self.rewindbody()
208         encoding = self.getencoding()
209         data = None
210         if encoding == 'base64':
211             # BUG: is base64 really used for text encoding or
212             # are we inserting zip files here. 
213             data = binascii.a2b_base64(self.fp.read())
214         elif encoding == 'quoted-printable':
215             # the quopri module wants to work with files
216             decoded = cStringIO.StringIO()
217             quopri.decode(self.fp, decoded)
218             data = decoded.getvalue()
219         elif encoding == 'uuencoded':
220             data = binascii.a2b_uu(self.fp.read())
221         else:
222             # take it as text
223             data = self.fp.read()
224         
225         # Encode message to unicode
226         charset = rfc2822.unaliasCharset(self.getparam("charset"))
227         if charset:
228             # Do conversion only if charset specified
229             edata = unicode(data, charset).encode('utf-8')
230             # Convert from dos eol to unix
231             edata = edata.replace('\r\n', '\n')
232         else:
233             # Leave message content as is
234             edata = data
235                 
236         return edata
238     # General multipart handling:
239     #   Take the first text/plain part, anything else is considered an 
240     #   attachment.
241     # multipart/mixed: multiple "unrelated" parts.
242     # multipart/signed (rfc 1847): 
243     #   The control information is carried in the second of the two 
244     #   required body parts.
245     #   ACTION: Default, so if content is text/plain we get it.
246     # multipart/encrypted (rfc 1847): 
247     #   The control information is carried in the first of the two 
248     #   required body parts.
249     #   ACTION: Not handleable as the content is encrypted.
250     # multipart/related (rfc 1872, 2112, 2387):
251     #   The Multipart/Related content-type addresses the MIME
252     #   representation of compound objects.
253     #   ACTION: Default. If we are lucky there is a text/plain.
254     #   TODO: One should use the start part and look for an Alternative
255     #   that is text/plain.
256     # multipart/Alternative (rfc 1872, 1892):
257     #   only in "related" ?
258     # multipart/report (rfc 1892):
259     #   e.g. mail system delivery status reports.
260     #   ACTION: Default. Could be ignored or used for Delivery Notification 
261     #   flagging.
262     # multipart/form-data:
263     #   For web forms only.
265     def extract_content(self, parent_type=None):
266         """Extract the body and the attachments recursively."""
267         content_type = self.gettype()
268         content = None
269         attachments = []
270         
271         if content_type == 'text/plain':
272             content = self.getbody()
273         elif content_type[:10] == 'multipart/':
274             for part in self.getparts():
275                 new_content, new_attach = part.extract_content(content_type)
277                 # If we haven't found a text/plain part yet, take this one,
278                 # otherwise make it an attachment.
279                 if not content:
280                     content = new_content
281                 elif new_content:
282                     attachments.append(part.as_attachment())
283                     
284                 attachments.extend(new_attach)
285         elif (parent_type == 'multipart/signed' and
286               content_type == 'application/pgp-signature'):
287             # ignore it so it won't be saved as an attachment
288             pass
289         else:
290             attachments.append(self.as_attachment())
291         return content, attachments
293     def as_attachment(self):
294         """Return this message as an attachment."""
295         return (self.getname(), self.gettype(), self.getbody())
297 class MailGW:
299     # Matches subjects like:
300     # Re: "[issue1234] title of issue [status=resolved]"
301     subject_re = re.compile(r'''
302         (?P<refwd>\s*\W?\s*(fw|fwd|re|aw)\W\s*)*\s*   # Re:
303         (?P<quote>")?                                 # Leading "
304         (\[(?P<classname>[^\d\s]+)                    # [issue..
305            (?P<nodeid>\d+)?                           # ..1234]
306          \])?\s*
307         (?P<title>[^[]+)?                             # issue title 
308         "?                                            # Trailing "
309         (\[(?P<args>.+?)\])?                          # [prop=value]
310         ''', re.IGNORECASE|re.VERBOSE)
312     def __init__(self, instance, db, arguments={}):
313         self.instance = instance
314         self.db = db
315         self.arguments = arguments
316         self.mailer = Mailer(instance.config)
318         # should we trap exceptions (normal usage) or pass them through
319         # (for testing)
320         self.trapExceptions = 1
322     def do_pipe(self):
323         """ Read a message from standard input and pass it to the mail handler.
325             Read into an internal structure that we can seek on (in case
326             there's an error).
328             XXX: we may want to read this into a temporary file instead...
329         """
330         s = cStringIO.StringIO()
331         s.write(sys.stdin.read())
332         s.seek(0)
333         self.main(s)
334         return 0
336     def do_mailbox(self, filename):
337         """ Read a series of messages from the specified unix mailbox file and
338             pass each to the mail handler.
339         """
340         # open the spool file and lock it
341         import fcntl
342         # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
343         if hasattr(fcntl, 'LOCK_EX'):
344             FCNTL = fcntl
345         else:
346             import FCNTL
347         f = open(filename, 'r+')
348         fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
350         # handle and clear the mailbox
351         try:
352             from mailbox import UnixMailbox
353             mailbox = UnixMailbox(f, factory=Message)
354             # grab one message
355             message = mailbox.next()
356             while message:
357                 # handle this message
358                 self.handle_Message(message)
359                 message = mailbox.next()
360             # nuke the file contents
361             os.ftruncate(f.fileno(), 0)
362         except:
363             import traceback
364             traceback.print_exc()
365             return 1
366         fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
367         return 0
369     def do_apop(self, server, user='', password=''):
370         ''' Do authentication POP
371         '''
372         self.do_pop(server, user, password, apop=1)
374     def do_pop(self, server, user='', password='', apop=0):
375         '''Read a series of messages from the specified POP server.
376         '''
377         import getpass, poplib, socket
378         try:
379             if not user:
380                 user = raw_input(_('User: '))
381             if not password:
382                 password = getpass.getpass()
383         except (KeyboardInterrupt, EOFError):
384             # Ctrl C or D maybe also Ctrl Z under Windows.
385             print "\nAborted by user."
386             return 1
388         # open a connection to the server and retrieve all messages
389         try:
390             server = poplib.POP3(server)
391         except socket.error, message:
392             print "POP server error:", message
393             return 1
394         if apop:
395             server.apop(user, password)
396         else:
397             server.user(user)
398             server.pass_(password)
399         numMessages = len(server.list()[1])
400         for i in range(1, numMessages+1):
401             # retr: returns 
402             # [ pop response e.g. '+OK 459 octets',
403             #   [ array of message lines ],
404             #   number of octets ]
405             lines = server.retr(i)[1]
406             s = cStringIO.StringIO('\n'.join(lines))
407             s.seek(0)
408             self.handle_Message(Message(s))
409             # delete the message
410             server.dele(i)
412         # quit the server to commit changes.
413         server.quit()
414         return 0
416     def main(self, fp):
417         ''' fp - the file from which to read the Message.
418         '''
419         return self.handle_Message(Message(fp))
421     def handle_Message(self, message):
422         """Handle an RFC822 Message
424         Handle the Message object by calling handle_message() and then cope
425         with any errors raised by handle_message.
426         This method's job is to make that call and handle any
427         errors in a sane manner. It should be replaced if you wish to
428         handle errors in a different manner.
429         """
430         # in some rare cases, a particularly stuffed-up e-mail will make
431         # its way into here... try to handle it gracefully
432         sendto = message.getaddrlist('resent-from')
433         if not sendto:
434             sendto = message.getaddrlist('from')
435         if not sendto:
436             # very bad-looking message - we don't even know who sent it
437             # XXX we should use a log file here...
438             sendto = [self.instance.config.ADMIN_EMAIL]
439             m = ['Subject: badly formed message from mail gateway']
440             m.append('')
441             m.append('The mail gateway retrieved a message which has no From:')
442             m.append('line, indicating that it is corrupt. Please check your')
443             m.append('mail gateway source. Failed message is attached.')
444             m.append('')
445             self.mailer.bounce_message(message, sendto, m,
446                 subject='Badly formed message from mail gateway')
447             return
449         # try normal message-handling
450         if not self.trapExceptions:
451             return self.handle_message(message)
452         try:
453             return self.handle_message(message)
454         except MailUsageHelp:
455             # bounce the message back to the sender with the usage message
456             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
457             sendto = [sendto[0][1]]
458             m = ['']
459             m.append('\n\nMail Gateway Help\n=================')
460             m.append(fulldoc)
461             self.mailer.bounce_message(message, sendto, m,
462                 subject="Mail Gateway Help")
463         except MailUsageError, value:
464             # bounce the message back to the sender with the usage message
465             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
466             sendto = [sendto[0][1]]
467             m = ['']
468             m.append(str(value))
469             m.append('\n\nMail Gateway Help\n=================')
470             m.append(fulldoc)
471             self.mailer.bounce_message(message, sendto, m)
472         except Unauthorized, value:
473             # just inform the user that he is not authorized
474             sendto = [sendto[0][1]]
475             m = ['']
476             m.append(str(value))
477             self.mailer.bounce_message(message, sendto, m)
478         except IgnoreMessage:
479             # XXX we should use a log file here...
480             # do not take any action
481             # this exception is thrown when email should be ignored
482             return
483         except:
484             # bounce the message back to the sender with the error message
485             # XXX we should use a log file here...
486             sendto = [sendto[0][1], self.instance.config.ADMIN_EMAIL]
487             m = ['']
488             m.append('An unexpected error occurred during the processing')
489             m.append('of your message. The tracker administrator is being')
490             m.append('notified.\n')
491             m.append('----  traceback of failure  ----')
492             s = cStringIO.StringIO()
493             import traceback
494             traceback.print_exc(None, s)
495             m.append(s.getvalue())
496             self.mailer.bounce_message(message, sendto, m)
498     def handle_message(self, message):
499         ''' message - a Message instance
501         Parse the message as per the module docstring.
502         '''
503         # detect loops
504         if message.getheader('x-roundup-loop', ''):
505             raise IgnoreLoop
507         # detect Precedence: Bulk
508         if (message.getheader('precedence', '') == 'bulk'):
509             raise IgnoreBulk
511         # XXX Don't enable. This doesn't work yet.
512 #  "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
513         # handle delivery to addresses like:tracker+issue25@some.dom.ain
514         # use the embedded issue number as our issue
515 #        if hasattr(self.instance.config, 'EMAIL_ISSUE_ADDRESS_RE') and \
516 #                self.instance.config.EMAIL_ISSUE_ADDRESS_RE:
517 #            issue_re = self.instance.config.EMAIL_ISSUE_ADDRESS_RE
518 #            for header in ['to', 'cc', 'bcc']:
519 #                addresses = message.getheader(header, '')
520 #            if addresses:
521 #              # FIXME, this only finds the first match in the addresses.
522 #                issue = re.search(issue_re, addresses, 'i')
523 #                if issue:
524 #                    classname = issue.group('classname')
525 #                    nodeid = issue.group('nodeid')
526 #                    break
528         # determine the sender's address
529         from_list = message.getaddrlist('resent-from')
530         if not from_list:
531             from_list = message.getaddrlist('from')
533         # handle the subject line
534         subject = message.getheader('subject', '')
536         if not subject:
537             raise MailUsageError, '''
538 Emails to Roundup trackers must include a Subject: line!
539 '''
541         if subject.strip().lower() == 'help':
542             raise MailUsageHelp
544         m = self.subject_re.match(subject)
546         # check for well-formed subject line
547         if m:
548             # get the classname
549             classname = m.group('classname')
550             if classname is None:
551                 # no classname, check if this a registration confirmation email
552                 # or fallback on the default class
553                 otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
554                 otk = otk_re.search(m.group('title'))
555                 if otk:
556                     self.db.confirm_registration(otk.group('otk'))
557                     subject = 'Your registration to %s is complete' % \
558                               self.instance.config.TRACKER_NAME
559                     sendto = [from_list[0][1]]
560                     self.mailer.standard_message(sendto, subject, '') 
561                     return
562                 elif hasattr(self.instance.config, 'MAIL_DEFAULT_CLASS') and \
563                          self.instance.config.MAIL_DEFAULT_CLASS:
564                     classname = self.instance.config.MAIL_DEFAULT_CLASS
565                 else:
566                     # fail
567                     m = None
569         if not m:
570             raise MailUsageError, """
571 The message you sent to roundup did not contain a properly formed subject
572 line. The subject must contain a class name or designator to indicate the
573 'topic' of the message. For example:
574     Subject: [issue] This is a new issue
575       - this will create a new issue in the tracker with the title 'This is
576         a new issue'.
577     Subject: [issue1234] This is a followup to issue 1234
578       - this will append the message's contents to the existing issue 1234
579         in the tracker.
581 Subject was: '%s'
582 """%subject
584         # get the class
585         try:
586             cl = self.db.getclass(classname)
587         except KeyError:
588             raise MailUsageError, '''
589 The class name you identified in the subject line ("%s") does not exist in the
590 database.
592 Valid class names are: %s
593 Subject was: "%s"
594 '''%(classname, ', '.join(self.db.getclasses()), subject)
596         # get the optional nodeid
597         nodeid = m.group('nodeid')
599         # title is optional too
600         title = m.group('title')
601         if title:
602             title = title.strip()
603         else:
604             title = ''
606         # strip off the quotes that dumb emailers put around the subject, like
607         #      Re: "[issue1] bla blah"
608         if m.group('quote') and title.endswith('"'):
609             title = title[:-1]
611         # but we do need either a title or a nodeid...
612         if nodeid is None and not title:
613             raise MailUsageError, '''
614 I cannot match your message to a node in the database - you need to either
615 supply a full node identifier (with number, eg "[issue123]" or keep the
616 previous subject title intact so I can match that.
618 Subject was: "%s"
619 '''%subject
621         # If there's no nodeid, check to see if this is a followup and
622         # maybe someone's responded to the initial mail that created an
623         # entry. Try to find the matching nodes with the same title, and
624         # use the _last_ one matched (since that'll _usually_ be the most
625         # recent...)
626         if nodeid is None and m.group('refwd'):
627             l = cl.stringFind(title=title)
628             if l:
629                 nodeid = l[-1]
631         # if a nodeid was specified, make sure it's valid
632         if nodeid is not None and not cl.hasnode(nodeid):
633             raise MailUsageError, '''
634 The node specified by the designator in the subject of your message ("%s")
635 does not exist.
637 Subject was: "%s"
638 '''%(nodeid, subject)
640         # Handle the arguments specified by the email gateway command line.
641         # We do this by looping over the list of self.arguments looking for
642         # a -C to tell us what class then the -S setting string.
643         msg_props = {}
644         user_props = {}
645         file_props = {}
646         issue_props = {}
647         # so, if we have any arguments, use them
648         if self.arguments:
649             current_class = 'msg'
650             for option, propstring in self.arguments:
651                 if option in ( '-C', '--class'):
652                     current_class = propstring.strip()
653                     if current_class not in ('msg', 'file', 'user', 'issue'):
654                         raise MailUsageError, '''
655 The mail gateway is not properly set up. Please contact
656 %s and have them fix the incorrect class specified as:
657   %s
658 '''%(self.instance.config.ADMIN_EMAIL, current_class)
659                 if option in ('-S', '--set'):
660                     if current_class == 'issue' :
661                         errors, issue_props = setPropArrayFromString(self,
662                             cl, propstring.strip(), nodeid)
663                     elif current_class == 'file' :
664                         temp_cl = self.db.getclass('file')
665                         errors, file_props = setPropArrayFromString(self,
666                             temp_cl, propstring.strip())
667                     elif current_class == 'msg' :
668                         temp_cl = self.db.getclass('msg')
669                         errors, msg_props = setPropArrayFromString(self,
670                             temp_cl, propstring.strip())
671                     elif current_class == 'user' :
672                         temp_cl = self.db.getclass('user')
673                         errors, user_props = setPropArrayFromString(self,
674                             temp_cl, propstring.strip())
675                     if errors:
676                         raise MailUsageError, '''
677 The mail gateway is not properly set up. Please contact
678 %s and have them fix the incorrect properties:
679   %s
680 '''%(self.instance.config.ADMIN_EMAIL, errors)
682         #
683         # handle the users
684         #
685         # Don't create users if anonymous isn't allowed to register
686         create = 1
687         anonid = self.db.user.lookup('anonymous')
688         if not self.db.security.hasPermission('Email Registration', anonid):
689             create = 0
691         # ok, now figure out who the author is - create a new user if the
692         # "create" flag is true
693         author = uidFromAddress(self.db, from_list[0], create=create)
695         # if we're not recognised, and we don't get added as a user, then we
696         # must be anonymous
697         if not author:
698             author = anonid
700         # make sure the author has permission to use the email interface
701         if not self.db.security.hasPermission('Email Access', author):
702             if author == anonid:
703                 # we're anonymous and we need to be a registered user
704                 raise Unauthorized, '''
705 You are not a registered user.
707 Unknown address: %s
708 '''%from_list[0][1]
709             else:
710                 # we're registered and we're _still_ not allowed access
711                 raise Unauthorized, 'You are not permitted to access '\
712                     'this tracker.'
714         # make sure they're allowed to edit this class of information
715         if not self.db.security.hasPermission('Edit', author, classname):
716             raise Unauthorized, 'You are not permitted to edit %s.'%classname
718         # the author may have been created - make sure the change is
719         # committed before we reopen the database
720         self.db.commit()
722         # reopen the database as the author
723         username = self.db.user.get(author, 'username')
724         self.db.close()
725         self.db = self.instance.open(username)
727         # re-get the class with the new database connection
728         cl = self.db.getclass(classname)
730         # now update the recipients list
731         recipients = []
732         tracker_email = self.instance.config.TRACKER_EMAIL.lower()
733         for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
734             r = recipient[1].strip().lower()
735             if r == tracker_email or not r:
736                 continue
738             # look up the recipient - create if necessary (and we're
739             # allowed to)
740             recipient = uidFromAddress(self.db, recipient, create, **user_props)
742             # if all's well, add the recipient to the list
743             if recipient:
744                 recipients.append(recipient)
746         #
747         # handle the subject argument list
748         #
749         # figure what the properties of this Class are
750         properties = cl.getprops()
751         props = {}
752         args = m.group('args')
753         if args:
754             errors, props = setPropArrayFromString(self, cl, args, nodeid)
755             # handle any errors parsing the argument list
756             if errors:
757                 errors = '\n- '.join(map(str, errors))
758                 raise MailUsageError, '''
759 There were problems handling your subject line argument list:
760 - %s
762 Subject was: "%s"
763 '''%(errors, subject)
766         # set the issue title to the subject
767         if properties.has_key('title') and not issue_props.has_key('title'):
768             issue_props['title'] = title.strip()
770         #
771         # handle message-id and in-reply-to
772         #
773         messageid = message.getheader('message-id')
774         inreplyto = message.getheader('in-reply-to') or ''
775         # generate a messageid if there isn't one
776         if not messageid:
777             messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
778                 classname, nodeid, self.instance.config.MAIL_DOMAIN)
780         # now handle the body - find the message
781         content, attachments = message.extract_content()
782         if content is None:
783             raise MailUsageError, '''
784 Roundup requires the submission to be plain text. The message parser could
785 not find a text/plain part to use.
786 '''
787  
788         # figure how much we should muck around with the email body
789         keep_citations = getattr(self.instance.config, 'EMAIL_KEEP_QUOTED_TEXT',
790             'no') == 'yes'
791         keep_body = getattr(self.instance.config, 'EMAIL_LEAVE_BODY_UNCHANGED',
792             'no') == 'yes'
794         # parse the body of the message, stripping out bits as appropriate
795         summary, content = parseContent(content, keep_citations, 
796             keep_body)
797         content = content.strip()
799         # 
800         # handle the attachments
801         #
802         if properties.has_key('files'):
803             files = []
804             for (name, mime_type, data) in attachments:
805                 if not name:
806                     name = "unnamed"
807                 files.append(self.db.file.create(type=mime_type, name=name,
808                                                  content=data, **file_props))
809             # attach the files to the issue
810             if nodeid:
811                 # extend the existing files list
812                 fileprop = cl.get(nodeid, 'files')
813                 fileprop.extend(files)
814                 props['files'] = fileprop
815             else:
816                 # pre-load the files list
817                 props['files'] = files
819         # 
820         # create the message if there's a message body (content)
821         #
822         if (content and properties.has_key('messages')):
823             message_id = self.db.msg.create(author=author,
824                 recipients=recipients, date=date.Date('.'), summary=summary,
825                 content=content, files=files, messageid=messageid,
826                 inreplyto=inreplyto, **msg_props)
828             # attach the message to the node
829             if nodeid:
830                 # add the message to the node's list
831                 messages = cl.get(nodeid, 'messages')
832                 messages.append(message_id)
833                 props['messages'] = messages
834             else:
835                 # pre-load the messages list
836                 props['messages'] = [message_id]
838         #
839         # perform the node change / create
840         #
841         try:
842             # merge the command line props defined in issue_props into
843             # the props dictionary because function(**props, **issue_props)
844             # is a syntax error.
845             for prop in issue_props.keys() :
846                 if not props.has_key(prop) :
847                     props[prop] = issue_props[prop]
848             if nodeid:
849                 cl.set(nodeid, **props)
850             else:
851                 nodeid = cl.create(**props)
852         except (TypeError, IndexError, ValueError), message:
853             raise MailUsageError, '''
854 There was a problem with the message you sent:
855    %s
856 '''%message
858         # commit the changes to the DB
859         self.db.commit()
861         return nodeid
863  
864 def setPropArrayFromString(self, cl, propString, nodeid=None):
865     ''' takes string of form prop=value,value;prop2=value
866         and returns (error, prop[..])
867     '''
868     props = {}
869     errors = []
870     for prop in string.split(propString, ';'):
871         # extract the property name and value
872         try:
873             propname, value = prop.split('=')
874         except ValueError, message:
875             errors.append('not of form [arg=value,value,...;'
876                 'arg=value,value,...]')
877             return (errors, props)
878         # convert the value to a hyperdb-usable value
879         propname = propname.strip()
880         try:
881             props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
882                 propname, value)
883         except hyperdb.HyperdbValueError, message:
884             errors.append(message)
885     return errors, props
888 def extractUserFromList(userClass, users):
889     '''Given a list of users, try to extract the first non-anonymous user
890        and return that user, otherwise return None
891     '''
892     if len(users) > 1:
893         for user in users:
894             # make sure we don't match the anonymous or admin user
895             if userClass.get(user, 'username') in ('admin', 'anonymous'):
896                 continue
897             # first valid match will do
898             return user
899         # well, I guess we have no choice
900         return user[0]
901     elif users:
902         return users[0]
903     return None
906 def uidFromAddress(db, address, create=1, **user_props):
907     ''' address is from the rfc822 module, and therefore is (name, addr)
909         user is created if they don't exist in the db already
910         user_props may supply additional user information
911     '''
912     (realname, address) = address
914     # try a straight match of the address
915     user = extractUserFromList(db.user, db.user.stringFind(address=address))
916     if user is not None:
917         return user
919     # try the user alternate addresses if possible
920     props = db.user.getprops()
921     if props.has_key('alternate_addresses'):
922         users = db.user.filter(None, {'alternate_addresses': address})
923         user = extractUserFromList(db.user, users)
924         if user is not None:
925             return user
927     # try to match the username to the address (for local
928     # submissions where the address is empty)
929     user = extractUserFromList(db.user, db.user.stringFind(username=address))
931     # couldn't match address or username, so create a new user
932     if create:
933         # generate a username
934         if '@' in address:
935             username = address.split('@')[0]
936         else:
937             username = address
938         trying = username
939         n = 0
940         while 1:
941             try:
942                 # does this username exist already?
943                 db.user.lookup(trying)
944             except KeyError:
945                 break
946             n += 1
947             trying = username + str(n)
949         # create!
950         return db.user.create(username=trying, address=address,
951             realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
952             password=password.Password(password.generatePassword()),
953             **user_props)
954     else:
955         return 0
958 def parseContent(content, keep_citations, keep_body,
959         blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
960         eol=re.compile(r'[\r\n]+'), 
961         signature=re.compile(r'^[>|\s]*-- ?$'),
962         original_msg=re.compile(r'^[>|\s]*-----\s?Original Message\s?-----$')):
963     ''' The message body is divided into sections by blank lines.
964         Sections where the second and all subsequent lines begin with a ">"
965         or "|" character are considered "quoting sections". The first line of
966         the first non-quoting section becomes the summary of the message. 
968         If keep_citations is true, then we keep the "quoting sections" in the
969         content.
970         If keep_body is true, we even keep the signature sections.
971     '''
972     # strip off leading carriage-returns / newlines
973     i = 0
974     for i in range(len(content)):
975         if content[i] not in '\r\n':
976             break
977     if i > 0:
978         sections = blank_line.split(content[i:])
979     else:
980         sections = blank_line.split(content)
982     # extract out the summary from the message
983     summary = ''
984     l = []
985     for section in sections:
986         #section = section.strip()
987         if not section:
988             continue
989         lines = eol.split(section)
990         if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
991                 lines[1] and lines[1][0] in '>|'):
992             # see if there's a response somewhere inside this section (ie.
993             # no blank line between quoted message and response)
994             for line in lines[1:]:
995                 if line and line[0] not in '>|':
996                     break
997             else:
998                 # we keep quoted bits if specified in the config
999                 if keep_citations:
1000                     l.append(section)
1001                 continue
1002             # keep this section - it has reponse stuff in it
1003             lines = lines[lines.index(line):]
1004             section = '\n'.join(lines)
1005             # and while we're at it, use the first non-quoted bit as
1006             # our summary
1007             summary = section
1009         if not summary:
1010             # if we don't have our summary yet use the first line of this
1011             # section
1012             summary = section
1013         elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1014             # lose any signature
1015             break
1016         elif original_msg.match(lines[0]):
1017             # ditch the stupid Outlook quoting of the entire original message
1018             break
1020         # and add the section to the output
1021         l.append(section)
1023     # figure the summary - find the first sentence-ending punctuation or the
1024     # first whole line, whichever is longest
1025     sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1026     if sentence:
1027         sentence = sentence.group(1)
1028     else:
1029         sentence = ''
1030     first = eol.split(summary)[0]
1031     summary = max(sentence, first)
1033     # Now reconstitute the message content minus the bits we don't care
1034     # about.
1035     if not keep_body:
1036         content = '\n\n'.join(l)
1038     return summary, content
1040 # vim: set filetype=python ts=4 sw=4 et si