OOoDocument.py 21.6 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
from Products.CMFCore.utils import getToolByName, _setCacheHeaders
Bartek Górny's avatar
Bartek Górny committed
38 39
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.Cache import CachingMethod
40
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
41
from Products.ERP5.Document.File import File
42 43 44
from Products.ERP5.Document.Document import ConversionCacheMixin
from Products.ERP5.Document.Document import ConversionError
from Products.ERP5.Document.Document import NotConvertedError
45
from Products.ERP5.Document.File import _unpackData
46
from zLOG import LOG, ERROR
47

Bartek Górny's avatar
Bartek Górny committed
48 49 50
enc=base64.encodestring
dec=base64.decodestring

51
_MARKER = []
52
STANDARD_IMAGE_FORMAT_LIST = ('png', 'jpg', 'gif', )
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
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)


76
class OOoDocument(File, ConversionCacheMixin):
Bartek Górny's avatar
Bartek Górny committed
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 104 105 106 107 108
  """
    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
109 110 111

    TODO:
    - better permissions
Bartek Górny's avatar
Bartek Górny committed
112 113 114 115 116 117 118
  """
  # CMF Type Definition
  meta_type = 'ERP5 OOo Document'
  portal_type = 'OOo Document'
  isPortalContent = 1
  isRADContent = 1

119
  searchable_property_list = ('asText', 'title', 'description', 'id', 'reference',
120 121
                              'version', 'short_title',
                              'subject', 'source_reference', 'source_project_title',)
Bartek Górny's avatar
Bartek Górny committed
122 123 124 125 126 127 128

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

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

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

145 146 147 148 149 150 151
  security.declareProtected(Permissions.ModifyPortalContent, 'isSupportBaseDataConversion')
  def isSupportBaseDataConversion(self):
    """
    OOoDocument is needed to conversion to base format.
    """
    return True

152 153 154 155
  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
156 157 158 159
      try:
        delattr(self, 'base_data')
      except AttributeError:
        pass
160

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

    # 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"
176
                         " in %s format" % (format or 'original'))
177

178
    # Return the original file by default
179
    if format is None:
180 181 182
      return File.index_html(self, REQUEST, RESPONSE)
    # Make sure file is converted to base format
    if not self.hasBaseData():
183
      raise NotConvertedError
184
    # Else try to convert the document and return it
185
    mime, result = self.convert(format=format, display=display, **kw)
186 187
    if not mime:
      mime = getToolByName(self, 'mimetypes_registry').lookupExtension('name.%s' % format)
188
    RESPONSE.setHeader('Content-Length', len(result))
189 190 191 192
    RESPONSE.setHeader('Content-Type', mime)
    RESPONSE.setHeader('Accept-Ranges', 'bytes')
    return result

193
  # Format conversion implementation
194
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
195
    """
196 197
      Returns the oood conversion server coordinates
      as defined in preferences.
Bartek Górny's avatar
Bartek Górny committed
198
    """
199 200 201
    preference_tool = getToolByName(self, 'portal_preferences')
    address = preference_tool.getPreferredOoodocServerAddress()
    port = preference_tool.getPreferredOoodocServerPortNumber()
202
    if address in ('', None) or port in ('', None) :
203
      raise ConversionError('OOoDocument: can not proceed with conversion:'
204
            ' conversion server host and port is not defined in preferences')
205
    return address, port
Bartek Górny's avatar
Bartek Górny committed
206 207 208

  def _mkProxy(self):
    """
209
      Create an XML-RPC proxy to access the conversion server.
Bartek Górny's avatar
Bartek Górny committed
210
    """
211 212 213 214
    server_proxy = xmlrpclib.ServerProxy(
             'http://%s:%d' % self._getServerCoordinate(),
             allow_none=True,
             transport=TimeoutTransport(timeout=360, scheme='http'))
215
    return server_proxy
Bartek Górny's avatar
Bartek Górny committed
216

217 218
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatItemList')
Bartek Górny's avatar
Bartek Górny committed
219 220 221 222 223
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

224 225
      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
226
    """
227
    if not self.hasBaseData():
228
      raise NotConvertedError
229

230
    def cached_getTargetFormatItemList(content_type):
231
      server_proxy = self._mkProxy()
232
      try:
233 234 235 236 237 238 239 240 241 242 243
        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), ''
        
244 245 246 247 248
        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
249
          raise ConversionError("OOoDocument: can not get list of allowed acceptable"
250 251
                                " formats for conversion: %s (%s)" % (
                                      response_code, response_message))
252

253 254 255 256
      except Fault, f:
        allowed = server_proxy.getAllowedTargets(content_type)
        warn('Your oood version is too old, using old method '
            'getAllowedTargets instead of getAllowedTargetList',
257
             DeprecationWarning)
258 259 260

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

262
    # Cache valid format list
263 264 265 266
    cached_getTargetFormatItemList = CachingMethod(
                                cached_getTargetFormatItemList,
                                id="OOoDocument_getTargetFormatItemList",
                                cache_factory='erp5_ui_medium')
Bartek Górny's avatar
Bartek Górny committed
267

268 269
    return cached_getTargetFormatItemList(self.getBaseContentType())

270 271
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatTitleList')
272
  def getTargetFormatTitleList(self):
Bartek Górny's avatar
Bartek Górny committed
273 274 275 276 277
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

278 279
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatList')
280
  def getTargetFormatList(self):
Bartek Górny's avatar
Bartek Górny committed
281
    """
