Document.py 55.2 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3
##############################################################################
#
4
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7
#
# WARNING: This program as such is intended to be used by professional
8
# programmers who take the whole responsibility of assessing all potential
Jean-Paul Smets's avatar
Jean-Paul Smets committed
9 10
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
11
# guarantees and support are strongly adviced to contract a Free Software
Jean-Paul Smets's avatar
Jean-Paul Smets committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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.
#
##############################################################################

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

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

62 63 64 65 66
def makeSortedTuple(kw):
  items = kw.items()
  items.sort()
  return tuple(items)

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 105 106 107
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

108
class ConversionError(Exception):pass
Bartek Górny's avatar
Bartek Górny committed
109

110 111
class DocumentProxyError(Exception):pass

112 113
class NotConvertedError(Exception):pass

114 115 116 117 118
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
119 120 121
    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).
122 123 124 125 126 127
  """

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

128 129 130
  def _getCacheFactory(self):
    """
    """
131 132
    if self.isTempObject():
      return
133 134
    cache_tool = getToolByName(self, 'portal_caches')
    preference_tool = getToolByName(self, 'portal_preferences')
135
    cache_factory_name = preference_tool.getPreferredConversionCacheFactory('document_cache_factory')
136
    cache_factory = cache_tool.getRamCacheRoot().get(cache_factory_name)
137 138 139
    #XXX This conditional statement should be remove as soon as
    #Broadcasting will be enable among all zeo clients.
    #Interaction which update portal_caches should interact with all nodes.
140 141 142
    if cache_factory is None and getattr(cache_tool, cache_factory_name, None) is not None:
      #ram_cache_root is not up to date for current node
      cache_tool.updateCache()
143 144
    return cache_tool.getRamCacheRoot().get(cache_factory_name)

145 146 147 148
  security.declareProtected(Permissions.ModifyPortalContent, 'clearConversionCache')
  def clearConversionCache(self):
    """
    """
149 150 151
    if self.isTempObject():
      self.temp_conversion_data = {}
      return
152 153
    for cache_plugin in self._getCacheFactory().getCachePluginList():
      cache_plugin.delete(self.getPath(), DEFAULT_CACHE_SCOPE)
Romain Courteaud's avatar
Romain Courteaud committed
154

155 156
  security.declareProtected(Permissions.View, 'hasConversion')
  def hasConversion(self, **kw):
157
    """
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    If you want to get conversion cache value if exists, please write
    the code like:

      try:
        mime, data = getConversion(**kw)
      except KeyError:
        ...

    instead of:

      if self.hasConversion(**kw):
        mime, data = self.getConversion(**kw)
      else:
        ...

    for better performance.
174
    """
175 176 177 178 179
    try:
      self.getConversion(**kw)
      return True
    except KeyError:
      return False
180

Bartek Górny's avatar
Bartek Górny committed
181
  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
182
  def setConversion(self, data, mime=None, calculation_time=None, **kw):
Bartek Górny's avatar
Bartek Górny committed
183 184
    """
    """
185
    cache_id = self.generateCacheId(**kw)
186
    if self.isTempObject():
187 188
      if getattr(aq_base(self), 'temp_conversion_data', None) is None:
        self.temp_conversion_data = {}
189
      self.temp_conversion_data[cache_id] = (mime, aq_base(data))
190
      return
191 192
    cache_factory = self._getCacheFactory()
    cache_duration = cache_factory.cache_duration
193
    if data is not None:
194
      for cache_plugin in cache_factory.getCachePluginList():
195
        try:
196 197
          cache_entry = cache_plugin.get(self.getPath(), DEFAULT_CACHE_SCOPE)
          cache_dict = cache_entry.getValue()
198
        except KeyError:
199
          cache_dict = {}
200
        cache_dict.update({cache_id: (self.getContentMd5(), mime, aq_base(data))})
201 202 203
        cache_plugin.set(self.getPath(), DEFAULT_CACHE_SCOPE,
                         cache_dict, calculation_time=calculation_time,
                         cache_duration=cache_duration)
204

Bartek Górny's avatar
Bartek Górny committed
205
  security.declareProtected(Permissions.View, 'getConversion')
206
  def getConversion(self, **kw):
Bartek Górny's avatar
Bartek Górny committed
207 208
    """
    """
209
    cache_id = self.generateCacheId(**kw)
210
    if self.isTempObject():
211
      return getattr(aq_base(self), 'temp_conversion_data', {})[cache_id]
212 213
    for cache_plugin in self._getCacheFactory().getCachePluginList():
      cache_entry = cache_plugin.get(self.getPath(), DEFAULT_CACHE_SCOPE)
214 215 216 217 218
      data_list = cache_entry.getValue().get(cache_id)
      if data_list:
        md5sum, mime, data = data_list
        if md5sum != self.getContentMd5():
          raise KeyError, 'Conversion cache key is compromised for %r' % cache_id
219
        return mime, data
220
    raise KeyError, 'Conversion cache key does not exists for %r' % cache_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
221 222

  security.declareProtected(Permissions.View, 'getConversionSize')
223
  def getConversionSize(self, **kw):
224
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
225
    """
