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

Nicolas Delaby's avatar
Nicolas Delaby committed
30
import re, sys, os
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 Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
37
from Products.ERP5Type.Globals import get_request
38
from Products.CMFCore.utils import getToolByName, _checkPermission
Nicolas Dumazet's avatar
Nicolas Dumazet committed
39
from Products.ERP5Type import Permissions, PropertySheet, interfaces
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40
from Products.ERP5Type.XMLObject import XMLObject
Nicolas Delaby's avatar
Nicolas Delaby committed
41 42
from Products.ERP5Type.DateUtils import convertDateToHour,\
                                number_of_hours_in_day, number_of_hours_in_year
43
from Products.ERP5Type.Utils import convertToUpperCase, fill_args_from_request
44
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
45
from Products.ERP5Type.ExtensibleTraversable import ExtensibleTraversableMixIn
46
from Products.ERP5Type.Cache import getReadOnlyTransactionCache
47
from Products.ERP5.Document.Url import UrlMixIn
48
from Products.ERP5.Tool.ContributionTool import MAX_REPEAT
49
from Products.ERP5Type.UnrestrictedMethod import unrestricted_apply
50
from Products.ZSQLCatalog.SQLCatalog import SQLQuery
51
from AccessControl import Unauthorized
52
import zope.interface
53
from Products.PythonScripts.Utility import allow_class
Nicolas Delaby's avatar
Nicolas Delaby committed
54 55
import tempfile
from subprocess import Popen, PIPE
56

57 58
# Mixin Import
from Products.ERP5.mixin.cached_convertable import CachedConvertableMixin
Nicolas Delaby's avatar
Nicolas Delaby committed
59 60
from Products.ERP5.mixin.text_convertable import TextConvertableMixin
from Products.ERP5.mixin.downloadable import DownloadableMixin
61
from Products.ERP5.mixin.document import DocumentMixin
62
from Products.ERP5.mixin.extensible_traversable import DocumentExtensibleTraversableMixin
63
from Products.ERP5.mixin.crawable import CrawableMixin
64

Bartek Górny's avatar
Bartek Górny committed
65
_MARKER = []
66
VALID_ORDER_KEY_LIST = ('user_login', 'content', 'file_name', 'input')
67

