OOoDocument.py 18.1 KB
Newer Older
Bartek Górny's avatar
Bartek Górny committed
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
##############################################################################
#
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
#
# 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.
#
##############################################################################

28 29 30 31 32 33 34
import xmlrpclib
import base64
import re
import zipfile
import cStringIO
from DateTime import DateTime

Bartek Górny's avatar
Bartek Górny committed
35 36 37 38 39 40 41 42
from AccessControl import ClassSecurityInfo
from OFS.Image import Pdata
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.WorkflowCore import WorkflowMethod
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.Message import Message
from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5Type.XMLObject import XMLObject
43 44
from Products.ERP5.Document.File import File, stripHtml
from Products.ERP5.Document.Document import ConversionCacheMixin
45
from Products.CMFCore.utils import getToolByName
46
from Products.DCWorkflow.DCWorkflow import ValidationFailed
Bartek Górny's avatar
Bartek Górny committed
47 48 49 50

enc=base64.encodestring
dec=base64.decodestring

51 52 53
_MARKER = []


54
class ConversionError(Exception):pass
Bartek Górny's avatar
Bartek Górny committed
55

56

57
class OOoDocument(File, ConversionCacheMixin):
Bartek Górny's avatar
Bartek Górny committed
58 59 60 61 62 63 64 65 66 67 68 69 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
  """
    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)
  """
  # CMF Type Definition
  meta_type = 'ERP5 OOo Document'
  portal_type = 'OOo Document'
  isPortalContent = 1
  isRADContent = 1

  # Global variables
98 99
  snapshot = None
  oo_data = None
Bartek Górny's avatar
Bartek Górny committed
100 101 102 103 104 105 106 107 108 109 110

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Reference
111
                    , PropertySheet.TextDocument
112
                    , PropertySheet.Document
Bartek Górny's avatar
Bartek Górny committed
113 114
                    )

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  _properties =  (
   # XXX-JPS mime_type should be guessed is possible for the stored file
   # In any case, it should be named differently because the name
   # is too unclear. Moreover, the usefulness of this property is
   # doubtful besides download of converted file. It would be acceptable
   # for me that this property is stored as an internal property
   # or, better, in the conversion workflow attributes.
   #
   # Properties are meant for "orginal document" information,
   # not for calculated attributes.
      { 'id'          : 'mime_type',
        'description' : 'mime type of the converted OOo file stored',
        'type'        : 'string',
        'mode'        : ''},
  )

131
  # regexps for stripping xml from docs
132 133
  rx_strip = re.compile('<[^>]*?>', re.DOTALL|re.MULTILINE)
  rx_compr = re.compile('\s+')
134

135
  searchable_property_list = File.searchable_property_list + ('text_content', ) # XXX - good idea - should'n this be made more general ?
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  def index_html(self, REQUEST, RESPONSE, format=None, force=0):
    """
      Standard function - gets converted version (from cache or new)
      sets headers and returns converted data.

      Format can be only one string (because we are OOoDocument and do not
      accept more formatting arguments).

      Force can force conversion.
    """
    self.log(format, force)
    if (not self.hasOOFile()) or force:
      self.convertToBase()
    if format is None:
      result = self.getOOFile()
      mime = self.getMimeType()
      self.log(mime)
    else:
      try:
        mime, result = self.convert(format=format, force=force)
      except ConversionError, e:
        raise # should we do something here?
    #RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) XXX to be implemented
    RESPONSE.setHeader('Content-Type', mime)
    #RESPONSE.setHeader('Content-Length', self.size) XXX to be implemented
    RESPONSE.setHeader('Accept-Ranges', 'bytes')
    # XXX here we should find out extension for this mime type and append to filename
    RESPONSE.setBase(None)
    return result

167
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
168
    """
169 170
      Returns OOo conversion server data from 
      preferences
Bartek Górny's avatar
Bartek Górny committed
171
    """
172
    pref = getToolByName(self, 'portal_preferences')
173 174
    adr = pref.getPreferredOoodocServerAddress()
    nr = pref.getPreferredOoodocServerPortNumber()
