Document.py 34.5 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets 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.
#
##############################################################################

Bartek Górny's avatar
Bartek Górny committed
29 30
from DateTime import DateTime
from operator import add
31
import re
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32

33
from AccessControl import ClassSecurityInfo, getSecurityManager
Romain Courteaud's avatar
Romain Courteaud committed
34 35
from Acquisition import aq_base
from Globals import PersistentMapping
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36
from Products.CMFCore.utils import getToolByName
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.XMLObject import XMLObject
39
from Products.ERP5Type.WebDAVSupport import TextContent
Bartek Górny's avatar
Bartek Górny committed
40
from Products.ERP5Type.Message import Message
41
from Products.ERP5Type.Utils import convertToUpperCase, convertToMixedCase
Bartek Górny's avatar
Bartek Górny committed
42 43

_MARKER = []
44
VALID_ORDER_KEY_LIST = ('user_login', 'content', 'file_name', 'input')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45

46 47 48 49 50
def makeSortedTuple(kw):
  items = kw.items()
  items.sort()
  return tuple(items)

Bartek Górny's avatar
Bartek Górny committed
51

52 53 54 55 56
class ConversionCacheMixin:
  """
    This class provides a generic API to store in the ZODB
    various converted versions of a file or of a string.

Bartek Górny's avatar
Bartek Górny committed
57 58 59 60
    Versions are stored in dictionaries; the class stores also
    generation time of every format and its mime-type string.
    Format can be a string or a tuple (e.g. format, resolution).

61 62 63 64
    TODO:
    * Implement ZODB BLOB
  """
  # time of generation of various formats
Romain Courteaud's avatar
Romain Courteaud committed
65
  _cached_time = None # Defensive programming - prevent caching to RAM
66
  # generated files (cache)
Romain Courteaud's avatar
Romain Courteaud committed
67
  _cached_data = None # Defensive programming - prevent caching to RAM
68
  # mime types for cached formats XXX to be refactored
Romain Courteaud's avatar
Romain Courteaud committed
69
  _cached_mime = None # Defensive programming - prevent caching to RAM
70 71 72 73 74 75 76 77 78 79 80

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

  security.declareProtected(Permissions.ModifyPortalContent, 'clearConversionCache')
  def clearConversionCache(self):
    """
    Clear cache (invoked by interaction workflow upon file upload
    needed here to overwrite class attribute with instance attrs
    """
