OOoDocument.py 15.4 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 28 29 30 31 32 33 34 35 36 37

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

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.ERP5.Document.File import File
from Products.ERP5Type.XMLObject import XMLObject
38
from Products.ERP5OOo.Document.DMSFile import DMSFile, CachingMixin, stripHtml
Bartek Górny's avatar
Bartek Górny committed
39
from DateTime import DateTime
40
import xmlrpclib, base64, re, zipfile, cStringIO
41 42
# to overwrite WebDAV methods
from Products.CMFDefault.File import File as CMFFile
43
from Products.CMFCore.utils import getToolByName
Bartek Górny's avatar
Bartek Górny committed
44 45 46 47 48 49

enc=base64.encodestring
dec=base64.decodestring

class ConvertionError(Exception):pass

50
class OOoDocument(DMSFile, CachingMixin):
Bartek Górny's avatar
Bartek Górny committed
51 52 53 54 55 56 57 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 98 99 100 101
  """
    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
  snapshot=None
  oo_data=None

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
102
                    , PropertySheet.Data
Bartek Górny's avatar
Bartek Górny committed
103 104
                    , PropertySheet.Version
                    , PropertySheet.Reference
105
                    , PropertySheet.Document
106
                    , PropertySheet.DMSFile
Bartek Górny's avatar
Bartek Górny committed
107 108 109
                    , PropertySheet.OOoDocument
                    )

110 111 112
  # regexps for stripping xml from docs
  rx_strip=re.compile('<[^>]*?>',re.DOTALL|re.MULTILINE)
  rx_compr=re.compile('\s+')
113

114
  searchable_attrs=DMSFile.searchable_attrs+('text_content',) # XXX - good idea - should'n this be made more general ?
115

116
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
117
    """
118 119
    Returns OOo conversion server data from 
    preferences
Bartek Górny's avatar
Bartek Górny committed
120
    """
121 122 123 124 125 126
    pref=getToolByName(self,'portal_preferences')
    adr=pref.getPreferredDmsOoodocServerAddress()
    nr=pref.getPreferredDmsOoodocServerPortNumber()
    if adr is None or nr is None:
      raise Exception('you should set conversion server coordinates in preferences')
    return adr,nr
Bartek Górny's avatar
Bartek Górny committed
127 128

  def _mkProxy(self):
129
    sp=xmlrpclib.ServerProxy('http://%s:%d' % self._getServerCoordinate(),allow_none=True)
Bartek Górny's avatar
Bartek Górny committed
130 131 132 133
    return sp

  def returnMessage(self,msg,code=0):
    """
134
    code > 0 indicates a problem