175 176
    if adr is None or nr is None:
      raise Exception('you should set conversion server coordinates in preferences')
177
    return adr, nr
Bartek Górny's avatar
Bartek Górny committed
178 179

  def _mkProxy(self):
180
    sp=xmlrpclib.ServerProxy('http://%s:%d' % self._getServerCoordinate(), allow_none=True)
Bartek Górny's avatar
Bartek Górny committed
181 182
    return sp

183
  def returnMessage(self, msg, code=0):
Bartek Górny's avatar
Bartek Górny committed
184
    """
185 186
      code > 0 indicates a problem
      we distinguish data return from message by checking if it is a tuple
Bartek Górny's avatar
Bartek Górny committed
187
    """
188 189
    m = Message(domain='ui', message=msg)
    return (code, m)
Bartek Górny's avatar
Bartek Górny committed
190

191 192
  security.declareProtected(Permissions.View, 'convert')
  def convertToBase(self, force=0, REQUEST=None):
Bartek Górny's avatar
Bartek Górny committed
193
    """
194 195 196
      Converts from the initial format to base format (ODF);
      communicates with the conversion server
      and gets converted file as well as metadata
Bartek Górny's avatar
Bartek Górny committed
197
    """
198 199 200 201 202
    def doConvert(force):
      if force == 0 and self.hasOOFile():
        return self.returnMessage('OOo file is up do date', 1)
      try:
        self._convertToBase()
203
      except Exception, e:
204 205 206 207 208 209 210
        return self.returnMessage('Problem: %s' % (str(e) or 'undefined'), 2)
      return self.returnMessage('converted to Open Document Format')
    msg_ob = doConvert(force)
    msg = str(msg_ob[1])
    portal_workflow = getToolByName(self, 'portal_workflow')
    portal_workflow.doActionFor(self, 'process', comment=msg)
    return msg_ob
Bartek Górny's avatar
Bartek Górny committed
211 212 213 214 215 216 217 218 219 220 221

  security.declareProtected(Permissions.AccessContentsInformation,'getTargetFormatList')
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

      XXX - to be implemented better (with extended API to conversion server)
      XXX - what does this mean? I don't understand
    """
    # Caching method implementation
222
    def cached_getTargetFormatItemList(content_type):
Bartek Górny's avatar
Bartek Górny committed
223
      sp=self._mkProxy()
224
      allowed=sp.getAllowedTargets(content_type)
225
      return [[y,x] for x,y in allowed] # have to reverse tuple order
Bartek Górny's avatar
Bartek Górny committed
226 227 228

    cached_getTargetFormatItemList = CachingMethod(cached_getTargetFormatItemList,
                                        id = "OOoDocument_getTargetFormatItemList" )
229
    return cached_getTargetFormatItemList(self.getContentType())
Bartek Górny's avatar
Bartek Górny committed
230

231
  security.declareProtected(Permissions.AccessContentsInformation, 'getTargetFormatList')
Bartek Górny's avatar
Bartek Górny committed
232 233 234 235 236 237
  def getTargetFormatList(self):
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

238
  security.declareProtected(Permissions.ModifyPortalContent, 'reset')
239
  def reset(self):
240 241 242
    """
      make the object a non-converted one, as if it was brand new
    """
243
    self.clearConversionCache()
244 245
    self.oo_data = None
    m = self.returnMessage('new')
246 247 248
    msg = str(m[1])
    portal_workflow = getToolByName(self, 'portal_workflow')
    portal_workflow.doActionFor(self, 'process', comment=msg)
249

Bartek Górny's avatar
Bartek Górny committed
250 251 252
  security.declareProtected(Permissions.ModifyPortalContent,'isAllowed')
  def isAllowed(self, format):
    """
253 254
      Checks if the current document can be converted
      into the specified format.
Bartek Górny's avatar
Bartek Górny committed
255
    """
256
    allowed = self.getTargetFormatItemList()
Bartek Górny's avatar
Bartek Górny committed
257
    if allowed is None: return False
258
    return (format in [x[1] for x in allowed])
Bartek Górny's avatar
Bartek Górny committed
259 260

  security.declareProtected(Permissions.ModifyPortalContent,'editMetadata')
261
  def editMetadata(self, newmeta):
Bartek Górny's avatar
Bartek Górny committed
262
    """