Romain Courteaud's avatar
Romain Courteaud committed
81 82 83 84 85 86 87
    self._cached_time = PersistentMapping()
    self._cached_data = PersistentMapping()
    self._cached_mime = PersistentMapping()

  security.declareProtected(Permissions.View, 'updateConversionCache')
  def updateConversionCache(self):
    aself = aq_base(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
88
    if not hasattr(aself, '_cached_time') or self._cached_time is None:
Romain Courteaud's avatar
Romain Courteaud committed
89
      self._cached_time = PersistentMapping()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
90
    if not hasattr(aself, '_cached_data') or self._cached_data is None:
Romain Courteaud's avatar
Romain Courteaud committed
91
      self._cached_data = PersistentMapping()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
92
    if not hasattr(aself, '_cached_mime') or self._cached_mime is None:
Romain Courteaud's avatar
Romain Courteaud committed
93
      self._cached_mime = PersistentMapping()
94 95 96 97 98 99

  security.declareProtected(Permissions.View, 'hasConversion')
  def hasConversion(self, **format):
    """
      Checks whether we have a version in this format
    """
Romain Courteaud's avatar
Romain Courteaud committed
100
    self.updateConversionCache()
101 102
    return self._cached_data.has_key(makeSortedTuple(format))

Bartek Górny's avatar
Bartek Górny committed
103
  security.declareProtected(Permissions.View, 'getCacheTime')
104 105 106 107
  def getCacheTime(self, **format):
    """
      Checks when if ever was the file produced
    """
Romain Courteaud's avatar
Romain Courteaud committed
108
    self.updateConversionCache()
109 110
    return self._cached_time.get(makeSortedTuple(format), 0)

Bartek Górny's avatar
Bartek Górny committed
111
  security.declareProtected(Permissions.ModifyPortalContent, 'updateConversion')
112
  def updateConversion(self, **format):
Romain Courteaud's avatar
Romain Courteaud committed
113 114
    self.updateConversionCache()
    self._cached_time[makeSortedTuple(format)] = DateTime()
115

Bartek Górny's avatar
Bartek Górny committed
116
  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
117
  def setConversion(self, data, mime=None, **format):
Bartek Górny's avatar
Bartek Górny committed
118 119 120 121
    """
    Saves a version of the document in a given format; records mime type
    and conversion time (which is right now).
    """
Romain Courteaud's avatar
Romain Courteaud committed
122
    self.updateConversionCache()
123 124 125 126 127
    tformat = makeSortedTuple(format)
    if mime is not None:
      self._cached_mime[tformat] = mime
    if data is not None:
      self._cached_data[tformat] = data
128
      self.updateConversion(**format)
129 130
    self._p_changed = 1

Bartek Górny's avatar
Bartek Górny committed
131
  security.declareProtected(Permissions.View, 'getConversion')
132
  def getConversion(self, **format):
Bartek Górny's avatar
Bartek Górny committed
133 134 135 136 137 138 139 140 141
    """
    Returns version of the document in a given format, if it has it; otherwise
    returns empty string (the caller should check hasConversion before calling
    this function.

    (we could be much cooler here - pass testing and updating methods to this function
    so that it does it all by itself; this'd eliminate the need for setConversion public method)
    XXX-BG: I'm not sure now what I meant by this...
    """
Romain Courteaud's avatar
Romain Courteaud committed
142
    self.updateConversionCache()
143 144 145 146 147 148 149
    tformat = makeSortedTuple(format)
    return self._cached_mime.get(tformat, ''), self._cached_data.get(tformat, '')

  security.declareProtected(Permissions.View, 'getConversionCacheInfo')
  def getConversionCacheInfo(self):
    """
    Get cache details as string (for debugging)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
150
    """
Romain Courteaud's avatar
Romain Courteaud committed
151
    self.updateConversionCache()
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    s = 'CACHE INFO:<br/><table><tr><td>format</td><td>size</td><td>time</td><td>is changed</td></tr>'
    for f in self._cached_time.keys():
      t = self._cached_time[f]
      data = self._cached_data.get(f)
      if data:
        if isinstance(data, str):
          ln = len(data)
        else:
          ln = 0
          while data is not None:
            ln += len(data.data)
            data = data.next
      else:
        ln = 'no data!!!'
      s += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (f, str(ln), str(t), '-')
    s += '</table>'
    return s

Bartek Górny's avatar
Bartek Górny committed
170

171
class Document(XMLObject):
Bartek Górny's avatar
Bartek Górny committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  """
      Document is an abstract class with all methods
      related to document management in ERP5. This includes
      searchable text, explicit relations, implicit relations,
      metadata, versions, languages, etc.

      There are currently two types of Document subclasses:

      * File for binary file based documents. File
        has subclasses such as Image, OOoDocument,
        PDFDocument, etc. to implement specific conversion
        methods.

      * TextDocument for text based documents. TextDocument
        has subclasses such as Wiki to implement specific
        methods.

      Document classes which implement conversion should use
      the ConversionCacheMixin class so that converted values are
191
      stored inside ZODB and do not need to be recalculated.
Bartek Górny's avatar
Bartek Górny committed
192 193 194 195 196 197 198 199 200 201 202 203

      XXX IDEA - ISSUE: generic API for conversion.
        converted_document = document.convert(...)

      Instances can be created directly, or via portal_contributions tool
      which manages document ingestion process whereby a file can be uploaded
      by http or sent in by email or dropped in by webdav or in some other
      way as yet unknown. The ingestion process has the following steps:

      (1) portal type detection
      (2) object creation and upload of data
      (3) metadata discovery (optionally with conversion of data to another format)
204 205
      (4) other possible actions to finalise the ingestion (ex. by assigning
          a reference)
Bartek Górny's avatar
Bartek Górny committed
206 207 208 209 210

      This class handles (3) and calls a ZMI script to do (4).

      Metadata can be drawn from various sources:

211 212 213 214 215
      input      -   data supplied with http request or set on the object during (2) (e.g.
                     discovered from email text)
      file_name  -    data which might be encoded in file name
      user_login -   information about user who is contributing the file
      content    -   data which might be derived from document content
Bartek Górny's avatar
Bartek Górny committed
216 217 218

      If a certain property is defined in more than one source, it is set according to
      preference order returned by a script 
219 220 221
         Document_getPreferredDocumentMetadataDiscoveryOrderList
         (or any type-based version since discovery is type dependent)

Bartek Górny's avatar
Bartek Górny committed
222
      Methods for discovering metadata are:
223

Bartek Górny's avatar
Bartek Górny committed
224 225 226 227 228
        getPropertyDictFromInput
        getPropertyDictFromFileName
        getPropertyDictFromUserLogin
        getPropertyDictFromContent

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
      Methods for processing content are implemented either in 
      Document class or in Base class:

        getSearchableReferenceList (Base)
        getSearchableText (Base)
        index_html (Document)

      Methods for handling relations are implemented either in 
      Document class or in Base class:

        getImplicitSuccessorValueList (Base)
        getImplicitPredecessorValueList (Base)
        getImplicitSimilarValueList (Base)
        getSimilarCloudValueList (Document)

      Implicit relations consist in finding document references inside
      searchable text (ex. INV-23456) and deducting relations from that.
      Two customisable methods required. One to find a list of implicit references
      inside the content (getSearchableReferenceList) and one to convert a given
      document reference into a list of reference strings which could
      be present in other content (asSearchableReferenceList).
Bartek Górny's avatar
Bartek Górny committed
250

251 252 253 254 255 256
      document.getSearchableReferenceList() returns
        [
         {'reference':' INV-12367'},
         {'reference': 'INV-1112', 'version':'012}', 
         {'reference': 'AB-CC-DRK', 'version':'011', 'language': 'en'}
        ]
Bartek Górny's avatar
Bartek Górny committed
257

258 259
      The Document class behaviour can be extended / customized through scripts
      (which are type-based so can be adjusted per portal type).
Bartek Górny's avatar
Bartek Górny committed
260

261
      * Document_getPropertyDictFromUserLogin - finds a user (by user_login or from session)
Bartek Górny's avatar
Bartek Górny committed
262 263
        and returns properties which should be set on the document

264
      * Document_getPropertyDictFromContent - analyzes document content and returns
Bartek Górny's avatar
Bartek Górny committed
265 266
        properties which should be set on the document

267
      * Base_getImplicitSuccessorValueList - finds appropriate all documents
268
        referenced in the current content
Bartek Górny's avatar
Bartek Górny committed
269

270
      * Base_getImplicitPredecessorValueList - finds document predecessors based on
Bartek Górny's avatar
Bartek Górny committed
271 272 273 274 275 276 277 278 279
        the document coordinates (can use only complete coordinates, or also partial)

      * Document_getPreferredDocumentMetadataDiscoveryOrderList - returns an order
        in which metadata should be set/overwritten

      * Document_finishIngestion - called by portal_activities after all the ingestion
        is completed (and after document has been converted, so text_content
        is available if the document has it)

280
      * Document_getNewRevision - calculates revision number which should be set
Bartek Górny's avatar
Bartek Górny committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        on this document. Implementation depends on revision numbering policy which
        can be very different. Interaction workflow should call setNewRevision method.

      Subcontent: documents may include subcontent (files, images, etc.)
      so that publication of rich content can be path independent.

    Consistency checking:
      Default implementation uses DocumentReferenceConstraint to check if the 
      reference/language/version triplet is unique. Additional constraints
      can be added if necessary.
  """

  meta_type = 'ERP5 Document'
  portal_type = 'Document'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1
  isDocument = 1
299
  __dav_collection__=0
Bartek Górny's avatar
Bartek Górny committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

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

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Document
                    )

  # Declarative interfaces
  __implements__ = ()

  searchable_property_list = ('title', 'description', 'id', 'reference',
                              'version', 'short_title', 'keyword',
                              'subject', 'source_reference', 'source_project_title')

