OOoDocument.py 21.4 KB
Newer Older
1
# -*- coding: utf-8 -*-
Bartek Górny's avatar
Bartek Górny committed
2 3 4
##############################################################################
#
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
5
# Copyright (c) 2006-2007 Nexedi SA and Contributors. All Rights Reserved.
Bartek Górny's avatar
Bartek Górny committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# 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.
#
##############################################################################

30
import xmlrpclib, base64, re, zipfile, cStringIO
31
from warnings import warn
32
from xmlrpclib import Fault
33 34
from xmlrpclib import Transport
from xmlrpclib import SafeTransport
Bartek Górny's avatar
Bartek Górny committed
35
from AccessControl import ClassSecurityInfo
36
from AccessControl import Unauthorized
Bartek Górny's avatar
Bartek Górny committed
37
from OFS.Image import Pdata
38
from OFS.Image import File as OFSFile
39 40 41 42
try:
    from OFS.content_types import guess_content_type
except ImportError:
    from zope.contenttype import guess_content_type
43 44
from Products.CMFCore.utils import getToolByName, _setCacheHeaders,\
    _ViewEmulator
45
from Products.ERP5Type import Permissions, PropertySheet, Constraint
Bartek Górny's avatar
Bartek Górny committed
46
from Products.ERP5Type.Cache import CachingMethod
47
from Products.ERP5.Document.File import File
48 49
from Products.ERP5.Document.Document import Document, PermanentURLMixIn,\
VALID_IMAGE_FORMAT_LIST, ConversionError, NotConvertedError
50
from zLOG import LOG, ERROR
51

52
# Mixin Import
53
from Products.ERP5.mixin.base_convertable import BaseConvertableFileMixin
54
from Products.ERP5.mixin.text_convertable import TextConvertableMixin
55

Bartek Górny's avatar
Bartek Górny committed
56 57 58
enc=base64.encodestring
dec=base64.decodestring

59 60
_MARKER = []

61 62 63 64 65 66
class TimeoutTransport(SafeTransport):
  """A xmlrpc transport with configurable timeout.
  """
  def __init__(self, timeout=None, scheme='http'):
    self._timeout = timeout
    self._scheme = scheme
67 68 69 70 71 72 73
    # On Python 2.6, .__init__() of Transport and SafeTransport must be called
    # to set up the ._use_datetime attribute.
    # sigh... too bad we can't use super() here, as SafeTransport is not
    # a new-style class (as of Python 2.4 to 2.6)
    # remove the gettattr below when we drop support for Python 2.4
    super__init__ = getattr(SafeTransport, '__init__', lambda self: None)
    super__init__(self)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

  def send_content(self, connection, request_body):
    connection.putheader("Content-Type", "text/xml")
    connection.putheader("Content-Length", str(len(request_body)))
    connection.endheaders()
    if self._timeout:
      connection._conn.sock.settimeout(self._timeout)
    if request_body:
      connection.send(request_body)

  def make_connection(self, h):
    if self._scheme == 'http':
      return Transport.make_connection(self, h)
    return SafeTransport.make_connection(self, h)


90 91
class OOoDocument(PermanentURLMixIn, BaseConvertableFileMixin, File,
                                               TextConvertableMixin, Document):
Bartek Górny's avatar
Bartek Górny committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  """
    A file document able to convert OOo compatible files to
    any OOo supported format, to capture metadata and to
    update metadata in OOo documents.

    This class can be used:

    - to create an OOo document database with powerful indexing (r/o)
      and metadata handling (r/w) features (ex. change title in ERP5 ->
      title is changed in OOo document)

    - to massively convert MS Office documents to OOo format

    - to easily keep snapshots (in PDF and/or OOo format) of OOo documents
      generated from OOo templates

    This class may be used in the future:

    - to create editable OOo templates (ex. by adding tags in WYSIWYG mode
      and using tags to make document dynamic - ask kevin for more info)

    - to automatically sign / encrypt OOo documents based on user

    - to automatically sign / encrypt PDF generated from OOo documents based on user

    This class should not be used:

    - to store files in formats not supported by OOo

    - to stored pure images (use Image for that)

    - as a general file conversion system (use portal_transforms for that)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
124 125 126

    TODO:
    - better permissions
Bartek Górny's avatar
Bartek Górny committed
127 128 129 130 131 132 133 134 135 136 137
  """
  # CMF Type Definition
  meta_type = 'ERP5 OOo Document'
  portal_type = 'OOo Document'

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
138 139
                    , PropertySheet.XMLObject
                    , PropertySheet.Reference