226
    try:
227
      return len(self.getConversion(**kw))
228 229
    except KeyError:
      return 0
230

231 232 233 234
  def generateCacheId(self, **kw):
    """Generate proper cache id based on **kw.
    Function inspired from ERP5Type.Cache
    """
235
    return str(makeSortedTuple(kw)).translate(string.maketrans('', ''), '[]()<>\'", ')
236

237
  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentMd5')
238
  def updateContentMd5(self):
239 240
    """Update md5 checksum from the original file
    """
241 242 243
    data = self.getData()
    self._setContentMd5(md5.new(data).digest()) #reindex is useless

244 245 246 247 248 249 250
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
251

252 253 254
  # Declarative security
  security = ClassSecurityInfo()

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  ### 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':
273
        user_folder = getattr(self.getPortalObject(), 'acl_users', None)
274 275 276 277
        if user_folder is not None:
          try:
            if request.get('PUBLISHED', _MARKER) is _MARKER:
              # request['PUBLISHED'] is required by validate
278
              request['PUBLISHED'] = self
279 280 281
              has_published = False
            else:
              has_published = True
282 283 284 285 286 287 288
            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
289
            if not has_published:
290 291 292 293 294 295
              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']
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
          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)
322

323 324 325
    # 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
326 327 328 329
    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:
330 331
        # force user to login as specified in Web Section
        raise Unauthorized
332

333 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
  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

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

    if cache is not None:
369 370 371 372 373 374 375
      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
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
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:
399
      raise DocumentProxyError("Unable to find a proxied document")
400 401
    return proxied_document

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
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):
    """
428
    Returns the document Creation Date Index which is the creation
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    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.
    """
451
    method = self._getTypeBasedMethod('isUpdatable',
452 453 454 455 456
        fallback_script_id = 'Document_isUpdatable')
    return method()


class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, SnapshotMixin, UpdateMixIn):
Bartek Górny's avatar
Bartek Górny committed
457 458 459 460 461 462 463 464 465
  """
  """

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

468 469
  zope.interface.implements( interfaces.IDocument, )

Jean-Paul Smets's avatar
Jean-Paul Smets committed
470 471
  # Regular expressions
  href_parser = re.compile('<a[^>]*href=[\'"](.*?)[\'"]',re.IGNORECASE)
472 473
  body_parser = re.compile('<body[^>]*>(.*?)</body>', re.IGNORECASE + re.DOTALL)
  title_parser = re.compile('<title[^>]*>(.*?)</title>', re.IGNORECASE + re.DOTALL)
474
  base_parser = re.compile('<base[^>]*href=[\'"](.*?)[\'"][^>]*>', re.IGNORECASE + re.DOTALL)
475
  charset_parser = re.compile('charset="?([a-z0-9\-]+)', re.IGNORECASE)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
476

Bartek Górny's avatar
Bartek Górny committed
477 478 479 480 481 482 483 484 485 486 487
  # 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
488 489
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
490
                    , PropertySheet.Periodicity
491
                    , PropertySheet.Snapshot
Bartek Górny's avatar
Bartek Górny committed
492 493
                    )

494 495 496
  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
497

498
  ### Content processing methods
499
  security.declareProtected(Permissions.View, 'index_html')
500
  def index_html(self, REQUEST, RESPONSE, format=None, **kw):
501 502
    """
      We follow here the standard Zope API for files and images
Jean-Paul Smets's avatar
Jean-Paul Smets committed
503 504 505 506 507 508 509 510 511 512 513
      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.

514 515 516
      Should return appropriate format (calling convert
      if necessary) and set headers.

517
      format -- the format specied in the form of an extension
518
      string (ex. jpeg, html, text, txt, etc.)
519 520

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
522 523 524
      TODO:
      - implement guards API so that conversion to certain
        formats require certain permission
525
    """
