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

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

Bartek Górny's avatar
Bartek Górny committed
52 53 54
enc=base64.encodestring
dec=base64.decodestring

55
_MARKER = []
56
STANDARD_IMAGE_FORMAT_LIST = ('png', 'jpg', 'gif', )
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
class TimeoutTransport(SafeTransport):
  """A xmlrpc transport with configurable timeout.
  """
  def __init__(self, timeout=None, scheme='http'):
    self._timeout = timeout
    self._scheme = scheme

  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)


80
class OOoDocument(PermanentURLMixIn, File, ConversionCacheMixin):
Bartek Górny's avatar
Bartek Górny committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  """
    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
113 114 115

    TODO:
    - better permissions
Bartek Górny's avatar
Bartek Górny committed
116 117 118 119 120 121 122
  """
  # CMF Type Definition
  meta_type = 'ERP5 OOo Document'
  portal_type = 'OOo Document'
  isPortalContent = 1
  isRADContent = 1

123
  searchable_property_list = ('asText', 'title', 'description', 'id', 'reference',
124 125
                              'version', 'short_title',
                              'subject', 'source_reference', 'source_project_title',)
Bartek Górny's avatar
Bartek Górny committed
126 127 128 129 130 131 132

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
133 134
                    , PropertySheet.XMLObject
                    , PropertySheet.Reference
Bartek Górny's avatar
Bartek Górny committed
135 136 137
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
138
                    , PropertySheet.Document
139 140 141 142
                    , PropertySheet.Snapshot
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.Periodicity
Bartek Górny's avatar
Bartek Górny committed
143 144
                    )

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

149 150
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
151 152 153 154 155 156
  def isSupportBaseDataConversion(self):
    """
    OOoDocument is needed to conversion to base format.
    """
    return True

157 158 159 160
  def _setFile(self, data, precondition=None):
    File._setFile(self, data, precondition=precondition)
    if self.hasBaseData():
      # This is a hack - XXX - new accessor needed to delete properties
Yusei Tahara's avatar
Yusei Tahara committed
161 162 163 164
      try:
        delattr(self, 'base_data')
      except AttributeError:
        pass
165

166
  security.declareProtected(Permissions.View, 'index_html')
167
  def index_html(self, REQUEST, RESPONSE, format=None, display=None, **kw):
168
    """
169 170 171
      Default renderer with conversion support. Format is
      a string. The list of available formats can be obtained
      by calling getTargetFormatItemList.
172
    """
173
    # Accelerate rendering in Web mode
174
    _setCacheHeaders(_ViewEmulator().__of__(self), {'format' : format})
175 176 177 178 179 180

    # Verify that the format is acceptable (from permission point of view)
    method = self._getTypeBasedMethod('checkConversionFormatPermission', 
        fallback_script_id = 'Document_checkConversionFormatPermission')
    if not method(format=format):
      raise Unauthorized("OOoDocument: user does not have enough permission to access document"
181
                         " in %s format" % (format or 'original'))
182

183
    # Return the original file by default
184 185 186 187
    if self.getSourceReference() is not None:
      filename = self.getSourceReference()
    else:
      filename = self.getId()
188
    if format is None:
189 190
      RESPONSE.setHeader('Content-Disposition',
                         'attachment; filename="%s"' % filename)
191 192 193
      return File.index_html(self, REQUEST, RESPONSE)
    # Make sure file is converted to base format
    if not self.hasBaseData():
194
      raise NotConvertedError
195
    # Else try to convert the document and return it
196
    mime, result = self.convert(format=format, display=display, **kw)
197
    converted_filename = '%s.%s'%(filename.split('.')[0],  format)
198 199
    if not mime:
      mime = getToolByName(self, 'mimetypes_registry').lookupExtension('name.%s' % format)
200
    RESPONSE.setHeader('Content-Length', len(result))
201 202
    RESPONSE.setHeader('Content-Type', mime)
    RESPONSE.setHeader('Accept-Ranges', 'bytes')
203 204
    RESPONSE.setHeader('Content-Disposition',
                       'attachment; filename="%s"' % converted_filename)