263 264 265
      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
266
    """
267 268 269
    sp = self._mkProxy()
    kw = sp.run_setmetadata(self.getTitle(), enc(self._unpackData(self.oo_data)), newmeta)
    self.oo_data = Pdata(dec(kw['data']))
270
    self._setMetaData(kw['meta'])
Bartek Górny's avatar
Bartek Górny committed
271 272
    return True # XXX why return ? - why not?

273
  security.declarePrivate('_convertToBase')
274
  def _convertToBase(self):
Bartek Górny's avatar
Bartek Górny committed
275
    """
276 277 278
      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
279
    """
280 281 282
    sp = self._mkProxy()
    kw = sp.run_convert(self.getSourceReference(), enc(self._unpackData(self.data)))
    self.oo_data = Pdata(dec(kw['data']))
283
    # now we get text content 
284
    text_data = self.extractTextContent()
285 286
    self.setTextContent(text_data)
    self._setMetaData(kw['meta'])
Bartek Górny's avatar
Bartek Górny committed
287

288 289 290
  security.declareProtected(Permissions.View,'extractTextContent')
  def extractTextContent(self):
    """
291
      extract plain text from ooo docs - the simplest way possible, works for all ODF formats
292
    """
293
    cs = cStringIO.StringIO()
294
    cs.write(self._unpackData(self.oo_data))
295 296 297 298
    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
299 300 301 302
    cs.close()
    z.close()
    return s

303

Bartek Górny's avatar
Bartek Górny committed
304 305 306
  security.declarePrivate('_setMetaData')
  def _setMetaData(self,meta):
    """
307
      Sets metadata properties of the ERP5 object.
Bartek Górny's avatar
Bartek Górny committed
308

309 310 311
      XXX - please double check that some properties
      are not already defined in the Document class (which is used
      for Web Page in ERP5)
Bartek Górny's avatar
Bartek Górny committed
312

313 314 315 316
      XXX - it would be quite nice if the metadata structure
            could also support user fields in OOo
            (user fields are so useful actually...)
            XXX - I think it does (BG)
Bartek Górny's avatar
Bartek Górny committed
317 318
    """
    for k,v in meta.items():
319 320 321 322
      meta[k] = v.encode('utf-8')
    self.setTitle(meta.get('title', ''))
    self.setSubject(meta.get('keywords', '').split())
    self.setDescription(meta.get('description', ''))
323
    #self.setLanguage(meta.get('language',''))
324
    if meta.get('MIMEType', False):
325
      self.setContentType(meta['MIMEType'])
326
    #self.setReference(meta.get('reference',''))
Bartek Górny's avatar
Bartek Górny committed
327

328
  security.declareProtected(Permissions.View, 'getOOFile')
329
  def getOOFile(self):
Bartek Górny's avatar
Bartek Górny committed
330
    """
331
      Return the converted OOo document.
Bartek Górny's avatar
Bartek Górny committed
332

333 334 335
      XXX - use a propertysheet for this instead. We have a type
            called data in property sheet. Look at File implementation
      XXX - doesn't seem to be there...
Bartek Górny's avatar
Bartek Górny committed
336
    """
337
    data = self.oo_data
Bartek Górny's avatar
Bartek Górny committed
338 339
    return data

340
  security.declareProtected(Permissions.View, 'hasOOFile')
341
  def hasOOFile(self):
Bartek Górny's avatar
Bartek Górny committed
342
    """
343
      Checks whether we have an OOo converted file
Bartek Górny's avatar
Bartek Górny committed
344
    """
345 346 347
    _marker = []
    if getattr(self, 'oo_data',_marker) is not _marker: # XXX - use propertysheet accessors
      return getattr(self, 'oo_data') is not None
Bartek Górny's avatar
Bartek Górny committed
348 349
    return False

350
  security.declareProtected(Permissions.View, 'hasSnapshot')
Bartek Górny's avatar
Bartek Górny committed
351 352
  def hasSnapshot(self):
    """
