Document.py 62.7 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.
#
##############################################################################

29
import zope.interface
30
import re, socket, sys
Bartek Górny's avatar
Bartek Górny committed
31 32
from DateTime import DateTime
from operator import add
33
from xmlrpclib import Fault
34
from zLOG import LOG, INFO
35
from AccessControl import ClassSecurityInfo, getSecurityManager
36
from AccessControl.SecurityManagement import newSecurityManager, setSecurityManager
Romain Courteaud's avatar
Romain Courteaud committed
37 38
from Acquisition import aq_base
from Globals import PersistentMapping
39
from Globals import get_request
40
from Products.CMFCore.utils import getToolByName, _checkPermission
41
from Products.ERP5Type import Permissions, PropertySheet, Constraint, interfaces
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42
from Products.ERP5Type.XMLObject import XMLObject
43
from Products.ERP5Type.DateUtils import convertDateToHour, number_of_hours_in_day, number_of_hours_in_year
44 45
from Products.ERP5Type.Utils import convertToUpperCase
from Products.ERP5Type.Base import WorkflowMethod
46
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
47 48
from Products.ERP5Type.ExtensibleTraversable import ExtensibleTraversableMixIn
from Products.ERP5Type.Cache import getReadOnlyTransactionCache
49
from Products.ERP5.Document.Url import UrlMixIn
50
from Products.ERP5.Tool.ContributionTool import MAX_REPEAT
51
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
52
from AccessControl import Unauthorized
53

Bartek Górny's avatar
Bartek Górny committed
54
_MARKER = []
55
VALID_ORDER_KEY_LIST = ('user_login', 'content', 'file_name', 'input')
56 57
# these property ids are unchangable
FIXED_PROPERTY_IDS =  ('id', 'uid', 'rid', 'sid') 
Jean-Paul Smets's avatar
Jean-Paul Smets committed
58

59 60 61 62 63
def makeSortedTuple(kw):
  items = kw.items()
  items.sort()
  return tuple(items)

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 102 103 104
class SnapshotMixin:
  """
    This class provides a generic API to store in the ZODB
    PDF snapshots of objects and documents with the
    goal to keep a facsimile copy of documents as they
    were at a given date.
  """

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

  security.declareProtected(Permissions.ModifyPortalContent, 'createSnapshot')
  def createSnapshot(self):
    """
      Create a snapshot (PDF). This is the normal way to modifiy
      snapshot_data. Once a snapshot is taken, a new snapshot
      can not be taken.

      NOTE: use getSnapshotData and hasSnapshotData accessors
      to access a snapshot.

      NOTE2: implementation of createSnapshot should probably
      be delegated to a types base method since this it
      is configuration dependent.
    """
    if self.hasSnapshotData():
      raise ConversionError('This document already has a snapshot.')
    self._setSnapshotData(self.convert(format='pdf'))

  security.declareProtected(Permissions.ManagePortal, 'deleteSnapshot')
  def deleteSnapshot(self):
    """
      Deletes the snapshot - in theory this should never be done.
      It is there for programmers and system administrators.
    """
    try:
      del(self.snapshot_data)
    except AttributeError:
      pass

105
class ConversionError(Exception):pass
Bartek Górny's avatar
Bartek Górny committed
106

107 108
class NotConvertedError(Exception):pass

109 110 111 112 113
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
114 115 116 117
    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).

118 119 120 121
    TODO:
    * Implement ZODB BLOB
  """
  # time of generation of various formats
Romain Courteaud's avatar
Romain Courteaud committed
122
  _cached_time = None # Defensive programming - prevent caching to RAM
123
  # generated files (cache)
Romain Courteaud's avatar
Romain Courteaud committed
124
  _cached_data = None # Defensive programming - prevent caching to RAM
125
  # mime types for cached formats XXX to be refactored
Romain Courteaud's avatar
Romain Courteaud committed
126
  _cached_mime = None # Defensive programming - prevent caching to RAM
127 128 129 130 131 132 133 134 135 136 137

  # 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
138 139
    self._cached_time = PersistentMapping()
    self._cached_data = PersistentMapping()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
140
    self._cached_size = PersistentMapping()
141
    self._cached_mime = PersistentMapping()
Romain Courteaud's avatar
Romain Courteaud committed
142 143 144 145

  security.declareProtected(Permissions.View, 'updateConversionCache')
  def updateConversionCache(self):
    aself = aq_base(self)
146
    if getattr(aself, '_cached_time', None) is None or self._cached_time is None:
Romain Courteaud's avatar
Romain Courteaud committed
147
      self._cached_time = PersistentMapping()
148
    if getattr(aself, '_cached_data', None) is None or self._cached_data is None:
Romain Courteaud's avatar
Romain Courteaud committed
149
      self._cached_data = PersistentMapping()
150
    if getattr(aself, '_cached_size', None) is None or self._cached_size is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
151
      self._cached_size = PersistentMapping()
152 153
    if getattr(aself, '_cached_mime', None) is None or self._cached_mime is None:
      self._cached_mime = PersistentMapping()
154 155 156 157 158 159

  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
160
    self.updateConversionCache()
161 162
    return self._cached_data.has_key(makeSortedTuple(format))

Bartek Górny's avatar
Bartek Górny committed
163
  security.declareProtected(Permissions.View, 'getCacheTime')
164 165
  def getCacheTime(self, **format):
    """
166
      Checks when if ever was the file produced
167
    """
Romain Courteaud's avatar
Romain Courteaud committed
168
    self.updateConversionCache()
169 170
    return self._cached_time.get(makeSortedTuple(format), 0)

Bartek Górny's avatar
Bartek Górny committed
171
  security.declareProtected(Permissions.ModifyPortalContent, 'updateConversion')
172
  def updateConversion(self, **format):
Romain Courteaud's avatar
Romain Courteaud committed
173 174
    self.updateConversionCache()
    self._cached_time[makeSortedTuple(format)] = DateTime()
175

Bartek Górny's avatar
Bartek Górny committed
176
  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
177
  def setConversion(self, data, mime=None, **format):
Bartek Górny's avatar
Bartek Górny committed
178 179 180 181
    """
    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
182
    self.updateConversionCache()
183 184 185 186
    tformat = makeSortedTuple(format)
    if mime is not None:
      self._cached_mime[tformat] = mime
    if data is not None:
187 188 189
      self._cached_data[tformat] = aq_base(data) # Use of aq_base 
        # is useful to remove the wrapper from a temp object
        # which may have been used to generate data
190
      self.updateConversion(**format)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
191 192 193
      self._cached_size[tformat] = len(data)
    else:
      self._cached_size[tformat] = 0
194 195
    self._p_changed = 1

Bartek Górny's avatar
Bartek Górny committed
196
  security.declareProtected(Permissions.View, 'getConversion')
197
  def getConversion(self, **format):