68
# these property ids are unchangable
Nicolas Delaby's avatar
Nicolas Delaby committed
69
FIXED_PROPERTY_IDS = ('id', 'uid', 'rid', 'sid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
70

71
# XXX: move to an easier to configure place (System Preference ?)
72 73 74 75 76
VALID_TEXT_FORMAT_LIST = ('text', 'txt', 'html', 'base_html',
                          'stripped-html')

VALID_IMAGE_FORMAT_LIST = ('jpg', 'jpeg', 'png', 'gif', 'pnm', 'ppm', 'tiff')

77 78 79
DEFAULT_DISPLAY_ID_LIST = ('nano', 'micro', 'thumbnail',
                            'xsmall', 'small', 'medium',
                            'large', 'large', 'xlarge',)
80 81
# default image quality
DEFAULT_IMAGE_QUALITY = 75
82

Ivan Tyagov's avatar
Ivan Tyagov committed
83 84
DEFAULT_CONTENT_TYPE = 'text/html'

85
class ConversionError(Exception):pass
Bartek Górny's avatar
Bartek Górny committed
86

87 88
class DocumentProxyError(Exception):pass

89
class NotConvertedError(Exception):pass
90
allow_class(NotConvertedError)
91

92
class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixIn, CachedConvertableMixin,
93
               CrawableMixin, TextConvertableMixin, DownloadableMixin, DocumentMixin):
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  """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.

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

  External Documents may be downloaded once or updated at regular interval.
  The later can be useful to update the content of an external source.
  Previous versions may be stored 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.

  There are currently two types of Document subclasses:

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

  * TextDocument for text based documents. TextDocument has subclasses such
    as Wiki to implement specific methods. 
    TextDocument itself has a subclass (XSLTDocument) which provides
    XSLT based analysis and transformation of XML content based on XSLT
    templates. 

  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.

  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)
  (4) other possible actions to finalise the ingestion (ex. by assigning
      a reference)

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

  Metadata can be drawn from various sources:

  input      -   data supplied with http request or set on the object during (2) (e.g.
                 discovered from email text)
  file_name  -   data which might be encoded in file name
  user_login -   information about user who is contributing the file
  content    -   data which might be derived from document content

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

  Methods for discovering metadata are:

    getPropertyDictFromInput
    getPropertyDictFromFileName
    getPropertyDictFromUserLogin
    getPropertyDictFromContent

  Methods for processing content are implemented either in Document class
  or in Base class:

    getSearchableReferenceList (Base)
    getSearchableText (Base)
    index_html (overriden in Document subclasses)

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

  document.getSearchableReferenceList() returns
    [
     {'reference':' INV-12367'},
     {'reference': 'INV-1112', 'version':'012}', 
     {'reference': 'AB-CC-DRK', 'version':'011', 'language': 'en'}
    ]

  The Document class behaviour can be extended / customized through scripts
  (which are type-based so can be adjusted per portal type).

  * Document_getPropertyDictFromUserLogin - finds a user (by user_login or
    from session) and returns properties which should be set on the document

  * Document_getPropertyDictFromContent - analyzes document content and returns
    properties which should be set on the document

  * Base_getImplicitSuccessorValueList - finds appropriate all documents
    referenced in the current content

  * Base_getImplicitPredecessorValueList - finds document predecessors based on
    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)

  * Document_getNewRevision - calculates revision number which should be set
    on this document. Implementation depends on revision numbering policy which
    can be very different. Interaction workflow should call setNewRevision method.

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

  Subcontent: documents may include subcontent (files, images, etc.)
  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.

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

  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.

    conversion API - not same as document - XXX BAD
    XXX make multiple interfaces

  TODO:
    - move all implementation bits to MixIn classes
    - in the end, Document class should have zero code
      and only serve as a quick and easy way to create 
      new types of documents (one could even consider 
      that this class should be trashed)
    - 
Bartek Górny's avatar
Bartek Górny committed
255 256 257 258 259
  """

  meta_type = 'ERP5 Document'
  portal_type = 'Document'
  add_permission = Permissions.AddPortalContent
260
  isDocument = ConstantGetter('isDocument', value=True)
261
  __dav_collection__=0
Bartek Górny's avatar
Bartek Górny committed
262

263 264 265 266 267 268 269
  zope.interface.implements(interfaces.IConvertable,
                            interfaces.ITextConvertable,
                            interfaces.IHtmlConvertable,
                            interfaces.ICachedConvertable,
                            interfaces.IVersionable,
                            interfaces.IDownloadable,
                            interfaces.ICrawlable,
270
                            interfaces.IDocument
271
                           )
272

Jean-Paul Smets's avatar
Jean-Paul Smets committed
273 274
  # Regular expressions
  href_parser = re.compile('<a[^>]*href=[\'"](.*?)[\'"]',re.IGNORECASE)
275 276
  body_parser = re.compile('<body[^>]*>(.*?)</body>', re.IGNORECASE + re.DOTALL)
  title_parser = re.compile('<title[^>]*>(.*?)</title>', re.IGNORECASE + re.DOTALL)
277
  base_parser = re.compile('<base[^>]*href=[\'"](.*?)[\'"][^>]*>', re.IGNORECASE + re.DOTALL)
278
  charset_parser = re.compile('(?P<keyword>charset="?)(?P<charset>[a-z0-9\-]+)', re.IGNORECASE)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
279

Bartek Górny's avatar
Bartek Górny committed
280 281 282 283 284 285 286 287 288 289 290
  # 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
291 292
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
293
                    , PropertySheet.Periodicity
Bartek Górny's avatar
Bartek Górny committed
294 295
                    )

Nicolas Delaby's avatar
Nicolas Delaby committed
296 297
  index_html = DownloadableMixin.index_html

298 299 300 301 302 303 304
  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
305
  ### Relation getters
306
  security.declareProtected(Permissions.AccessContentsInformation, 'getSearchableReferenceList')
307
  def getSearchableReferenceList(self):
Bartek Górny's avatar
Bartek Górny committed
308
    """
309 310 311 312 313
      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.
    """
314
    text = self.getSearchableText() # XXX getSearchableText or asText ?