205 206
    return result

207
  # Format conversion implementation
208
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
209
    """
210 211
      Returns the oood conversion server coordinates
      as defined in preferences.
Bartek Górny's avatar
Bartek Górny committed
212
    """
213 214 215
    preference_tool = getToolByName(self, 'portal_preferences')
    address = preference_tool.getPreferredOoodocServerAddress()
    port = preference_tool.getPreferredOoodocServerPortNumber()
216
    if address in ('', None) or port in ('', None) :
217
      raise ConversionError('OOoDocument: can not proceed with conversion:'
218
            ' conversion server host and port is not defined in preferences')
219
    return address, port
Bartek Górny's avatar
Bartek Górny committed
220 221 222

  def _mkProxy(self):
    """
223
      Create an XML-RPC proxy to access the conversion server.
Bartek Górny's avatar
Bartek Górny committed
224
    """
225 226 227 228
    server_proxy = xmlrpclib.ServerProxy(
             'http://%s:%d' % self._getServerCoordinate(),
             allow_none=True,
             transport=TimeoutTransport(timeout=360, scheme='http'))
229
    return server_proxy
Bartek Górny's avatar
Bartek Górny committed
230

231 232
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatItemList')
Bartek Górny's avatar
Bartek Górny committed
233 234 235 236 237
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

238 239
      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
240
    """
241
    if not self.hasBaseData():
242
      raise NotConvertedError
243

244
    def cached_getTargetFormatItemList(content_type):
245
      server_proxy = self._mkProxy()
246
      try:
247 248 249 250 251 252 253 254 255 256 257
        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), ''
        
258 259 260 261 262
        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
263
          raise ConversionError("OOoDocument: can not get list of allowed acceptable"
264 265
                                " formats for conversion: %s (%s)" % (
                                      response_code, response_message))
266

267 268 269 270
      except Fault, f:
        allowed = server_proxy.getAllowedTargets(content_type)
        warn('Your oood version is too old, using old method '
            'getAllowedTargets instead of getAllowedTargetList',
271
             DeprecationWarning)
272 273 274

      # 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
275

276
    # Cache valid format list
277 278 279 280
    cached_getTargetFormatItemList = CachingMethod(
                                cached_getTargetFormatItemList,
                                id="OOoDocument_getTargetFormatItemList",
                                cache_factory='erp5_ui_medium')
Bartek Górny's avatar
Bartek Górny committed
281

282 283
    return cached_getTargetFormatItemList(self.getBaseContentType())

284 285
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatTitleList')
286
  def getTargetFormatTitleList(self):
Bartek Górny's avatar
Bartek Górny committed
287 288 289 290 291
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

292 293
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatList')
294
  def getTargetFormatList(self):
Bartek Górny's avatar
Bartek Górny committed
295
    """
296
      Returns a list of acceptable formats for conversion
Bartek Górny's avatar
Bartek Górny committed
297
    """
298
    return map(lambda x: x[1], self.getTargetFormatItemList())
Bartek Górny's avatar
Bartek Górny committed
299

300 301
  security.declareProtected(Permissions.ModifyPortalContent,
                            'isTargetFormatAllowed')
302
  def isTargetFormatAllowed(self, format):
303
    """
304 305 306 307 308 309 310 311 312 313
      Checks if the current document can be converted
      into the specified target format.
    """
    return format in self.getTargetFormatList()

  security.declarePrivate('_convert')
  def _convert(self, format):
    """
      Communicates with server to convert a file 
    """
314
    if not self.hasBaseData():
315
      raise NotConvertedError
316 317 318
    if format == 'text-content':
      # Extract text from the ODF file
      cs = cStringIO.StringIO()
319
      cs.write(_unpackData(self.getBaseData()))
320 321 322 323 324 325
      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()
326
      return 'text/plain', s
327
    server_proxy = self._mkProxy()
328
    orig_format = self.getBaseContentType()
329
    generate_result = server_proxy.run_generate(self.getId(),
330
                                       enc(_unpackData(self.getBaseData())),
331
                                       None,
332 333
                                       format,
                                       orig_format)
334 335 336 337 338 339
    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
340

341
    # XXX: handle possible OOOd server failure
342
    return response_dict['mime'], Pdata(dec(response_dict['data']))
343

344
  # Conversion API
345
  security.declareProtected(Permissions.View, 'convert')
346
  def convert(self, format, display=None, **kw):
347 348 349 350
    """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