526
    raise NotImplementedError
527

Bartek Górny's avatar
Bartek Górny committed
528 529
  security.declareProtected(Permissions.View, 'getSearchableText')
  def getSearchableText(self, md=None):
530
    """
531 532 533
      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.
534

535 536
      XXX-JPS - This method is nice. It should probably be moved to Base class
      searchable_property_list could become a standard class attribute.
537

538
      TODO (future): Make this property a per portal type property.
Bartek Górny's avatar
Bartek Górny committed
539 540
    """
    def getPropertyListOrValue(property):
541
      """
542
        we try to get a list, else we get value and convert to list
543
      """
544 545 546 547 548 549 550
      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
551 552 553 554
      val = self.getPropertyList(property)
      if val is None:
        val = self.getProperty(property)
        if val is not None and val != '':
555
          val = [str(val)]
556 557 558
        else:
          val = []
      else:
559
        val = [str(v) for v in list(val) if v is not None]
Bartek Górny's avatar
Bartek Górny committed
560
      return val
561

562
    searchable_text = reduce(add, map(lambda x: getPropertyListOrValue(x),
Bartek Górny's avatar
Bartek Górny committed
563
                                                self.searchable_property_list))
564
    searchable_text = ' '.join(searchable_text)
Bartek Górny's avatar
Bartek Górny committed
565 566 567
    return searchable_text

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

570 571 572 573 574 575 576
  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
577
  ### Relation getters
578
  security.declareProtected(Permissions.AccessContentsInformation, 'getSearchableReferenceList')
579
  def getSearchableReferenceList(self):
Bartek Górny's avatar
Bartek Górny committed
580
    """
581 582 583 584 585
      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.
    """
586
    text = self.getSearchableText() # XXX getSearchableText or asText ?
587
    regexp = self.portal_preferences.getPreferredDocumentReferenceRegularExpression()
Bartek Górny's avatar
Bartek Górny committed
588
    try:
589
      rx_search = re.compile(regexp)
Bartek Górny's avatar
Bartek Górny committed
590
    except TypeError: # no regexp in preference
591 592 593
      LOG('ERP5/Document/Document.getSearchableReferenceList', 0,
          'Document regular expression must be set in portal preferences')
      return ()
594 595 596 597 598 599 600 601 602 603 604 605
    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

606
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSuccessorValueList')
Bartek Górny's avatar
Bartek Górny committed
607 608
  def getImplicitSuccessorValueList(self):
    """
609 610 611
      Find objects which we are referencing (if our text_content contains
      references of other documents). The whole implementation is delegated to
      Base_getImplicitSuccessorValueList script.
612

613
      The implementation goes in 2 steps:
614 615

    - Step 1: extract with a regular expression
616
      a list of distionaries with various parameters such as
617 618 619 620 621
      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
622
      with appropriate parameters (and if possible build
623 624
      a complex query whenever this becomes available in
      portal catalog)
625

626 627
      The script is reponsible for calling getSearchableReferenceList
      so that it can use another approach if needed.
628

629 630
      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
631
    """
632
    tv = getTransactionalVariable(self) # XXX Performance improvement required
633 634 635 636 637 638
    cache_key = ('getImplicitSuccessorValueList', self.getPhysicalPath())
    try:
      return tv[cache_key]
    except KeyError:
      pass

639
    reference_list = [r[1] for r in self.getSearchableReferenceList()]
640
    result = self.Base_getImplicitSuccessorValueList(reference_list)
641 642
    tv[cache_key] = result
    return result
Bartek Górny's avatar
Bartek Górny committed
643

644
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitPredecessorValueList')
Bartek Górny's avatar
Bartek Górny committed
645 646 647
  def getImplicitPredecessorValueList(self):
    """
      This function tries to find document which are referencing us - by reference only, or
648
      by reference/language etc. Implementation is passed to
649
        Base_getImplicitPredecessorValueList
650 651 652 653 654 655 656 657

      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)
658
      ( if possible build  a complex query whenever
659 660 661 662
      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
663
    """
664
    tv = getTransactionalVariable(self) # XXX Performance improvement required
665 666 667 668 669 670
    cache_key = ('getImplicitPredecessorValueList', self.getPhysicalPath())
    try:
      return tv[cache_key]
    except KeyError:
      pass

671
    method = self._getTypeBasedMethod('getImplicitPredecessorValueList',
672
        fallback_script_id = 'Base_getImplicitPredecessorValueList')