Bartek Górny's avatar
Bartek Górny committed
198 199 200 201 202 203 204 205 206
    """
    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
207
    self.updateConversionCache()
208
    tformat = makeSortedTuple(format)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
209 210 211 212 213 214 215 216 217 218 219 220
    return self._cached_mime[tformat], self._cached_data[tformat]

  security.declareProtected(Permissions.View, 'getConversionSize')
  def getConversionSize(self, **format):
    """
    Returns the size of the converted document.
    """
    self.updateConversionCache()
    tformat = makeSortedTuple(format)
    if not self._cached_size.has_key(tformat):
      self._cached_size[tformat] = len(self._cached_data[tformat])
    return self._cached_size[tformat]
221

222
  security.declareProtected(Permissions.ViewManagementScreens, 'getConversionCacheInfo')
223 224 225
  def getConversionCacheInfo(self):
    """
    Get cache details as string (for debugging)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
226
    """
Romain Courteaud's avatar
Romain Courteaud committed
227
    self.updateConversionCache()
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    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

246 247 248 249 250 251 252
class PermanentURLMixIn(ExtensibleTraversableMixIn):
  """
    Provides access to documents through their permanent URL.
    This class must be inherited by all document classes so
    that documents displayed outside a Web Site / Web Section
    can also use the permanent URL principle.
  """
Bartek Górny's avatar
Bartek Górny committed
253

254 255 256
  # Declarative security
  security = ClassSecurityInfo()

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  ### Extensible content
  def _getExtensibleContent(self, request, name):
    # Permanent URL traversal
    # First we must get the logged user by forcing identification
    cache = getReadOnlyTransactionCache(self)
    # LOG('getReadOnlyTransactionCache', 0, repr(cache)) # Currently, it is always None
    if cache is not None:
      key = ('__bobo_traverse__', self, 'user')
      try:
        user = cache[key]
      except KeyError:
        user = _MARKER
    else:
      user = _MARKER
    old_user = getSecurityManager().getUser()
    if user is _MARKER:
      user = None # By default, do nothing
      if old_user is None or old_user.getUserName() == 'Anonymous User':
275
        user_folder = getattr(self.getPortalObject(), 'acl_users', None)
276 277 278 279
        if user_folder is not None:
          try:
            if request.get('PUBLISHED', _MARKER) is _MARKER:
              # request['PUBLISHED'] is required by validate
280
              request['PUBLISHED'] = self
281 282 283
              has_published = False
            else:
              has_published = True
284 285 286 287 288 289 290
            try:
              user = user_folder.validate(request)
            except AttributeError:
              # This kind of error happens with unrestrictedTraverse,
              # because the request object is a fake, and it is just
              # a dict object.
              user = None
291
            if not has_published:
292 293 294 295 296 297
              try:
                del request.other['PUBLISHED']
              except AttributeError:
                # The same here as above. unrestrictedTraverse provides
                # just a plain dict, so request.other does not exist.
                del request['PUBLISHED']
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
          except:
            LOG("ERP5 WARNING",0,
                "Failed to retrieve user in __bobo_traverse__ of WebSection %s" % self.getPath(),
                error=sys.exc_info())
            user = None
      if user is not None and user.getUserName() == 'Anonymous User':
        user = None # If the user which is connected is anonymous,
                    # do not try to change SecurityManager
      if cache is not None:
        cache[key] = user
    if user is not None:
      # We need to perform identification
      old_manager = getSecurityManager()
      newSecurityManager(get_request(), user)
    # Next get the document per name
    portal = self.getPortalObject()
    document = self.getDocumentValue(name=name, portal=portal)
    # Last, cleanup everything
    if user is not None:
      setSecurityManager(old_manager)
    if document is not None:
      document = aq_base(document.asContext(id=name, # Hide some properties to permit locating the original
                                            original_container=document.getParentValue(),
                                            original_id=document.getId(),
                                            editable_absolute_url=document.absolute_url()))
      return document.__of__(self)
324

325 326 327
    # no document found for current user, still such document may exists
    # in some cases user (like Anonymous) can not view document according to portal catalog
    # but we may ask him to login if such a document exists
328 329 330 331
    isAuthorizationForced = getattr(self, 'isAuthorizationForced', None)
    if isAuthorizationForced is not None and isAuthorizationForced():
      getDocumentValue = UnrestrictedMethod(self.getDocumentValue)
      if getDocumentValue(name=name, portal=portal) is not None:
332 333
        # force user to login as specified in Web Section
        raise Unauthorized
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  security.declareProtected(Permissions.View, 'getDocumentValue')
  def getDocumentValue(self, name=None, portal=None, **kw):
    """
      Return the default document with the given
      name. The name parameter may represent anything
      such as a document reference, an identifier,
      etc.

      If name is not provided, the method defaults
      to returning the default document by calling
      getDefaultDocumentValue.

      kw parameters can be useful to filter content
      (ex. force a given validation state)

      This method must be implemented through a
      portal type dependent script:
        WebSection_getDocumentValue
    """
    if name is None:
      return self.getDefaultDocumentValue()

    cache = getReadOnlyTransactionCache(self)
    method = None
    if cache is not None:
      key = ('getDocumentValue', self)
      try:
        method = cache[key]
      except KeyError:
        pass

366 367 368
    if method is None:
      method = self._getTypeBasedMethod('getDocumentValue', 
              fallback_script_id='WebSection_getDocumentValue')
369 370

    if cache is not None:
371 372 373 374 375 376 377
      if cache.get(key, _MARKER) is _MARKER:
        cache[key] = method

    document = method(name, portal=portal, **kw)
    if document is not None:
      document = document.__of__(self)
    return document
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
class DocumentProxyMixin:
  """
  Provides access to documents referenced by the follow_up field
  """
  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  security.declareProtected(Permissions.AccessContentsInformation,
                            'index_html' )
  def index_html(self, REQUEST, RESPONSE, format=None, **kw):
    """ Only a proxy method """
    self.getProxiedDocument().index_html(REQUEST, RESPONSE, format, **kw)

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getProxiedDocument' )
  def getProxiedDocument(self):
    """
    Try to retrieve the original document
    """
    proxied_document = self.getDocumentProxyValue()
    if proxied_document is None:
      raise ValueError("Unable to find a proxied document")
    return proxied_document

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
class UpdateMixIn:
  """
    Provides an API to compute a date index based on the update
    frequency of the document.
  """

  # Declarative security
  security = ClassSecurityInfo()

  security.declareProtected(Permissions.AccessContentsInformation, 'getFrequencyIndex')
  def getFrequencyIndex(self):
    """
      Returns the document update frequency as an integer
      which is used by alamrs to decide which documents
      must be updates at which time. The index represents
      a time slot (ex. all days in a month, all hours in a week).
    """
    try:
      return self.getUpdateFrequencyValue().getIntIndex()
    except AttributeError:
      # Catch Attribute error or Key error - XXX not beautiful
      return 0

  security.declareProtected(Permissions.AccessContentsInformation, 'getCreationDateIndex')
  def getCreationDateIndex(self, at_date = None):
    """
    Returns the document Creation Date Index which is the creation 
    date converted into hours modulo the Frequency Index.
    """
    frequency_index = self.getFrequencyIndex()
    if not frequency_index: return -1 # If not update frequency is provided, make sure we never update
    hour = convertDateToHour(date=self.getCreationDate())
    creation_date_index = hour % frequency_index
    # in the case of bisextile year, we substract 24 hours from the creation date,
    # otherwise updating documents (frequency=yearly update) created the last
    # 24 hours of bissextile year will be launched once every 4 years.
    if creation_date_index >= number_of_hours_in_year:
      creation_date_index = creation_date_index - number_of_hours_in_day

    return creation_date_index

  security.declareProtected(Permissions.AccessContentsInformation, 'isUpdatable')
  def isUpdatable(self):
    """
      This method is used to decide which document can be updated
      in the crawling process. This can depend for example on
      workflow states (publication state,
      validation state) or on roles on the document.
    """
    method = self._getTypeBasedMethod('isUpdatable', 
        fallback_script_id = 'Document_isUpdatable')
    return method()


class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, SnapshotMixin, UpdateMixIn):
Bartek Górny's avatar
Bartek Górny committed
459 460 461 462 463 464
  """
      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.

