EmailDocument.py 23.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
##############################################################################
#
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import re, types
from DateTime import DateTime
from Globals import get_request
Yusei Tahara's avatar
Yusei Tahara committed
32
from AccessControl import ClassSecurityInfo, Unauthorized
33
from Products.ERP5Type.Base import WorkflowMethod
Yusei Tahara's avatar
Yusei Tahara committed
34
from Products.CMFCore.utils import getToolByName, _checkPermission
35
from Products.CMFCore.utils import _setCacheHeaders, _ViewEmulator
36
from Products.CMFDefault.utils import isHTMLSafe
37 38 39
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Document.TextDocument import TextDocument
from Products.ERP5.Document.File import File
Yusei Tahara's avatar
Yusei Tahara committed
40
from Products.ERP5.Document.Document import ConversionError
41 42
from Products.ERP5.Tool.NotificationTool import buildEmailMessage

43 44
from zLOG import LOG, INFO

45 46 47 48 49 50 51 52
try:
  from Products.MimetypesRegistry.common import MimeTypeException
except ImportError:
  class MimeTypeException(Exception):
    """
    A dummy exception class which is used when MimetypesRegistry product is
    not installed yet.
    """
53 54 55 56 57 58
try:
  import libxml2
  import libxslt
  import_libxml2 = 1
except ImportError:
  import_libxml2 = 0
59 60

from email import message_from_string
61
from email.Header import decode_header
62
from email.Utils import parsedate_tz, mktime_tz
63 64 65 66 67

DEFAULT_TEXT_FORMAT = 'text/html'
COMMASPACE = ', '
_MARKER = []

68 69
file_name_regexp = 'name="([^"]*)"'

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
class EmailDocument(File, TextDocument):
  """
    EmailDocument is a File which stores its metadata in a form which
    is similar to a TextDocument.
    A Text Document which stores raw HTML and can 
    convert it to various formats.
  """

  meta_type = 'ERP5 Email Document'
  portal_type = 'Email Document'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1
  isDocument = 1
  isDelivery = 1 # XXX must be removed later - only event is a delivery

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Document
                    , PropertySheet.Snapshot
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.TextDocument
                    , PropertySheet.Arrow
                    , PropertySheet.Task
                    , PropertySheet.ItemAggregation
104 105
                    , PropertySheet.EmailHeader
                    , PropertySheet.Reference
106 107 108 109 110
                    )

  # Declarative interfaces
  __implements__ = ()

111 112 113 114
  # Searchable Text - at least search the body message
  #                 - later: search attachments too
  searchable_property_list = TextDocument.searchable_property_list

115 116 117 118 119 120 121 122 123 124 125 126 127
  # Mail processing API
  def _getMessage(self):
    result = getattr(self, '_v_message', None)
    if result is None:
      result = message_from_string(str(self.getData()))
      self._v_message = result
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getContentInformation')
  def getContentInformation(self):
    """
    Returns the content information from the header information.
    This is used by the metadata discovery system.
128 129 130

    Header information is converted in UTF-8 since this is the standard
    way of representing strings in ERP5.
131 132 133
    """
    result = {}
    for (name, value) in self._getMessage().items():
134
      for text, encoding in decode_header(value):
135 136
        try:
          if encoding is not None:
137
            text = text.decode(encoding).encode('utf-8')
138 139 140 141 142
          else:
            text = text.decode().encode('utf-8')
        except UnicodeDecodeError:
          encoding = self._guessEncoding(text)
          if encoding is not None:
143
            text = text.decode(encoding).encode('utf-8')
144 145
          else:
            text = repr(text)
146 147
        if name in result:
          result[name] = '%s %s' % (result[name], text)
148
        else:
149
          result[name] = text
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getAttachmentInformationList')
  def getAttachmentInformationList(self, **kw):
    """
    Returns a list of dictionnaries for every attachment. Each dictionnary
    represents the metadata of the attachment.
    **kw - support for listbox (TODO: improve it)
    """
    result = []
    i = 0
    for part in self._getMessage().walk():
      if not part.is_multipart():
        kw = dict(part.items())
        kw['uid'] = 'part_%s' % i
        kw['index'] = i
        if kw.has_key('Content-Disposition'):
          content_disposition = kw['Content-Disposition']
          if content_disposition.split(';')[0] == 'attachment':