673
    result = method()
674 675
    tv[cache_key] = result
    return result
Bartek Górny's avatar
Bartek Górny committed
676

677
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSimilarValueList')
Bartek Górny's avatar
Bartek Górny committed
678 679 680
  def getImplicitSimilarValueList(self):
    """
      Analyses content of documents to find out by the content which documents
681
      are similar. Not implemented yet.
Bartek Górny's avatar
Bartek Górny committed
682 683 684 685 686

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

687
  security.declareProtected(Permissions.AccessContentsInformation, 'getSimilarCloudValueList')
688
  def getSimilarCloudValueList(self, depth=0):
Bartek Górny's avatar
Bartek Górny committed
689 690
    """
      Returns all documents which are similar to us, directly or indirectly, and
691
      in both directions. In other words, it is a transitive closure of similar
Bartek Górny's avatar
Bartek Górny committed
692 693 694 695 696
      relation. Every document is returned in the latest version available.
    """
    lista = {}
    depth = int(depth)

697 698
    #gettername = 'get%sValueList' % convertToUpperCase(category)
    #relatedgettername = 'get%sRelatedValueList' % convertToUpperCase(category)
Bartek Górny's avatar
Bartek Górny committed
699

700
    def getRelatedList(ob, level=0):
Bartek Górny's avatar
Bartek Górny committed
701
      level += 1
702 703 704 705
      #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
706 707 708
      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
709 710
          if level != depth:
            getRelatedList(r, level)
Bartek Górny's avatar
Bartek Górny committed
711

712
    getRelatedList(self)
Bartek Górny's avatar
Bartek Górny committed
713 714 715
    lista_latest = {}
    for o in lista.keys():
      lista_latest[o.getLatestVersionValue()] = True # get latest versions avoiding duplicates again
716
    if lista_latest.has_key(self):
Bartek Górny's avatar
Bartek Górny committed
717
      lista_latest.pop(self) # remove this document
718 719
    if lista_latest.has_key(self.getLatestVersionValue()):
      # remove last version of document itself from related documents
720
      lista_latest.pop(self.getLatestVersionValue())
Bartek Górny's avatar
Bartek Górny committed
721 722 723

    return lista_latest.keys()

724
  ### Version and language getters - might be moved one day to a mixin class in base
Bartek Górny's avatar
Bartek Górny committed
725 726 727
  security.declareProtected(Permissions.View, 'getLatestVersionValue')
  def getLatestVersionValue(self, language=None):
    """
728 729
      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
730

731 732
      If language is provided, return the latest document
      in the language.
Bartek Górny's avatar
Bartek Górny committed
733

734 735 736
      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
737
    """
Bartek Górny's avatar
Bartek Górny committed
738 739
    if not self.getReference():
      return self
740
    catalog = getToolByName(self, 'portal_catalog', None)
741
    kw = dict(reference=self.getReference(), sort_on=(('version','descending'),))
742 743 744 745 746 747
    if language is not None: kw['language'] = language
    res = catalog(**kw)

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

748
    # if language was given return it (if there are any docs in this language)
749
    if language is not None:
750 751 752 753
      try:
        return res[0].getObject()
      except IndexError:
        return None
754 755 756 757 758 759 760
    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
761
            return in_original.getObject()
762
          else:
Bartek Górny's avatar
Bartek Górny committed
763
            return first.getObject() # this shouldn't happen in real life
764 765
        if ob.getLanguage() == user_language:
          # we found it in the user language
Bartek Górny's avatar
Bartek Górny committed
766
          return ob.getObject()
767 768 769
        if ob.getLanguage() == original_language:
          # this is in original language
          in_original = ob
770 771
    # this is the only doc in this version
    return self
Bartek Górny's avatar
Bartek Górny committed
772 773 774 775 776 777 778

  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
779
    catalog = getToolByName(self, 'portal_catalog', None)
780
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781
                   reference=self.getReference(),
782
                   sort_on=(('version', 'descending', 'SIGNED'),)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
783
                  )
784 785 786
    if version: kw['version'] = version
    if language: kw['language'] = language
    return catalog(**kw)
Bartek Górny's avatar
Bartek Górny committed
787

788
  security.declareProtected(Permissions.AccessContentsInformation, 'isVersionUnique')
Bartek Górny's avatar
Bartek Górny committed
789 790
  def isVersionUnique(self):
    """