321
  data = '' # some day this will be in property sheets
Bartek Górny's avatar
Bartek Górny committed
322

323
  ### Content processing methods
324 325
  security.declareProtected(Permissions.View, 'index_html')
  def index_html(self, REQUEST, RESPONSE, format=None, force=0, **kw):
326 327
    """
      We follow here the standard Zope API for files and images
Jean-Paul Smets's avatar
Jean-Paul Smets committed
328 329 330 331 332 333 334 335 336 337 338
      and extend it to support format conversion. The idea
      is that an image which ID is "something.jpg" should
      ne directly accessible through the URL
      /a/b/something.jpg. The same is true for a file and
      for any document type which primary purpose is to
      be used by a helper application rather than displayed
      as HTML in a web browser. Exceptions to this approach
      include Web Pages which are intended to be primarily rendered
      withing the layout of a Web Site or withing a standard ERP5 page.
      Please refer to the index_html of TextDocument.

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
      Should return appropriate format (calling convert
      if necessary) and set headers.

      format - the format specied in the form of an extension
      string (ex. jpeg, html, text, txt, etc.)
      force - convert doc even if it has a cached version which seems to be up2date
      **kw can be various things - e.g. resolution

    """
    pass

  security.declareProtected(Permissions.View, 'convert')
  def convert(self, format, **kw):
    """
      Main content conversion function, returns result which should
      be returned and stored in cache.
      format - the format specied in the form of an extension
356
      string (ex. jpeg, html, text, txt, etc.)
357
      **kw can be various things - e.g. resolution
358 359
    """
    pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
360

Bartek Górny's avatar
Bartek Górny committed
361 362
  security.declareProtected(Permissions.View, 'getSearchableText')
  def getSearchableText(self, md=None):
