source: trunk/email2trac.py.in @ 500

Last change on this file since 500 was 500, checked in by bas, 13 years ago

fixed a bug when sending html and text messages. we did get empty tickets :-(

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 61.7 KB
Line 
1#!@PYTHON@
2# Copyright (C) 2002
3#
4# This file is part of the email2trac utils
5#
6# This program is free software; you can redistribute it and/or modify it
7# under the terms of the GNU General Public License as published by the
8# Free Software Foundation; either version 2, or (at your option) any
9# later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
19#
20# For vi/emacs or other use tabstop=4 (vi: set ts=4)
21#
22"""
23email2trac.py -- Email tickets to Trac.
24
25A simple MTA filter to create Trac tickets from inbound emails.
26
27Copyright 2005, Daniel Lundin <daniel@edgewall.com>
28Copyright 2005, Edgewall Software
29
30Authors:
31  Bas van der Vlies <basv@sara.nl>
32  Walter de Jong <walter@sara.nl>
33
34The scripts reads emails from stdin and inserts directly into a Trac database.
35
36How to use
37----------
38 * See https://subtrac.sara.nl/oss/email2trac/
39
40 * Create an config file:
41    [DEFAULT]                        # REQUIRED
42    project      : /data/trac/test   # REQUIRED
43    debug        : 1                 # OPTIONAL, if set print some DEBUG info
44
45    [jouvin]                         # OPTIONAL project declaration, if set both fields necessary
46    project      : /data/trac/jouvin # use -p|--project jouvin. 
47       
48 * default config file is : /etc/email2trac.conf
49
50 * Commandline opions:
51                -h,--help
52                                -d, --debug
53                -f,--file  <configuration file>
54                -n,--dry-run
55                -p, --project <project name>
56                -t, --ticket_prefix <name>
57
58SVN Info:
59        $Id: email2trac.py.in 500 2011-01-04 10:27:44Z bas $
60"""
61import os
62import sys
63import string
64import getopt
65import time
66import email
67import email.Iterators
68import email.Header
69import re
70import urllib
71import unicodedata
72import mimetypes
73import traceback
74import logging
75import logging.handlers
76import UserDict
77import tempfile
78
79from datetime import tzinfo, timedelta, datetime
80from stat import *
81
82
83from trac import __version__ as trac_version
84from trac import config as trac_config
85
86# Some global variables
87#
88m = None
89
90class SaraDict(UserDict.UserDict):
91        def __init__(self, dictin = None):
92                UserDict.UserDict.__init__(self)
93                self.name = None
94               
95                if dictin:
96                        if dictin.has_key('name'):
97                                self.name = dictin['name']
98                                del dictin['name']
99                        self.data = dictin
100                       
101        def get_value(self, name):
102                if self.has_key(name):
103                        return self[name]
104                else:
105                        return None
106                               
107        def __repr__(self):
108                return repr(self.data)
109
110        def __str__(self):
111                return str(self.data)
112                       
113        def __getattr__(self, name):
114                """
115                override the class attribute get method. Return the value
116                from the dictionary
117                """
118                if self.data.has_key(name):
119                        return self.data[name]
120                else:
121                        return None
122                       
123        def __setattr__(self, name, value):
124                """
125                override the class attribute set method only when the UserDict
126                has set its class attribute
127                """
128                if self.__dict__.has_key('data'):
129                        self.data[name] = value
130                else:
131                        self.__dict__[name] = value
132
133        def __iter__(self):
134                return iter(self.data.keys())
135
136class TicketEmailParser(object):
137        env = None
138        comment = '> '
139
140        def __init__(self, env, parameters, logger, version):
141                self.env = env
142
143                # Database connection
144                #
145                self.db = None
146
147                # Save parameters
148                #
149                self.parameters = parameters
150                self.logger = logger
151
152                # Some useful mail constants
153                #
154                self.email_name = None
155                self.email_addr = None
156                self.email_from = None
157                self.author     = None
158                self.id         = None
159               
160                self.STRIP_CONTENT_TYPES = list()
161
162                ## fields properties via body_text
163                #
164                self.properties = dict()
165
166                self.VERSION = version
167
168                self.get_config = self.env.config.get
169
170                ## init function ##
171                #
172                self.setup_parameters()
173
174        def setup_parameters(self):
175                if self.parameters.umask:
176                        os.umask(self.parameters.umask)
177
178                if not self.parameters.spam_level:
179                        self.parameters.spam_level = 0
180
181                if not self.parameters.spam_header:
182                        self.parameters.spam_header = 'X-Spam-Score'
183
184                if not self.parameters.email_quote:
185                        self.parameters.email_quote = '> '
186
187                if not self.parameters.ticket_update_by_subject_lookback:
188                        self.parameters.ticket_update_by_subject_lookback = 30
189
190                if self.parameters.verbatim_format == None:
191                        self.parameters.verbatim_format = 1
192
193                if self.parameters.reflow == None:
194                        self.parameters.reflow = 1
195
196                if self.parameters.binhex:
197                        self.STRIP_CONTENT_TYPES.append('application/mac-binhex40')
198
199                if self.parameters.applesingle:
200                        self.STRIP_CONTENT_TYPES.append('application/applefile')
201
202                if self.parameters.appledouble:
203                        self.STRIP_CONTENT_TYPES.append('application/applefile')
204
205                if self.parameters.strip_content_types:
206                        items = self.parameters.strip_content_types.split(',')
207                        for item in items:
208                                self.STRIP_CONTENT_TYPES.append(item.strip())
209
210                if self.parameters.tmpdir:
211                        self.parameters.tmpdir = os.path.normcase(str(self.parameters['tmpdir']))
212                else:
213                        self.parameters.tmpdir = os.path.normcase('/tmp')
214
215                if self.parameters.email_triggers_workflow == None:
216                        self.parameters.email_triggers_workflow = 1
217
218                if not self.parameters.subject_field_separator:
219                        self.parameters.subject_field_separator = '&'
220                else:
221                        self.parameters.subject_field_separator = self.parameters.subject_field_separator.strip()
222
223                self.trac_smtp_from = self.get_config('notification', 'smtp_from')
224                self.smtp_default_domain = self.get_config('notification', 'smtp_default_domain')
225
226
227                self.system = None
228
229########## Email Header Functions ###########################################################
230
231        def spam(self, message):
232                """
233                # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_
234                # Note if Spam_level then '*' are included
235                """
236                spam = False
237                if message.has_key(self.parameters.spam_header):
238                        spam_l = string.split(message[self.parameters.spam_header])
239
240                        try:
241                                number = spam_l[0].count('*')
242                        except IndexError, detail:
243                                number = 0
244                               
245                        if number >= self.parameters.spam_level:
246                                spam = True
247                               
248                # treat virus mails as spam
249                #
250                elif message.has_key('X-Virus-found'):                 
251                        spam = True
252
253                # How to handle SPAM messages
254                #
255                if self.parameters.drop_spam and spam:
256
257                        self.logger.info('Message is a SPAM. Automatic ticket insertion refused (SPAM level > %d)' %self.parameters.spam_level)
258                        return 'drop'   
259
260                elif spam:
261
262                        return 'Spam'   
263                else:
264
265                        return False
266
267        def email_header_acl(self, keyword, header_field, default):
268                """
269                This function wil check if the email address is allowed or denied
270                to send mail to the ticket list
271            """
272                self.logger.debug('function email_header_acl: %s' %keyword)
273
274                try:
275                        mail_addresses = self.parameters[keyword]
276
277                        # Check if we have an empty string
278                        #
279                        if not mail_addresses:
280                                return default
281
282                except KeyError, detail:
283                        self.logger.debug('%s not defined, all messages are allowed.' %(keyword))
284
285                        return default
286
287                mail_addresses = string.split(mail_addresses, ',')
288
289                for entry in mail_addresses:
290                        entry = entry.strip()
291                        TO_RE = re.compile(entry, re.VERBOSE|re.IGNORECASE)
292                        result =  TO_RE.search(header_field)
293                        if result:
294                                return True
295
296                return False
297
298        def email_header_txt(self, m):
299                """
300                Display To and CC addresses in description field
301                """
302                s = ''
303
304                if m['To'] and len(m['To']) > 0:
305                        s = "'''To:''' %s\r\n" %(m['To'])
306                if m['Cc'] and len(m['Cc']) > 0:
307                        s = "%s'''Cc:''' %s\r\n" % (s, m['Cc'])
308
309                return  self.email_to_unicode(s)
310
311
312        def get_sender_info(self, message):
313                """
314                Get the default author name and email address from the message
315                """
316
317                self.email_to = self.email_to_unicode(message['to'])
318                self.to_name, self.to_email_addr = email.Utils.parseaddr (self.email_to)
319
320                self.email_from = self.email_to_unicode(message['from'])
321                self.email_name, self.email_addr  = email.Utils.parseaddr(self.email_from)
322
323                ## Trac can not handle author's name that contains spaces
324                #
325                if self.email_addr == self.trac_smtp_from:
326                        if self.email_name:
327                                self.author = self.email_name
328                        else:
329                                self.author = "email2trac"
330                else:
331                        self.author = self.email_addr
332
333                if self.parameters.ignore_trac_user_settings:
334                        return
335
336                # Is this a registered user, use email address as search key:
337                # result:
338                #   u : login name
339                #   n : Name that the user has set in the settings tab
340                #   e : email address that the user has set in the settings tab
341                #
342                users = [ (u,n,e) for (u, n, e) in self.env.get_known_users(self.db)
343                        if (
344                                (e and (e.lower() == self.email_addr.lower())) or
345                            (u + '@' + self.smtp_default_domain.lower() == self.email_addr.lower())
346                        )
347                        ]
348
349                if len(users) >= 1:
350                        self.email_from = users[0][0]
351                        self.author = users[0][0]
352
353        def set_reply_fields(self, ticket, message):
354                """
355                Set all the right fields for a new ticket
356                """
357                self.logger.debug('function set_reply_fields')
358
359                ## Only use name or email adress
360                #ticket['reporter'] = self.email_from
361                ticket['reporter'] = self.author
362
363
364                # Put all CC-addresses in ticket CC field
365                #
366                if self.parameters.reply_all:
367
368                        email_cc = ''
369
370                        cc_addrs = email.Utils.getaddresses( message.get_all('cc', []) )
371
372                        if not cc_addrs:
373                                return
374
375                        ## Build a list of forbidden CC addresses
376                        #
377                        #to_addrs = email.Utils.getaddresses( message.get_all('to', []) )
378                        #to_list = list()
379                        #for n,e in to_addrs:
380                        #       to_list.append(e)
381                               
382                        # Always Remove reporter email address from cc-list
383                        #
384                        try:
385                                cc_addrs.remove((self.author, self.email_addr))
386                        except ValueError, detail:
387                                pass
388
389                        for name,addr in cc_addrs:
390               
391                                ## Prevent mail loop
392                                #
393                                #if addr in to_list:
394
395                                if addr == self.trac_smtp_from:
396                                        self.logger.debug("Skipping %s mail address for CC-field" %(addr))
397                                        continue
398
399                                if email_cc:
400                                        email_cc = '%s, %s' %(email_cc, addr)
401                                else:
402                                        email_cc = addr
403
404                        if email_cc:
405                                self.logger.debug('set_reply_fields: %s' %email_cc)
406
407                                ticket['cc'] = self.email_to_unicode(email_cc)
408
409
410########## DEBUG functions  ###########################################################
411
412        def debug_body(self, message_body, temporary_file=False):
413                if temporary_file:
414                        body_file = tempfile.mktemp('.email2trac')
415                else:
416                        body_file = os.path.join(self.parameters.tmpdir, 'body.txt')
417
418                if self.parameters.dry_run:
419                        print 'DRY-RUN: not saving body to %s' %(body_file)
420                        return
421
422                print 'writing body to %s' %(body_file)
423                fx = open(body_file, 'wb')
424                if not message_body:
425                                message_body = '(None)'
426
427                message_body = message_body.encode('utf-8')
428                #message_body = unicode(message_body, 'iso-8859-15')
429
430                fx.write(message_body)
431                fx.close()
432                try:
433                        os.chmod(body_file,S_IRWXU|S_IRWXG|S_IRWXO)
434                except OSError:
435                        pass
436
437        def debug_attachments(self, message_parts):
438                """
439                """
440                self.logger.debug('function debug_attachments')
441               
442                n = 0
443                for item in message_parts:
444                        # Skip inline text parts
445                        if not isinstance(item, tuple):
446                                continue
447                               
448                        (original, filename, part) = item
449
450                        n = n + 1
451                        print 'part%d: Content-Type: %s' % (n, part.get_content_type())
452               
453                        s = 'part%d: filename: %s' %(n, filename)
454                        self.print_unicode(s)
455       
456                        ## Forbidden chars
457                        #
458                        filename = filename.replace('\\', '_')
459                        filename = filename.replace('/', '_')
460       
461
462                        part_file = os.path.join(self.parameters.tmpdir, filename)
463                        s = 'writing part%d (%s)' % (n,part_file)
464                        self.print_unicode(s)
465
466                        if self.parameters.dry_run:
467                                print 'DRY_RUN: NOT saving attachments'
468                                continue
469
470                        part_file = util.text.unicode_quote(part_file)
471
472                        fx = open(part_file, 'wb')
473                        text = part.get_payload(decode=1)
474
475                        if not text:
476                                text = '(None)'
477
478                        fx.write(text)
479                        fx.close()
480
481                        try:
482                                os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO)
483                        except OSError:
484                                pass
485
486        def save_email_for_debug(self, message, create_tempfile=False):
487
488                if create_tempfile:
489                        msg_file = tempfile.mktemp('.email2trac')
490                else:
491                        #msg_file = '/var/tmp/msg.txt'
492                        msg_file = os.path.join(self.parameters.tmpdir, 'msg.txt')
493
494                if self.parameters.dry_run:
495                        print 'DRY_RUN: NOT saving email message to %s' %(msg_file)
496                else:
497                        print 'saving email to %s' %(msg_file)
498
499                        fx = open(msg_file, 'wb')
500                        fx.write('%s' % message)
501                        fx.close()
502                       
503                        try:
504                                os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO)
505                        except OSError:
506                                pass
507
508                message_parts = self.get_message_parts(message)
509                message_parts = self.unique_attachment_names(message_parts)
510                body_text = self.get_body_text(message_parts)
511                self.debug_body(body_text, True)
512                self.debug_attachments(message_parts)
513
514########## Conversion functions  ###########################################################
515
516        def email_to_unicode(self, message_str):
517                """
518                Email has 7 bit ASCII code, convert it to unicode with the charset
519                that is encoded in 7-bit ASCII code and encode it as utf-8 so Trac
520                understands it.
521                """
522                self.logger.debug("function email_to_unicode")
523
524                results =  email.Header.decode_header(message_str)
525
526                s = None
527                for text,format in results:
528                        if format:
529                                try:
530                                        temp = unicode(text, format)
531                                except UnicodeError, detail:
532                                        # This always works
533                                        #
534                                        temp = unicode(text, 'iso-8859-15')
535                                except LookupError, detail:
536                                        #text = 'ERROR: Could not find charset: %s, please install' %format
537                                        #temp = unicode(text, 'iso-8859-15')
538                                        temp = message_str
539                                       
540                        else:
541                                temp = string.strip(text)
542                                temp = unicode(text, 'iso-8859-15')
543
544                        if s:
545                                s = '%s %s' %(s, temp)
546                        else:
547                                s = '%s' %temp
548
549                #s = s.encode('utf-8')
550                return s
551
552        def str_to_dict(self, s):
553                """
554                Transfrom a string of the form [<key>=<value>]+ to dict[<key>] = <value>
555                """
556                self.logger.debug("function str_to_dict")
557
558                fields = string.split(s, self.parameters.subject_field_separator)
559
560                result = dict()
561                for field in fields:
562                        try:
563                                index, value = string.split(field, '=')
564
565                                # We can not change the description of a ticket via the subject
566                                # line. The description is the body of the email
567                                #
568                                if index.lower() in ['description']:
569                                        continue
570
571                                if value:
572                                        result[index.lower()] = value
573
574                        except ValueError:
575                                pass
576                return result
577
578        def print_unicode(self,s):
579                """
580                This function prints unicode strings if possible else it will quote it
581                """
582                try:
583                        self.logger.debug(s)
584                except UnicodeEncodeError, detail:
585                        self.logger.debug(util.text.unicode_quote(s))
586
587########## TRAC ticket functions  ###########################################################
588
589        def check_permission_participants(self, tkt, action):
590                """
591                Check if the mailer is allowed to update the ticket
592                """
593                self.logger.debug('function check_permission_participants')
594
595                if tkt['reporter'].lower() in [self.author, self.email_addr]:
596                        self.logger.debug('ALLOW, %s is the ticket reporter' %(self.email_addr))
597
598                        return True
599
600                perm = PermissionSystem(self.env)
601                if perm.check_permission(action, self.author):
602                        self.logger.debug('ALLOW, %s has trac permission to update the ticket' %(self.author))
603
604                        return True
605               
606                # Is the updater in the CC?
607                try:
608                        cc_list = tkt['cc'].split(',')
609                        for cc in cc_list:
610                                if self.email_addr.lower() in cc.strip():
611                                        self.logger.debug('ALLOW, %s is in the CC' %(self.email_addr))
612
613                                        return True
614
615                except KeyError:
616                        pass
617
618                return False
619
620        def check_permission(self, tkt, action):
621                """
622                check if the reporter has the right permission for the action:
623          - TICKET_CREATE
624          - TICKET_MODIFY
625          - TICKET_APPEND
626          - TICKET_CHGPROP
627
628                There are three models:
629                        - None      : no checking at all
630                        - trac      : check the permission via trac permission model
631                        - email2trac: ....
632                """
633                self.logger.debug("function check_permission")
634
635                if self.parameters.ticket_permission_system in ['trac']:
636
637                        perm = PermissionSystem(self.env)
638                        if perm.check_permission(action, self.author):
639                                return True
640                        else:
641                                return False
642
643                elif self.parameters.ticket_permission_system in ['update_restricted_to_participants']:
644                        return (self.check_permission_participants(tkt, action))       
645
646                ## Default is to allow everybody ticket updates and ticket creation
647                #
648                else:
649                                return True
650
651
652        def update_ticket_fields(self, ticket, user_dict, new=None):
653                """
654                This will update the ticket fields. It will check if the
655                given fields are known and if the right values are specified
656                It will only update the ticket field value:
657                        - If the field is known
658                        - If the value supplied is valid for the ticket field.
659                          If not then there are two options:
660                           1) Skip the value (new=None)
661                           2) Set default value for field (new=1)
662                """
663                self.logger.debug("function update_ticket_fields")
664
665                ## Check only permission model on ticket updates
666                #
667                if not new:
668                        if self.parameters.ticket_permission_system:
669                                if not self.check_permission(ticket, 'TICKET_CHGPROP'):
670                                        self.logger.info('Reporter: %s has no permission to change ticket properties' %self.author)
671                                        return False
672
673                ## Build a system dictionary from the ticket fields
674                #  with field as index and option as value
675                #
676                sys_dict = dict()
677                for field in ticket.fields:
678                        try:
679                                sys_dict[field['name']] = field['options']
680
681                        except KeyError:
682                                #sys_dict[field['name']] = None
683                                pass
684
685                ## Check user supplied fields an compare them with the
686                #  system one's
687                #
688                for field,value in user_dict.items():
689                        if self.parameters.debug:
690                                s = 'user_field\t %s = %s' %(field,value)
691                                self.print_unicode(s)
692
693                        ## To prevent mail loop
694                        #
695                        if field == 'cc':
696
697                                cc_list = user_dict['cc'].split(',')
698
699                                if self.trac_smtp_from in cc_list:
700                                        self.logger.debug('MAIL LOOP: %s is not allowed as CC address' %(self.trac_smtp_from))
701
702                                        cc_list.remove(self.trac_smtp_from)
703
704                                value = ','.join(cc_list)
705                               
706
707                        ## Check if every value is allowed for this field
708                        #
709                        if sys_dict.has_key(field):
710
711                                if value in sys_dict[field]:
712                                        ticket[field] = value
713                                else:
714                                        ## Must we set a default if value is not allowed
715                                        #
716                                        if new:
717                                                value = self.get_config('ticket', 'default_%s' %(field) )
718
719                        else:
720                                ## Only set if we have a value
721                                #
722                                #if value:
723                                #       ticket[field] = value
724                                ticket[field] = value
725
726                        if self.parameters.debug:
727                                s = 'ticket_field\t %s = %s' %(field,  ticket[field])
728                                self.print_unicode(s)
729
730        def ticket_update(self, m, id, spam):
731                """
732                If the current email is a reply to an existing ticket, this function
733                will append the contents of this email to that ticket, instead of
734                creating a new one.
735                """
736                self.logger.debug("function ticket_update")
737
738                if not self.parameters.ticket_update:
739                        self.logger.debug("ticket_update disabled")
740                        return False
741
742                ## Must we update ticket fields
743                #
744                update_fields = dict()
745                try:
746                        id, keywords = string.split(id, '?')
747
748                        update_fields = self.str_to_dict(keywords)
749
750                        ## Strip '#'
751                        #
752                        self.id = int(id[1:])
753
754                except ValueError:
755
756                        ## Strip '#'
757                        #
758                        self.id = int(id[1:])
759
760                self.logger.debug("ticket_update id %s" %id)
761
762                ## When is the change committed
763                #
764                if self.VERSION < 0.11:
765                        when = int(time.time())
766                else:
767                        when = datetime.now(util.datefmt.utc)
768
769                try:
770                        tkt = Ticket(self.env, self.id, self.db)
771
772                except util.TracError, detail:
773
774                        ## Not a valid ticket
775                        #
776                        self.id = None
777                        return False
778
779                ## Check the permission of the reporter
780                #
781                if self.parameters.ticket_permission_system:
782                        if not self.check_permission(tkt, 'TICKET_APPEND'):
783                                self.logger.info('Reporter: %s has no permission to add comments or attachments to tickets' %self.author)
784                                return False
785
786                ## How many changes has this ticket
787                #
788                # cnum = len(tkt.get_changelog())
789                grouped = TicketModule(self.env).grouped_changelog_entries(tkt, self.db)
790                cnum = sum(1 for e in grouped) + 1
791
792
793                ## reopen the ticket if it is was closed
794                #  We must use the ticket workflow framework
795                #
796                if self.parameters.email_triggers_workflow and (self.VERSION >= 0.11):
797
798                        self.logger.debug('Workflow ticket update fields: ')
799
800                        from trac.ticket.default_workflow import ConfigurableTicketWorkflow
801                        from trac.test import Mock, MockPerm
802
803                        req = Mock(authname=self.author, perm=MockPerm(), args={})
804                        try:
805                                workflow = self.parameters['workflow_%s' %tkt['status']]
806                        except KeyError:
807                                ## fallback for compability (Will be deprecated)
808                                #
809                                if tkt['status'] in ['closed']:
810                                        workflow = self.parameters.workflow
811                                else:   
812                                        workflow = None
813
814                        controller = ConfigurableTicketWorkflow(self.env)
815                        #print controller.actions
816                        #print controller.actions.keys()
817                        #print controller.get_ticket_actions(req, tkt)
818                        #print controller.actions[workflow]
819                        #print controller.actions[workflow]['permissions'] is a list
820
821                        if workflow:
822
823                                if self.parameters.ticket_permission_system:
824
825                                        if self.check_permission(tkt, controller.actions[workflow]['permissions'][0]):
826                                                fields = controller.get_ticket_changes(req, tkt, workflow)
827                                        else:
828                                                fields = dict()
829                                                self.logger.info('Reporter: %s has no permission to trigger workflow' %self.author)
830
831                                else:
832                                        fields = controller.get_ticket_changes(req, tkt, workflow)
833
834                                for key in fields.keys():
835                                        self.logger.debug('\t %s : %s' %(key, fields[key]))
836                                        tkt[key] = fields[key]
837
838                ## Old pre 0.11 situation
839                #
840                elif self.parameters.email_triggers_workflow:
841
842                        self.logger.debug('email triggers workflow pre trac 0.11')
843
844                        if tkt['status'] in ['closed']:
845                                tkt['status'] = 'reopened'
846                                tkt['resolution'] = ''
847
848                else:
849                        self.logger.debug('email triggers workflow disabled')
850
851                ## Must we update some ticket fields properties via subject line
852                #
853                if update_fields:
854                        self.update_ticket_fields(tkt, update_fields)
855
856                message_parts = self.get_message_parts(m)
857                message_parts = self.unique_attachment_names(message_parts)
858
859                ## Must we update some ticket fields properties via body_text
860                #
861                if self.properties:
862                                self.update_ticket_fields(tkt, self.properties)
863
864                if self.parameters.email_header:
865                        message_parts.insert(0, self.email_header_txt(m))
866
867                body_text = self.get_body_text(message_parts)
868
869                error_with_attachments = self.attach_attachments(message_parts)
870
871                if body_text.strip() or update_fields or self.properties:
872                        if self.parameters.dry_run:
873                                print 'DRY_RUN: tkt.save_changes(self.author, body_text, ticket_change_number) ', self.author, cnum
874                        else:
875                                if error_with_attachments:
876                                        body_text = '%s\\%s' %(error_with_attachments, body_text)
877                                self.logger.debug('tkt.save_changes(%s, %d)' %(self.author, cnum))
878                                tkt.save_changes(self.author, body_text, when, None, str(cnum))
879                       
880
881                if not spam:
882                        self.notify(tkt, False, when)
883
884                return True
885
886        def set_ticket_fields(self, ticket):
887                """
888                set the ticket fields to value specified
889                        - /etc/email2trac.conf with <prefix>_<field>
890                        - trac default values, trac.ini
891                """
892                self.logger.debug('function set_ticket_fields')
893
894                user_dict = dict()
895
896                for field in ticket.fields:
897
898                        name = field['name']
899
900                        ## default trac value
901                        #
902                        if not field.get('custom'):
903                                value = self.get_config('ticket', 'default_%s' %(name) )
904                                if (name in ['resolution']) and (value in ['fixed']):
905                                        value = None
906                        else:
907                                ##  Else get the default value for reporter
908                                #
909                                value = field.get('value')
910                                options = field.get('options')
911
912                                if value and options and (value not in options):
913                                         value = options[int(value)]
914       
915                        if self.parameters.debug:
916                                s = 'trac[%s] = %s' %(name, value)
917                                self.print_unicode(s)
918
919                        ## email2trac.conf settings
920                        #
921                        prefix = self.parameters.ticket_prefix
922                        try:
923                                value = self.parameters['%s_%s' %(prefix, name)]
924                                if self.parameters.debug:
925                                        s = 'email2trac[%s] = %s ' %(name, value)
926                                        self.print_unicode(s)
927
928                        except KeyError, detail:
929                                pass
930               
931                        if value:
932                                user_dict[name] = value
933                                if self.parameters.debug:
934                                        s = 'used %s = %s' %(name, value)
935                                        self.print_unicode(s)
936
937                self.update_ticket_fields(ticket, user_dict, new=1)
938
939                if 'status' not in user_dict.keys():
940                        ticket['status'] = 'new'
941
942
943        def ticket_update_by_subject(self, subject):
944                """
945                This list of Re: prefixes is probably incomplete. Taken from
946                wikipedia. Here is how the subject is matched
947                  - Re: <subject>
948                  - Re: (<Mail list label>:)+ <subject>
949
950                So we must have the last column
951                """
952                self.logger.debug('function ticket_update_by_subject')
953
954                matched_id = None
955                if self.parameters.ticket_update and self.parameters.ticket_update_by_subject:
956                               
957                        SUBJECT_RE = re.compile(r'^(?:(?:RE|AW|VS|SV|FW|FWD):\s*)+(.*)', re.IGNORECASE)
958                        result = SUBJECT_RE.search(subject)
959
960                        if result:
961                                ## This is a reply
962                                #
963                                orig_subject = result.group(1)
964
965                                self.logger.debug('subject search string: %s' %(orig_subject))
966
967                                cursor = self.db.cursor()
968                                summaries = [orig_subject, '%%: %s' % orig_subject]
969
970                                ## Convert days to seconds
971                                #
972                                lookback = int(time.mktime(time.gmtime())) - \
973                                                self.parameters.ticket_update_by_subject_lookback * 24 * 3600
974
975
976                                for summary in summaries:
977                                        self.logger.debug('Looking for summary matching: "%s"' % summary)
978
979                                        sql = """SELECT id FROM ticket
980                                                        WHERE changetime >= %s AND summary LIKE %s
981                                                        ORDER BY changetime DESC"""
982                                        cursor.execute(sql, [lookback, summary.strip()])
983
984                                        for row in cursor:
985                                                (matched_id,) = row
986
987                                                self.logger.debug('Found matching ticket id: %d' % matched_id)
988
989                                                break
990
991                                        if matched_id:
992                                                matched_id = '#%d' % matched_id
993                                                return (matched_id, orig_subject)
994                                       
995                                        subject = orig_subject
996
997                return (matched_id, subject)
998
999
1000        def new_ticket(self, msg, subject, spam, set_fields = None):
1001                """
1002                Create a new ticket
1003                """
1004                self.logger.debug('function new_ticket')
1005
1006                tkt = Ticket(self.env)
1007
1008                self.set_reply_fields(tkt, msg)
1009
1010                self.set_ticket_fields(tkt)
1011
1012                ## Check the permission of the reporter
1013                #
1014                if self.parameters.ticket_permission_system:
1015                        if not self.check_permission(tkt, 'TICKET_CREATE'):
1016                                self.logger.info('Reporter: %s has no permission to create tickets' %self.author)
1017                                return False
1018
1019                ## Old style setting for component, will be removed
1020                #
1021                if spam:
1022                        tkt['component'] = 'Spam'
1023
1024                elif self.parameters.has_key('component'):
1025                        tkt['component'] = self.parameters['component']
1026
1027                if not msg['Subject']:
1028                        tkt['summary'] = u'(No subject)'
1029                else:
1030                        tkt['summary'] = subject
1031
1032
1033                if set_fields:
1034                        rest, keywords = string.split(set_fields, '?')
1035
1036                        if keywords:
1037                                update_fields = self.str_to_dict(keywords)
1038                                self.update_ticket_fields(tkt, update_fields)
1039
1040
1041                message_parts = self.get_message_parts(msg)
1042
1043                ## Must we update some ticket fields properties via body_text
1044                #
1045                if self.properties:
1046                                self.update_ticket_fields(tkt, self.properties)
1047
1048                message_parts = self.unique_attachment_names(message_parts)
1049               
1050                ## produce e-mail like header
1051                #
1052                head = ''
1053                if self.parameters.email_header:
1054                        head = self.email_header_txt(msg)
1055                        message_parts.insert(0, head)
1056                       
1057                body_text = self.get_body_text(message_parts)
1058
1059                tkt['description'] = body_text
1060
1061                ## When is the change committed
1062                #
1063                if self.VERSION < 0.11:
1064                        when = int(time.time())
1065                else:
1066                        when = datetime.now(util.datefmt.utc)
1067
1068                if self.parameters.dry_run:
1069                        print 'DRY_RUN: tkt.insert()'
1070                else:
1071                        self.id = tkt.insert()
1072       
1073                changed = False
1074                comment = ''
1075
1076                ## some routines in trac are dependend on ticket id     
1077                #  like alternate notify template
1078                #
1079                if self.parameters.alternate_notify_template:
1080                        tkt['id'] = self.id
1081                        changed = True
1082
1083                ## Rewrite the description if we have mailto enabled
1084                #
1085                if self.parameters.mailto_link:
1086                        changed = True
1087                        comment = u'\nadded mailto line\n'
1088                        mailto = self.html_mailto_link( m['Subject'])
1089
1090                        tkt['description'] = u'%s\r\n%s%s\r\n' \
1091                                %(head, mailto, body_text)
1092       
1093                ## Save the attachments to the ticket   
1094                #
1095                error_with_attachments =  self.attach_attachments(message_parts)
1096
1097                if error_with_attachments:
1098                        changed = True
1099                        comment = '%s\n%s\n' %(comment, error_with_attachments)
1100
1101                if changed:
1102                        if self.parameters.dry_run:
1103                                print 'DRY_RUN: tkt.save_changes(%s, comment) real reporter = %s' %( tkt['reporter'], self.author)
1104                        else:
1105                                tkt.save_changes(tkt['reporter'], comment)
1106                                #print tkt.get_changelog(self.db, when)
1107
1108                if not spam:
1109                        self.notify(tkt, True)
1110
1111
1112        def attach_attachments(self, message_parts, update=False):
1113                '''
1114                save any attachments as files in the ticket's directory
1115                '''
1116                self.logger.debug('function attach_attachments()')
1117
1118                if self.parameters.dry_run:
1119                        print "DRY_RUN: no attachments attached to tickets"
1120                        return ''
1121
1122                count = 0
1123
1124                ## Get Maxium attachment size
1125                #
1126                max_size = int(self.get_config('attachment', 'max_size'))
1127                status   = None
1128               
1129                for item in message_parts:
1130                        ## Skip body parts
1131                        #
1132                        if not isinstance(item, tuple):
1133                                continue
1134                               
1135                        (original, filename, part) = item
1136
1137                        ## We have to determine the size so we use this temporary solution. we must escape it
1138                        #  else we get UnicodeErrors.
1139                        #
1140                        path, fd =  util.create_unique_file(os.path.join(self.parameters.tmpdir, util.text.unicode_quote(filename)))
1141                        text = part.get_payload(decode=1)
1142                        if not text:
1143                                text = '(None)'
1144                        fd.write(text)
1145                        fd.close()
1146
1147                        ## get the file_size
1148                        #
1149                        stats = os.lstat(path)
1150                        file_size = stats[ST_SIZE]
1151
1152                        ## Check if the attachment size is allowed
1153                        #
1154                        if (max_size != -1) and (file_size > max_size):
1155                                status = '%s\nFile %s is larger then allowed attachment size (%d > %d)\n\n' \
1156                                        %(status, original, file_size, max_size)
1157
1158                                os.unlink(path)
1159                                continue
1160                        else:
1161                                count = count + 1
1162                                       
1163                        ## Insert the attachment
1164                        #
1165                        fd = open(path, 'rb')
1166                        if self.system == 'discussion':
1167                                att = attachment.Attachment(self.env, 'discussion', 'topic/%s'
1168                                  % (self.id,))
1169                        else:
1170                                self.logger.debug('Attach %s to ticket %d' %(util.text.unicode_quote(filename), self.id))
1171                                att = attachment.Attachment(self.env, 'ticket', self.id)
1172 
1173                        ## This will break the ticket_update system, the body_text is vaporized
1174                        #  ;-(
1175                        #
1176                        if not update:
1177                                att.author = self.author
1178                                att.description = self.email_to_unicode('Added by email2trac')
1179
1180                        try:
1181                                self.logger.debug('Insert atachment')
1182                                att.insert(filename, fd, file_size)
1183                        except OSError, detail:
1184                                self.logger.info('%s\nFilename %s could not be saved, problem: %s' %(status, filename, detail))
1185                                status = '%s\nFilename %s could not be saved, problem: %s' %(status, filename, detail)
1186
1187                        ## Remove the created temporary filename
1188                        #
1189                        fd.close()
1190                        os.unlink(path)
1191
1192                ## return error
1193                #
1194                return status
1195
1196########## Fullblog functions  #################################################
1197
1198        def blog(self, id):
1199                """
1200                The blog create/update function
1201                """
1202                ## import the modules
1203                #
1204                from tracfullblog.core import FullBlogCore
1205                from tracfullblog.model import BlogPost, BlogComment
1206                from trac.test import Mock, MockPerm
1207
1208                ## instantiate blog core
1209                #
1210                blog = FullBlogCore(self.env)
1211                req = Mock(authname='anonymous', perm=MockPerm(), args={})
1212
1213                if id:
1214
1215                        ## update blog
1216                        #
1217                        comment = BlogComment(self.env, id)
1218                        comment.author = self.author
1219
1220                        message_parts = self.get_message_parts(m)
1221                        comment.comment = self.get_body_text(message_parts)
1222
1223                        blog.create_comment(req, comment)
1224
1225                else:
1226                        ## create blog
1227                        #
1228                        import time
1229                        post = BlogPost(self.env, 'blog_'+time.strftime("%Y%m%d%H%M%S", time.gmtime()))
1230
1231                        #post = BlogPost(self.env, blog._get_default_postname(self.env))
1232                       
1233                        post.author = self.author
1234                        post.title = self.email_to_unicode(m['Subject'])
1235
1236                        message_parts = self.get_message_parts(m)
1237                        post.body = self.get_body_text(message_parts)
1238                       
1239                        blog.create_post(req, post, self.author, u'Created by email2trac', False)
1240
1241
1242########## Discussion functions  ##############################################
1243
1244        def discussion_topic(self, content, subject):
1245
1246                ## Import modules.
1247                #
1248                from tracdiscussion.api import DiscussionApi
1249                from trac.util.datefmt import to_timestamp, utc
1250
1251                self.logger.debug('Creating a new topic in forum:', self.id)
1252
1253                ## Get dissussion API component.
1254                #
1255                api = self.env[DiscussionApi]
1256                context = self._create_context(content, subject)
1257
1258                ## Get forum for new topic.
1259                #
1260                forum = api.get_forum(context, self.id)
1261
1262                if not forum:
1263                        self.logger.error("ERROR: Replied forum doesn't exist")
1264
1265                ## Prepare topic.
1266                #
1267                topic = {'forum' : forum['id'],
1268                                 'subject' : context.subject,
1269                                 'time': to_timestamp(datetime.now(utc)),
1270                                 'author' : self.author,
1271                                 'subscribers' : [self.email_addr],
1272                                 'body' : self.get_body_text(context.content_parts)}
1273
1274                ## Add topic to DB and commit it.
1275                #
1276                self._add_topic(api, context, topic)
1277                self.db.commit()
1278
1279        def discussion_topic_reply(self, content, subject):
1280
1281                ## Import modules.
1282                #
1283                from tracdiscussion.api import DiscussionApi
1284                from trac.util.datefmt import to_timestamp, utc
1285
1286                self.logger.debug('Replying to discussion topic', self.id)
1287
1288                ## Get dissussion API component.
1289                #
1290                api = self.env[DiscussionApi]
1291                context = self._create_context(content, subject)
1292
1293                ## Get replied topic.
1294                #
1295                topic = api.get_topic(context, self.id)
1296
1297                if not topic:
1298                        self.logger.error("ERROR: Replied topic doesn't exist")
1299
1300                ## Prepare message.
1301                #
1302                message = {'forum' : topic['forum'],
1303                                   'topic' : topic['id'],
1304                                   'replyto' : -1,
1305                                   'time' : to_timestamp(datetime.now(utc)),
1306                                   'author' : self.author,
1307                                   'body' : self.get_body_text(context.content_parts)}
1308
1309                ## Add message to DB and commit it.
1310                #
1311                self._add_message(api, context, message)
1312                self.db.commit()
1313
1314        def discussion_message_reply(self, content, subject):
1315
1316                ## Import modules.
1317                #
1318                from tracdiscussion.api import DiscussionApi
1319                from trac.util.datefmt import to_timestamp, utc
1320
1321                self.logger.debug('Replying to discussion message', self.id)
1322
1323                ## Get dissussion API component.
1324                #
1325                api = self.env[DiscussionApi]
1326                context = self._create_context(content, subject)
1327
1328                ## Get replied message.
1329                #
1330                message = api.get_message(context, self.id)
1331
1332                if not message:
1333                        self.logger.error("ERROR: Replied message doesn't exist")
1334
1335                ## Prepare message.
1336                #
1337                message = {'forum' : message['forum'],
1338                                   'topic' : message['topic'],
1339                                   'replyto' : message['id'],
1340                                   'time' : to_timestamp(datetime.now(utc)),
1341                                   'author' : self.author,
1342                                   'body' : self.get_body_text(context.content_parts)}
1343
1344                ## Add message to DB and commit it.
1345                #
1346                self._add_message(api, context, message)
1347                self.db.commit()
1348
1349        def _create_context(self, content, subject):
1350
1351                ## Import modules.
1352                #
1353                from trac.mimeview import Context
1354                from trac.web.api import Request
1355                from trac.perm import PermissionCache
1356
1357                ## TODO: Read server base URL from config.
1358                #  Create request object to mockup context creation.
1359                #
1360                environ = {'SERVER_PORT' : 80,
1361                                   'SERVER_NAME' : 'test',
1362                                   'REQUEST_METHOD' : 'POST',
1363                                   'wsgi.url_scheme' : 'http',
1364                                   'wsgi.input' : sys.stdin}
1365                chrome =  {'links': {},
1366                                   'scripts': [],
1367                                   'ctxtnav': [],
1368                                   'warnings': [],
1369                                   'notices': []}
1370
1371                if self.env.base_url_for_redirect:
1372                        environ['trac.base_url'] = self.env.base_url
1373
1374                req = Request(environ, None)
1375                req.chrome = chrome
1376                req.tz = 'missing'
1377                req.authname = self.author
1378                req.perm = PermissionCache(self.env, self.author)
1379                req.locale = None
1380
1381                ## Create and return context.
1382                #
1383                context = Context.from_request(req)
1384                context.realm = 'discussion-email2trac'
1385                context.cursor = self.db.cursor()
1386                context.content = content
1387                context.subject = subject
1388
1389                ## Read content parts from content.
1390                #
1391                context.content_parts = self.get_message_parts(content)
1392                context.content_parts = self.unique_attachment_names(
1393                  context.content_parts)
1394
1395                return context
1396
1397        def _add_topic(self, api, context, topic):
1398                context.req.perm.assert_permission('DISCUSSION_APPEND')
1399
1400                ## Filter topic.
1401                #
1402                for discussion_filter in api.discussion_filters:
1403                        accept, topic_or_error = discussion_filter.filter_topic(
1404                          context, topic)
1405                        if accept:
1406                                topic = topic_or_error
1407                        else:
1408                                raise TracError(topic_or_error)
1409
1410                ## Add a new topic.
1411                #
1412                api.add_topic(context, topic)
1413
1414                ## Get inserted topic with new ID.
1415                #
1416                topic = api.get_topic_by_time(context, topic['time'])
1417
1418                ## Attach attachments.
1419                #
1420                self.id = topic['id']
1421                self.attach_attachments(context.content_parts, True)
1422
1423                ## Notify change listeners.
1424                #
1425                for listener in api.topic_change_listeners:
1426                        listener.topic_created(context, topic)
1427
1428        def _add_message(self, api, context, message):
1429                context.req.perm.assert_permission('DISCUSSION_APPEND')
1430
1431                ## Filter message.
1432                #
1433                for discussion_filter in api.discussion_filters:
1434                        accept, message_or_error = discussion_filter.filter_message(
1435                          context, message)
1436                        if accept:
1437                                message = message_or_error
1438                        else:
1439                                raise TracError(message_or_error)
1440
1441                ## Add message.
1442                #
1443                api.add_message(context, message)
1444
1445                ## Get inserted message with new ID.
1446                #
1447                message = api.get_message_by_time(context, message['time'])
1448
1449                ## Attach attachments.
1450                #
1451                self.id = message['topic']
1452                self.attach_attachments(context.content_parts, True)
1453
1454                ## Notify change listeners.
1455                #
1456                for listener in api.message_change_listeners:
1457                        listener.message_created(context, message)
1458
1459########## MAIN function  ######################################################
1460
1461        def parse(self, fp):
1462                """
1463                """
1464                self.logger.debug('Main function parse')
1465                global m
1466
1467                m = email.message_from_file(fp)
1468               
1469                if not m:
1470                        self.logger.debug('This is not a valid email message format')
1471                        return
1472                       
1473                ## Work around lack of header folding in Python; see http://bugs.python.org/issue4696
1474                #
1475                try:
1476                        m.replace_header('Subject', m['Subject'].replace('\r', '').replace('\n', ''))
1477                except AttributeError, detail:
1478                        pass
1479
1480                if self.parameters.debug:         # save the entire e-mail message text
1481                        self.save_email_for_debug(m, True)
1482
1483                self.db = self.env.get_db_cnx()
1484                self.get_sender_info(m)
1485
1486                if not self.email_header_acl('white_list', self.email_addr, True):
1487                        self.logger.info('Message rejected : %s not in white list' %(self.email_addr))
1488                        return False
1489
1490                if self.email_header_acl('black_list', self.email_addr, False):
1491                        self.logger.info('Message rejected : %s in black list' %(self.email_addr))
1492                        return False
1493
1494                if not self.email_header_acl('recipient_list', self.to_email_addr, True):
1495                        self.logger.info('Message rejected : %s not in recipient list' %(self.to_email_addr))
1496                        return False
1497
1498                ## If spam drop the message
1499                #
1500                if self.spam(m) == 'drop':
1501                        return False
1502
1503                elif self.spam(m) == 'spam':
1504                        spam_msg = True
1505                else:
1506                        spam_msg = False
1507
1508                if not m['Subject']:
1509                        subject  = 'No Subject'
1510                else:
1511                        subject  = self.email_to_unicode(m['Subject'])
1512
1513                self.logger.debug('subject: %s' %subject)
1514
1515                ## [hic] #1529: Re: LRZ
1516                #  [hic] #1529?owner=bas,priority=medium: Re: LRZ
1517                #
1518                ticket_regex = r'''
1519                        (?P<new_fields>[#][?].*)
1520                        |(?P<reply>(?P<id>[#][\d]+)(?P<fields>\?.*)?:)
1521                        '''
1522                ## Check if  FullBlogPlugin is installed
1523                #
1524                blog_enabled = None
1525                blog_regex = ''
1526                if self.get_config('components', 'tracfullblog.*') in ['enabled']:
1527                        self.logger.debug('Trac BLOG support enabled')
1528                        blog_enabled = True
1529                        blog_regex = '''|(?P<blog>blog:(?P<blog_id>\w*))'''
1530
1531
1532                ## Check if DiscussionPlugin is installed
1533                #
1534                discussion_enabled = None
1535                discussion_regex = ''
1536                if self.get_config('components', 'tracdiscussion.api.discussionapi') in ['enabled']:
1537                        self.logger.debug('Trac Discussion support enabled')
1538                        discussion_enabled = True
1539                        discussion_regex = r'''
1540                        |(?P<forum>Forum[ ][#](?P<forum_id>\d+)[ ]-[ ]?)
1541                        |(?P<topic>Topic[ ][#](?P<topic_id>\d+)[ ]-[ ]?)
1542                        |(?P<message>Message[ ][#](?P<message_id>\d+)[ ]-[ ]?)
1543                        '''
1544
1545
1546                regex_str = ticket_regex + blog_regex + discussion_regex
1547                SYSTEM_RE = re.compile(regex_str, re.VERBOSE)
1548
1549                ## Find out if this is a ticket, a blog or a discussion
1550                #
1551                result =  SYSTEM_RE.search(subject)
1552
1553                if result:
1554                        ## update ticket + fields
1555                        #
1556                        if result.group('reply'):
1557                                self.system = 'ticket'
1558
1559                                ## Skip the last ':' character
1560                                #
1561                                if not self.ticket_update(m, result.group('reply')[:-1], spam_msg):
1562                                        self.new_ticket(m, subject, spam_msg)
1563
1564                        ## New ticket + fields
1565                        #
1566                        elif result.group('new_fields'):
1567                                self.system = 'ticket'
1568                                self.new_ticket(m, subject[:result.start('new_fields')], spam_msg, result.group('new_fields'))
1569
1570                        if blog_enabled:
1571                                if result.group('blog'):
1572                                        self.system = 'blog'
1573                                        self.blog(result.group('blog_id'))
1574
1575                        if discussion_enabled:
1576                                ## New topic.
1577                                #
1578                                if result.group('forum'):
1579                                        self.system = 'discussion'
1580                                        self.id = int(result.group('forum_id'))
1581                                        self.discussion_topic(m, subject[result.end('forum'):])
1582
1583                                ## Reply to topic.
1584                                #
1585                                elif result.group('topic'):
1586                                        self.system = 'discussion'
1587                                        self.id = int(result.group('topic_id'))
1588                                        self.discussion_topic_reply(m, subject[result.end('topic'):])
1589
1590                                ## Reply to topic message.
1591                                #
1592                                elif result.group('message'):
1593                                        self.system = 'discussion'
1594                                        self.id = int(result.group('message_id'))
1595                                        self.discussion_message_reply(m, subject[result.end('message'):])
1596
1597                else:
1598                        self.system = 'ticket'
1599                        (matched_id, subject) = self.ticket_update_by_subject(subject)
1600                        if matched_id:
1601                                if not self.ticket_update(m, matched_id, spam_msg):
1602                                        self.new_ticket(m, subject, spam_msg)
1603                        else:
1604                                ## No update by subject, so just create a new ticket
1605                                #
1606                                self.new_ticket(m, subject, spam_msg)
1607
1608
1609########## BODY TEXT functions  ###########################################################
1610
1611        def strip_signature(self, text):
1612                """
1613                Strip signature from message, inspired by Mailman software
1614                """
1615                self.logger.debug('function strip_signature')
1616
1617                body = []
1618                for line in text.splitlines():
1619                        if line == '-- ':
1620                                break
1621                        body.append(line)
1622
1623                return ('\n'.join(body))
1624
1625        def reflow(self, text, delsp = 0):
1626                """
1627                Reflow the message based on the format="flowed" specification (RFC 3676)
1628                """
1629                flowedlines = []
1630                quotelevel = 0
1631                prevflowed = 0
1632
1633                for line in text.splitlines():
1634                        from re import match
1635                       
1636                        ## Figure out the quote level and the content of the current line
1637                        #
1638                        m = match('(>*)( ?)(.*)', line)
1639                        linequotelevel = len(m.group(1))
1640                        line = m.group(3)
1641
1642                        ## Determine whether this line is flowed
1643                        #
1644                        if line and line != '-- ' and line[-1] == ' ':
1645                                flowed = 1
1646                        else:
1647                                flowed = 0
1648
1649                        if flowed and delsp and line and line[-1] == ' ':
1650                                line = line[:-1]
1651
1652                        ## If the previous line is flowed, append this line to it
1653                        #
1654                        if prevflowed and line != '-- ' and linequotelevel == quotelevel:
1655                                flowedlines[-1] += line
1656
1657                        ## Otherwise, start a new line
1658                        #
1659                        else:
1660                                flowedlines.append('>' * linequotelevel + line)
1661
1662                        prevflowed = flowed
1663                       
1664
1665                return '\n'.join(flowedlines)
1666
1667        def strip_quotes(self, text):
1668                """
1669                Strip quotes from message by Nicolas Mendoza
1670                """
1671                self.logger.debug('function strip_quotes')
1672
1673                body = []
1674                for line in text.splitlines():
1675                        try:
1676
1677                                if line.startswith(self.parameters.email_quote):
1678                                        continue
1679
1680                        except UnicodeDecodeError:
1681
1682                                tmp_line = self.email_to_unicode(line)
1683                                if tmp_line.startswith(self.parameters.email_quote):
1684                                        continue
1685                               
1686                        body.append(line)
1687
1688                return ('\n'.join(body))
1689
1690        def inline_properties(self, text):
1691                """
1692                Parse text if we use inline keywords to set ticket fields
1693                """
1694                self.logger.debug('function inline_properties')
1695
1696                properties = dict()
1697                body = list()
1698
1699                INLINE_EXP = re.compile('\s*[@]\s*(\w+)\s*:(.*)$')
1700
1701                for line in text.splitlines():
1702                        match = INLINE_EXP.match(line)
1703                        if match:
1704                                keyword, value = match.groups()
1705                                self.properties[keyword] = value.strip()
1706
1707                                self.logger.debug('inline properties: %s : %s' %(keyword,value))
1708
1709                        else:
1710                                body.append(line)
1711                               
1712                return '\n'.join(body)
1713
1714
1715        def wrap_text(self, text, replace_whitespace = False):
1716                """
1717                Will break a lines longer then given length into several small
1718                lines of size given length
1719                """
1720                import textwrap
1721
1722                LINESEPARATOR = '\n'
1723                reformat = ''
1724
1725                for s in text.split(LINESEPARATOR):
1726                        tmp = textwrap.fill(s, self.parameters.use_textwrap)
1727                        if tmp:
1728                                reformat = '%s\n%s' %(reformat,tmp)
1729                        else:
1730                                reformat = '%s\n' %reformat
1731
1732                return reformat
1733
1734                # Python2.4 and higher
1735                #
1736                #return LINESEPARATOR.join(textwrap.fill(s,width) for s in str.split(LINESEPARATOR))
1737                #
1738
1739########## EMAIL attachements functions ###########################################################
1740
1741        def inline_part(self, part):
1742                """
1743                """
1744                self.logger.debug('function inline_part()')
1745
1746                return part.get_param('inline', None, 'Content-Disposition') == '' or not part.has_key('Content-Disposition')
1747
1748        def get_message_parts(self, msg):
1749                """
1750                parses the email message and returns a list of body parts and attachments
1751                body parts are returned as strings, attachments are returned as tuples of (filename, Message object)
1752                """
1753                self.logger.debug('function get_message_parts()')
1754
1755                message_parts = list()
1756       
1757                ALTERNATIVE_MULTIPART = False
1758
1759                for part in msg.walk():
1760                        content_maintype = part.get_content_maintype()
1761                        content_type =  part.get_content_type()
1762
1763                        self.logger.debug('\t Message part: Main-Type: %s' % content_maintype)
1764                        self.logger.debug('\t Message part: Content-Type: %s' % content_type)
1765
1766                        ## Check content type
1767                        #
1768                        if content_type in self.STRIP_CONTENT_TYPES:
1769                                self.logger.debug("\t A %s attachment named '%s' was skipped" %(content_type, part.get_filename()))
1770                                continue
1771
1772                        ## Catch some mulitpart execptions
1773                        #
1774                        if content_type == 'multipart/alternative':
1775                                ALTERNATIVE_MULTIPART = True
1776                                continue
1777
1778                        ## Skip multipart containers
1779                        #
1780                        if content_maintype == 'multipart':
1781                                self.logger.debug("\t Skipping multipart container")
1782                                continue
1783                       
1784                        ## Check if this is an inline part. It's inline if there is co Cont-Disp header, or if there is one and it says "inline"
1785                        #
1786                        inline = self.inline_part(part)
1787
1788                        ## Drop HTML message
1789                        #
1790                        if ALTERNATIVE_MULTIPART and self.parameters.drop_alternative_html_version:
1791                                if content_type == 'text/html':
1792                                        self.logger.debug('\t Skipping alternative HTML message')
1793                                        ALTERNATIVE_MULTIPART = False
1794                                        continue
1795
1796
1797                        ## Save all non plain text message as attachment
1798                        #
1799                        if not content_type in ['text/plain']:
1800
1801                                if self.parameters.debug:
1802                                        s = '\t Filename: %s' % part.get_filename()
1803                                        self.print_unicode(s)
1804
1805                                ## First try to use email header function to convert filename.
1806                                #  If this fails the use the plain filename
1807                                #
1808                                try:
1809                                        filename = self.email_to_unicode(part.get_filename())
1810                                except UnicodeEncodeError, detail:
1811                                        filename = part.get_filename()
1812
1813                                message_parts.append((filename, part))
1814
1815                                ## We van only convert html messages
1816                                #
1817                                if not content_type == 'text/html':
1818                                        self.logger.debug('\t Appending content_type = %s' %(content_type))
1819                                        continue
1820
1821                        if not inline:
1822                                        self.logger.debug('\t Skipping %s, not an inline messsage part' %(content_type))
1823                                        continue
1824                               
1825                        ## Try to decode message part. We have a html or plain text messafe
1826                        #
1827                        body_text = part.get_payload(decode=1)
1828                        if not body_text:                       
1829                                body_text = part.get_payload(decode=0)
1830
1831                        ## Try to convert html message
1832                        #
1833                        if content_type == 'text/html':
1834                                if self.parameters.html2text_cmd:
1835
1836                                        tmp_file = tempfile.mktemp('.email2trac')
1837                                        cmd = '%s %s' %(self.parameters.html2text_cmd, tmp_file)
1838                                        self.logger.debug('\t html2text conversion %s'%(cmd))
1839                                       
1840                                        if self.parameters.dry_run:
1841                                                print 'DRY_RUN: html2text conversion command: %s\n' %(cmd)
1842                                        else:
1843                                                f = open(tmp_file, "w+")
1844                                                f.write(body_text)
1845                                                f.close()
1846
1847                                                lines = os.popen(cmd).readlines()
1848                                                body_text = ''.join(lines)
1849
1850                                                os.unlink(tmp_file)
1851
1852                                else:
1853                                        self.logger.debug('\t No html2text conversion tool specified in email2trac.conf')
1854                                        continue
1855
1856                        format = email.Utils.collapse_rfc2231_value(part.get_param('Format', 'fixed')).lower()
1857                        delsp = email.Utils.collapse_rfc2231_value(part.get_param('DelSp', 'no')).lower()
1858
1859                        if self.parameters.reflow and not self.parameters.verbatim_format and format == 'flowed':
1860                                body_text = self.reflow(body_text, delsp == 'yes')
1861       
1862                        if self.parameters.strip_signature:
1863                                body_text = self.strip_signature(body_text)
1864
1865                        if self.parameters.strip_quotes:
1866                                body_text = self.strip_quotes(body_text)
1867
1868                        if self.parameters.inline_properties:
1869                                body_text = self.inline_properties(body_text)
1870
1871                        if self.parameters.use_textwrap:
1872                                body_text = self.wrap_text(body_text)
1873
1874                        ## Get contents charset (iso-8859-15 if not defined in mail headers)
1875                        #
1876                        charset = part.get_content_charset()
1877                        if not charset:
1878                                charset = 'iso-8859-15'
1879
1880                        try:
1881                                ubody_text = unicode(body_text, charset)
1882
1883                        except UnicodeError, detail:
1884                                ubody_text = unicode(body_text, 'iso-8859-15')
1885
1886                        except LookupError, detail:
1887                                ubody_text = 'ERROR: Could not find charset: %s, please install' %(charset)
1888
1889                        if self.parameters.verbatim_format:
1890                                message_parts.append('{{{\r\n%s\r\n}}}' %ubody_text)
1891                        else:
1892                                message_parts.append('%s' %ubody_text)
1893
1894                return message_parts
1895               
1896        def unique_attachment_names(self, message_parts):
1897                """
1898            Make sure we have unique names attachments:
1899                  - check if it contains illegal characters
1900                  - Rename "None" filenames to "untitled-part"
1901                """
1902                self.logger.debug('function unique_attachment_names()')
1903                renamed_parts = []
1904                attachment_names = set()
1905
1906                for item in message_parts:
1907                       
1908                        ## If not an attachment, leave it alone
1909                        #
1910                        if not isinstance(item, tuple):
1911                                renamed_parts.append(item)
1912                                continue
1913                               
1914                        (filename, part) = item
1915
1916                        ## If filename = None, use a default one
1917                        #
1918                        if filename in [ 'None']:
1919                                filename = 'untitled-part'
1920                                self.logger.info('Rename filename "None" to: %s' %filename)
1921
1922                                ## Guess the extension from the content type, use non strict mode
1923                                #  some additional non-standard but commonly used MIME types
1924                                #  are also recognized
1925                                #
1926                                ext = mimetypes.guess_extension(part.get_content_type(), False)
1927                                if not ext:
1928                                        ext = '.bin'
1929
1930                                filename = '%s%s' % (filename, ext)
1931
1932                        ## Discard relative paths for windows/unix in attachment names
1933                        #
1934                        #filename = filename.replace('\\', '/').replace(':', '/')
1935                        filename = filename.replace('\\', '_')
1936                        filename = filename.replace('/', '_')
1937
1938                        ## remove linefeed char
1939                        #
1940                        for forbidden_char in ['\r', '\n']:
1941                                filename = filename.replace(forbidden_char,'')
1942
1943                        ## We try to normalize the filename to utf-8 NFC if we can.
1944                        #  Files uploaded from OS X might be in NFD.
1945                        #  Check python version and then try it
1946                        #
1947                        #if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3):
1948                        #       try:
1949                        #               filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8') 
1950                        #       except TypeError:
1951                        #               pass
1952
1953                        ## Make the filename unique for this ticket
1954                        #
1955                        num = 0
1956                        unique_filename = filename
1957                        dummy_filename, ext = os.path.splitext(filename)
1958
1959                        while (unique_filename in attachment_names) or self.attachment_exists(unique_filename):
1960                                num += 1
1961                                unique_filename = "%s-%s%s" % (dummy_filename, num, ext)
1962                               
1963                        if self.parameters.debug:
1964                                s = 'Attachment with filename %s will be saved as %s' % (filename, unique_filename)
1965                                self.print_unicode(s)
1966
1967                        attachment_names.add(unique_filename)
1968
1969                        renamed_parts.append((filename, unique_filename, part))
1970       
1971                return renamed_parts
1972                       
1973                       
1974        def attachment_exists(self, filename):
1975
1976                if self.parameters.debug:
1977                        s = 'attachment already exists: Id : %s, Filename : %s' %(self.id, filename)
1978                        self.print_unicode(s)
1979
1980                ## We have no valid ticket id
1981                #
1982                if not self.id:
1983                        return False
1984
1985                try:
1986                        if self.system == 'discussion':
1987                                att = attachment.Attachment(self.env, 'discussion', 'ticket/%s'
1988                                  % (self.id,), filename)
1989                        else:
1990                                att = attachment.Attachment(self.env, 'ticket', self.id,
1991                                  filename)
1992                        return True
1993                except attachment.ResourceNotFound:
1994                        return False
1995
1996########## TRAC Ticket Text ###########################################################
1997                       
1998        def get_body_text(self, message_parts):
1999                """
2000                """
2001                self.logger.debug('function get_body_text()')
2002
2003                body_text = []
2004               
2005                for part in message_parts:
2006               
2007                        ## Plain text part, append it
2008                        #
2009                        if not isinstance(part, tuple):
2010                                body_text.extend(part.strip().splitlines())
2011                                body_text.append("")
2012                                continue
2013
2014                        (original, filename, part) = part
2015                        inline = self.inline_part(part)
2016
2017                        ## Skip generation of attachment link if html is converted to text
2018                        #
2019                        if part.get_content_type() == 'text/html' and self.parameters.html2text_cmd and inline:
2020                                s = 'Skipping attachment link for html part: %s' %(filename)
2021                                self.print_unicode(s)
2022                                continue
2023                       
2024                        if part.get_content_maintype() == 'image' and inline:
2025                                if self.system != 'discussion':
2026                                        s = 'wiki image link for: %s' %(filename)
2027                                        self.print_unicode(s)
2028                                        body_text.append('[[Image(%s)]]' % filename)
2029                                body_text.append("")
2030                        else:
2031                                if self.system != 'discussion':
2032                                        s = 'wiki attachment link for: %s' %(filename)
2033                                        self.print_unicode(s)
2034                                        body_text.append('[attachment:"%s"]' % filename)
2035                                body_text.append("")
2036
2037                ## Convert list body_texts to string
2038                #
2039                body_text = '\r\n'.join(body_text)
2040                return body_text
2041
2042        def html_mailto_link(self, subject):
2043                """
2044                This function returns a HTML mailto tag with the ticket id and author email address
2045                """
2046                if not self.author:
2047                        author = self.email_addr
2048                else:   
2049                        author = self.author
2050
2051                if not self.parameters.mailto_cc:
2052                        self.parameters.mailto_cc = ''
2053
2054                ## use urllib to escape the chars
2055                #
2056                s = 'mailto:%s?Subject=%s&Cc=%s' %(
2057                       urllib.quote(self.email_addr),
2058                           urllib.quote('Re: #%s: %s' %(self.id, subject)),
2059                           urllib.quote(self.parameters.mailto_cc)
2060                           )
2061
2062                s = '\r\n{{{\r\n#!html\r\n<a\r\n href="%s">Reply to: %s\r\n</a>\r\n}}}\r\n' %(s, author)
2063                return s
2064
2065########## TRAC notify section ###########################################################
2066
2067        def notify(self, tkt, new=True, modtime=0):
2068                """
2069                A wrapper for the TRAC notify function. So we can use templates
2070                """
2071                self.logger.debug('function notify()')
2072
2073                if self.parameters.dry_run:
2074                                print 'DRY_RUN: self.notify(tkt, True) reporter = %s' %tkt['reporter']
2075                                return
2076                try:
2077
2078                        #from trac.ticket.web_ui import TicketModule
2079                        #from trac.ticket.notification import TicketNotificationSystem
2080                        #ticket_sys = TicketNotificationSystem(self.env)
2081                        #a = TicketModule(self.env)
2082                        #print a.__dict__
2083                        #tn_sys = TicketNotificationSystem(self.env)
2084                        #print tn_sys
2085                        #print tn_sys.__dict__
2086                        #sys.exit(0)
2087
2088                        ## create false {abs_}href properties, to trick Notify()
2089                        #
2090                        if not (self.VERSION in [0.11, 0.12]):
2091                                self.env.abs_href = Href(self.get_config('project', 'url'))
2092                                self.env.href = Href(self.get_config('project', 'url'))
2093
2094
2095                        tn = TicketNotifyEmail(self.env)
2096
2097                        if self.parameters.alternate_notify_template:
2098
2099                                if self.VERSION >= 0.11:
2100
2101                                        from trac.web.chrome import Chrome
2102
2103                                        if  self.parameters.alternate_notify_template_update and not new:
2104                                                tn.template_name = self.parameters.alternate_notify_template_update
2105                                        else:
2106                                                tn.template_name = self.parameters.alternate_notify_template
2107
2108                                        tn.template = Chrome(tn.env).load_template(tn.template_name, method='text')
2109                                               
2110                                else:
2111
2112                                        tn.template_name = self.parameters.alternate_notify_template
2113
2114                        tn.notify(tkt, new, modtime)
2115
2116                except Exception, e:
2117                        self.logger.error('Failure sending notification on creation of ticket #%s: %s' %(self.id, e))
2118
2119
2120
2121########## Parse Config File  ###########################################################
2122
2123def ReadConfig(file, name):
2124        """
2125        Parse the config file
2126        """
2127        if not os.path.isfile(file):
2128                print 'File %s does not exist' %file
2129                sys.exit(1)
2130
2131        config = trac_config.Configuration(file)
2132       
2133        parentdir = config.get('DEFAULT', 'parentdir')
2134        sections = config.sections()
2135
2136        ## use some trac internals to get the defaults
2137        #
2138        tmp = config.parser.defaults()
2139        project =  SaraDict()
2140
2141        for option, value in tmp.items():
2142                try:
2143                        project[option] = int(value)
2144                except ValueError:
2145                        project[option] = value
2146
2147        if name:
2148                if name in sections:
2149                        project =  SaraDict()
2150                        for option, value in  config.options(name):
2151                                try:
2152                                        project[option] = int(value)
2153                                except ValueError:
2154                                        project[option] = value
2155
2156                elif not parentdir:
2157                        print "Not a valid project name: %s, valid names are: %s" %(name, sections)
2158                        print "or set parentdir in the [DEFAULT] section"
2159                        sys.exit(1)
2160
2161        ## If parentdir the set project dir to parentdir + name
2162        #
2163        if not project.has_key('project'):
2164                if not parentdir:
2165                        print "You must set project or parentdir in your configuration file"
2166                        sys.exit(1)
2167                elif not name:
2168                        print "You must set project in your configuration file"
2169                else:
2170                        project['project'] = os.path.join(parentdir, name)
2171
2172        return project
2173
2174########## Setup Logging ###############################################################
2175
2176def setup_log(parameters, project_name, interactive=None):
2177        """
2178        Setup loging
2179
2180        Note for log format the usage of `$(...)s` instead of `%(...)s` as the latter form
2181    would be interpreted by the ConfigParser itself.
2182        """
2183        logger = logging.getLogger('email2trac %s' %project_name)
2184
2185        if interactive:
2186                parameters.log_type = 'stderr'
2187
2188        if not parameters.log_type:
2189                if sys.platform in ['win32', 'cygwin']:
2190                        paramters.log_type = 'eventlog'
2191                else:
2192                        parameters.log_type = 'syslog'
2193
2194        if parameters.log_type == 'file':
2195
2196                if not parameters.log_file:
2197                        parameters.log_file = 'email2trac.log'
2198
2199                if not os.path.isabs(parameters.log_file):
2200                        parameters.log_file = os.path.join(tempfile.gettempdir(), parameters.log_file)
2201
2202                log_handler = logging.FileHandler(parameters.log_file)
2203
2204        elif parameters.log_type in ('winlog', 'eventlog', 'nteventlog'):
2205                ## Requires win32 extensions
2206                #
2207                log_handler = logging.handlers.NTEventLogHandler(logid, logtype='Application')
2208
2209        elif parameters.log_type in ('syslog', 'unix'):
2210                log_handler = logging.handlers.SysLogHandler('/dev/log')
2211
2212        elif parameters.log_type in ('stderr'):
2213                log_handler = logging.StreamHandler(sys.stderr)
2214
2215        else:
2216                log_handler = logging.handlers.BufferingHandler(0)
2217
2218        if parameters.log_format:
2219                parameters.log_format = parameters.log_format.replace('$(', '%(')
2220        else:
2221                parameters.log_format = '%(name)s: %(message)s'
2222
2223        log_formatter = logging.Formatter(parameters.log_format)
2224        log_handler.setFormatter(log_formatter)
2225        logger.addHandler(log_handler)
2226
2227        if (parameters.log_level in ['DEBUG', 'ALL']) or (parameters.debug > 0):
2228                logger.setLevel(logging.DEBUG)
2229                parameters.debug = 1
2230
2231        elif parameters.log_level in ['INFO'] or parameters.verbose:
2232                logger.setLevel(logging.INFO)
2233
2234        elif parameters.log_level in ['WARNING']:
2235                logger.setLevel(logging.WARNING)
2236
2237        elif parameters.log_level in ['ERROR']:
2238                logger.setLevel(logging.ERROR)
2239
2240        elif parameters.log_level in ['CRITICAL']:
2241                logger.setLevel(logging.CRITICAL)
2242
2243        else:
2244                logger.setLevel(logging.INFO)
2245
2246        return logger
2247
2248
2249if __name__ == '__main__':
2250        ## Default config file
2251        #
2252        configfile = '@email2trac_conf@'
2253        project = ''
2254        component = ''
2255        ticket_prefix = 'default'
2256        dry_run = None
2257        verbose = None
2258        debug_interactive = None
2259
2260        SHORT_OPT = 'cdhf:np:t:v'
2261        LONG_OPT  =  ['component=', 'debug', 'dry-run', 'help', 'file=', 'project=', 'ticket_prefix=', 'verbose']
2262
2263        try:
2264                opts, args = getopt.getopt(sys.argv[1:], SHORT_OPT, LONG_OPT)
2265        except getopt.error,detail:
2266                print __doc__
2267                print detail
2268                sys.exit(1)
2269       
2270        project_name = None
2271        for opt,value in opts:
2272                if opt in [ '-h', '--help']:
2273                        print __doc__
2274                        sys.exit(0)
2275                elif opt in ['-c', '--component']:
2276                        component = value
2277                elif opt in ['-d', '--debug']:
2278                        debug_interactive = 1
2279                elif opt in ['-f', '--file']:
2280                        configfile = value
2281                elif opt in ['-n', '--dry-run']:
2282                        dry_run = True
2283                elif opt in ['-p', '--project']:
2284                        project_name = value
2285                elif opt in ['-t', '--ticket_prefix']:
2286                        ticket_prefix = value
2287                elif opt in ['-v', '--verbose']:
2288                        verbose = True
2289       
2290        settings = ReadConfig(configfile, project_name)
2291
2292        ## The default prefix for ticket values in email2trac.conf
2293        #
2294        settings.ticket_prefix = ticket_prefix
2295        settings.dry_run = dry_run
2296        settings.verbose = verbose
2297
2298        if not settings.debug and debug_interactive:
2299                settings.debug = debug_interactive
2300
2301        if not settings.project:
2302                print __doc__
2303                print 'No Trac project is defined in the email2trac config file.'
2304                sys.exit(1)
2305
2306        logger = setup_log(settings, os.path.basename(settings.project), debug_interactive)
2307       
2308        if component:
2309                settings['component'] = component
2310
2311        ## Determine major trac version used to be in email2trac.conf
2312        # Quick hack for 0.12
2313        #
2314        version = '0.%s' %(trac_version.split('.')[1])
2315        if version.startswith('0.12'):
2316                version = '0.12'
2317
2318        logger.debug("Found trac version: %s" %(version))
2319       
2320        try:
2321                if version == '0.10':
2322                        from trac import attachment
2323                        from trac.env import Environment
2324                        from trac.ticket import Ticket
2325                        from trac.web.href import Href
2326                        from trac import util
2327                        from trac.ticket.web_ui import TicketModule
2328
2329                        #
2330                        # return  util.text.to_unicode(str)
2331                        #
2332                        # see http://projects.edgewall.com/trac/changeset/2799
2333                        from trac.ticket.notification import TicketNotifyEmail
2334                        from trac import config as trac_config
2335                        from trac.core import TracError
2336
2337                elif version == '0.11':
2338                        from trac import attachment
2339                        from trac.env import Environment
2340                        from trac.ticket import Ticket
2341                        from trac.web.href import Href
2342                        from trac import config as trac_config
2343                        from trac import util
2344                        from trac.core import TracError
2345                        from trac.perm import PermissionSystem
2346                        from trac.ticket.web_ui import TicketModule
2347
2348                        #
2349                        # return  util.text.to_unicode(str)
2350                        #
2351                        # see http://projects.edgewall.com/trac/changeset/2799
2352                        from trac.ticket.notification import TicketNotifyEmail
2353
2354                elif version == '0.12':
2355                        from trac import attachment
2356                        from trac.env import Environment
2357                        from trac.ticket import Ticket
2358                        from trac.web.href import Href
2359                        from trac import config as trac_config
2360                        from trac import util
2361                        from trac.core import TracError
2362                        from trac.perm import PermissionSystem
2363                        from trac.ticket.web_ui import TicketModule
2364
2365                        #
2366                        # return  util.text.to_unicode(str)
2367                        #
2368                        # see http://projects.edgewall.com/trac/changeset/2799
2369                        from trac.ticket.notification import TicketNotifyEmail
2370
2371
2372                else:
2373                        logger.error('TRAC version %s is not supported' %version)
2374                        sys.exit(1)
2375
2376                ## Must be set before environment is created
2377                #
2378                if settings.has_key('python_egg_cache'):
2379                        python_egg_cache = str(settings['python_egg_cache'])
2380                        os.environ['PYTHON_EGG_CACHE'] = python_egg_cache
2381
2382                if settings.debug > 0:
2383                        logger.debug('Loading environment %s', settings.project)
2384
2385                try:
2386                        env = Environment(settings['project'], create=0)
2387                except IOError, detail:
2388                        print "Trac project does not exists: %s" %(settings['project'])
2389                        sys.exit(1)
2390
2391                tktparser = TicketEmailParser(env, settings, logger, float(version))
2392                tktparser.parse(sys.stdin)
2393
2394        ## Catch all errors and use the logging module
2395        #
2396        except Exception, error:
2397
2398                etype, evalue, etb = sys.exc_info()
2399                for e in traceback.format_exception(etype, evalue, etb):
2400                        logger.critical(e)
2401
2402                if m:
2403                        tktparser.save_email_for_debug(m, True)
2404
2405                sys.exit(1)
2406# EOB
Note: See TracBrowser for help on using the repository browser.