465 466 467 468 469 470 471 472 473 474
      Documents may either store their content directly or
      cache content which is retrieved from a specified URL.
      The second case if often referred as "External Document".
      Standalone "External Documents" may be created by specifying
      a URL to the contribution tool which is in charge of initiating
      the download process and selecting the appropriate document type.
      Groups of "External Documents" may also be generated from
      so-called "External Source" (refer to ExternalSource class
      for more information).

Jean-Paul Smets's avatar
Jean-Paul Smets committed
475
      External Documents may be downloaded once or updated at
476 477
      regular interval. The later can be useful to update the content
      of an external source. Previous versions may be stored
Jean-Paul Smets's avatar
Jean-Paul Smets committed
478 479 480 481
      in place or kept in a separate file. This feature
      is known as the crawling API. It is mostly implemented
      in ContributionTool with wrappers in the Document class.
      It can be useful for create a small search engine.
482

Bartek Górny's avatar
Bartek Górny committed
483 484 485 486 487 488 489 490 491
      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
492 493 494 495
        methods. TextDocument itself has a subclass
        (XSLTDocument) which provides XSLT based analysis
        and transformation of XML content based on XSLT
        templates. 
Bartek Górny's avatar
Bartek Górny committed
496 497 498

      Document classes which implement conversion should use
      the ConversionCacheMixin class so that converted values are
499
      stored inside ZODB and do not need to be recalculated.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
500 501 502 503 504 505
      More generally, conversion should be achieved through
      the convert method and other methods of the conversion
      API (convertToBaseFormat, etc.). Moreover, any Document
      subclass must ne able to convert documents to text
      (asText method) and HTML (asHTML method). Text is required
      for full text indexing. HTML is required for crawling.
Bartek Górny's avatar
Bartek Górny committed
506 507 508 509 510 511 512 513 514

      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)
515 516
      (4) other possible actions to finalise the ingestion (ex. by assigning
          a reference)
Bartek Górny's avatar
Bartek Górny committed
517 518 519 520 521

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

      Metadata can be drawn from various sources:

522 523
      input      -   data supplied with http request or set on the object during (2) (e.g.
                     discovered from email text)
524
      file_name  -   data which might be encoded in file name
525 526
      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
527 528 529

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

Bartek Górny's avatar
Bartek Górny committed
533
      Methods for discovering metadata are:
534

Bartek Górny's avatar
Bartek Górny committed
535 536 537 538 539
        getPropertyDictFromInput
        getPropertyDictFromFileName
        getPropertyDictFromUserLogin
        getPropertyDictFromContent

540 541 542 543 544
      Methods for processing content are implemented either in 
      Document class or in Base class:

        getSearchableReferenceList (Base)
        getSearchableText (Base)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
545
        index_html (overriden in Document subclasses)
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

      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
561

562 563 564 565 566 567
      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
568

569 570
      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
571

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

575
      * Document_getPropertyDictFromContent - analyzes document content and returns
Bartek Górny's avatar
Bartek Górny committed
576 577
        properties which should be set on the document

578
      * Base_getImplicitSuccessorValueList - finds appropriate all documents
579
        referenced in the current content
Bartek Górny's avatar
Bartek Górny committed
580

581
      * Base_getImplicitPredecessorValueList - finds document predecessors based on
Bartek Górny's avatar
Bartek Górny committed
582 583 584 585 586 587 588 589 590
        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)

591
      * Document_getNewRevision - calculates revision number which should be set
Bartek Górny's avatar
Bartek Górny committed
592 593 594
        on this document. Implementation depends on revision numbering policy which
        can be very different. Interaction workflow should call setNewRevision method.

Jean-Paul Smets's avatar
Jean-Paul Smets committed
595 596 597 598
      * Document_populateContent - analyses the document content and produces
        subcontent based on it (ex. images, news, etc.). This scripts can
        involve for example an XSLT transformation to process XML.

Bartek Górny's avatar
Bartek Górny committed
599
      Subcontent: documents may include subcontent (files, images, etc.)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
600 601 602
      so that publication of rich content can be path independent. Subcontent
      can also be used to help the rendering in HTML of complex documents
      such as ODF documents.
Bartek Górny's avatar
Bartek Górny committed
603 604 605 606 607

    Consistency checking:
      Default implementation uses DocumentReferenceConstraint to check if the 
      reference/language/version triplet is unique. Additional constraints
      can be added if necessary.
608 609 610 611 612 613 614 615 616 617 618 619 620

    NOTE: Document.py supports a notion of revision which is very specific.
    The underlying concept is that, as soon as a document has a reference,
    the association of (reference, version, language) must be unique
    accross the whole system. This means that a given document in a given
    version in a given language is unique. The underlying idea is similar
    to the one in a Wiki system in which each page is unique and acts
    the the atom of collaboration. In the case of ERP5, if a team collaborates
    on a Text document written with an offline word processor, all
    updates should be placed inside the same object. A Contribution
    will thus modify an existing document, if allowed from security
    point of view, and increase the revision number. Same goes for
    properties (title). Each change generates a new revision.