351
    """
352 353
    #XXX if document is empty, stop to try to convert.
    #XXX but I don't know what is a appropriate mime-type.(Yusei)
354
    if self.get_size() == 0:
355
      return 'text/plain', ''
356

357 358
    # Make sure we can support html and pdf by default
    is_html = 0
359
    requires_pdf_first = 0
360
    original_format = format
361
    if format == 'base-data':
362 363
      if not self.hasBaseData():
        raise NotConvertedError
364
      return self.getBaseContentType(), self.getBaseData()
365
    if format == 'pdf':
366 367
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith('pdf')]
368
      format = format_list[0]
369
    elif format in STANDARD_IMAGE_FORMAT_LIST:
370 371
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith(format)]
372 373 374 375 376 377 378 379
      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]
380
    elif format == 'html':
381 382
      format_list = [x for x in self.getTargetFormatList()
                              if x.startswith('html') or x.endswith('html')]
383 384
      format = format_list[0]
      is_html = 1
385 386
    elif format in ('txt', 'text', 'text-content'):
      format_list = self.getTargetFormatList()
387 388 389 390
      # 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:
391
        return self.asTextContent()
392 393
    # Raise an error if the format is not supported
    if not self.isTargetFormatAllowed(format):
394
      raise ConversionError("OOoDocument: target format %s is not supported" % format)
395 396
    # Check if we have already a base conversion
    if not self.hasBaseData():
397
      raise NotConvertedError
398
    # Return converted file
399 400 401 402 403 404 405 406 407
    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)
    elif display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST:
408 409 410 411
      has_format = self.hasConversion(format=format)
    else:
      has_format = self.hasConversion(format=format, display=display)
    if not has_format:
412 413 414 415 416 417
      # Do real conversion
      mime, data = self._convert(format)
      if is_html:
        # Extra processing required since
        # we receive a zip file
        cs = cStringIO.StringIO()
418
        cs.write(_unpackData(data))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
419
        z = zipfile.ZipFile(cs) # A disk file would be more RAM efficient
420 421 422
        for f in z.infolist():
          fn = f.filename
          if fn.endswith('html'):
423 424 425
            if self.getPortalType() == 'Presentation'\
                  and not (fn.find('impr') >= 0):
              continue
426 427 428
            data = z.read(fn)
            break
        mime = 'text/html'
429
        self._populateConversionCacheWithHTML(zip_file=z) # Maybe some parts should be asynchronous for
430
                                         # better usability
431 432
        z.close()
        cs.close()
433 434
      if (display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST) \
        and not requires_pdf_first:
435 436
        self.setConversion(data, mime, format=format)
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
437
        temp_image = self.portal_contributions.newContent(
438 439 440
                                       portal_type='Image',
                                       temp_object=1)
        temp_image._setData(data)
441
        mime, data = temp_image.convert(original_format, display=display)
442 443 444 445 446 447 448 449 450 451 452 453
        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:
            self.setConversion(data, mime, format=format)
          else:
            self.setConversion(data, mime, format=format, display=display)
    if requires_pdf_first:
      format = original_format
454 455 456 457 458
    if display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST:
      return self.getConversion(format=format)
    else:
      return self.getConversion(format=format, display=display)

459 460 461 462 463 464 465
  security.declareProtected(Permissions.View, 'asTextContent')
  def asTextContent(self):
    """
      Extract plain text from ooo docs by stripping the XML file.
      This is the simplest way, the most universal and it is compatible
      will all formats.
    """
466
    return self._convert(format='text-content')
467

468
  security.declareProtected(Permissions.ModifyPortalContent,
469 470
                            '_populateConversionCacheWithHTML')
  def _populateConversionCacheWithHTML(self, zip_file=None):
471 472 473 474 475
    """
    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:
476
      format_list = [x for x in self.getTargetFormatList()
477
                                if x.startswith('html') or x.endswith('html')]
478 479 480
      format = format_list[0]
      mime, data = self._convert(format)
      archive_file = cStringIO.StringIO()
481
      archive_file.write(_unpackData(data))
482 483 484 485 486 487
      zip_file = zipfile.ZipFile(archive_file)
      must_close = 1
    else:
      must_close = 0
    for f in zip_file.infolist():
      file_name = f.filename
488 489
      document = self.get(file_name, None)
      if document is not None:
490
        self.manage_delObjects([file_name]) # For compatibility with old implementation
491
      if file_name.endswith('html'):
492 493
        mime = 'text/html'
        data = zip_file.read(file_name)
494
      else:
495 496 497
        mime = guess_content_type(file_name)[0]
        data = Pdata(zip_file.read(file_name))
      self.setConversion(data, mime, format='_embedded', file_name=file_name)
498 499 500 501
    if must_close:
      zip_file.close()
      archive_file.close()

502 503 504 505 506 507
  def _getExtensibleContent(self, request, name):
    if self.hasConversion(format='_embedded', file_name=name):
      mime, data = self.getConversion(format='_embedded', file_name=name)
      return OFSFile(name, name, data, content_type=mime)
    return PermanentURLMixIn._getExtensibleContent(self, request, name)

508
  # Base format implementation
509 510 511 512 513 514
  security.declareProtected(Permissions.AccessContentsInformation, 'hasBaseData')
  def hasBaseData(self):
    """
      OOo instances implement conversion to a base format. We should therefore
      use the default accessor.
    """
Jean-Paul Smets's avatar
Typo.  
Jean-Paul Smets committed
515
    return self._baseHasBaseData()
516

517 518
  security.declarePrivate('_convertToBaseFormat')
  def _convertToBaseFormat(self):
Bartek Górny's avatar
Bartek Górny committed
519
    """
520 521 522
      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
523
    """
524
    server_proxy = self._mkProxy()
525 526
    response_code, response_dict, response_message = server_proxy.run_convert(
                                      self.getSourceReference() or self.getId(),
527
                                      enc(_unpackData(self.getData())))
528 529 530 531 532 533 534 535
    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:
        self._setBaseContentType(metadata['MIMEType'])
    else:
536 537
      # Explicitly raise the exception!
      raise ConversionError(
538 539
                "OOoDocument: Error converting document to base format %s:%s:"
                                       % (response_code, response_message))
Bartek Górny's avatar
Bartek Górny committed
540

541 542
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getContentInformation')
543
  def getContentInformation(self):
Bartek Górny's avatar
Bartek Górny committed
544
    """
545 546
      Returns the metadata extracted by the conversion
      server.
Bartek Górny's avatar
Bartek Górny committed
547
    """
548
    return self._base_metadata
Bartek Górny's avatar
Bartek Górny committed
549

550 551
  security.declareProtected(Permissions.ModifyPortalContent,
                            'updateBaseMetadata')
552
  def updateBaseMetadata(self, **kw):
Bartek Górny's avatar
Bartek Górny committed
553
    """
554 555 556
      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
557
    """
558 559 560 561
    if not self.hasBaseData():
      raise NotConvertedError

    self.clearConversionCache()
562

563
    server_proxy = self._mkProxy()
564 565
    response_code, response_dict, response_message = \
          server_proxy.run_setmetadata(self.getId(),
566
                                       enc(_unpackData(self.getBaseData())),
567
                                       kw)
568 569 570
    if response_code == 200:
      # successful meta data extraction
      self._setBaseData(dec(response_dict['data']))
571
      self.updateFileMetadata() # record in workflow history # XXX must put appropriate comments.
572
    else:
573
      # Explicitly raise the exception!
574
      raise ConversionError("OOoDocument: error getting document metadata %s:%s"
575
                        % (response_code, response_message))