363
    """
364 365 366
      Used by the catalog for basic full text indexing.
      Uses searchable_property_list attribute to put together various properties
      of the document into one searchable text string.
367

368 369
      XXX-JPS - This method is nice. It should probably be moved to Base class
      searchable_property_list could become a standard class attribute.
370

371
      TODO (future): Make this property a per portal type property.
Bartek Górny's avatar
Bartek Górny committed
372 373
    """
    def getPropertyListOrValue(property):
374
      """
375
        we try to get a list, else we get value and convert to list
376
      """
Bartek Górny's avatar
Bartek Górny committed
377 378 379 380
      val = self.getPropertyList(property)
      if val is None:
        val = self.getProperty(property)
        if val is not None and val != '':
381 382 383 384 385
          val = [val]
        else:
          val = []
      else:
        val = list(val)
Bartek Górny's avatar
Bartek Górny committed
386
      return val
387
    searchable_text = reduce(add, map(lambda x: getPropertyListOrValue(x),
Bartek Górny's avatar
Bartek Górny committed
388
                                                self.searchable_property_list))
389
    searchable_text = ' '.join(searchable_text)
Bartek Górny's avatar
Bartek Górny committed
390 391 392 393 394 395
    return searchable_text

  # Compatibility with CMF Catalog
  SearchableText = getSearchableText # XXX-JPS - Here wa have a security issue - ask seb what to do

  ### Relation getters
396
  def getSearchableReferenceList(self):
Bartek Górny's avatar
Bartek Górny committed
397
    """
398
      Public Method
Bartek Górny's avatar
Bartek Górny committed
399
      
400 401 402 403 404 405
      This method returns a list of dictionaries which can
      be used to find objects by reference. It uses for
      that a regular expression defined at system level
      preferences.
    """
    text = self.getSearchableText()
406
    regexp = self.portal_preferences.getPreferredDocumentReferenceRegularExpression()
Bartek Górny's avatar
Bartek Górny committed
407
    try:
408
      rx_search = re.compile(regexp)
Bartek Górny's avatar
Bartek Górny committed
409 410 411
    except TypeError: # no regexp in preference
      self.log('please set document reference regexp in preferences')
      return []
412
    res = rx_search.finditer(text)
Bartek Górny's avatar
Bartek Górny committed
413 414
    res = [(r.group(),r.groupdict()) for r in res]
    return res
415
    
Bartek Górny's avatar
Bartek Górny committed
416 417 418
  security.declareProtected(Permissions.View, 'getImplicitSuccessorValueList')
  def getImplicitSuccessorValueList(self):
    """
419 420 421
      Find objects which we are referencing (if our text_content contains
      references of other documents). The whole implementation is delegated to
      Base_getImplicitSuccessorValueList script.
422

423
      The implementation goes in 2 steps:
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

    - Step 1: extract with a regular expression
      a list of distionaries with various parameters such as 
      reference, portal_type, language, version, user, etc. This
      part is configured through a portal preference.

    - Step 2: read the list of dictionaries
      and build a list of values by calling portal_catalog
      with appropriate parameters (and if possible build 
      a complex query whenever this becomes available in
      portal catalog)
      
      The script is reponsible for calling getSearchableReferenceList
      so that it can use another approach if needed.
      
      NOTE: passing a group_by parameter may be useful at a
      later stage of the implementation.
Bartek Górny's avatar
Bartek Górny committed
441 442
    """
    # XXX results should be cached as volatile attributes
443 444 445 446 447 448
    refs = [r[1] for r in self.getSearchableReferenceList()]
    res = self.Base_getImplicitSuccessorValueList(refs)
    # get unique latest (most relevant) versions
    res = [r.getObject().getLatestVersionValue() for r in res]
    res_dict = dict.fromkeys(res)
    return res_dict.keys()
Bartek Górny's avatar
Bartek Górny committed
449 450 451 452 453

  security.declareProtected(Permissions.View, 'getImplicitPredecessorValueList')
  def getImplicitPredecessorValueList(self):
    """
      This function tries to find document which are referencing us - by reference only, or
454
      by reference/language etc. Implementation is passed to 
455
        Base_getImplicitPredecessorValueList
456 457 458 459 460 461 462 463 464 465 466 467 468

      The script should proceed in two steps:

      Step 1: build a list of references out of the context
      (ex. INV-123456, 123456, etc.)

      Step 2: search using the portal_catalog and use
      priorities (ex. INV-123456 before 123456)
      ( if possible build  a complex query whenever 
      this becomes available in portal catalog )

      NOTE: passing a group_by parameter may be useful at a
      later stage of the implementation.
Bartek Górny's avatar
Bartek Górny committed
469 470
    """
    # XXX results should be cached as volatile attributes