Bartek Górny's avatar
Bartek Górny committed
621 622 623 624 625 626 627 628
  """

  meta_type = 'ERP5 Document'
  portal_type = 'Document'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1
  isDocument = 1
629
  __dav_collection__=0
Bartek Górny's avatar
Bartek Górny committed
630

Jean-Paul Smets's avatar
Jean-Paul Smets committed
631 632
  # Regular expressions
  href_parser = re.compile('<a[^>]*href=[\'"](.*?)[\'"]',re.IGNORECASE)
633 634
  body_parser = re.compile('<body[^>]*>(.*?)</body>', re.IGNORECASE + re.DOTALL)
  title_parser = re.compile('<title[^>]*>(.*?)</title>', re.IGNORECASE + re.DOTALL)
635
  base_parser = re.compile('<base[^>]*href=[\'"](.*?)[\'"][^>]*>', re.IGNORECASE + re.DOTALL)
636
  charset_parser = re.compile('charset="?([a-z0-9\-]+)', re.IGNORECASE)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
637

Bartek Górny's avatar
Bartek Górny committed
638 639 640 641 642 643 644 645 646 647 648
  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Document
Jean-Paul Smets's avatar
Jean-Paul Smets committed
649 650
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
651
                    , PropertySheet.Periodicity
652
                    , PropertySheet.Snapshot
Bartek Górny's avatar
Bartek Górny committed
653 654 655
                    )

  # Declarative interfaces
656
  zope.interface.implements()
Bartek Górny's avatar
Bartek Górny committed
657

658 659 660
  searchable_property_list = ('asText', 'title', 'description', 'id', 'reference',
                              'version', 'short_title',
                              'subject', 'source_reference', 'source_project_title',)
Bartek Górny's avatar
Bartek Górny committed
661

662
  ### Content processing methods
663
  security.declareProtected(Permissions.View, 'index_html')
664
  def index_html(self, REQUEST, RESPONSE, format=None, **kw):
665 666
    """
      We follow here the standard Zope API for files and images
Jean-Paul Smets's avatar
Jean-Paul Smets committed
667 668 669 670 671 672 673 674 675 676 677
      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.

678 679 680
      Should return appropriate format (calling convert
      if necessary) and set headers.

681
      format -- the format specied in the form of an extension
682
      string (ex. jpeg, html, text, txt, etc.)
683 684

      **kw -- can be various things - e.g. resolution
685

Jean-Paul Smets's avatar
Jean-Paul Smets committed
686 687 688
      TODO:
      - implement guards API so that conversion to certain
        formats require certain permission
689
    """
690
    raise NotImplementedError
691

Bartek Górny's avatar
Bartek Górny committed
692 693
  security.declareProtected(Permissions.View, 'getSearchableText')
  def getSearchableText(self, md=None):
694
    """
695 696 697
      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.
698

699 700
      XXX-JPS - This method is nice. It should probably be moved to Base class
      searchable_property_list could become a standard class attribute.
701

702
      TODO (future): Make this property a per portal type property.
Bartek Górny's avatar
Bartek Górny committed
703 704
    """
    def getPropertyListOrValue(property):
705
      """
706
        we try to get a list, else we get value and convert to list
707
      """
708 709 710 711 712 713 714
      method = getattr(self, property, None)
      if method is not None:
        if callable(method):
          val = method()
          if isinstance(val, list) or isinstance(val, tuple):
            return list(val)
          return [str(val)]
Bartek Górny's avatar
Bartek Górny committed
715 716 717 718
      val = self.getPropertyList(property)
      if val is None:
        val = self.getProperty(property)
        if val is not None and val != '':
719
          val = [str(val)]
720 721 722
        else:
          val = []
      else:
723
        val = [str(v) for v in list(val) if v is not None]
Bartek Górny's avatar
Bartek Górny committed
724
      return val
725

726
    searchable_text = reduce(add, map(lambda x: getPropertyListOrValue(x),
Bartek Górny's avatar
Bartek Górny committed
727
                                                self.searchable_property_list))
728
    searchable_text = ' '.join(searchable_text)
Bartek Górny's avatar
Bartek Górny committed
729 730 731
    return searchable_text

  # Compatibility with CMF Catalog
Jean-Paul Smets's avatar
Jean-Paul Smets committed
732
  SearchableText = getSearchableText
Bartek Górny's avatar
Bartek Górny committed
733

734 735 736 737 738 739 740
  security.declareProtected(Permissions.AccessContentsInformation, 'isExternalDocument')
  def isExternalDocument(self):
    """
    Return true if this document was obtained from an external source
    """
    return bool(self.getUrlString())

Bartek Górny's avatar
Bartek Górny committed
741
  ### Relation getters
742
  security.declareProtected(Permissions.AccessContentsInformation, 'getSearchableReferenceList')
743
  def getSearchableReferenceList(self):
Bartek Górny's avatar
Bartek Górny committed
744
    """
745 746 747 748 749
      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.
    """
750
    text = self.getSearchableText() # XXX getSearchableText or asText ?
751
    regexp = self.portal_preferences.getPreferredDocumentReferenceRegularExpression()
Bartek Górny's avatar
Bartek Górny committed
752
    try:
753
      rx_search = re.compile(regexp)
Bartek Górny's avatar
Bartek Górny committed
754
    except TypeError: # no regexp in preference
755 756 757
      LOG('ERP5/Document/Document.getSearchableReferenceList', 0,
          'Document regular expression must be set in portal preferences')
      return ()
758 759 760 761 762 763 764 765 766 767 768 769
    result = []
    tmp = {}
    for match in rx_search.finditer(text):
      group = match.group()
      group_item_list = match.groupdict().items()
      group_item_list.sort()
      key = (group, tuple(group_item_list))
      tmp[key] = None
    for group, group_item_tuple in tmp.keys():
      result.append((group, dict(group_item_tuple)))
    return result

770
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSuccessorValueList')
Bartek Górny's avatar
Bartek Górny committed
771 772
  def getImplicitSuccessorValueList(self):
    """
773 774 775
      Find objects which we are referencing (if our text_content contains
      references of other documents). The whole implementation is delegated to
      Base_getImplicitSuccessorValueList script.
776

777
      The implementation goes in 2 steps:
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

    - 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
795
    """
796
    tv = getTransactionalVariable(self) # XXX Performance improvement required
797 798 799 800 801 802
    cache_key = ('getImplicitSuccessorValueList', self.getPhysicalPath())
    try:
      return tv[cache_key]
    except KeyError:
      pass

803
    reference_list = [r[1] for r in self.getSearchableReferenceList()]
804
    result = self.Base_getImplicitSuccessorValueList(reference_list)
805 806
    tv[cache_key] = result
    return result
Bartek Górny's avatar
Bartek Górny committed
807

808
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitPredecessorValueList')
Bartek Górny's avatar
Bartek Górny committed
809 810 811
  def getImplicitPredecessorValueList(self):
    """
      This function tries to find document which are referencing us - by reference only, or
812
      by reference/language etc. Implementation is passed to 
813
        Base_getImplicitPredecessorValueList
814 815 816 817 818 819 820 821 822 823 824 825 826

      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