Bartek Górny's avatar
Bartek Górny committed
140 141 142
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
143
                    , PropertySheet.Document
144 145 146 147
                    , PropertySheet.Snapshot
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.Periodicity
148
                    , PropertySheet.SortIndex
Bartek Górny's avatar
Bartek Górny committed
149 150
                    )

151
  # regular expressions for stripping xml from ODF documents
152 153
  rx_strip = re.compile('<[^>]*?>', re.DOTALL|re.MULTILINE)
  rx_compr = re.compile('\s+')
154

155 156
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
157 158 159 160 161 162
  def isSupportBaseDataConversion(self):
    """
    OOoDocument is needed to conversion to base format.
    """
    return True

163
  # Format conversion implementation
164
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
165
    """
166 167
      Returns the oood conversion server coordinates
      as defined in preferences.
Bartek Górny's avatar
Bartek Górny committed
168
    """
169 170 171
    preference_tool = getToolByName(self, 'portal_preferences')
    address = preference_tool.getPreferredOoodocServerAddress()
    port = preference_tool.getPreferredOoodocServerPortNumber()
172
    if address in ('', None) or port in ('', None) :
173
      raise ConversionError('OOoDocument: can not proceed with conversion:'
174
            ' conversion server host and port is not defined in preferences')
175
    return address, port
Bartek Górny's avatar
Bartek Górny committed
176 177 178

  def _mkProxy(self):
    """
179
      Create an XML-RPC proxy to access the conversion server.
Bartek Górny's avatar
Bartek Górny committed
180
    """
181 182 183 184
    server_proxy = xmlrpclib.ServerProxy(
             'http://%s:%d' % self._getServerCoordinate(),
             allow_none=True,
             transport=TimeoutTransport(timeout=360, scheme='http'))
185
    return server_proxy
Bartek Górny's avatar
Bartek Górny committed
186

187 188
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatItemList')
Bartek Górny's avatar
Bartek Górny committed
189 190 191 192 193
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

194 195
      NOTE: it is the responsability of the conversion server
      to provide an extensive list of conversion formats.
Bartek Górny's avatar
Bartek Górny committed
196
    """
197
    if not self.hasBaseData():
198
      raise NotConvertedError
199

200
    def cached_getTargetFormatItemList(content_type):
201
      server_proxy = self._mkProxy()
202
      try:
203 204 205 206 207 208 209 210 211 212
        allowed_target_item_list = server_proxy.getAllowedTargetItemList(
                                                      content_type)
        try:
          response_code, response_dict, response_message = \
                                             allowed_target_item_list
        except ValueError:
          # Compatibility with older oood where getAllowedTargetItemList only
          # returned response_dict
          response_code, response_dict, response_message = \
                         200, dict(response_data=allowed_target_item_list), ''
213

214 215 216 217 218
        if response_code == 200:
          allowed = response_dict['response_data']
        else:
          # This is very temporary code - XXX needs to be changed
          # so that the system can retry
219
          raise ConversionError("OOoDocument: can not get list of allowed acceptable"
220 221
                                " formats for conversion: %s (%s)" % (
                                      response_code, response_message))
222

223 224 225 226
      except Fault, f:
        allowed = server_proxy.getAllowedTargets(content_type)
        warn('Your oood version is too old, using old method '
            'getAllowedTargets instead of getAllowedTargetList',
227 228
             DeprecationWarning)

229 230
      # tuple order is reversed to be compatible with ERP5 Form
      return [(y, x) for x, y in allowed]
Bartek Górny's avatar
Bartek Górny committed
231

232
    # Cache valid format list
233 234 235 236
    cached_getTargetFormatItemList = CachingMethod(
                                cached_getTargetFormatItemList,
                                id="OOoDocument_getTargetFormatItemList",
                                cache_factory='erp5_ui_medium')
Bartek Górny's avatar
Bartek Górny committed
237

238 239
    return cached_getTargetFormatItemList(self.getBaseContentType())

240 241
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatTitleList')
242
  def getTargetFormatTitleList(self):
Bartek Górny's avatar
Bartek Górny committed
243 244 245 246 247
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

248 249
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatList')
250
  def getTargetFormatList(self):
Bartek Górny's avatar
Bartek Górny committed
251
    """