471 472
    method = self._getTypeBasedMethod('getImplicitPredecessorValueList', 
        fallback_script_id = 'Base_getImplicitPredecessorValueList')
Bartek Górny's avatar
Bartek Górny committed
473
    lst = method()
474 475 476 477
    # make it unique first time (before getting lastversionvalue)
    di = dict.fromkeys([r.getObject() for r in lst])
    # then get latest version and make unique again
    di = dict.fromkeys([o.getLatestVersionValue() for o in di.keys()])
Bartek Górny's avatar
Bartek Górny committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491
    ref = self.getReference()
    return [o for o in di.keys() if o.getReference() != ref] # every object has its own reference in SearchableText

  security.declareProtected(Permissions.View, 'getImplicitSimilarValueList')
  def getImplicitSimilarValueList(self):
    """
      Analyses content of documents to find out by the content which documents
      are similar. Not implemented yet. 

      No cloud needed because transitive process
    """
    return []

  security.declareProtected(Permissions.View, 'getSimilarCloudValueList')
492
  def getSimilarCloudValueList(self, depth=0):
Bartek Górny's avatar
Bartek Górny committed
493 494 495 496 497 498 499 500
    """
      Returns all documents which are similar to us, directly or indirectly, and
      in both directions. In other words, it is a transitive closure of similar 
      relation. Every document is returned in the latest version available.
    """
    lista = {}
    depth = int(depth)

501 502
    #gettername = 'get%sValueList' % convertToUpperCase(category)
    #relatedgettername = 'get%sRelatedValueList' % convertToUpperCase(category)
Bartek Górny's avatar
Bartek Górny committed
503

504
    def getRelatedList(ob, level=0):
Bartek Górny's avatar
Bartek Górny committed
505
      level += 1
506 507 508 509
      #getter = getattr(self, gettername)
      #relatedgetter = getattr(self, relatedgettername)
      #res = getter() + relatedgetter()
      res = ob.getSimilarValueList() + ob.getSimilarRelatedValueList()
Bartek Górny's avatar
Bartek Górny committed
510 511 512
      for r in res:
        if lista.get(r) is None:
          lista[r] = True # we use dict keys to ensure uniqueness
Bartek Górny's avatar
Bartek Górny committed
513 514
          if level != depth:
            getRelatedList(r, level)
Bartek Górny's avatar
Bartek Górny committed
515

516
    getRelatedList(self)
Bartek Górny's avatar
Bartek Górny committed
517 518 519
    lista_latest = {}
    for o in lista.keys():
      lista_latest[o.getLatestVersionValue()] = True # get latest versions avoiding duplicates again
Bartek Górny's avatar
Bartek Górny committed
520 521 522 523
    if lista_latest.has_key(self): 
      lista_latest.pop(self) # remove this document
    if lista_latest.has_key(self.getLatestVersionValue()): 
      lista_latest.pop(self()) # remove this document
Bartek Górny's avatar
Bartek Górny committed
524 525 526

    return lista_latest.keys()

527 528 529 530 531 532 533 534 535 536
  security.declareProtected(Permissions.View, 'hasFile')
  def hasFile(self):
    """
    Checks whether we have an initial file
    """
    _marker = []
    if getattr(self,'data', _marker) is not _marker: # XXX-JPS - use propertysheet accessors
      return getattr(self, 'data') is not None
    return False

537
  ### Version and language getters - might be moved one day to a mixin class in base
Bartek Górny's avatar
Bartek Górny committed
538 539 540
  security.declareProtected(Permissions.View, 'getLatestVersionValue')
  def getLatestVersionValue(self, language=None):
    """
541 542
      Tries to find the latest version with the latest revision
      of self which the current user is allowed to access.
Bartek Górny's avatar
Bartek Górny committed
543

544 545
      If language is provided, return the latest document
      in the language.
Bartek Górny's avatar
Bartek Górny committed
546

547 548 549
      If language is not provided, return the latest version
      in original language or in the user language if the version is
      the same.
Bartek Górny's avatar
Bartek Górny committed
550
    """
Bartek Górny's avatar
Bartek Górny committed
551 552
    if not self.getReference():
      return self
553 554 555 556 557 558 559 560 561 562
    catalog = getToolByName(self, 'portal_catalog', None)
    kw = dict(reference=self.getReference(), sort_on=(('version','descending'),('revision','descending'),))
    if language is not None: kw['language'] = language
    res = catalog(**kw)

    original_language = self.getOriginalLanguage()
    user_language = self.Localizer.get_selected_language()

    # if language was given return it
    if language is not None:
Bartek Górny's avatar
Bartek Górny committed
563
      return res[0].getObject()