Bartek Górny's avatar
Bartek Górny committed
135 136 137 138 139 140
    we distinguish data return from message by checking if it is a tuple
    """
    m=Message(domain='ui',message=msg)
    return (code,m)

  security.declareProtected(Permissions.ModifyPortalContent,'convert')
141
  def convert(self,force=0,REQUEST=None):
Bartek Górny's avatar
Bartek Górny committed
142 143 144 145 146
    """
    Converts from the initial format to OOo format;
    communicates with the conversion server
    and gets converted file as well as metadata
    """
147
    if force==0 and self.hasOOFile():
148
      return self.returnMessage('OOo file is up do date',1)
Bartek Górny's avatar
Bartek Górny committed
149 150 151
    try:
      self._convert()
    except xmlrpclib.Fault,e:
152
      return self.returnMessage('Problem: %s' % str(e),2)
Bartek Górny's avatar
Bartek Górny committed
153 154 155 156 157 158 159 160 161 162 163 164
    return self.returnMessage('converted')

  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
165
    def cached_getTargetFormatItemList(content_type):
Bartek Górny's avatar
Bartek Górny committed
166
      sp=self._mkProxy()
167
      allowed=sp.getAllowedTargets(content_type)
168
      return [[y,x] for x,y in allowed] # have to reverse tuple order
Bartek Górny's avatar
Bartek Górny committed
169 170 171 172

    cached_getTargetFormatItemList = CachingMethod(cached_getTargetFormatItemList,
                                        id = "OOoDocument_getTargetFormatItemList" )

173
    return cached_getTargetFormatItemList(self.getContentType())
Bartek Górny's avatar
Bartek Górny committed
174 175 176 177 178 179 180 181 182 183


  security.declareProtected(Permissions.AccessContentsInformation,'getTargetFormatList')
  def getTargetFormatList(self):
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())


184 185 186 187 188
  security.declareProtected(Permissions.ModifyPortalContent,'reset')
  def reset(self):
    self.clearCache()
    self.oo_data=None
    m=self.returnMessage('new')
189
    self.setExternalProcessingStatusMessage(str(m[1]))
190

Bartek Górny's avatar
Bartek Górny committed
191 192 193 194 195 196 197
  security.declareProtected(Permissions.ModifyPortalContent,'isAllowed')
  def isAllowed(self, format):
    """
    Checks if the current document can be converted
    into the specified format.

    """
198
    if not self.hasOOFile(): return False
199
    allowed=self.getTargetFormatItemList()
Bartek Górny's avatar
Bartek Górny committed
200
    if allowed is None: return False
201
    return (format in [x[1] for x in allowed])
Bartek Górny's avatar
Bartek Górny committed
202 203 204 205 206 207 208 209 210

  security.declareProtected(Permissions.ModifyPortalContent,'editMetadata')
  def editMetadata(self,newmeta):
    """
    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.
    """
    sp=self._mkProxy()
211 212 213
    kw=sp.run_setmetadata(self.getTitle(),enc(self._unpackData(self.oo_data)),newmeta)
    self.oo_data=Pdata(dec(kw['data']))
    self._setMetaData(kw['meta'])
Bartek Górny's avatar
Bartek Górny committed
214 215 216 217 218 219 220 221 222 223
    return True # XXX why return ? - why not?

  security.declarePrivate('_convert')
  def _convert(self):
    """
    Converts the original document into OOo document
    by invoking the conversion server. Store the result
    on the object. Update metadata information.
    """
    sp=self._mkProxy()
224
    kw=sp.run_convert(self.getSourceReference(),enc(self._unpackData(self.data)))
225
    self.oo_data=Pdata(dec(kw['data']))
226
    # now we get text content 
227
    text_data=self.extractTextContent()
228 229
    self.setTextContent(text_data)
    self._setMetaData(kw['meta'])
Bartek Górny's avatar
Bartek Górny committed
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  security.declareProtected(Permissions.View,'extractTextContent')
  def extractTextContent(self):
    """
    extract plain text from ooo docs - the simplest way possible, works for all ODF formats
    """
    cs=cStringIO.StringIO()
    cs.write(self._unpackData(self.oo_data))
    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()
    return s

Bartek Górny's avatar
Bartek Górny committed
246 247 248 249 250 251 252 253 254 255 256 257
  security.declarePrivate('_setMetaData')
  def _setMetaData(self,meta):
    """
    Sets metadata properties of the ERP5 object.

    XXX - please double check that some properties
    are not already defined in the Document class (which is used
    for Web Page in ERP5)

    XXX - it would be quite nice if the metadata structure
          could also support user fields in OOo
          (user fields are so useful actually...)
258
          XXX - I think it does (BG)
Bartek Górny's avatar
Bartek Górny committed
259 260 261
    """
    for k,v in meta.items():
      meta[k]=v.encode('utf-8')
262
    self.setTitle(meta.get('title',''))
263
    self.setSubject(meta.get('keywords','').split())
264
    self.setDescription(meta.get('description',''))
265
    #self.setLanguage(meta.get('language',''))
Bartek Górny's avatar
Bartek Górny committed
266
    if meta.get('MIMEType',False):
267
      self.setContentType(meta['MIMEType'])
268
    #self.setReference(meta.get('reference',''))
Bartek Górny's avatar
Bartek Górny committed
269

270 271
  security.declareProtected(Permissions.View,'getOOFile')
  def getOOFile(self):
Bartek Górny's avatar
Bartek Górny committed
272 273 274 275 276 277 278 279 280 281
    """
    Return the converted OOo document.

    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...
    """
    data=self.oo_data
    return data

282 283
  security.declareProtected(Permissions.View,'hasOOFile')
  def hasOOFile(self):
Bartek Górny's avatar
Bartek Górny committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    """
    Checks whether we have an OOo converted file
    """
    _marker=[]
    if getattr(self,'oo_data',_marker) is not _marker: # XXX - use propertysheet accessors
      return getattr(self,'oo_data') is not None
    return False

  security.declareProtected(Permissions.View,'hasSnapshot')
  def hasSnapshot(self):
    """
    Checks whether we have a snapshot.
    """
    _marker=[]
    if getattr(self,'snapshot',_marker) is not _marker: # XXX - use propertysheet accessors
      return getattr(self,'snapshot') is not None
    return False

  security.declareProtected(Permissions.ModifyPortalContent,'createSnapshot')
  def createSnapshot(self,REQUEST=None):
    """
    Create a PDF snapshot

    XXX - we should not create a snapshot if some error happened at conversion
          is this checked ?
309
    XXX - error at conversion raises an exception, so it should be ok