252
      Returns a list of acceptable formats for conversion
Bartek Górny's avatar
Bartek Górny committed
253
    """
254
    return map(lambda x: x[1], self.getTargetFormatItemList())
Bartek Górny's avatar
Bartek Górny committed
255

256 257
  security.declareProtected(Permissions.ModifyPortalContent,
                            'isTargetFormatAllowed')
258
  def isTargetFormatAllowed(self, format):
259
    """
260
      Checks if the current document can be converted
261
      into the specified target format.
262 263 264
    """
    return format in self.getTargetFormatList()

265
  def _getConversionFromProxyServer(self, format):
266 267 268
    """
      Communicates with server to convert a file 
    """
269
    if not self.hasBaseData():
270
      raise NotConvertedError
271 272 273
    if format == 'text-content':
      # Extract text from the ODF file
      cs = cStringIO.StringIO()
274
      cs.write(str(self.getBaseData()))
275 276 277 278 279 280
      z = zipfile.ZipFile(cs)
      s = z.read('content.xml')
      s = self.rx_strip.sub(" ", s) # strip xml
      s = self.rx_compr.sub(" ", s) # compress multiple spaces
      cs.close()
      z.close()
281
      return 'text/plain', s
282
    server_proxy = self._mkProxy()
283
    orig_format = self.getBaseContentType()
284
    generate_result = server_proxy.run_generate(self.getId(),
285
                                       enc(str(self.getBaseData())),
286
                                       None,
287 288
                                       format,
                                       orig_format)
289 290 291 292 293 294
    try:
      response_code, response_dict, response_message = generate_result
    except ValueError:
      # This is for backward compatibility with older oood version returning
      # only response_dict
      response_dict = generate_result
295

296
    # XXX: handle possible OOOd server failure
297
    return response_dict['mime'], Pdata(dec(response_dict['data']))
298

299
  # Conversion API
300
  def _convert(self, format, display=None, **kw):
301 302 303 304
    """Convert the document to the given format.

    If a conversion is already stored for this format, it is returned
    directly, otherwise the conversion is stored for the next time.