564 565 566 567 568 569 570 571 572 573
    else:
      first = res[0]
      in_original = None
      for ob in res:
        if ob.getLanguage() == original_language:
          # this is in original language
          in_original = ob
        if ob.getVersion() != first.getVersion():
          # we are out of the latest version - return in_original or first
          if in_original is not None:
Bartek Górny's avatar
Bartek Górny committed
574
            return in_original.getObject()
575
          else:
Bartek Górny's avatar
Bartek Górny committed
576
            return first.getObject() # this shouldn't happen in real life
577 578
        if ob.getLanguage() == user_language:
          # we found it in the user language
Bartek Górny's avatar
Bartek Górny committed
579
          return ob.getObject()
580 581
    # this is the only doc in this version
    return self
Bartek Górny's avatar
Bartek Górny committed
582 583 584 585 586 587 588

  security.declareProtected(Permissions.View, 'getVersionValueList')
  def getVersionValueList(self, version=None, language=None):
    """
      Returns a list of documents with same reference, same portal_type
      but different version and given language or any language if not given.
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
589
    catalog = getToolByName(self, 'portal_catalog', None)
590
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
591 592 593 594
                   reference=self.getReference(),
                   group_by=('revision',),
                   order_by=(('revision', 'descending', 'SIGNED'),)
                  )
595 596 597
    if version: kw['version'] = version
    if language: kw['language'] = language
    return catalog(**kw)
Bartek Górny's avatar
Bartek Górny committed
598 599 600 601

  security.declareProtected(Permissions.View, 'isVersionUnique')
  def isVersionUnique(self):
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
602 603
      Returns true if no other document of the same
      portal_type and reference has the same version and language
604 605
      
      XXX should delegate to script with proxy roles
Bartek Górny's avatar
Bartek Górny committed
606
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
607
    catalog = getToolByName(self, 'portal_catalog', None)
608 609 610 611 612 613 614
    # XXX why this does not work???
    #return catalog.countResults(portal_type=self.getPortalType(),
                                #reference=self.getReference(),
                                #version=self.getVersion(),
                                #language=self.getLanguage(),
                                #) <= 1
    return len(catalog(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
615 616 617
                                reference=self.getReference(),
                                version=self.getVersion(),
                                language=self.getLanguage(),
618
                                )) <= 1
Bartek Górny's avatar
Bartek Górny committed
619 620 621 622 623 624

  security.declareProtected(Permissions.View, 'getLatestRevisionValue')
  def getLatestRevisionValue(self):
    """
      Returns the latest revision of ourselves
    """
625 626 627 628 629 630 631 632 633 634 635 636
    if not self._checkCompleteCoordinates():
      return None
    catalog = getToolByName(self, 'portal_catalog', None)
    res = catalog(
        reference=self.getReference(),
        language=self.getLanguage(),
        version=self.getVersion(),
        sort_on=(('revision','descending'),)
        )
    if len(res) == 0:
      return None
    return res[0].getObject()
Bartek Górny's avatar
Bartek Górny committed
637 638 639 640 641

  security.declareProtected(Permissions.View, 'getRevisionValueList')
  def getRevisionValueList(self):
    """
      Returns a list revision strings for a given reference, version, language
642
      XXX should it return revision strings, or docs (as the func name would suggest)?
Bartek Górny's avatar
Bartek Górny committed
643
    """
644
    # Use portal_catalog
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    if not self._checkCompleteCoordinates():
      return []
    res = self.portal_catalog(reference=self.getReference(),
                  language=self.getLanguage(),
                  version=self.getVersion()
                  )
    d = {}
    for r in res:
      d[r.getRevision()] = True
      revs = d.keys()
      revs.sort(reverse=True)
    return revs

  security.declarePrivate('_checkCompleteCoordinates')
  def _checkCompleteCoordinates(self):
    """
      test if the doc has all coordinates
    """
    reference = self.getReference()
    version = self.getVersion()
    language = self.getLanguage()
    return (reference and version and language)
667
  
Bartek Górny's avatar
Bartek Górny committed
668
  security.declareProtected(Permissions.ModifyPortalContent, 'setNewRevision')
669
  def setNewRevision(self, immediate_reindex=False):
Bartek Górny's avatar
Bartek Górny committed
670 671 672 673
    """
      Set a new revision number automatically
      Delegates to ZMI script because revision numbering policies can be different.
      Should be called by interaction workflow upon appropriate action.
674 675 676

      Sometimes we should reindex immediately, to avoid other doc setting
      the same revision (if revisions are global and there is heavy traffic)