Bartek Górny's avatar
Bartek Górny committed
310 311 312 313 314 315
    """
    if self.hasSnapshot():
      if REQUEST is not None:
        return self.returnMessage('already has a snapshot')
      raise ConvertionError('already has a snapshot')
    # making snapshot
316 317 318 319 320 321 322 323
    # we have to figure out which pdf format to use
    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')
    if len(tgts)==0:
      return self.returnMessage('no pdf format found')
    fmt=tgts[0]
    self.makeFile(fmt)
324
    self.snapshot=Pdata(self._unpackData(self.cacheGet(fmt)[1]))
Bartek Górny's avatar
Bartek Górny committed
325 326 327 328 329 330 331 332 333 334
    return self.returnMessage('snapshot created')

  security.declareProtected(Permissions.View,'getSnapshot')
  def getSnapshot(self,REQUEST=None):
    """
    Returns the snapshot.
    """
    '''getSnapshot'''
    if not self.hasSnapshot():
      self.createSnapshot()
335
    return self.snapshot
Bartek Górny's avatar
Bartek Górny committed
336 337 338 339 340 341 342 343 344 345 346

  security.declareProtected(Permissions.ManagePortal,'deleteSnapshot')
  def deleteSnapshot(self):
    """
    Deletes the snapshot - in theory this should never be done
    """
    try:
      del(self.snapshot)
    except AttributeError:
      pass

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
  def getHtmlRepresentation(self):
    '''
    get simplified html version to display
    '''
    # we have to figure out which html format to use
    tgts=[x[1] for x in self.getTargetFormatItemList() if x[1].startswith('html')]
    if len(tgts)==0:
      return 'no html representation available'
    fmt=tgts[0]
    fmt,data=self.getTargetFile(fmt)
    cs=cStringIO.StringIO()
    cs.write(self._unpackData(data))
    z=zipfile.ZipFile(cs)
    h='could not extract anything'
    for f in z.infolist():
      fn=f.filename
      if fn.endswith('html'):
        h=z.read(fn)
        break
    z.close()
    cs.close()
368
    return stripHtml(h)
369

Bartek Górny's avatar
Bartek Górny committed
370 371 372 373 374 375 376 377 378
  security.declareProtected(Permissions.View,'getTargetFile')
  def getTargetFile(self,format,REQUEST=None):
    """
    Get (possibly generate) file in a given format
    """
    if not self.isAllowed(format):
      return self.returnMessage('can not convert to '+format+' for some reason')
    try:
      self.makeFile(format)
379
      return self.cacheGet(format)
Bartek Górny's avatar
Bartek Górny committed
380 381 382 383 384 385 386 387 388
    except ConvertionError,e:
      return self.returnMessage(str(e))

  security.declareProtected(Permissions.View,'isFileChanged')
  def isFileChanged(self,format):
    """
    Checks whether the file was converted (or uploaded) after last generation of
    the target format
    """
389
    return not self.hasFileCache(format)
Bartek Górny's avatar
Bartek Górny committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

  security.declareProtected(Permissions.ModifyPortalContent,'makeFile')
  def makeFile(self,format,REQUEST=None):
    """
    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

    TODO:
      * support of images in html conversion (as subobjects for example)
    """
    if not self.isAllowed(format):
      errstr='%s format is not supported' % format
      if REQUEST is not None:
        return self.returnMessage(errstr)
      raise ConvertionError(errstr)
408
    if not self.hasOOFile():
Bartek Górny's avatar
Bartek Górny committed
409 410 411 412 413
      if REQUEST is not None:
        return self.returnMessage('needs conversion')
      raise ConvertionError('needs conversion')
    if self.isFileChanged(format):
      try:
414 415
        mime,data=self._makeFile(format)
        self.cacheSet(format,mime,data)
Bartek Górny's avatar
Bartek Górny committed
416 417 418 419 420 421
        self._p_changed=1 # XXX not sure it is necessary
      except xmlrpclib.Fault,e:
        if REQUEST is not None:
          return self.returnMessage('Problem: %s' % str(e))
        else:
          raise ConvertionError(str(e))
422
      self.cacheUpdate(format)
Bartek Górny's avatar
Bartek Górny committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436
      if REQUEST is not None:
        return self.returnMessage('%s created' % format)
    else:
      if REQUEST is not None:
        return self.returnMessage('%s file is up to date' % format)
      return ConvertionError('%s file is up to date' % format)

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

440 441 442 443 444 445 446 447 448 449 450 451 452
  # make sure to call the right edit methods
  _edit=File._edit
  edit=File.edit

  # BG copied from File in case
  index_html = CMFFile.index_html
  PUT = CMFFile.PUT
  security.declareProtected('FTP access', 'manage_FTPget', 'manage_FTPstat', 'manage_FTPlist')
  manage_FTPget = CMFFile.manage_FTPget
  manage_FTPlist = CMFFile.manage_FTPlist
  manage_FTPstat = CMFFile.manage_FTPstat


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