315
    regexp = self.portal_preferences.getPreferredDocumentReferenceRegularExpression()
Bartek Górny's avatar
Bartek Górny committed
316
    try:
317
      rx_search = re.compile(regexp)
Bartek Górny's avatar
Bartek Górny committed
318
    except TypeError: # no regexp in preference
319 320 321
      LOG('ERP5/Document/Document.getSearchableReferenceList', 0,
          'Document regular expression must be set in portal preferences')
      return ()
322 323 324 325 326 327 328 329 330 331 332 333
    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

334
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSuccessorValueList')
Bartek Górny's avatar
Bartek Górny committed
335 336
  def getImplicitSuccessorValueList(self):
    """
337 338 339
      Find objects which we are referencing (if our text_content contains
      references of other documents). The whole implementation is delegated to
      Base_getImplicitSuccessorValueList script.
340

341
      The implementation goes in 2 steps:
342 343

    - Step 1: extract with a regular expression
344
      a list of distionaries with various parameters such as
345 346 347 348 349
      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
350
      with appropriate parameters (and if possible build
351 352
      a complex query whenever this becomes available in
      portal catalog)
353

354 355
      The script is reponsible for calling getSearchableReferenceList
      so that it can use another approach if needed.
356

357 358
      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
359
    """
360
    tv = getTransactionalVariable(self) # XXX Performance improvement required
361 362 363 364 365 366
    cache_key = ('getImplicitSuccessorValueList', self.getPhysicalPath())
    try:
      return tv[cache_key]
    except KeyError:
      pass

367
    reference_list = [r[1] for r in self.getSearchableReferenceList()]
368
    result = self.Base_getImplicitSuccessorValueList(reference_list)
369 370
    tv[cache_key] = result
    return result
Bartek Górny's avatar
Bartek Górny committed
371

372
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitPredecessorValueList')
Bartek Górny's avatar
Bartek Górny committed
373 374 375
  def getImplicitPredecessorValueList(self):
    """
      This function tries to find document which are referencing us - by reference only, or
376
      by reference/language etc. Implementation is passed to
377
        Base_getImplicitPredecessorValueList
378 379 380 381 382 383 384 385

      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)
386
      ( if possible build  a complex query whenever
387 388 389 390
      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
391
    """
392
    return self._getTypeBasedMethod('getImplicitPredecessorValueList')()
Bartek Górny's avatar
Bartek Górny committed
393

394
  security.declareProtected(Permissions.AccessContentsInformation, 'getImplicitSimilarValueList')
Bartek Górny's avatar
Bartek Górny committed
395 396 397
  def getImplicitSimilarValueList(self):
    """
      Analyses content of documents to find out by the content which documents
398
      are similar. Not implemented yet.
Bartek Górny's avatar
Bartek Górny committed
399 400 401 402 403

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

404
  security.declareProtected(Permissions.AccessContentsInformation, 'getSimilarCloudValueList')
405
  def getSimilarCloudValueList(self, depth=0):
Bartek Górny's avatar
Bartek Górny committed
406 407
    """
      Returns all documents which are similar to us, directly or indirectly, and
408
      in both directions. In other words, it is a transitive closure of similar
Bartek Górny's avatar
Bartek Górny committed
409 410 411 412 413
      relation. Every document is returned in the latest version available.
    """
    lista = {}
    depth = int(depth)

414 415
    #gettername = 'get%sValueList' % convertToUpperCase(category)
    #relatedgettername = 'get%sRelatedValueList' % convertToUpperCase(category)
Bartek Górny's avatar
Bartek Górny committed
416

417
    def getRelatedList(ob, level=0):
Bartek Górny's avatar
Bartek Górny committed
418
      level += 1
419 420 421 422
      #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
423 424 425
      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
426 427
          if level != depth:
            getRelatedList(r, level)
Bartek Górny's avatar
Bartek Górny committed
428

429
    getRelatedList(self)
Bartek Górny's avatar
Bartek Górny committed
430 431 432
    lista_latest = {}
    for o in lista.keys():
      lista_latest[o.getLatestVersionValue()] = True # get latest versions avoiding duplicates again
433
    if lista_latest.has_key(self):
Bartek Górny's avatar
Bartek Górny committed
434
      lista_latest.pop(self) # remove this document
435 436
    if lista_latest.has_key(self.getLatestVersionValue()):
      # remove last version of document itself from related documents
437
      lista_latest.pop(self.getLatestVersionValue())
Bartek Górny's avatar
Bartek Górny committed
438 439 440

    return lista_latest.keys()

441
  ### Version and language getters - might be moved one day to a mixin class in base
Bartek Górny's avatar
Bartek Górny committed
442 443 444
  security.declareProtected(Permissions.View, 'getLatestVersionValue')
  def getLatestVersionValue(self, language=None):
    """