353
      Checks whether we have a snapshot.
Bartek Górny's avatar
Bartek Górny committed
354
    """
355 356 357
    _marker = []
    if getattr(self, 'snapshot', _marker) is not _marker: # XXX - use propertysheet accessors
      return getattr(self, 'snapshot') is not None
Bartek Górny's avatar
Bartek Górny committed
358 359 360 361 362
    return False

  security.declareProtected(Permissions.ModifyPortalContent,'createSnapshot')
  def createSnapshot(self,REQUEST=None):
    """
363
      Create a PDF snapshot
Bartek Górny's avatar
Bartek Górny committed
364

365 366 367
      XXX - we should not create a snapshot if some error happened at conversion
            is this checked ?
      XXX - error at conversion raises an exception, so it should be ok
Bartek Górny's avatar
Bartek Górny committed
368 369 370
    """
    if self.hasSnapshot():
      if REQUEST is not None:
371
        return self.returnMessage('already has a snapshot', 1)
372
      raise ConversionError('already has a snapshot')
Bartek Górny's avatar
Bartek Górny committed
373
    # making snapshot
374
    # we have to figure out which pdf format to use
375 376 377
    tgts = [x[1] for x in self.getTargetFormatItemList() if x[1].endswith('pdf')]
    if len(tgts) > 1:
      return self.returnMessage('multiple pdf formats found - this shouldnt happen', 2)
378
    if len(tgts)==0:
379
      return self.returnMessage('no pdf format found',1)
380
    fmt = tgts[0]
381
    self.makeFile(fmt)
382
    self.snapshot = Pdata(self._unpackData(self.getConversion(format = fmt)[1]))
Bartek Górny's avatar
Bartek Górny committed
383 384 385
    return self.returnMessage('snapshot created')

  security.declareProtected(Permissions.View,'getSnapshot')
386
  def getSnapshot(self, REQUEST=None):
Bartek Górny's avatar
Bartek Górny committed
387
    """
388
      Returns the snapshot.
Bartek Górny's avatar
Bartek Górny committed
389 390 391
    """
    if not self.hasSnapshot():
      self.createSnapshot()
392
    return self.snapshot
Bartek Górny's avatar
Bartek Górny committed
393 394 395 396

  security.declareProtected(Permissions.ManagePortal,'deleteSnapshot')
  def deleteSnapshot(self):
    """
397
      Deletes the snapshot - in theory this should never be done
Bartek Górny's avatar
Bartek Górny committed
398 399 400 401 402 403
    """
    try:
      del(self.snapshot)
    except AttributeError:
      pass

404
  def getHtmlRepresentation(self):
405 406 407
    """
      get simplified html version to display
    """
408
    # we have to figure out which html format to use
409 410
    tgts = [x[1] for x in self.getTargetFormatItemList() if x[1].startswith('html')]
    if len(tgts) == 0:
411
      return 'no html representation available'
412 413 414
    fmt = tgts[0]
    fmt, data = self.convert(fmt)
    cs = cStringIO.StringIO()
415
    cs.write(self._unpackData(data))
416 417
    z = zipfile.ZipFile(cs)
    h = 'could not extract anything'
418
    for f in z.infolist():
419
      fn = f.filename
420
      if fn.endswith('html'):
421
        h = z.read(fn)
422 423 424
        break
    z.close()
    cs.close()
425
    return stripHtml(h)
426

427 428
  security.declareProtected(Permissions.View, 'convert')
  def convert(self, format, REQUEST=None, force=0):
Bartek Górny's avatar
Bartek Górny committed
429
    """
430 431 432
      Get file in a given format.
      Runs makeFile to make sure we have the requested version cached,
      then returns from cache.