827
    """
828
    tv = getTransactionalVariable(self) # XXX Performance improvement required
829 830 831 832 833 834
    cache_key = ('getImplicitPredecessorValueList', self.getPhysicalPath())
    try:
      return tv[cache_key]
    except KeyError:
      pass

835 836
    method = self._getTypeBasedMethod('getImplicitPredecessorValueList', 
        fallback_script_id = 'Base_getImplicitPredecessorValueList')
837
    result = method()
838 839
    tv[cache_key] = result
    return result
Bartek Górny's avatar
Bartek Górny committed
840

841
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSimilarValueList')
Bartek Górny's avatar
Bartek Górny committed
842 843 844
  def getImplicitSimilarValueList(self):
    """
      Analyses content of documents to find out by the content which documents
845
      are similar. Not implemented yet.
Bartek Górny's avatar
Bartek Górny committed
846 847 848 849 850

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

851
  security.declareProtected(Permissions.AccessContentsInformation, 'getSimilarCloudValueList')
852
  def getSimilarCloudValueList(self, depth=0):
Bartek Górny's avatar
Bartek Górny committed
853 854 855 856 857 858 859 860
    """
      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)

861 862
    #gettername = 'get%sValueList' % convertToUpperCase(category)
    #relatedgettername = 'get%sRelatedValueList' % convertToUpperCase(category)
Bartek Górny's avatar
Bartek Górny committed
863

864
    def getRelatedList(ob, level=0):
Bartek Górny's avatar
Bartek Górny committed
865
      level += 1
866 867 868 869
      #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
870 871 872
      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
873 874
          if level != depth:
            getRelatedList(r, level)
Bartek Górny's avatar
Bartek Górny committed
875

876
    getRelatedList(self)
Bartek Górny's avatar
Bartek Górny committed
877 878 879
    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
880 881
    if lista_latest.has_key(self): 
      lista_latest.pop(self) # remove this document
882 883 884
    if lista_latest.has_key(self.getLatestVersionValue()):
      # remove last version of document itself from related documents
      lista_latest.pop(self.getLatestVersionValue()) 
Bartek Górny's avatar
Bartek Górny committed
885 886 887

    return lista_latest.keys()

888
  ### Version and language getters - might be moved one day to a mixin class in base
Bartek Górny's avatar
Bartek Górny committed
889 890 891
  security.declareProtected(Permissions.View, 'getLatestVersionValue')
  def getLatestVersionValue(self, language=None):
    """
892 893
      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
894

895 896
      If language is provided, return the latest document
      in the language.
Bartek Górny's avatar
Bartek Górny committed
897

898 899 900
      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
901
    """
Bartek Górny's avatar
Bartek Górny committed
902 903
    if not self.getReference():
      return self
904
    catalog = getToolByName(self, 'portal_catalog', None)
905
    kw = dict(reference=self.getReference(), sort_on=(('version','descending'),))
906 907 908 909 910 911
    if language is not None: kw['language'] = language
    res = catalog(**kw)

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

912
    # if language was given return it (if there are any docs in this language)
913
    if language is not None:
914 915 916 917
      try:
        return res[0].getObject()
      except IndexError:
        return None
918 919 920 921 922 923 924
    else:
      first = res[0]
      in_original = None
      for ob in res:
        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
925
            return in_original.getObject()
926
          else:
Bartek Górny's avatar
Bartek Górny committed
927
            return first.getObject() # this shouldn't happen in real life
928 929
        if ob.getLanguage() == user_language:
          # we found it in the user language
Bartek Górny's avatar
Bartek Górny committed
930
          return ob.getObject()
931 932 933
        if ob.getLanguage() == original_language:
          # this is in original language
          in_original = ob
934 935
    # this is the only doc in this version
    return self
Bartek Górny's avatar
Bartek Górny committed
936 937 938 939 940 941 942

  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
943
    catalog = getToolByName(self, 'portal_catalog', None)
944
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
945
                   reference=self.getReference(),
946
                   order_by=(('version', 'descending', 'SIGNED'),)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
947
                  )
948 949 950
    if version: kw['version'] = version
    if language: kw['language'] = language
    return catalog(**kw)
Bartek Górny's avatar
Bartek Górny committed
951

952
  security.declareProtected(Permissions.AccessContentsInformation, 'isVersionUnique')
Bartek Górny's avatar
Bartek Górny committed
953 954
  def isVersionUnique(self):
    """
955 956 957
      Returns true if no other document exists with the same
      reference, version and language, or if the current
      document has no reference.
Bartek Górny's avatar
Bartek Górny committed
958
    """
959 960
    if not self.getReference():
      return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
961
    catalog = getToolByName(self, 'portal_catalog', None)
962
    self_count = catalog.unrestrictedCountResults(portal_type=self.getPortalDocumentTypeList(),
963 964 965
                                            reference=self.getReference(),
                                            version=self.getVersion(),
                                            language=self.getLanguage(),
966
                                            uid=self.getUid(),
967
                                            validation_state="!=cancelled"
968 969 970 971 972
                                            )[0][0]
    count = catalog.unrestrictedCountResults(portal_type=self.getPortalDocumentTypeList(),
                                            reference=self.getReference(),
                                            version=self.getVersion(),
                                            language=self.getLanguage(),
Ivan Tyagov's avatar
Ivan Tyagov committed
973
                                            validation_state="!=cancelled"
974 975 976 977
                                            )[0][0]
    # If self is not indexed yet, then if count == 1, version is not unique
    return count <= self_count

978 979 980 981
  security.declareProtected(Permissions.AccessContentsInformation, 'getRevision')
  def getRevision(self):
    """
      Returns the current revision by analysing the change log