169 170 171 172 173
            file_name = re.findall(file_name_regexp, content_disposition, re.MULTILINE)
            if file_name:
              kw['file_name'] = file_name[0]
            else:
              kw['file_name'] = 'attachment_%s' % i
174
          elif content_disposition.split(';')[0] == 'inline':
175 176 177 178 179
            file_name = re.findall(file_name_regexp, content_disposition, re.MULTILINE)
            if file_name:
              kw['file_name'] = file_name[0]
            else:
              kw['file_name'] = 'inline_%s' % i
180 181
          else:
            kw['file_name'] = 'part_%s' % i
182 183 184 185 186
        if kw.has_key('Content-Type'):
          content_type = kw['Content-Type']
          file_name = re.findall(file_name_regexp, content_type, re.MULTILINE)
          if file_name: kw['file_name'] = file_name[0]
          kw['content_type'] = content_type.split(';')[0]
187 188 189 190 191
        result.append(kw)
      i += 1
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getAttachmentData')
192
  def getAttachmentData(self, index, REQUEST=None):
193 194 195 196 197 198
    """
    Returns the decoded data of an attachment.
    """
    i = 0
    for part in self._getMessage().walk():
      if index == i:
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        # This part should be handled in skin script
        # but it was a bit easier to access items here
        if REQUEST is not None:
          kw = dict(part.items())
          RESPONSE = REQUEST.RESPONSE
          RESPONSE.setHeader('Accept-Ranges', 'bytes')
          if kw.has_key('Content-Type'):
            RESPONSE.setHeader('Content-Type', kw['Content-Type'])
            content_type = kw['Content-Type']
          elif kw.has_key('Content-type'):
            RESPONSE.setHeader('Content-Type', kw['Content-type'])
            content_type = kw['Content-type']
          else:
            content_type = None
          if kw.has_key('Content-Disposition'):
            content_disposition = kw['Content-Disposition']
          elif kw.has_key('Content-disposition'):
            content_disposition = kw['Content-disposition']
          else:
            content_disposition = None
          file_name = None
          if content_type:
            file_name = re.findall(file_name_regexp, content_type, re.MULTILINE)
          if content_disposition:
            if not file_name:
              file_name = re.findall(file_name_regexp, content_disposition, re.MULTILINE)
          if file_name:
            file_name = file_name[0]
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
227
            RESPONSE.setHeader('Content-disposition', 'attachment; filename="%s"' % file_name)