282
      Returns a list of acceptable formats for conversion
Bartek Górny's avatar
Bartek Górny committed
283
    """
284
    return map(lambda x: x[1], self.getTargetFormatItemList())
Bartek Górny's avatar
Bartek Górny committed
285

286 287
  security.declareProtected(Permissions.ModifyPortalContent,
                            'isTargetFormatAllowed')
288
  def isTargetFormatAllowed(self, format):
289
    """
290 291 292 293 294 295 296 297 298 299
      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 
    """
300
    if not self.hasBaseData():
301
      raise NotConvertedError
302 303 304
    if format == 'text-content':
      # Extract text from the ODF file
      cs = cStringIO.StringIO()
305
      cs.write(_unpackData(self.getBaseData()))
306 307 308 309 310 311
      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()
312
      return 'text/plain', s
313
    server_proxy = self._mkProxy()
314

315
    generate_result = server_proxy.run_generate(self.getId(),
316
                                       enc(_unpackData(self.getBaseData())),
317
                                       None,
318
                                       format)
319 320 321 322 323 324
    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
325

326
    # XXX: handle possible OOOd server failure
327
    return response_dict['mime'], Pdata(dec(response_dict['data']))
328

329
  # Conversion API
330
  security.declareProtected(Permissions.View, 'convert')
331
  def convert(self, format, display=None, **kw):
332 333 334 335
    """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
336
    """
337 338
    #XXX if document is empty, stop to try to convert.
    #XXX but I don't know what is a appropriate mime-type.(Yusei)
339
    if self.get_size() == 0:
340
      return 'text/plain', ''
341

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

440 441 442 443 444 445 446
  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.
    """
447
    return self._convert(format='text-content')
448

449 450
  security.declareProtected(Permissions.ModifyPortalContent,
                            'populateContent')
451 452 453 454 455 456
  def populateContent(self, zip_file=None):
    """
    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:
457
      format_list = [x for x in self.getTargetFormatList()
458
                                if x.startswith('html') or x.endswith('html')]
459 460 461
      format = format_list[0]
      mime, data = self._convert(format)
      archive_file = cStringIO.StringIO()
462
      archive_file.write(_unpackData(data))
463 464 465 466
      zip_file = zipfile.ZipFile(archive_file)
      must_close = 1
    else:
      must_close = 0
467
    first_page = True
468 469
    for f in zip_file.infolist():
      file_name = f.filename
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
      if file_name.endswith('html') and self.getPortalType() != 'Presentation':
      #if file_name.endswith('html'):
        continue
      #if first_page and file_name.endswith('html'):
      #  first_page = False
      #  break
      LOG('file_name', 0, file_name)
      document = self.get(file_name, None)
      if document is not None:
        self.manage_delObjects([file_name])
      newContent = UnrestrictedMethod(self.portal_contributions.newContent)
      if file_name.endswith('html'):
        newContent(id=file_name, container=self, portal_type='Web Page',
                  file_name=file_name,
                  data=zip_file.read(file_name))
      else:
486
        newContent(id=file_name, container=self,
487 488
                  file_name=file_name,
                  data=zip_file.read(file_name))
489 490 491 492 493
    if must_close:
      zip_file.close()
      archive_file.close()

  # Base format implementation
494 495 496 497 498 499
  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
500
    return self._baseHasBaseData()
501

502 503
  security.declarePrivate('_convertToBaseFormat')
  def _convertToBaseFormat(self):
Bartek Górny's avatar
Bartek Górny committed
504
    """
505 506 507
      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
508
    """
509
    server_proxy = self._mkProxy()
510 511
    response_code, response_dict, response_message = server_proxy.run_convert(
                                      self.getSourceReference() or self.getId(),
512
                                      enc(_unpackData(self.getData())))
513 514 515 516 517 518 519 520
    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:
521 522
      # Explicitly raise the exception!
      raise ConversionError(
523 524
                "OOoDocument: Error converting document to base format %s:%s:"
                                       % (response_code, response_message))
Bartek Górny's avatar
Bartek Górny committed
525

526 527
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getContentInformation')
528
  def getContentInformation(self):
Bartek Górny's avatar
Bartek Górny committed
529
    """
530 531
      Returns the metadata extracted by the conversion
      server.
Bartek Górny's avatar
Bartek Górny committed
532
    """
533
    return self._base_metadata
Bartek Górny's avatar
Bartek Górny committed
534

535 536
  security.declareProtected(Permissions.ModifyPortalContent,
                            'updateBaseMetadata')
537
  def updateBaseMetadata(self, **kw):
Bartek Górny's avatar
Bartek Górny committed
538
    """
539 540 541
      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
542
    """
543 544 545 546
    if not self.hasBaseData():
      raise NotConvertedError

    self.clearConversionCache()
547

548
    server_proxy = self._mkProxy()
549 550
    response_code, response_dict, response_message = \
          server_proxy.run_setmetadata(self.getId(),
551
                                       enc(_unpackData(self.getBaseData())),
552
                                       kw)
553 554 555
    if response_code == 200:
      # successful meta data extraction
      self._setBaseData(dec(response_dict['data']))
556
      self.updateFileMetadata() # record in workflow history # XXX must put appropriate comments.
557
    else:
558
      # Explicitly raise the exception!
559
      raise ConversionError("OOoDocument: error getting document metadata %s:%s"
560
                        % (response_code, response_message))