982 983 984 985
      of the current object. The return value is a string
      in order to be consistent with the property sheet
      definition.
      
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
      NOTE: for now, workflow choice is hardcoded. This is
      an optimisation hack. If a document does neither use
      edit_workflow or processing_status_workflow, the
      first workflow in the chain has prioriot. Better
      implementation would require to be able to define
      which workflow in a chain is the default one for
      revision tracking (and for modification date).
    """
    portal_workflow = getToolByName(self, 'portal_workflow')
    wf_list = list(portal_workflow.getWorkflowsFor(self))
    wf = portal_workflow.getWorkflowById('edit_workflow')
    if wf is not None: wf_list = [wf] + wf_list
    wf = portal_workflow.getWorkflowById('processing_status_workflow')
    if wf is not None: wf_list = [wf] + wf_list
    for wf in wf_list:
      history = wf.getInfoFor(self, 'history', None)
      if history:
1003 1004
        return str(len(filter(lambda x:x.get('action', None) in ('edit', 'upload'), history)))
    return ''
1005 1006 1007 1008 1009 1010 1011

  security.declareProtected(Permissions.AccessContentsInformation, 'getRevisionList')
  def getRevisionList(self):
    """
      Returns the list of revision numbers of the current document
      by by analysing the change log of the current object.
    """
1012 1013 1014 1015
    revision = self.getRevision()
    if revision == '':
      return []
    return [str(r) for r in range(0, int(self.getRevision()))]
1016

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  security.declareProtected(Permissions.ModifyPortalContent, 'mergeRevision')
  def mergeRevision(self):
    """
      Merge the current document with any previous revision
      or change its version to make sure it is still unique.

      NOTE: revision support is implemented in the Document
      class rather than within the ContributionTool
      because the ingestion process requires to analyse the content
      of the document first. Hence, it is not possible to
      do any kind of update operation until the whole ingestion
      process is completed, since update requires to know
      reference, version, language, etc. In addition,
      we have chosen to try to merge revisions after each
      metadata discovery as a way to make sure that any
      content added in the system through the ContributionTool
      (ex. through webdav) will be merged if necessary.
      It may be posssible though to split disoverMetadata and
      finishIngestion.
    """
    document = self
    catalog = getToolByName(self, 'portal_catalog', None)
    if self.getReference():
      # Find all document with same (reference, version, language)
      kw = dict(portal_type=self.getPortalDocumentTypeList(),
                reference=self.getReference(),
1043
                where_expression="validation_state NOT IN ('cancelled', 'deleted')")
1044 1045 1046 1047 1048 1049
      if self.getVersion(): kw['version'] = self.getVersion()
      if self.getLanguage(): kw['language'] = self.getLanguage()
      document_list = catalog.unrestrictedSearchResults(**kw)
      existing_document = None
      # Select the first one which is not self and which
      # shares the same coordinates
1050
      document_list = list(document_list)
1051
      document_list.sort(key=lambda x: x.getId())
Ivan Tyagov's avatar
Ivan Tyagov committed
1052
      #LOG('[DMS] Existing documents for %s' %self.getSourceReference(), INFO, len(document_list))
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
      for o in document_list:
        if o.getRelativeUrl() != self.getRelativeUrl() and\
           o.getVersion() == self.getVersion() and\
           o.getLanguage() == self.getLanguage():
          existing_document = o.getObject()
          break
      # We found an existing document to update
      if existing_document is not None:
        document = existing_document
        if existing_document.getPortalType() != self.getPortalType():
1063
          raise ValueError, "[DMS] Ingestion may not change the type of an existing document"
1064 1065
        elif not _checkPermission(Permissions.ModifyPortalContent, existing_document):
          self.setUniqueReference(suffix='unauthorized')
1066
          raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % existing_document.getId()
1067 1068 1069
        else:
          update_kw = {}
          for k in self.propertyIds():
1070
            if k not in FIXED_PROPERTY_IDS and self.hasProperty(k):
1071 1072 1073 1074 1075 1076
              update_kw[k] = self.getProperty(k)
          existing_document.edit(**update_kw)
          # Erase self
          self.delete() # XXX Do we want to delete by workflow or for real ?
    return document

1077
  security.declareProtected(Permissions.AccessContentsInformation, 'getLanguageList')
Bartek Górny's avatar
Bartek Górny committed
1078 1079 1080 1081 1082
  def getLanguageList(self, version=None):
    """
      Returns a list of languages which this document is available in
      for the current user.
    """
1083
    if not self.getReference(): return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1084
    catalog = getToolByName(self, 'portal_catalog', None)
1085
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1086
                           reference=self.getReference(),
1087 1088 1089 1090
                           group_by=('language',))
    if version is not None:
      kw['version'] = version
    return map(lambda o:o.getLanguage(), catalog(**kw))
Bartek Górny's avatar
Bartek Górny committed
1091

1092
  security.declareProtected(Permissions.AccessContentsInformation, 'getOriginalLanguage')
Bartek Górny's avatar
Bartek Górny committed
1093 1094 1095
  def getOriginalLanguage(self):
    """
      Returns the original language of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1096 1097

      XXX-JPS not implemented yet ?
Bartek Górny's avatar
Bartek Górny committed
1098 1099 1100 1101 1102
    """
    # 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?
1103 1104 1105 1106 1107 1108 1109
    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
1110 1111 1112 1113 1114 1115

  ### 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')
1116
  def getPropertyDictFromUserLogin(self, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
1117 1118 1119 1120 1121
    """
      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:
1122 1123
      user_login = str(getSecurityManager().getUser())
    method = self._getTypeBasedMethod('getPropertyDictFromUserLogin',
Bartek Górny's avatar
Bartek Górny committed
1124
        fallback_script_id='Document_getPropertyDictFromUserLogin')
1125
    return method(user_login)
Bartek Górny's avatar
Bartek Górny committed
1126 1127 1128 1129 1130 1131 1132

  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
    """
1133
    if not self.hasBaseData():
1134
      raise NotConvertedError
1135
    method = self._getTypeBasedMethod('getPropertyDictFromContent',
Bartek Górny's avatar
Bartek Górny committed
1136
        fallback_script_id='Document_getPropertyDictFromContent')
1137
    return method()
Bartek Górny's avatar
Bartek Górny committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151

  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).
1152 1153 1154 1155 1156

      The implementation consists in saving document properties
      into _backup_input by supposing that original input parameters were
      set on the document by ContributionTool.newContent as soon
      as the document was created.
Bartek Górny's avatar
Bartek Górny committed
1157 1158 1159 1160 1161 1162
    """
    if hasattr(self, '_backup_input'):
      return getattr(self, '_backup_input')
    kw = {}
    for id in self.propertyIds():
      # We should not consider file data
1163 1164
      if id not in ('data', 'categories_list', 'uid', 'id',
                    'text_content', 'base_data',) \
1165
            and self.hasProperty(id):
Bartek Górny's avatar
Bartek Górny committed
1166 1167 1168 1169 1170 1171
        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

1172 1173 1174 1175 1176 1177
  security.declareProtected(Permissions.AccessContentsInformation, 'getStandardFileName')
  def getStandardFileName(self):
    """
    Returns the document coordinates as a standard file name. This
    method is the reverse of getPropertyDictFromFileName.
    """
1178 1179 1180
    method = self._getTypeBasedMethod('getStandardFileName', 
        fallback_script_id = 'Document_getStandardFileName')
    return method()
1181

Bartek Górny's avatar
Bartek Górny committed
1182 1183
  ### Metadata disovery and ingestion methods
  security.declareProtected(Permissions.ModifyPortalContent, 'discoverMetadata')
1184
  def discoverMetadata(self, file_name=None, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
1185
    """
1186 1187
      This is the main metadata discovery function - controls the process
      of discovering data from various sources. The discovery itself is
1188 1189 1190
      delegated to scripts or uses preference-configurable regexps. The
      method returns either self or the document which has been
      merged in the discovery process.
Bartek Górny's avatar
Bartek Górny committed
1191

1192
      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
1193

1194
      user_login - this is a login string of a person; can be None if the user is
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1195
                   currently logged in, then we'll get him from session
1196
    """
Bartek Górny's avatar
Bartek Górny committed
1197 1198 1199
    # Preference is made of a sequence of 'user_login', 'content', 'file_name', 'input'
    method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList', 
        fallback_script_id = 'Document_getPreferredDocumentMetadataDiscoveryOrderList')