Bartek Górny's avatar
Bartek Górny committed
305
    """
306 307
    #XXX if document is empty, stop to try to convert.
    #XXX but I don't know what is a appropriate mime-type.(Yusei)
308
    if not self.hasData():
309
      return 'text/plain', ''
310 311 312 313 314 315 316
    # if no conversion asked (format empty)
    # return raw data
    if not format:
      return self.getContentType(), self.getData()
    # Check if we have already a base conversion
    if not self.hasBaseData():
      raise NotConvertedError
317 318
    # Make sure we can support html and pdf by default
    is_html = 0
319
    requires_pdf_first = 0
320
    original_format = format
321
    if format == 'base-data':
322
      return self.getBaseContentType(), str(self.getBaseData())
323
    if format == 'pdf':
324 325
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith('pdf')]
326
      format = format_list[0]
327
    elif format in VALID_IMAGE_FORMAT_LIST:
328 329
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith(format)]
330 331 332 333 334 335 336 337
      if len(format_list):
        format = format_list[0]
      else:
        # We must fist make a PDF
        requires_pdf_first = 1
        format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith('pdf')]
        format = format_list[0]
338
    elif format == 'html':
339 340
      format_list = [x for x in self.getTargetFormatList()
                              if x.startswith('html') or x.endswith('html')]
341 342
      format = format_list[0]
      is_html = 1
343 344
    elif format in ('txt', 'text', 'text-content'):
      format_list = self.getTargetFormatList()
345 346 347 348
      # if possible, we try to get utf8 text. ('enc.txt' will encode to utf8)
      if 'enc.txt' in format_list:
        format = 'enc.txt'
      elif format not in format_list:
349 350 351
        #Text conversion is not supported by oood, do it in other way
        if not self.hasConversion(format=original_format):
          #Do real conversion for text
352
          mime, data = self._getConversionFromProxyServer(format='text-content')
353 354 355
          self.setConversion(data, mime, format=original_format)
          return mime, data
        return self.getConversion(format=original_format)
356 357
    # Raise an error if the format is not supported
    if not self.isTargetFormatAllowed(format):
358
      raise ConversionError("OOoDocument: target format %s is not supported" % format)
359
    # Return converted file
360 361 362 363 364 365 366 367
    if requires_pdf_first:
      # We should use original_format whenever we wish to
      # display an image version of a document which needs to go
      # through PDF
      if display is None:
        has_format = self.hasConversion(format=original_format)
      else:
        has_format = self.hasConversion(format=original_format, display=display)
368
    elif display is None or original_format not in VALID_IMAGE_FORMAT_LIST:
369
      has_format = self.hasConversion(format=original_format)
370
    else:
371
      has_format = self.hasConversion(format=original_format, display=display)
372
    if not has_format:
373
      # Do real conversion
374
      mime, data = self._getConversionFromProxyServer(format)
375 376 377 378
      if is_html:
        # Extra processing required since
        # we receive a zip file
        cs = cStringIO.StringIO()
379
        cs.write(str(data))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
380
        z = zipfile.ZipFile(cs) # A disk file would be more RAM efficient
381 382 383
        for f in z.infolist():
          fn = f.filename
          if fn.endswith('html'):
384 385 386
            if self.getPortalType() == 'Presentation'\
                  and not (fn.find('impr') >= 0):
              continue
387 388 389
            data = z.read(fn)
            break
        mime = 'text/html'
390
        self._populateConversionCacheWithHTML(zip_file=z) # Maybe some parts should be asynchronous for
391
                                         # better usability
392 393
        z.close()
        cs.close()
394
      if (display is None or original_format not in VALID_IMAGE_FORMAT_LIST) \
395
        and not requires_pdf_first:
396
        self.setConversion(data, mime, format=original_format)
397
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
398
        temp_image = self.portal_contributions.newContent(
399
                                       portal_type='Image',
400 401
                                       file=cStringIO.StringIO(),
                                       file_name=self.getId(),
402 403
                                       temp_object=1)
        temp_image._setData(data)
404
        mime, data = temp_image.convert(original_format, display=display)
405 406 407 408 409 410 411
        if requires_pdf_first:
          if display is None:
            self.setConversion(data, mime, format=original_format)
          else:
            self.setConversion(data, mime, format=original_format, display=display)
        else:
          if display is None:
412
            self.setConversion(data, mime, format=original_format)
413
          else:
414
            self.setConversion(data, mime, format=original_format, display=display)
415 416
    if requires_pdf_first:
      format = original_format
417
    if display is None or original_format not in VALID_IMAGE_FORMAT_LIST:
418
      return self.getConversion(format=original_format)
419
    else:
420
      return self.getConversion(format=original_format, display=display)
421

422 423
  security.declareProtected(Permissions.AccessContentsInformation,
                                                               'asTextContent')
424 425
  def asTextContent(self):
    """
426
      Backward compatibility