445 446
      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
447

448 449
      If language is provided, return the latest document
      in the language.
Bartek Górny's avatar
Bartek Górny committed
450

451 452 453
      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
454
    """
Bartek Górny's avatar
Bartek Górny committed
455 456
    if not self.getReference():
      return self
Nicolas Delaby's avatar
Nicolas Delaby committed
457
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
458
    kw = dict(reference=self.getReference(), sort_on=(('version','descending'),))
459 460
    if language is not None:
      kw['language'] = language
461
    result_list = catalog(**kw)
462 463 464 465

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

466
    # if language was given return it (if there are any docs in this language)
467
    if language is not None:
468
      try:
Nicolas Delaby's avatar
Nicolas Delaby committed
469
        return result_list[0].getObject()
470 471
      except IndexError:
        return None
472
    else:
Nicolas Delaby's avatar
Nicolas Delaby committed
473
      first = result_list[0].getObject()
474
      in_original = None
Nicolas Delaby's avatar
Nicolas Delaby committed
475 476 477
      for record in result_list:
        document = record.getObject()
        if document.getVersion() != first.getVersion():
478 479
          # we are out of the latest version - return in_original or first
          if in_original is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
480
            return in_original
481
          else:
Nicolas Delaby's avatar
Nicolas Delaby committed
482 483
            return first # this shouldn't happen in real life
        if document.getLanguage() == user_language:
484
          # we found it in the user language
Nicolas Delaby's avatar
Nicolas Delaby committed
485 486
          return document
        if document.getLanguage() == original_language:
487
          # this is in original language
Nicolas Delaby's avatar
Nicolas Delaby committed
488
          in_original = document
489 490
    # this is the only doc in this version
    return self
Bartek Górny's avatar
Bartek Górny committed
491 492 493 494 495 496 497

  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.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
498
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
499
    kw = dict(portal_type=self.getPortalType(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
500
                   reference=self.getReference(),
501
                   sort_on=(('version', 'descending', 'SIGNED'),)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
502
                  )
Jérome Perrin's avatar
Jérome Perrin committed
503 504 505 506
    if version:
      kw['version'] = version
    if language:
      kw['language'] = language
507
    return catalog(**kw)
Bartek Górny's avatar
Bartek Górny committed
508

509
  security.declareProtected(Permissions.AccessContentsInformation, 'isVersionUnique')
Bartek Górny's avatar
Bartek Górny committed
510 511
  def isVersionUnique(self):
    """
512 513 514
      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
515
    """
516
    if not self.getReference():
Jérome Perrin's avatar
Jérome Perrin committed
517
      return True
Nicolas Delaby's avatar
Nicolas Delaby committed
518
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
519
    self_count = catalog.unrestrictedCountResults(portal_type=self.getPortalDocumentTypeList(),
520 521 522
                                            reference=self.getReference(),
                                            version=self.getVersion(),
                                            language=self.getLanguage(),
523
                                            uid=self.getUid(),
524
                                            validation_state="!=cancelled"
525 526 527 528 529
                                            )[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
530
                                            validation_state="!=cancelled"
531 532 533 534
                                            )[0][0]
    # If self is not indexed yet, then if count == 1, version is not unique
    return count <= self_count

535 536 537 538
  security.declareProtected(Permissions.AccessContentsInformation, 'getRevision')
  def getRevision(self):
    """
      Returns the current revision by analysing the change log
539 540 541
      of the current object. The return value is a string
      in order to be consistent with the property sheet
      definition.
542
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
543 544
    getInfoFor = getToolByName(self.getPortalObject(),
                                                  'portal_workflow').getInfoFor