Bartek Górny's avatar
Bartek Górny committed
677
    """
678
    # Use portal_catalog without security (proxy roles on scripts)
679 680
    method = self._getTypeBasedMethod('getNewRevision', 
        fallback_script_id = 'Document_getNewRevision')
Bartek Górny's avatar
Bartek Górny committed
681 682
    new_rev = method()
    self.setRevision(new_rev)
683 684 685 686
    if immediate_reindex:
      self.immediateReindexObject()
    else:
      self.reindexObject()
Bartek Górny's avatar
Bartek Górny committed
687 688 689 690 691 692 693
  
  security.declareProtected(Permissions.View, 'getLanguageList')
  def getLanguageList(self, version=None):
    """
      Returns a list of languages which this document is available in
      for the current user.
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
694 695 696 697 698 699 700
    catalog = getToolByName(self, 'portal_catalog', None)
    return map(lambda o:o.getLanguage(),
                   catalog(portal_type=self.getPortalType(),
                           reference=self.getReference(),
                           version=version,
                           group_by=('language',),
                           ))
Bartek Górny's avatar
Bartek Górny committed
701 702 703 704 705 706 707 708 709 710

  security.declareProtected(Permissions.View, 'getOriginalLanguage')
  def getOriginalLanguage(self):
    """
      Returns the original language of this document.
    """
    # Approach 1: use portal_catalog and creation dates
    # Approach 2: use workflow analysis (delegate to script if necessary)
    #             workflow analysis is the only way for multiple orginals
    # XXX - cache or set?
711 712 713 714 715 716 717 718
    reference = self.getReference()
    if not reference:
      return 
    catalog = getToolByName(self, 'portal_catalog', None)
    res = catalog(reference=self.getReference(), sort_on=(('creation_date','ascending'),))
    # XXX this should be security-unaware - delegate to script with proxy roles
    return res[0].getLanguage() # XXX what happens if it is empty?
    
Bartek Górny's avatar
Bartek Górny committed
719 720 721 722 723 724

  ### Property getters
  # Property Getters are document dependent so that we can
  # handle the weird cases in which needed properties change with the type of document
  # and the usual cases in which accessing content changes with the meta type
  security.declareProtected(Permissions.ModifyPortalContent,'getPropertyDictFromUserLogin')
725
  def getPropertyDictFromUserLogin(self, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
726 727 728 729 730
    """
      Based on the user_login, find out as many properties as needed.
      returns properties which should be set on the document
    """
    if user_login is None:
731 732
      user_login = str(getSecurityManager().getUser())
    method = self._getTypeBasedMethod('getPropertyDictFromUserLogin',
Bartek Górny's avatar
Bartek Górny committed
733
        fallback_script_id='Document_getPropertyDictFromUserLogin')
734
    return method()
Bartek Górny's avatar
Bartek Górny committed
735 736 737 738 739 740 741

  security.declareProtected(Permissions.ModifyPortalContent,'getPropertyDictFromContent')
  def getPropertyDictFromContent(self):
    """
      Based on the document content, find out as many properties as needed.
      returns properties which should be set on the document
    """
742 743
    # XXX this method should first make sure we have text content
    # or do a conversion
744
    method = self._getTypeBasedMethod('getPropertyDictFromContent',
Bartek Górny's avatar
Bartek Górny committed
745
        fallback_script_id='Document_getPropertyDictFromContent')
746
    return method()
Bartek Górny's avatar
Bartek Górny committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

  security.declareProtected(Permissions.ModifyPortalContent,'getPropertyDictFromFileName')
  def getPropertyDictFromFileName(self, file_name):
    """
      Based on the file name, find out as many properties as needed.
      returns properties which should be set on the document
    """
    return self.portal_contributions.getPropertyDictFromFileName(file_name)

  security.declareProtected(Permissions.ModifyPortalContent,'getPropertyDictFromInput')
  def getPropertyDictFromInput(self):
    """
      Get properties which were supplied explicitly to the ingestion method
      (discovered or supplied before the document was created).
    """
    if hasattr(self, '_backup_input'):
      return getattr(self, '_backup_input')
    kw = {}
    for id in self.propertyIds():
      # We should not consider file data
      if id is not 'data' and self.hasProperty(id):
        kw[id] = self.getProperty(id)
    self._backup_input = kw # We could use volatile and pass kw in activate
                            # if we are garanteed that _backup_input does not
                            # disappear within a given transaction
    return kw

774

Bartek Górny's avatar
Bartek Górny committed
775 776
  ### Metadata disovery and ingestion methods
  security.declareProtected(Permissions.ModifyPortalContent, 'discoverMetadata')
777
  def discoverMetadata(self, file_name, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
778
    """
779 780 781
      This is the main metadata discovery function - controls the process
      of discovering data from various sources. The discovery itself is
      delegated to scripts or uses preferences-configurable regexps.
Bartek Górny's avatar
Bartek Górny committed
782

783
      file_name - this parameter is a file name of the form "AA-BBB-CCC-223-en"
Bartek Górny's avatar
Bartek Górny committed
784

785 786
      user_login - this is a login string of a person; can be None if the user is
        currently logged in, then we'll get him from session
Bartek Górny's avatar
Bartek Górny committed
787 788 789 790
    """

    # Get the order
    # Preference is made of a sequence of 'user_login', 'content', 'file_name', 'input'
791
    self.setSourceReference(file_name)
Bartek Górny's avatar
Bartek Górny committed
792 793
    method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList', 
        fallback_script_id = 'Document_getPreferredDocumentMetadataDiscoveryOrderList')
794
    order_list = list(method())
Bartek Górny's avatar
Bartek Górny committed
795 796 797 798 799 800

    # Start with everything until content
    content_index = order_list.index('content')

    # Start with everything until content - build a dictionnary according to the order
    kw = {}
Bartek Górny's avatar
Bartek Górny committed
801
    first_list = order_list[:content_index]
802 803
    first_list.reverse()
    for order_id in first_list:
Bartek Górny's avatar
Bartek Górny committed
804 805
      if order_id not in VALID_ORDER_KEY_LIST:
        # Prevent security attack or bad preferences
806
        raise AttributeError, "%s is not in valid order key list" % order_id
Bartek Górny's avatar
Bartek Górny committed
807 808 809 810 811
      method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id)
      method = getattr(self, method_id)
      if order_id == 'file_name':
        result = method(file_name)
      elif order_id == 'user_login':