791 792 793
      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
794
    """
795 796
    if not self.getReference():
      return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
797
    catalog = getToolByName(self, 'portal_catalog', None)
798
    self_count = catalog.unrestrictedCountResults(portal_type=self.getPortalDocumentTypeList(),
799 800 801
                                            reference=self.getReference(),
                                            version=self.getVersion(),
                                            language=self.getLanguage(),
802
                                            uid=self.getUid(),
803
                                            validation_state="!=cancelled"
804 805 806 807 808
                                            )[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
809
                                            validation_state="!=cancelled"
810 811 812 813
                                            )[0][0]
    # If self is not indexed yet, then if count == 1, version is not unique
    return count <= self_count

814 815 816 817
  security.declareProtected(Permissions.AccessContentsInformation, 'getRevision')
  def getRevision(self):
    """
      Returns the current revision by analysing the change log
818 819 820
      of the current object. The return value is a string
      in order to be consistent with the property sheet
      definition.
821
    """
822 823
    getInfoFor = getToolByName(self, 'portal_workflow').getInfoFor
    revision = len(getInfoFor(self, 'history', (), 'edit_workflow'))
824
    # XXX Also look at processing_status_workflow for compatibility.
825 826
    for history_item in getInfoFor(self, 'history', (),
                                   'processing_status_workflow'):
827 828 829
      if history_item.get('action') == 'edit':
        revision += 1
    return str(revision)
830 831 832 833 834 835 836

  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.
    """
837
    return map(str, range(1, 1 + int(self.getRevision())))
838

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
  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(),
865
                where_expression=SQLQuery("validation_state NOT IN ('cancelled', 'deleted')"))
866 867 868 869 870 871
      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
872
      document_list = list(document_list)
873
      document_list.sort(key=lambda x: x.getId())
Ivan Tyagov's avatar
Ivan Tyagov committed
874
      #LOG('[DMS] Existing documents for %s' %self.getSourceReference(), INFO, len(document_list))
875 876 877 878 879 880 881 882 883 884
      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():
885
          raise ValueError, "[DMS] Ingestion may not change the type of an existing document"
886 887
        elif not _checkPermission(Permissions.ModifyPortalContent, existing_document):
          self.setUniqueReference(suffix='unauthorized')
888
          raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % existing_document.getId()
889 890 891
        else:
          update_kw = {}
          for k in self.propertyIds():
892
            if k not in FIXED_PROPERTY_IDS and self.hasProperty(k):
893 894 895 896 897 898
              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

899
  security.declareProtected(Permissions.AccessContentsInformation, 'getLanguageList')
Bartek Górny's avatar
Bartek Górny committed
900 901 902 903 904
  def getLanguageList(self, version=None):
    """
      Returns a list of languages which this document is available in
      for the current user.
    """
905
    if not self.getReference(): return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
906
    catalog = getToolByName(self, 'portal_catalog', None)
907
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
908
                           reference=self.getReference(),
909 910 911 912
                           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
913

914
  security.declareProtected(Permissions.AccessContentsInformation, 'getOriginalLanguage')
Bartek Górny's avatar
Bartek Górny committed
915 916 917
  def getOriginalLanguage(self):
    """
      Returns the original language of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
918 919

      XXX-JPS not implemented yet ?
Bartek Górny's avatar
Bartek Górny committed
920 921 922 923 924
    """
    # 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?
925 926
    reference = self.getReference()
    if not reference:
927
      return
928 929 930 931
    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
932 933 934 935 936 937

  ### 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')
938
  def getPropertyDictFromUserLogin(self, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
939 940 941 942 943
    """
      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:
944 945
      user_login = str(getSecurityManager().getUser())
    method = self._getTypeBasedMethod('getPropertyDictFromUserLogin',
Bartek Górny's avatar
Bartek Górny committed
946
        fallback_script_id='Document_getPropertyDictFromUserLogin')
947
    return method(user_login)
Bartek Górny's avatar
Bartek Górny committed
948 949 950 951 952 953 954

  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
    """
955
    if not self.hasBaseData():
956
      raise NotConvertedError
957
    method = self._getTypeBasedMethod('getPropertyDictFromContent',
Bartek Górny's avatar
Bartek Górny committed
958
        fallback_script_id='Document_getPropertyDictFromContent')
959
    return method()
Bartek Górny's avatar
Bartek Górny committed
960 961 962 963 964 965 966 967 968 969 970 971 972 973

  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).