228 229 230 231
        return part.get_payload(decode=1)
      i += 1
    return KeyError, "No attachment with index %s" % index

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
  # Helper methods which override header property sheet
  security.declareProtected(Permissions.AccessContentsInformation, 'getSender')
  def getSender(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetSender(*args)
    return self.getContentInformation().get('From', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getRecipient')
  def getRecipient(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetRecipient(*args)
    return self.getContentInformation().get('To', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getCcRecipient')
  def getCcRecipient(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetCcRecipient(*args)
    return self.getContentInformation().get('Cc', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getGroupingReference')
  def getGroupingReference(self, *args):
    """
      The reference refers here to the Thread of messages.
    """
    if not self.hasData():
      result = self._baseGetGroupingReference(*args)
    else:
      if not len(args):
	args = (self._baseGetGroupingReference(),)
      result = self.getContentInformation().get('References', *args)
      if result:
	result = result.split() # Only take the first reference
	if result:
	  result = result[0]
    if result:
      return result
    return self.getSourceReference(*args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getSourceReference')
  def getSourceReference(self, *args):
    """
      The Message-ID is considered here as the source reference
      of the message on the sender side (source)
    """
    if not self.hasData():
      return self._baseGetSourceReference(*args)
    if not len(args):
      args = (self._baseGetSourceReference(),)
    content_information = self.getContentInformation()
    return content_information.get('Message-ID') or content_information.get('Message-Id', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getDestinationReference')
  def getDestinationReference(self, *args):
    """
      The In-Reply-To is considered here as the reference
      of the thread on the side of a former sender (destination)

      This is a hack which can be acceptable since 
      the reference of an email is shared.
    """
    if not self.hasData():
      return self._baseGetDestinationReference(*args)
    if not len(args):
      args = (self._baseGetDestinationReference(),)
    return self.getContentInformation().get('In-Reply-To', *args)

304 305 306 307
  # Overriden methods
  security.declareProtected(Permissions.AccessContentsInformation, 'getTitle')
  def getTitle(self, default=_MARKER):
    """
308
    Returns the title from the mail subject
309 310 311 312 313 314 315
    """
    if not self.hasFile():
      # Return the standard text content if no file was provided
      if default is _MARKER:
        return self._baseGetTitle()
      else:
        return self._baseGetTitle(default)
316
    message = self._getMessage()
Yusei Tahara's avatar
Yusei Tahara committed
317 318 319 320 321 322 323
    subject = self.getContentInformation().get('Subject', '')
    # Remove all newlines
    if '\r' in subject:
      subject = ''.join(subject.split('\r'))
    if '\n' in subject:
      subject = ''.join(subject.split('\n'))
    return subject
324
  
325 326 327
  security.declareProtected(Permissions.AccessContentsInformation, 'getStartDate')
  def getStartDate(self, default=_MARKER):
    """
328
    Returns the date from the mail date
329 330 331 332 333 334 335 336 337
    """
    if not self.hasFile():
      # Return the standard start date if no file was provided
      if default is _MARKER:
        return self._baseGetStartDate()
      else:
        return self._baseGetStartDate(default)
    date_string = self.getContentInformation().get('Date', None)
    if date_string:
338
      parsed_date_string = parsedate_tz(date_string)
339
      if parsed_date_string is not None:
340
        time = mktime_tz(parsed_date_string)
341 342
        if time:
          return DateTime(time)
343 344 345 346 347 348 349 350 351 352
    return self.getCreationDate()

  security.declareProtected(Permissions.AccessContentsInformation, 'getTextContent')
  def getTextContent(self, default=_MARKER):
    """
    Returns the content of the email as text. This is useful
    to display the content of an email.
    
    TODO: add support for legacy objects
    """
353
    if not self.hasFile() or self._baseGetTextContent() is not None:
354
      # Return the standard text content if no file was provided
355
      # Or standard text content is not empty.
356 357 358 359
      if default is _MARKER:
        return self._baseGetTextContent()
      else:
        return self._baseGetTextContent(default)
360 361

    # find from mail message
362 363 364 365
    text_result = None
    html_result = None
    for part in self._getMessage().walk():
      if part.get_content_type() == 'text/plain' and not text_result and not part.is_multipart():
366
        part_encoding = part.get_content_charset()
367 368
        message_text = part.get_payload(decode=1)
        if part_encoding != 'utf-8':
369
          try:
370 371 372 373
            if part_encoding is not None:
              text_result = message_text.decode(part_encoding).encode('utf-8')
            else:
              text_result = message_text.decode().encode('utf-8')
374 375 376
          except (UnicodeDecodeError, LookupError), error_message:
            LOG('EmailDocument.getTextContent', INFO, 
                'Failed to decode %s TEXT message with error: %s' % (part_encoding, error_message))
377 378
            codec = self._guessEncoding(message_text)
            if codec is not None:
379 380 381 382
              try:
                text_result = message_text.decode(codec).encode('utf-8')
              except (UnicodeDecodeError, LookupError):
                text_result = repr(message_text)
383 384
            else:
              text_result = repr(message_text)
385
        else:
386
          text_result = message_text
387
      elif part.get_content_type() == 'text/html' and not html_result and not part.is_multipart():
388
        part_encoding = part.get_content_charset()
389 390 391 392 393 394
        part_html = part.get_payload(decode=1)
        # Invoke Document class HTML stripper
        html_result = self._stripHTML(part_html, charset=part_encoding)
    if html_result:
      # Give priority to HTML
      text_result = html_result
395 396 397
    if default is _MARKER:
      return text_result
    return text_result or default
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

  security.declareProtected(Permissions.AccessContentsInformation, 'getTextFormat')
  def getTextFormat(self, default=_MARKER):
    """
    Returns the format of the email (text or html).
    
    TODO: add support for legacy objects
    """
    if not self.hasFile():
      # Return the standard text format if no file was provided
      if default is _MARKER:
        return self._baseGetTextFormat()
      else:
        return self._baseGetTextFormat(default)
    for part in self._getMessage().walk():
      if part.get_content_type() == 'text/html' and not part.is_multipart():
        return 'text/html'
    return 'text/plain'

417
  # Conversion API Implementation
418 419 420 421 422 423 424 425
  def _convertToBaseFormat(self):
    """
      Build a structure which can be later used
      to extract content information from this mail
      message.
    """
    pass

426
  security.declareProtected(Permissions.View, 'index_html')
427 428
  index_html = TextDocument.index_html

429
  security.declareProtected(Permissions.View, 'convert')
430
  convert = TextDocument.convert
431 432 433

  security.declareProtected(Permissions.AccessContentsInformation, 'hasBaseData')
  def hasBaseData(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
434
    """
435
      Since there is no need to convert to a base format, we consider that 
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436 437
      we always have the base format data if and only is we have
      some text defined or a file.
438 439 440 441 442 443 444 445 446 447
    """
    return self.hasFile() or self.hasTextContent()

  # Methods which can be useful to prepare a reply by email to an event
  security.declareProtected(Permissions.AccessContentsInformation, 'getReplyBody')
  def getReplyBody(self):
    """
      This is used in order to respond to a mail,
      this put a '> ' before each line of the body
    """
448 449 450 451 452
    if self.getTextFormat() == 'text/plain':
      body = self.asText()
      if body:
        return '> ' + str(body).replace('\n', '\n> ')
    elif self.getTextFormat() == 'text/html':
453
      return '<br/><blockquote type="cite">\n%s\n</blockquote>' %\
454
                                self.asStrippedHTML()
455 456 457 458 459 460 461
    return ''

  security.declareProtected(Permissions.AccessContentsInformation, 'getReplySubject')
  def getReplySubject(self):
    """
      This is used in order to respond to a mail,
      this put a 'Re: ' before the orignal subject
462 463

      XXX - not multilingual
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    """
    reply_subject = self.getTitle()
    if reply_subject.find('Re: ') != 0:
      reply_subject = 'Re: ' + reply_subject
    return reply_subject

  security.declareProtected(Permissions.AccessContentsInformation, 'getReplyTo')
  def getReplyTo(self):
    """
      Returns the send of this message based on getContentInformation
    """
    content_information = self.getContentInformation()
    return content_information.get('Return-Path', content_information.get('From'))

  security.declareProtected(Permissions.UseMailhostServices, 'send')
  def send(self, from_url=None, to_url=None, reply_url=None, subject=None,
Yusei Tahara's avatar
Yusei Tahara committed
480
           body=None, attachment_format=None, attachment_list=None, download=False):
481 482 483 484
    """
      Sends the current event content by email. If documents are
      attached through the aggregate category, enclose them.

485 486
      XXX - needs to be unified with Event methods

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
      from_url - the sender of this email. If not provided
                 we will use source to find a valid
                 email address

      to_url   - the recipients of this email. If not provided
                 we will use destination category to 
                 find a list of valid email addresses

      reply_url - the email address to reply to. If nothing
                 is provided, use the email defined in 
                 preferences.

      subject  - a custom title. If not provided, we will use
                 getTitle

      body     - a body message If not provided, we will
                 use the text representation of the event
504
                 as body (UTF-8)
505

Yusei Tahara's avatar
Yusei Tahara committed
506 507 508 509
      attachment_list -- list of dictionary which contains raw data and
                         name and mimetype for attachment.
                         See NotificationTool.buildEmailMessage.

510 511 512 513 514 515 516 517 518 519 520 521
      attachment_format - defines an option format
                 to convet attachments to (ex. application/pdf)

      download - if set to True returns, the message online
                rather than sending it.

      TODO: support conversion to base format and use
      base format rather than original format

      TODO2: consider turning this method into a general method for
      any ERP5 document.
    """
Yusei Tahara's avatar
Yusei Tahara committed
522 523 524
    if not _checkPermission(Permissions.View, self):
      raise Unauthorized

525
    #
526
    # Build mail message
527
    # This part will be replaced with MailTemplate soon.
528
    #
529 530
    if body is None:
      body = self.asText()
531 532

    # Subject
533 534
    if subject is None:
      subject = self.getTitle()
535 536

    # From
537
    if from_url is None:
538 539 540 541 542 543
      sender = self.getSourceValue()
      if sender.getTitle():
        from_url = '"%s" <%s>' % (sender.getTitle(),
                                sender.getDefaultEmailText())
      else:
        from_url = sender.getDefaultEmailText()
544 545

    # Return-Path
546 547
    if reply_url is None:
      reply_url = self.portal_preferences.getPreferredEventSenderEmail()
548 549 550 551 552 553
    additional_headers = None
    if reply_url:
      additional_headers = {'Return-Path':reply_url}

    # To (multiple)
    to_url_list = []
554 555 556 557
    if to_url is None:
      for recipient in self.getDestinationValueList():
        email = recipient.getDefaultEmailText()
        if email:
558
          if recipient.getTitle():
559
            to_url_list.append('"%s" <%s>' % (recipient.getTitle(), email))
560
          else:
561
            to_url_list.append(email)
562 563 564
        else:
          raise ValueError, 'Recipient %s has no defined email' % recipient
    elif type(to_url) in types.StringTypes:
565 566 567
      to_url_list.append(to_url)

    # Attachments
Yusei Tahara's avatar
Yusei Tahara committed
568 569
    if attachment_list is None:
      attachment_list = []
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    document_type_list = self.getPortalDocumentTypeList()
    for attachment in self.getAggregateValueList():
      mime_type = None
      content = None
      name = None
      if not attachment.getPortalType() in document_type_list:
        mime_type = 'application/pdf'
        content = attachment.asPDF() # XXX - Not implemented yet
      else:
        #
        # Document type attachment
        #

        # WARNING - this could fail since getContentType
        # is not (yet) part of Document API
        if getattr(attachment, 'getContentType', None) is not None:
          mime_type = attachment.getContentType()
        elif getattr(attachment, 'getTextFormat', None) is not None:
          mime_type = attachment.getTextFormat()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
589
        else:
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
          raise ValueError, "Cannot find mimetype of the document."

        if mime_type is not None:
          try:
            mime_type, content = attachment.convert(mime_type)
          except ConversionError:
            mime_type = attachment.getBaseContentType()
            content = attachment.getBaseData()
          except (NotImplementedError, MimeTypeException):
            pass

        if content is None:
          if getattr(attachment, 'getTextContent', None) is not None:
            content = attachment.getTextContent()
          elif getattr(attachment, 'getData', None) is not None:
            content = attachment.getData()
          elif getattr(attachment, 'getBaseData', None) is not None:
            content = attachment.getBaseData()

      if not isinstance(content, str):
        content = str(content)

      attachment_list.append({'mime_type':mime_type,
                              'content':content,
                              'name':attachment.getReference()}
                             )

617 618 619 620 621 622
    for to_url in to_url_list:
      mime_message = buildEmailMessage(from_url=from_url, to_url=to_url,
                                       msg=body, subject=subject,
                                       attachment_list=attachment_list,
                                       additional_headers=additional_headers)
      mail_message = mime_message.as_string()
623
      self.activate(activity='SQLQueue').sendMailHostMessage(mail_message)
624

625 626 627
    # Save one of mail messages.
    self.setData(mail_message)

628 629
    # Only for debugging purpose
    if download:
630
      return mail_message
631 632 633 634 635

  security.declareProtected(Permissions.UseMailhostServices, 'sendMailHostMessage')
  def sendMailHostMessage(self, message):
    """
      Send one by one
636 637

      XXX - Needs to be unified with Event methods
638 639
    """
    self.MailHost.send(message)