1200
    order_list = list(method())
1201
    order_list.reverse()
1202
    # build a dictionary according to the order
Bartek Górny's avatar
Bartek Górny committed
1203
    kw = {}
1204
    for order_id in order_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1205
      result = None
Bartek Górny's avatar
Bartek Górny committed
1206 1207
      if order_id not in VALID_ORDER_KEY_LIST:
        # Prevent security attack or bad preferences
1208
        raise AttributeError, "%s is not in valid order key list" % order_id
Bartek Górny's avatar
Bartek Górny committed
1209 1210 1211
      method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id)
      method = getattr(self, method_id)
      if order_id == 'file_name':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1212 1213
        if file_name is not None:
          result = method(file_name)
Bartek Górny's avatar
Bartek Górny committed
1214
      elif order_id == 'user_login':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1215 1216
        if user_login is not None:
          result = method(user_login)
Bartek Górny's avatar
Bartek Górny committed
1217 1218
      else:
        result = method()
1219 1220
      if result is not None:
        kw.update(result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1221

1222 1223 1224
    if file_name is not None:
      # filename is often undefined....
      kw['source_reference'] = file_name
1225
    # Prepare the content edit parameters - portal_type should not be changed
1226 1227 1228 1229
    kw.pop('portal_type', None)
    # Try not to invoke an automatic transition here
    self._edit(**kw)
    # Finish ingestion by calling method
1230
    self.finishIngestion()
1231
    self.reindexObject()
1232 1233
    # Revision merge is tightly coupled
    # to metadata discovery - refer to the documentation of mergeRevision method
1234 1235
    merged_doc = self.mergeRevision()
    merged_doc.reindexObject()
1236
    return merged_doc
Bartek Górny's avatar
Bartek Górny committed
1237 1238 1239 1240

  security.declareProtected(Permissions.ModifyPortalContent, 'finishIngestion')
  def finishIngestion(self):
    """
1241 1242 1243
      Finish the ingestion process by calling the appropriate script. This
      script can for example allocate a reference number automatically if
      no reference was defined.
Bartek Górny's avatar
Bartek Górny committed
1244
    """
1245 1246
    method = self._getTypeBasedMethod('finishIngestion', fallback_script_id='Document_finishIngestion')
    return method()
Bartek Górny's avatar
Bartek Górny committed
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  # Conversion methods
  security.declareProtected(Permissions.ModifyPortalContent, '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
      string (ex. jpeg, html, text, txt, etc.)
      **kw can be various things - e.g. resolution

1258 1259 1260
      Default implementation returns an empty string (html, text)
      or raises an error.

1261 1262 1263 1264
      TODO:
      - implement guards API so that conversion to certain
        formats require certain permission
    """
1265
    if format == 'html':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1266
      return 'text/html', '' # XXX - Why ?
1267
    if format in ('text', 'txt'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1268
      return 'text/plain', '' # XXX - Why ?
1269
    raise NotImplementedError
1270

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1271 1272 1273 1274 1275 1276 1277
  def getConvertedSize(self, format):
    """
      Returns the size of the converted document
    """
    format, data = self.convert(format)
    return len(data)

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  security.declareProtected(Permissions.View, 'asSubjectText')
  def asSubjectText(self, **kw):
    """
      Converts the subject of the document to a textual representation.
    """
    subject = self.getSubject()
    if not subject:
      # XXX not sure if this fallback is a good idea.
      subject = self.getTitle()
    if subject is None:
      subject = ''
    return str(subject)

1291
  security.declareProtected(Permissions.View, 'asText')
1292
  def asText(self, **kw):
1293 1294 1295
    """
      Converts the content of the document to a textual representation.
    """
1296 1297
    kw['format'] = 'txt'
    mime, data = self.convert(**kw)
1298
    return str(data)
1299

1300
  security.declareProtected(Permissions.View, 'asEntireHTML')
1301
  def asEntireHTML(self, **kw):
1302 1303
    """
      Returns a complete HTML representation of the document
1304 1305 1306
      (with body tags, etc.). Adds if necessary a base
      tag so that the document can be displayed in an iframe
      or standalone.
1307 1308

      Actual conversion is delegated to _asHTML
1309
    """
1310
    html = self._asHTML(**kw)
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    if self.getUrlString():
      # If a URL is defined, add the base tag
      # if base is defined yet.
      html = str(html)
      if not html.find('<base') >= 0:
        base = '<base href="%s">' % self.getContentBaseURL()
        html = html.replace('<head>', '<head>%s' % base)
      # We do not implement cache yet since it increases ZODB
      # for probably no reason. More research needed
      # self.setConversion(html, mime='text/html', format='base-html')
    return html
1322

1323
  security.declarePrivate('_asHTML')
1324
  def _asHTML(self, **kw):
1325 1326 1327 1328
    """
      A private method which converts to HTML. This method
      is the one to override in subclasses.
    """
1329
    if not self.hasBaseData():
1330
      raise ConversionError('This document has not been processed yet.')
1331
    if self.hasConversion(format='base-html'):
1332
      # FIXME: no substitution may occur in this case.
1333 1334
      mime, data = self.getConversion(format='base-html')
      return data
1335 1336
    kw['format'] = 'html'
    mime, html = self.convert(**kw)
1337 1338
    return html

1339
  security.declareProtected(Permissions.View, 'asStrippedHTML')
1340
  def asStrippedHTML(self, **kw):
1341
    """
1342 1343
      Returns a stripped HTML representation of the document
      (without html and body tags, etc.) which can be used to inline
1344 1345
      a preview of the document.
    """
1346
    if not self.hasBaseData():
1347
      return ''
1348
    if self.hasConversion(format='stripped-html'): # XXX this is redundant since we never set it
1349
      # FIXME: no substitution may occur in this case.
1350 1351
      mime, data = self.getConversion(format='stripped-html')
      return data
1352 1353
    kw['format'] = 'html'
    mime, html = self.convert(**kw)
1354 1355
    return self._stripHTML(str(html))

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
  def _guessEncoding(self, string):
    """
      Try to guess the encoding for this string.
      Returns None if no encoding can be guessed.
    """
    try:
      import chardet
    except ImportError:
      return None
    return chardet.detect(string).get('encoding', None)

1367 1368 1369 1370 1371
  def _stripHTML(self, html, charset=None):
    """
      A private method which can be reused by subclasses
      to strip HTML content
    """
1372 1373
    body_list = re.findall(self.body_parser, str(html))
    if len(body_list):
1374 1375 1376 1377
      stripped_html = body_list[0]
    else:
      stripped_html = html
    # find charset and convert to utf-8
1378 1379
    charset_list = self.charset_parser.findall(str(html)) # XXX - Not efficient if this 
                                         # is datastream instance but hard to do better
1380 1381 1382
    if charset and not charset_list:
      # Use optional parameter is we can not find encoding in HTML
      charset_list = [charset]
1383
    if charset_list and charset_list[0] not in ('utf-8', 'UTF-8'):
1384 1385 1386
      try:
        stripped_html = unicode(str(stripped_html), 
                                charset_list[0]).encode('utf-8')
Nicolas Delaby's avatar
Nicolas Delaby committed
1387
      except (UnicodeDecodeError, LookupError):
1388
        return str(stripped_html)
1389
    return stripped_html
1390

1391

1392 1393 1394 1395 1396 1397 1398 1399 1400
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentInformation')
  def getContentInformation(self):
    """
    Returns the content information from the HTML conversion.
    The default implementation tries to build a dictionnary
    from the HTML conversion of the document and extract
    the document title.
    """
    result = {}
Yusei Tahara's avatar
Yusei Tahara committed
1401
    html = self.asEntireHTML()
1402 1403 1404 1405 1406
    if not html: return result
    title_list = re.findall(self.title_parser, str(html))
    if title_list:
      result['title'] = title_list[0]
    return result
1407 1408

  # Base format support
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1409
  security.declareProtected(Permissions.ModifyPortalContent, 'convertToBaseFormat')
1410
  def convertToBaseFormat(self):
1411
    """
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
      Converts the content of the document to a base format
      which is later used for all conversions. This method
      is common to all kinds of documents and handles
      exceptions in a unified way.

      Implementation is delegated to _convertToBaseFormat which
      must be overloaded by subclasses of Document which
      need a base format.

      convertToBaseFormat is called upon file upload, document
      ingestion by the processing_status_workflow.

      NOTE: the data of the base format conversion should be stored
      using the base_data property. Refer to Document.py propertysheet.
      Use accessors (getBaseData, setBaseData, hasBaseData, etc.)
1427 1428
    """
    try:
1429
      message = self._convertToBaseFormat() # Call implemetation method
1430
      self.clearConversionCache() # Conversion cache is now invalid
1431 1432 1433 1434 1435 1436 1437
      if message is None:
        # XXX Need to translate.
        message = 'Converted to %s.' % self.getBaseContentType()
      self.convertFile(comment=message) # Invoke workflow method
    except NotImplementedError:
      message = ''
    return message
1438

1439
  def _convertToBaseFormat(self):
1440
    """
1441 1442 1443 1444 1445
      Placeholder method. Must be subclassed by classes
      which need a base format. Refer to OOoDocument
      for an example of ODF base format which is used
      as a way to convert about any file format into
      about any file format.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1446

1447
      Other possible applications: conversion of HTML
1448
      text to tiddy HTML such as described here:
1449 1450
      http://www.xml.com/pub/a/2004/09/08/pyxml.html
      so that resulting text can be processed more
1451 1452 1453
      easily by XSLT parsers. Conversion of internal
      links to images of an HTML document to local
      links (in combindation with populate).
1454
    """
1455
    raise NotImplementedError
1456

1457 1458
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
1459 1460 1461 1462 1463 1464 1465
  def isSupportBaseDataConversion(self):
    """
    This is a public interface to check a document that is support conversion
    to base format and can be overridden in subclasses.
    """
    return False

1466
  def convertFile(self, **kw):
1467 1468 1469 1470 1471
    """
    Workflow transition invoked when conversion occurs.
    """
  convertFile = WorkflowMethod(convertFile)

1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getMetadataMappingDict')
  def getMetadataMappingDict(self):
    """
    Return a dict of metadata mapping used to update base metadata of the
    document
    """
    try:
      method = self._getTypeBasedMethod('getMetadataMappingDict')
    except KeyError, AttributeError:
      method = None
    if method is not None: 
      return method()
    else:
      return {}

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
  security.declareProtected(Permissions.ModifyPortalContent, 'updateBaseMetadata')
  def updateBaseMetadata(self, **kw):
    """
    Update the base format data with the latest properties entered
    by the user. For example, if title is changed in ERP5 interface,
    the base format file should be updated accordingly.

    Default implementation does nothing. Refer to OOoDocument class
    for an example of implementation.
    """
    pass

1500
  # Transformation API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1501
  security.declareProtected(Permissions.ModifyPortalContent, 'populateContent')
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
  def populateContent(self):
    """
      Populates the Document with subcontent based on the
      document base data.

      This can be used for example to transform the XML
      of an RSS feed into a single piece per news or
      to transform an XML export from a database into
      individual records. Other application: populate
      an HTML text document with its images, used in
      conversion with convertToBaseFormat.
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1514 1515 1516 1517 1518
    try:
      method = self._getTypeBasedMethod('populateContent')
    except KeyError, AttributeError:
      method = None
    if method is not None: method()
1519 1520

  # Crawling API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1521
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentURLList')
1522 1523 1524
  def getContentURLList(self):
    """
      Returns a list of URLs referenced by the content of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1525 1526 1527 1528 1529 1530
      Default implementation consists in analysing the document
      converted to HTML. Subclasses may overload this method
      if necessary. However, it is better to extend the conversion
      methods in order to produce valid HTML, which is useful to
      many people, rather than overload this method which is only
      useful for crawling.
1531
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1532 1533
    html_content = self.asStrippedHTML()
    return re.findall(self.href_parser, str(html_content))
1534

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1535
  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentFromURL')
1536
  def updateContentFromURL(self, repeat=MAX_REPEAT, crawling_depth=0):
1537 1538
    """
      Download and update content of this document from its source URL.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1539 1540
      Implementation is handled by ContributionTool.
    """
1541
    self.portal_contributions.updateContentFromURL(self, repeat=repeat, crawling_depth=crawling_depth)
1542

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1543 1544
  security.declareProtected(Permissions.ModifyPortalContent, 'crawlContent')
  def crawlContent(self):
1545
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1546 1547 1548 1549
      Initialises the crawling process on the current document.
    """
    self.portal_contributions.crawlContent(self)

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  security.declareProtected(Permissions.View, 'isIndexContent')
  def isIndexContent(self, container=None):
    """
      Ask container if we are and index, or a content.
      In the vast majority of cases we are content.
      This method is required in a crawling process to make
      a difference between URLs which return an index (ex. the 
      list of files in remote server which is accessed through HTTP)
      and the files themselves.
    """
    if container is None:
      container = self.getParentValue()
    if hasattr(aq_base(container), 'isIndexContent'):
      return container.isIndexContent(self)
    return False

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1566 1567 1568 1569 1570 1571 1572 1573
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentBaseURL')
  def getContentBaseURL(self):
    """
      Returns the content base URL based on the actual content or
      on its URL.
    """
    base_url = self.asURL()
    base_url_list = base_url.split('/')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1574
    if len(base_url_list):
1575
      if base_url_list[-1] and base_url_list[-1].find('.') > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1576
        # Cut the trailing part in http://www.some.site/at/trailing.html
1577
        # but not in http://www.some.site/at
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1578
        base_url = '/'.join(base_url_list[:-1])
1579
    return base_url