974 975 976 977 978

      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
979 980 981 982 983 984
    """
    if hasattr(self, '_backup_input'):
      return getattr(self, '_backup_input')
    kw = {}
    for id in self.propertyIds():
      # We should not consider file data
985 986
      if id not in ('data', 'categories_list', 'uid', 'id',
                    'text_content', 'base_data',) \
987
            and self.hasProperty(id):
Bartek Górny's avatar
Bartek Górny committed
988 989 990 991 992 993
        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

994 995 996 997 998 999
  security.declareProtected(Permissions.AccessContentsInformation, 'getStandardFileName')
  def getStandardFileName(self):
    """
    Returns the document coordinates as a standard file name. This
    method is the reverse of getPropertyDictFromFileName.
    """
1000
    method = self._getTypeBasedMethod('getStandardFileName',
1001 1002
        fallback_script_id = 'Document_getStandardFileName')
    return method()
1003

Bartek Górny's avatar
Bartek Górny committed
1004 1005
  ### Metadata disovery and ingestion methods
  security.declareProtected(Permissions.ModifyPortalContent, 'discoverMetadata')
1006
  def discoverMetadata(self, file_name=None, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
1007
    """
1008 1009
      This is the main metadata discovery function - controls the process
      of discovering data from various sources. The discovery itself is
1010 1011 1012
      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
1013

1014
      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
1015

1016
      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
1017
                   currently logged in, then we'll get him from session
1018
    """
Bartek Górny's avatar
Bartek Górny committed
1019
    # Preference is made of a sequence of 'user_login', 'content', 'file_name', 'input'
1020
    method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList',
Bartek Górny's avatar
Bartek Górny committed
1021
        fallback_script_id = 'Document_getPreferredDocumentMetadataDiscoveryOrderList')
1022
    order_list = list(method())
1023
    order_list.reverse()
1024
    # build a dictionary according to the order
Bartek Górny's avatar
Bartek Górny committed
1025
    kw = {}
1026
    for order_id in order_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1027
      result = None
Bartek Górny's avatar
Bartek Górny committed
1028 1029
      if order_id not in VALID_ORDER_KEY_LIST:
        # Prevent security attack or bad preferences
1030
        raise AttributeError, "%s is not in valid order key list" % order_id
Bartek Górny's avatar
Bartek Górny committed
1031 1032 1033
      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
1034 1035
        if file_name is not None:
          result = method(file_name)
Bartek Górny's avatar
Bartek Górny committed
1036
      elif order_id == 'user_login':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1037 1038
        if user_login is not None:
          result = method(user_login)
Bartek Górny's avatar
Bartek Górny committed
1039 1040
      else:
        result = method()
1041 1042
      if result is not None:
        kw.update(result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1043

1044 1045 1046
    if file_name is not None:
      # filename is often undefined....
      kw['source_reference'] = file_name
1047
    # Prepare the content edit parameters - portal_type should not be changed
1048 1049 1050 1051
    kw.pop('portal_type', None)
    # Try not to invoke an automatic transition here
    self._edit(**kw)
    # Finish ingestion by calling method
1052
    self.finishIngestion()
1053
    self.reindexObject()
1054 1055
    # Revision merge is tightly coupled
    # to metadata discovery - refer to the documentation of mergeRevision method
1056 1057
    merged_doc = self.mergeRevision()
    merged_doc.reindexObject()
1058
    return merged_doc
Bartek Górny's avatar
Bartek Górny committed
1059 1060 1061 1062

  security.declareProtected(Permissions.ModifyPortalContent, 'finishIngestion')
  def finishIngestion(self):
    """
1063 1064 1065
      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
1066
    """
1067 1068
    method = self._getTypeBasedMethod('finishIngestion', fallback_script_id='Document_finishIngestion')
    return method()
Bartek Górny's avatar
Bartek Górny committed
1069

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
  # 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

1080 1081 1082
      Default implementation returns an empty string (html, text)
      or raises an error.

1083 1084 1085 1086
      TODO:
      - implement guards API so that conversion to certain
        formats require certain permission
    """
1087
    if format == 'html':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1088
      return 'text/html', '' # XXX - Why ?
1089
    if format in ('text', 'txt'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1090
      return 'text/plain', '' # XXX - Why ?
1091
    raise NotImplementedError
1092

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1093 1094 1095 1096 1097 1098 1099
  def getConvertedSize(self, format):
    """
      Returns the size of the converted document
    """
    format, data = self.convert(format)
    return len(data)

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  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)