545
    revision = len(getInfoFor(self, 'history', (), 'edit_workflow'))
546
    # XXX Also look at processing_status_workflow for compatibility.
Nicolas Delaby's avatar
Nicolas Delaby committed
547 548 549
    revision += len([history_item for history_item in\
                 getInfoFor(self, 'history', (), 'processing_status_workflow')\
                 if history_item.get('action') == 'edit'])
550
    return str(revision)
551 552 553 554 555 556 557

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

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  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
Nicolas Delaby's avatar
Nicolas Delaby committed
581
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
582 583 584 585
    if self.getReference():
      # Find all document with same (reference, version, language)
      kw = dict(portal_type=self.getPortalDocumentTypeList(),
                reference=self.getReference(),
586
                where_expression=SQLQuery("validation_state NOT IN ('cancelled', 'deleted')"))
Jérome Perrin's avatar
Jérome Perrin committed
587 588 589 590
      if self.getVersion():
        kw['version'] = self.getVersion()
      if self.getLanguage():
        kw['language'] = self.getLanguage()
591 592 593 594
      document_list = catalog.unrestrictedSearchResults(**kw)
      existing_document = None
      # Select the first one which is not self and which
      # shares the same coordinates
595
      document_list = list(document_list)
596
      document_list.sort(key=lambda x: x.getId())
597 598 599 600 601 602 603 604 605 606
      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():
607
          raise ValueError, "[DMS] Ingestion may not change the type of an existing document"
608
        elif not _checkPermission(Permissions.ModifyPortalContent, existing_document):
609
          raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % existing_document.getId()
610 611 612
        else:
          update_kw = {}
          for k in self.propertyIds():
613
            if k not in FIXED_PROPERTY_IDS and self.hasProperty(k):
614 615 616 617 618 619
              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

620
  security.declareProtected(Permissions.AccessContentsInformation, 'getLanguageList')
Bartek Górny's avatar
Bartek Górny committed
621 622 623 624 625
  def getLanguageList(self, version=None):
    """
      Returns a list of languages which this document is available in
      for the current user.
    """
626
    if not self.getReference(): return []
Nicolas Delaby's avatar
Nicolas Delaby committed
627
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
628
    kw = dict(portal_type=self.getPortalType(),
Jérome Perrin's avatar
Jérome Perrin committed
629 630
              reference=self.getReference(),
              group_by=('language',))
631 632 633
    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
634

635
  security.declareProtected(Permissions.AccessContentsInformation, 'getOriginalLanguage')
Bartek Górny's avatar
Bartek Górny committed
636 637 638
  def getOriginalLanguage(self):
    """
      Returns the original language of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
639 640

      XXX-JPS not implemented yet ?
Bartek Górny's avatar
Bartek Górny committed
641 642 643 644 645
    """
    # 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?
646 647
    reference = self.getReference()
    if not reference:
648
      return
Nicolas Delaby's avatar
Nicolas Delaby committed
649
    catalog = getToolByName(self.getPortalObject(), 'portal_catalog')
650 651 652
    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
653 654 655 656 657 658

  ### 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')
659
  def getPropertyDictFromUserLogin(self, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
660 661 662 663 664
    """
      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:
665 666
      user_login = str(getSecurityManager().getUser())
    method = self._getTypeBasedMethod('getPropertyDictFromUserLogin',
Bartek Górny's avatar
Bartek Górny committed
667
        fallback_script_id='Document_getPropertyDictFromUserLogin')
668
    return method(user_login)
Bartek Górny's avatar
Bartek Górny committed
669 670 671 672 673 674 675

  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
    """
676 677 678 679 680
    # accesss data through convert
    mime, content = self.convert(None)
    if not content:
       # if document is empty, we will not find anything in its content
      return {}
681
    method = self._getTypeBasedMethod('getPropertyDictFromContent',
Bartek Górny's avatar
Bartek Górny committed
682
        fallback_script_id='Document_getPropertyDictFromContent')
683
    return method()
Bartek Górny's avatar
Bartek Górny committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697

  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).
698 699 700 701 702

      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