Bartek Górny's avatar
Bartek Górny committed
433
    """
434 435 436
    # first check if we have base
    if not self.hasOOFile():
      self.convertToBase()
Bartek Górny's avatar
Bartek Górny committed
437
    if not self.isAllowed(format):
438 439 440 441
      if REQUEST is not None:
        return self.returnMessage('can not convert to ' + format + ' for some reason',1)
      else:
        raise ConversionError, 'can not convert to ' + format + ' for some reason'
Bartek Górny's avatar
Bartek Górny committed
442
    try:
443 444
      # make if necessary, return from cache
      self.makeFile(format, force)
445 446
      return self.getConversion(format = format)
    except ConversionError,e:
447 448 449
      if REQUEST is not None:
        return self.returnMessage(str(e), 2)
      raise
Bartek Górny's avatar
Bartek Górny committed
450

451 452
  security.declareProtected(Permissions.View, 'isFileChanged')
  def isFileChanged(self, format):
Bartek Górny's avatar
Bartek Górny committed
453
    """
454 455
      Checks whether the file was converted (or uploaded) after last generation of
      the target format
Bartek Górny's avatar
Bartek Górny committed
456
    """
457
    return not self.hasConversion(format=format)
Bartek Górny's avatar
Bartek Górny committed
458

459 460
  security.declareProtected(Permissions.ModifyPortalContent, 'makeFile')
  def makeFile(self, format, force=0, REQUEST=None, **kw):
Bartek Górny's avatar
Bartek Górny committed
461
    """
462 463 464 465 466 467 468
      This method implement the file conversion cache:
        * check if the format is supported
        * check date of last conversion to OOo, compare with date of last
        * if necessary, create new file and cache
        * update file generation time

      Fails silently if we have an up to date version.
Bartek Górny's avatar
Bartek Górny committed
469

470 471
      TODO:
        * support of images in html conversion (as subobjects for example)
Bartek Górny's avatar
Bartek Górny committed
472 473
    """
    if not self.isAllowed(format):
474
      errstr = '%s format is not supported' % format
Bartek Górny's avatar
Bartek Górny committed
475
      if REQUEST is not None:
476
        return self.returnMessage(errstr, 2)
477
      raise ConversionError(errstr)
478
    if not self.hasOOFile():
Bartek Górny's avatar
Bartek Górny committed
479
      if REQUEST is not None:
480
        return self.returnMessage('needs conversion', 1)
481
      raise ConversionError('needs conversion')
482
    if self.isFileChanged(format) or force:
Bartek Górny's avatar
Bartek Górny committed
483
      try:
484
        mime, data = self._makeFile(format)
485
        self.setConversion(data, mime, format = format)
486
        #self._p_changed = 1 # XXX not sure it is necessary
487
      except xmlrpclib.Fault, e:
Bartek Górny's avatar
Bartek Górny committed
488
        if REQUEST is not None:
489
          return self.returnMessage('Problem: %s' % str(e), 2)
Bartek Górny's avatar
Bartek Górny committed
490
        else:
491 492
          raise ConversionError(str(e))
      self.updateConversion(format = format)
Bartek Górny's avatar
Bartek Górny committed
493 494 495 496
      if REQUEST is not None:
        return self.returnMessage('%s created' % format)
    else:
      if REQUEST is not None:
497
        return self.returnMessage('%s file is up to date' % format, 1)
Bartek Górny's avatar
Bartek Górny committed
498 499 500 501

  security.declarePrivate('_makeFile')
  def _makeFile(self,format):
    """
502
      Communicates with server to convert a file
Bartek Górny's avatar
Bartek Górny committed
503 504
    """
    # real version:
505 506 507
    sp = self._mkProxy()
    kw = sp.run_generate(self.getSourceReference(), enc(self._unpackData(self.oo_data)), None, format)
    return kw['mime'], Pdata(dec(kw['data']))
Bartek Górny's avatar
Bartek Górny committed
508

509
  # make sure to call the right edit methods
510 511
  _edit = File._edit
  edit = File.edit
512 513 514

  # BG copied from File in case
  security.declareProtected('FTP access', 'manage_FTPget', 'manage_FTPstat', 'manage_FTPlist')
515 516 517
  manage_FTPget = File.manage_FTPget
  manage_FTPlist = File.manage_FTPlist
  manage_FTPstat = File.manage_FTPstat
518 519


Bartek Górny's avatar
Bartek Górny committed
520 521
# vim: syntax=python shiftwidth=2