1113
  security.declareProtected(Permissions.View, 'asText')
1114
  def asText(self, **kw):
1115 1116 1117
    """
      Converts the content of the document to a textual representation.
    """
1118 1119
    kw['format'] = 'txt'
    mime, data = self.convert(**kw)
1120
    return str(data)
1121

1122
  security.declareProtected(Permissions.View, 'asEntireHTML')
1123
  def asEntireHTML(self, **kw):
1124 1125
    """
      Returns a complete HTML representation of the document
1126 1127 1128
      (with body tags, etc.). Adds if necessary a base
      tag so that the document can be displayed in an iframe
      or standalone.
1129 1130

      Actual conversion is delegated to _asHTML
1131
    """
1132
    html = self._asHTML(**kw)
1133 1134 1135 1136 1137 1138 1139
    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)
1140
      self.setConversion(html, mime='text/html', format='base-html')
1141
    return html
1142

1143
  security.declarePrivate('_asHTML')
1144
  def _asHTML(self, **kw):
1145 1146 1147 1148
    """
      A private method which converts to HTML. This method
      is the one to override in subclasses.
    """
1149
    if not self.hasBaseData():
1150
      raise ConversionError('This document has not been processed yet.')
1151
    try:
1152
      # FIXME: no substitution may occur in this case.
1153 1154
      mime, data = self.getConversion(format='base-html')
      return data
1155 1156 1157 1158
    except KeyError:
      kw['format'] = 'html'
      mime, html = self.convert(**kw)
      return html
1159

1160
  security.declareProtected(Permissions.View, 'asStrippedHTML')
1161
  def asStrippedHTML(self, **kw):
1162
    """
1163 1164
      Returns a stripped HTML representation of the document
      (without html and body tags, etc.) which can be used to inline
1165 1166
      a preview of the document.
    """
1167
    if not self.hasBaseData():
1168
      return ''
1169
    try:
1170
      # FIXME: no substitution may occur in this case.
1171 1172
      mime, data = self.getConversion(format='stripped-html')
      return data
1173 1174 1175 1176
    except KeyError:
      kw['format'] = 'html'
      mime, html = self.convert(**kw)
      return self._stripHTML(str(html))
1177

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  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)

1189 1190 1191 1192 1193
  def _stripHTML(self, html, charset=None):
    """
      A private method which can be reused by subclasses
      to strip HTML content
    """
1194 1195
    body_list = re.findall(self.body_parser, str(html))
    if len(body_list):
1196 1197 1198 1199
      stripped_html = body_list[0]
    else:
      stripped_html = html
    # find charset and convert to utf-8
1200
    charset_list = self.charset_parser.findall(str(html)) # XXX - Not efficient if this
1201
                                         # is datastream instance but hard to do better
1202 1203 1204
    if charset and not charset_list:
      # Use optional parameter is we can not find encoding in HTML
      charset_list = [charset]
1205
    if charset_list and charset_list[0] not in ('utf-8', 'UTF-8'):
1206
      try:
1207
        stripped_html = unicode(str(stripped_html),
1208
                                charset_list[0]).encode('utf-8')
Nicolas Delaby's avatar
Nicolas Delaby committed
1209
      except (UnicodeDecodeError, LookupError):
1210
        return str(stripped_html)
1211
    return stripped_html
1212

1213

1214 1215 1216 1217 1218 1219 1220 1221 1222
  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
1223
    html = self.asEntireHTML()
1224 1225 1226 1227 1228
    if not html: return result
    title_list = re.findall(self.title_parser, str(html))
    if title_list:
      result['title'] = title_list[0]
    return result
1229 1230

  # Base format support
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1231
  security.declareProtected(Permissions.ModifyPortalContent, 'convertToBaseFormat')
1232
  def convertToBaseFormat(self, **kw):
1233
    """
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
      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.)
1249 1250
    """
    try:
1251
      message = self._convertToBaseFormat() # Call implemetation method
1252
      self.clearConversionCache() # Conversion cache is now invalid
1253 1254 1255 1256 1257 1258 1259
      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
1260

1261
  def _convertToBaseFormat(self):
1262 1263
    """
    """
1264
    raise NotImplementedError
1265

1266 1267
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
1268 1269 1270 1271 1272
  def isSupportBaseDataConversion(self):
    """
    """
    return False

1273
  def convertFile(self, **kw):