703
    """
704 705 706
    kw = getattr(self, '_backup_input', {})
    if kw:
      return kw
Bartek Górny's avatar
Bartek Górny committed
707 708
    for id in self.propertyIds():
      # We should not consider file data
709 710
      if id not in ('data', 'categories_list', 'uid', 'id',
                    'text_content', 'base_data',) \
711
            and self.hasProperty(id):
Bartek Górny's avatar
Bartek Górny committed
712 713 714 715 716 717 718 719
        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

  ### Metadata disovery and ingestion methods
  security.declareProtected(Permissions.ModifyPortalContent, 'discoverMetadata')
720
  def discoverMetadata(self, file_name=None, user_login=None):
Bartek Górny's avatar
Bartek Górny committed
721
    """
722 723
      This is the main metadata discovery function - controls the process
      of discovering data from various sources. The discovery itself is
724 725 726
      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
727

728
      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
729

730
      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
731
                   currently logged in, then we'll get him from session
732
    """
Bartek Górny's avatar
Bartek Górny committed
733
    # Preference is made of a sequence of 'user_login', 'content', 'file_name', 'input'
734
    method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList',
Bartek Górny's avatar
Bartek Górny committed
735
        fallback_script_id = 'Document_getPreferredDocumentMetadataDiscoveryOrderList')
736
    order_list = list(method())
737
    order_list.reverse()
738
    # build a dictionary according to the order
Bartek Górny's avatar
Bartek Górny committed
739
    kw = {}
740
    for order_id in order_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
741
      result = None
Bartek Górny's avatar
Bartek Górny committed
742 743
      if order_id not in VALID_ORDER_KEY_LIST:
        # Prevent security attack or bad preferences
744
        raise AttributeError, "%s is not in valid order key list" % order_id
Bartek Górny's avatar
Bartek Górny committed
745 746 747
      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
748 749
        if file_name is not None:
          result = method(file_name)
Bartek Górny's avatar
Bartek Górny committed
750
      elif order_id == 'user_login':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
751 752
        if user_login is not None:
          result = method(user_login)
Bartek Górny's avatar
Bartek Górny committed
753 754
      else:
        result = method()
755 756 757 758
      if result is not None:
        for key, value in result.iteritems():
          if value not in (None, ''):
            kw[key]=value
Jean-Paul Smets's avatar
Jean-Paul Smets committed
759

760 761 762
    if file_name is not None:
      # filename is often undefined....
      kw['source_reference'] = file_name
763
    # Prepare the content edit parameters - portal_type should not be changed
764 765 766 767
    kw.pop('portal_type', None)
    # Try not to invoke an automatic transition here
    self._edit(**kw)
    # Finish ingestion by calling method
768 769
    self.finishIngestion() # XXX - is this really the right place ?
    self.reindexObject() # XXX - is this really the right place ?
770 771
    # Revision merge is tightly coupled
    # to metadata discovery - refer to the documentation of mergeRevision method
772 773 774
    merged_doc = self.mergeRevision() # XXX - is this really the right place ?
    merged_doc.reindexObject() # XXX - is this really the right place ?
    return merged_doc # XXX - is this really the right place ?
Bartek Górny's avatar
Bartek Górny committed
775 776 777 778

  security.declareProtected(Permissions.ModifyPortalContent, 'finishIngestion')
  def finishIngestion(self):
    """
779 780 781
      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
782
    """
783 784
    method = self._getTypeBasedMethod('finishIngestion', fallback_script_id='Document_finishIngestion')
    return method()
Bartek Górny's avatar
Bartek Górny committed
785

786 787 788 789 790
  security.declareProtected(Permissions.View, 'asSubjectText')
  def asSubjectText(self, **kw):
    """
      Converts the subject of the document to a textual representation.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
791
    subject = self.getSubject('')
792 793
    if not subject:
      # XXX not sure if this fallback is a good idea.