812
        result = method(user_login)
Bartek Górny's avatar
Bartek Górny committed
813 814
      else:
        result = method()
815 816
      if result is not None:
        kw.update(result)
Bartek Górny's avatar
Bartek Górny committed
817 818
      
    # Edit content
819 820 821 822 823
    try:
      del(kw['portal_type'])
    except KeyError:
      pass
    self.edit(**kw)
Bartek Górny's avatar
Bartek Górny committed
824 825 826 827 828 829 830

    # Finish in second stage
    self.activate().finishMetadataDiscovery()
    
  security.declareProtected(Permissions.ModifyPortalContent, 'finishMetadataDiscovery')
  def finishMetadataDiscovery(self):
    """
831 832 833
      This is called by portal_activities, to leave time-consuming procedures
      for later. It converts what needs conversion to base, and
      does things that can be done only after it is converted).
Bartek Górny's avatar
Bartek Górny committed
834
    """
835
    self.convertToBase()
Bartek Górny's avatar
Bartek Górny committed
836 837 838 839
    # Get the order from preferences
    # Preference is made of a sequence of 'user_login', 'content', 'file_name', 'input'
    method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList', 
        fallback_script_id = 'Document_getPreferredDocumentMetadataDiscoveryOrderList')
840
    order_list = list(method())
Bartek Górny's avatar
Bartek Górny committed
841 842 843 844

    # Start with everything until content
    content_index = order_list.index('content')

845
    # do content and everything that is later
Bartek Górny's avatar
Bartek Górny committed
846 847 848 849
    kw = {}
    for order_id in order_list[content_index:]:
      if order_id not in VALID_ORDER_KEY_LIST:
        # Prevent security attack or bad preferences
850
        raise AttributeError, "%s is not in valid order key list" % order_id
Bartek Górny's avatar
Bartek Górny committed
851 852 853
      method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id)
      method = getattr(self, method_id)
      if order_id == 'file_name':
854 855 856 857 858 859
        result = method(self.getSourceReference())
      # XXX a problem - if user_login was explicitly supplied 
      # we don't have it here (volatile attr would have been lost by now)
      # so we can't have user_login after content
      #elif order_id == 'user_login':
        #result = method(user_login)
Bartek Górny's avatar
Bartek Górny committed
860
      elif order_id == 'user_login':
861
        raise AttributeError, "user_login can not be done in second stage"
Bartek Górny's avatar
Bartek Górny committed
862 863
      else:
        result = method()
864 865
      if result is not None:
        kw.update(result)
Bartek Górny's avatar
Bartek Górny committed
866 867
      
    # Edit content
868
    self.edit(**kw)
Bartek Górny's avatar
Bartek Górny committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883

    # Erase backup attributes
    delattr(self, '_backup_input')

    # Finish ingestion by calling method
    self.finishIngestion()

  security.declareProtected(Permissions.ModifyPortalContent, 'finishIngestion')
  def finishIngestion(self):
    """
      Finish the ingestion process by calling the appropriate script
    """
    return self._getTypeBasedMethod('finishIngestion',
        fallback_script_id='Document_finishIngestion')

884 885 886 887 888 889 890
  def convertToBase(self):
    """
      API method - some subclasses store data in a certain 'base' format
      (e.g. OOoDocument uses ODF)
    """
    pass

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