427
    """
428
    return self.asText()
429

430
  security.declareProtected(Permissions.ModifyPortalContent,
431 432
                            '_populateConversionCacheWithHTML')
  def _populateConversionCacheWithHTML(self, zip_file=None):
433 434 435 436 437
    """
    Extract content from the ODF zip file and populate the document.
    Optional parameter zip_file prevents from converting content twice.
    """
    if zip_file is None:
438
      format_list = [x for x in self.getTargetFormatList()
439
                                if x.startswith('html') or x.endswith('html')]
440
      format = format_list[0]
441
      mime, data = self._getConversionFromProxyServer(format)
442
      archive_file = cStringIO.StringIO()
443
      archive_file.write(str(data))
444 445 446 447 448 449
      zip_file = zipfile.ZipFile(archive_file)
      must_close = 1
    else:
      must_close = 0
    for f in zip_file.infolist():
      file_name = f.filename
450 451
      document = self.get(file_name, None)
      if document is not None:
452
        self.manage_delObjects([file_name]) # For compatibility with old implementation
453
      if file_name.endswith('html'):
454
        mime = 'text/html'
455 456 457 458 459 460 461
        # call portal_transforms to strip HTML in safe mode
        portal = self.getPortalObject()
        transform_tool = getToolByName(portal, 'portal_transforms')
        data = transform_tool.convertToData('text/xhtml-safe',
                                            zip_file.read(file_name),
                                            object=self, context=self,
                                            mimetype=mime)
462
      else:
463 464
        mime = guess_content_type(file_name)[0]
        data = Pdata(zip_file.read(file_name))
465
      self.setConversion(data, mime=mime, format='_embedded', file_name=file_name)
466 467 468 469
    if must_close:
      zip_file.close()
      archive_file.close()

470
  def _getExtensibleContent(self, request, name):
471 472
    # Be sure that html conversion is done,
    # as it is required to extract extensible content
473
    try:
474 475 476 477
      self._convert(format='html')
      web_cache_kw = {'name': name,
                      'format': '_embedded'}
      _setCacheHeaders(_ViewEmulator().__of__(self), web_cache_kw)
478
      mime, data = self.getConversion(format='_embedded', file_name=name)
479
      return OFSFile(name, name, data, content_type=mime).__of__(self.aq_parent)
480
    except (NotConvertedError, ConversionError, KeyError):
481
      return PermanentURLMixIn._getExtensibleContent(self, request, name)
482

483 484
  security.declarePrivate('_convertToBaseFormat')
  def _convertToBaseFormat(self):
Bartek Górny's avatar
Bartek Górny committed
485
    """
486 487 488
      Converts the original document into ODF
      by invoking the conversion server. Store the result
      on the object. Update metadata information.
Bartek Górny's avatar
Bartek Górny committed
489
    """
490
    server_proxy = self._mkProxy()
491 492
    response_code, response_dict, response_message = server_proxy.run_convert(
                                      self.getSourceReference() or self.getId(),
493
                                      enc(str(self.getData())))
494 495 496 497 498 499
    if response_code == 200:
      # sucessfully converted document
      self._setBaseData(dec(response_dict['data']))
      metadata = response_dict['meta']
      self._base_metadata = metadata
      if metadata.get('MIMEType', None) is not None:
500
        self._setBaseContentType(metadata['MIMEType'])
501
    else:
502 503
      # Explicitly raise the exception!
      raise ConversionError(
504 505
                "OOoDocument: Error converting document to base format %s:%s:"
                                       % (response_code, response_message))
506

507 508
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getContentInformation')
509
  def getContentInformation(self):
Bartek Górny's avatar
Bartek Górny committed
510
    """
511 512
      Returns the metadata extracted by the conversion
      server.
Bartek Górny's avatar
Bartek Górny committed
513
    """
514
    return getattr(self, '_base_metadata', {})
Bartek Górny's avatar
Bartek Górny committed
515

516 517
  security.declareProtected(Permissions.ModifyPortalContent,
                            'updateBaseMetadata')
518
  def updateBaseMetadata(self, **kw):
Bartek Górny's avatar
Bartek Górny committed
519
    """
520 521 522
      Updates metadata information in the converted OOo document
      based on the values provided by the user. This is implemented
      through the invocation of the conversion server.
Bartek Górny's avatar
Bartek Górny committed
523
    """
524 525 526
    if not self.hasBaseData():
      raise NotConvertedError

527
    server_proxy = self._mkProxy()
528 529
    response_code, response_dict, response_message = \
          server_proxy.run_setmetadata(self.getId(),
530
                                       enc(str(self.getBaseData())),
531
                                       kw)
532 533 534
    if response_code == 200:
      # successful meta data extraction
      self._setBaseData(dec(response_dict['data']))
535
      self.updateFileMetadata() # record in workflow history # XXX must put appropriate comments.
536
    else:
537
      # Explicitly raise the exception!
538
      raise ConversionError("OOoDocument: error getting document metadata %s:%s"
539
                        % (response_code, response_message))