Nicolas Delaby's avatar
Nicolas Delaby committed
794
      subject = self.getTitle('')
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
    return str(subject)

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

      Actual conversion is delegated to _asHTML
    """
    html = self._asHTML(**kw)
    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:
Nicolas Delaby's avatar
Nicolas Delaby committed
813 814
        base = '<base href="%s"/>' % self.getContentBaseURL()
        html = html.replace('<head>', '<head>%s' % base, 1)
815 816 817 818 819 820 821 822 823
      self.setConversion(html, mime='text/html', format='base-html')
    return html

  security.declarePrivate('_asHTML')
  def _asHTML(self, **kw):
    """
      A private method which converts to HTML. This method
      is the one to override in subclasses.
    """
824 825 826
    kw['format'] = 'html'
    mime, html = self.convert(**kw)
    return html
827 828 829 830 831 832 833 834

  security.declareProtected(Permissions.View, 'asStrippedHTML')
  def asStrippedHTML(self, **kw):
    """
      Returns a stripped HTML representation of the document
      (without html and body tags, etc.) which can be used to inline
      a preview of the document.
    """
835
    return self._stripHTML(self._asHTML(**kw))
836

837 838
  security.declarePrivate('_guessEncoding')
  def _guessEncoding(self, string, mime='text/html'):
839 840 841 842 843 844 845
    """
      Try to guess the encoding for this string.
      Returns None if no encoding can be guessed.
    """
    try:
      import chardet
    except ImportError:
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
      chardet = None
    if chardet is not None and (mime == 'text/html'\
                                               or os.sys.platform != 'linux2'):
      # chardet works fine on html document and its platform independent
      return chardet.detect(string).get('encoding', None)
    else:
      # file command provide better result
      # for text/plain documents
      # store the content into tempfile
      file_descriptor, path = tempfile.mkstemp()
      file_object = os.fdopen(file_descriptor, 'w')
      file_object.write(string)
      file_object.close()
      # run file command against tempfile to and read encoded
      command_result = Popen(['file', '-b', '--mime-encoding', path],
                                                  stdout=PIPE).communicate()[0]
      # return detected encoding
      return command_result.strip()
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908

  def _stripHTML(self, html, charset=None):
    """
      A private method which can be reused by subclasses
      to strip HTML content
    """
    body_list = re.findall(self.body_parser, str(html))
    if len(body_list):
      stripped_html = body_list[0]
    else:
      stripped_html = html
    return stripped_html

  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 = {}
    html = self.asEntireHTML()
    if not html: return result
    title_list = re.findall(self.title_parser, str(html))
    if title_list:
      result['title'] = title_list[0]
    return result

  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 {}

909
  # Transformation API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
910
  security.declareProtected(Permissions.ModifyPortalContent, 'populateContent')
911 912 913 914 915 916 917 918 919 920 921 922
  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
923 924 925 926 927
    try:
      method = self._getTypeBasedMethod('populateContent')
    except KeyError, AttributeError:
      method = None
    if method is not None: method()
928 929

  # Crawling API
Jean-Paul Smets's avatar
Jean-Paul Smets committed
930
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentURLList')
931 932 933
  def getContentURLList(self):
    """
      Returns a list of URLs referenced by the content of this document.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
934 935 936 937 938 939
      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.
940
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
941 942
    html_content = self.asStrippedHTML()
    return re.findall(self.href_parser, str(html_content))
943

Jean-Paul Smets's avatar
Jean-Paul Smets committed
944
  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentFromURL')
945
  def updateContentFromURL(self, repeat=MAX_REPEAT, crawling_depth=0):
946 947
    """
      Download and update content of this document from its source URL.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
948 949
      Implementation is handled by ContributionTool.
    """
950
    self.portal_contributions.updateContentFromURL(self, repeat=repeat, crawling_depth=crawling_depth)
951

Jean-Paul Smets's avatar
Jean-Paul Smets committed
952 953
  security.declareProtected(Permissions.ModifyPortalContent, 'crawlContent')
  def crawlContent(self):
954
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
955 956 957 958
      Initialises the crawling process on the current document.
    """
    self.portal_contributions.crawlContent(self)

959 960 961 962 963 964
  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
965
      a difference between URLs which return an index (ex. the
966 967 968 969 970 971 972 973 974
      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
975 976 977 978 979 980 981 982
  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
983
    if len(base_url_list):
984
      if base_url_list[-1] and base_url_list[-1].find('.') > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
985
        # Cut the trailing part in http://www.some.site/at/trailing.html
986
        # but not in http://www.some.site/at
Jean-Paul Smets's avatar
Jean-Paul Smets committed
987
        base_url = '/'.join(base_url_list[:-1])
988
    return base_url