1274 1275 1276 1277 1278
    """
    Workflow transition invoked when conversion occurs.
    """
  convertFile = WorkflowMethod(convertFile)

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
  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
1290
    if method is not None:
1291 1292 1293 1294
      return method()
    else:
      return {}

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  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

1307
  # Transformation API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1308
  security.declareProtected(Permissions.ModifyPortalContent, 'populateContent')
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  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
1321 1322 1323 1324 1325
    try:
      method = self._getTypeBasedMethod('populateContent')
    except KeyError, AttributeError:
      method = None
    if method is not None: method()
1326 1327

  # Crawling API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1328
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentURLList')
1329 1330 1331
  def getContentURLList(self):
    """
      Returns a list of URLs referenced by the content of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1332 1333 1334 1335 1336 1337
      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.
1338
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1339 1340
    html_content = self.asStrippedHTML()
    return re.findall(self.href_parser, str(html_content))
1341

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1342
  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentFromURL')
1343
  def updateContentFromURL(self, repeat=MAX_REPEAT, crawling_depth=0):
1344 1345
    """
      Download and update content of this document from its source URL.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1346 1347
      Implementation is handled by ContributionTool.
    """
1348
    self.portal_contributions.updateContentFromURL(self, repeat=repeat, crawling_depth=crawling_depth)
1349

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1350 1351
  security.declareProtected(Permissions.ModifyPortalContent, 'crawlContent')
  def crawlContent(self):
1352
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1353 1354 1355 1356
      Initialises the crawling process on the current document.
    """
    self.portal_contributions.crawlContent(self)

1357 1358 1359 1360 1361 1362
  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
1363
      a difference between URLs which return an index (ex. the
1364 1365 1366 1367 1368 1369 1370 1371 1372
      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
1373 1374 1375 1376 1377 1378 1379 1380
  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
1381
    if len(base_url_list):
1382
      if base_url_list[-1] and base_url_list[-1].find('.') > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1383
        # Cut the trailing part in http://www.some.site/at/trailing.html
1384
        # but not in http://www.some.site/at
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1385
        base_url = '/'.join(base_url_list[:-1])
1386
    return base_url
1387 1388 1389

  security.declareProtected(Permissions.ModifyPortalContent, '_setBaseData')
  def _setBaseData(self, data):
1390 1391 1392 1393 1394 1395 1396 1397 1398
    """
      XXX - it is really wrong to put this method here since not
      all documents are subclasses of "File". Instead, there should
      be a interface for all classes which can convert their data
      to a base format.
    """
    if not isinstance(data, Pdata) and data is not None:
      file = cStringIO.StringIO(data)
      data, size = self._read_data(file)
1399
    self._baseSetBaseData(data)
1400 1401 1402 1403 1404

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getBaseData')
  def getBaseData(self, default=None):
    """return BaseData as str."""
1405 1406 1407 1408 1409
    base_data = self._baseGetBaseData()
    if base_data is None:
      return None
    else:
      return str(base_data)
1410 1411 1412

  security.declareProtected(Permissions.ModifyPortalContent, '_setData')
  def _setData(self, data):
1413 1414 1415 1416 1417 1418
    """
      XXX - it is really wrong to put this method here since not
      all documents are subclasses of "File". Instead, there should
      be a interface for all classes which can act as a File.
    """
    size = None
1419 1420 1421 1422 1423
    # update_data use len(data) when size is None, which breaks this method.
    # define size = 0 will prevent len be use and keep the consistency of 
    # getData() and setData()
    if data is None:
      size = 0
1424 1425 1426
    if not isinstance(data, Pdata) and data is not None:
      file = cStringIO.StringIO(data)
      data, size = self._read_data(file)
Julien Muchembled's avatar
typo  
Julien Muchembled committed
1427
    if getattr(self, 'update_data', None) is not None:
1428 1429
      # We call this method to make sure size is set and caches reset
      self.update_data(data, size=size)
1430 1431 1432 1433 1434 1435
    else:
      self._baseSetData(data) # XXX - It would be better to always use this accessor
      self.size=size # Using accessor or caching method would be better
      self.ZCacheable_invalidate()
      self.ZCacheable_set(None)
      self.http__refreshEtag()
1436 1437 1438 1439

  security.declareProtected(Permissions.AccessContentsInformation, 'getData')
  def getData(self, default=None):
    """return Data as str."""
1440 1441 1442 1443 1444
    data = self._baseGetData()
    if data is None:
      return None
    else:
      return str(data)