ContributionTool.py 27.4 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2007 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

30
import cStringIO
31
import re
32
import socket
Jean-Paul Smets's avatar
Jean-Paul Smets committed
33
import urllib2, urllib
34 35 36
import urlparse
from cgi import parse_header
import os
37

Bartek Górny's avatar
Bartek Górny committed
38
from AccessControl import ClassSecurityInfo, getSecurityManager
39
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
40
from Products.CMFCore.utils import _checkPermission
41 42
from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions
43
from Products.ERP5Type.Utils import reencodeUrlEscapes
44
from Products.ERP5 import _dtmldir
Nicolas Delaby's avatar
Nicolas Delaby committed
45
from Products.ERP5.Document.Url import no_crawl_protocol_list
46
from Products.ERP5Type.Utils import fill_args_from_request
Ivan Tyagov's avatar
Ivan Tyagov committed
47
from AccessControl import Unauthorized
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
from DateTime import DateTime
Nicolas Delaby's avatar
Nicolas Delaby committed
50
import warnings
51

52 53 54 55 56 57
# Install openers
import ContributionOpener
opener = urllib2.build_opener(ContributionOpener.DirectoryFileHandler)
urllib2.install_opener(opener)

# Global parameters
58
TEMP_NEW_OBJECT_KEY = '_v_new_object'
59
MAX_REPEAT = 10
60 61

_marker = []  # Create a new marker object.
62 63 64 65

class ContributionTool(BaseTool):
  """
    ContributionTool provides an abstraction layer to unify the contribution
66
    of documents into an ERP5 Site.
67

68 69
    ContributionTool needs to be configured in portal_types (allowed contents) so
    that it can store Text, Spreadsheet, PDF, etc. 
70

71 72 73
    The main method of ContributionTool is newContent. This method can
    be provided various parameters from which the portal type and document
    metadata can be derived. 
74 75

    Configuration Scripts:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
76

Nicolas Delaby's avatar
Nicolas Delaby committed
77
      - ContributionTool_getPropertyDictFromFilename: receives file name and a 
78 79
        dict derived from filename by regular expression, and does any necesary
        operations (e.g. mapping document type id onto a real portal_type).
Jean-Paul Smets's avatar
Jean-Paul Smets committed
80 81 82 83 84 85

    Problems which are not solved

      - handling of relative links in HTML contents (or others...)
        some text rewriting is necessary.

86 87 88 89 90 91
  """
  title = 'Contribution Tool'
  id = 'portal_contributions'
  meta_type = 'ERP5 Contribution Tool'
  portal_type = 'Contribution Tool'

Nicolas Delaby's avatar
Nicolas Delaby committed
92
  
Jean-Paul Smets's avatar
Jean-Paul Smets committed
93

94 95 96 97 98 99 100
  # Declarative Security
  security = ClassSecurityInfo()

  security.declareProtected(Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainContributionTool', _dtmldir )

  security.declareProtected(Permissions.AddPortalContent, 'newContent')
101 102 103
  @fill_args_from_request('data', 'filename', 'portal_type', 'container_path',
                          'discover_metadata', 'temp_object', 'reference')
  def newContent(self, REQUEST=None, **kw):
104 105 106 107 108 109
    """
      The newContent method is overriden to implement smart content
      creation by detecting the portal type based on whatever information
      was provided and finding out the most appropriate module to store
      the content.

Nicolas Delaby's avatar
Nicolas Delaby committed
110
      explicit named parameters was:
111
        id - id of document
Nicolas Delaby's avatar
Nicolas Delaby committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        portal_type - explicit portal_type parameter, must be honoured
        url - Identifier of external resource. Content will be downloaded
              from it
        container - if specified, it is possible to define
                    where to contribute the content. Else, ContributionTool
                    tries to guess.
        container_path - if specified, defines the container path
                         and has precedence over container
        discover_metadata - Enable metadata extraction and discovery
                            (default True)
        temp_object - build tempObject or not (default False)
        user_login - is the name under which the content will be created
                     XXX - this is a security hole which needs to be fixed by
                     making sure only Manager can use this parameter
        data - Binary representation of content
        filename - explicit filename of content
128
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
129 130 131 132 133 134 135 136 137 138
    # Useful for metadata discovery, keep it as it as been provided
    input_parameter_dict = kw.copy()
    # But file and data are exceptions.
    # They are potentialy too big to be keept into memory.
    # We want to keep only one reference of thoses values
    # on futur created document only !
    if 'file' in input_parameter_dict:
      del input_parameter_dict['file']
    if 'data' in input_parameter_dict:
      del input_parameter_dict['data']
139 140 141 142 143
    if 'container' in input_parameter_dict:
      # Container is a persistent object
      # keep only its path in container_path key
      container = input_parameter_dict.pop('container')
      input_parameter_dict['container_path'] = container.getPath()
Nicolas Delaby's avatar
Nicolas Delaby committed
144 145 146 147 148 149
    # pop: remove keys which are not document properties
    url = kw.pop('url', None)
    container = kw.pop('container', None)
    container_path = kw.pop('container_path', None)
    discover_metadata = kw.pop('discover_metadata', True)
    user_login = kw.pop('user_login', None)
150
    document_id = kw.pop('id', None)
Nicolas Delaby's avatar
Nicolas Delaby committed
151 152 153 154 155 156 157
    # check file_name argument for backward compatibility.
    if 'file_name' in kw:
      if 'filename' not in kw:
        kw['filename'] = kw['file_name']
      del(kw['file_name'])
    filename = kw.get('filename', None)
    temp_object = kw.get('temp_object', False)
158

159
    document = None
Nicolas Delaby's avatar
Nicolas Delaby committed
160
    portal = self.getPortalObject()
161 162 163 164
    if container is None and container_path:
      # Get persistent object from its path.
      # Container may disappear, be smoother by passing default value
      container = portal.restrictedTraverse(container_path, None)
Nicolas Delaby's avatar
Nicolas Delaby committed
165
    # Try to find the filename
166
    if not url:
167
      # check if file was provided
Nicolas Delaby's avatar
Nicolas Delaby committed
168 169 170
      file_object = kw.get('file')
      if file_object is not None:
        if not filename:
171
          filename = getattr(file_object, 'filename', None)
172 173 174 175
      else:
        # some channels supply data and file-name separately
        # this is the case for example for email ingestion
        # in this case, we build a file wrapper for it
176 177 178 179 180
        try:
          data = kw.pop('data')
        except KeyError:
          raise ValueError('data must be provided')
        if data is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
181 182 183 184
          file_object = cStringIO.StringIO()
          file_object.write(data)
          file_object.seek(0)
          kw['file'] = file_object
185
      content_type = kw.pop('content_type', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
186
    else:
Nicolas Delaby's avatar
Nicolas Delaby committed
187
      file_object, filename, content_type = self._openURL(url)
188
      content_type = kw.pop('content_type', None) or content_type
Nicolas Delaby's avatar
Nicolas Delaby committed
189
      kw['file'] = file_object
190

191 192 193
    if not filename:
      raise ValueError('filename must be provided')

194 195 196 197
    if not content_type:
      # fallback to a default content_type according provided
      # filename
      content_type = self.guessMimeTypeFromFilename(filename)
198 199 200 201 202
    if content_type:
      kw['content_type'] = content_type

    portal_type = kw.pop('portal_type', None)
    if not portal_type:
203 204 205 206 207 208
      # Guess it with help of portal_contribution_registry
      portal_type = portal.portal_contribution_registry.findPortalTypeName(
        filename=filename, content_type=content_type)
      if not (container is None or container.isModuleType() or
              container.getTypeInfo().allowType(portal_type)):
          portal_type = 'Embedded File'
209

210 211 212 213 214 215 216 217 218 219 220
    if container is None:
      # If the portal_type was provided, we can go faster
      if portal_type:
        # We know the portal_type, let us find the default module
        # and use it as container
        try:
          container = portal.getDefaultModule(portal_type)
        except ValueError:
          pass

    elif not url:
221 222 223
      # Simplify things here and return a document immediately
      # XXX Nicolas: This will break support of WebDAV
      # if _setObject is not called
224
      document = container.newContent(document_id, portal_type, **kw)
225 226 227 228 229 230
      if discover_metadata:
        document.activate(after_path_and_method_id=(document.getPath(),
            ('convertToBaseFormat', 'Document_tryToConvertToBaseFormat')))\
              .discoverMetadata(filename=filename, 
                                user_login=user_login,
                                input_parameter_dict=input_parameter_dict)
231 232
      if REQUEST is not None:
        return REQUEST.RESPONSE.redirect(self.absolute_url())
233 234
      return document

235 236
    #
    # Check if same file is already exists. if it exists, then update it.
237
    #
Nicolas Delaby's avatar
Nicolas Delaby committed
238 239 240 241 242
    property_dict = self.getMatchedFilenamePatternDict(filename)
    reference = property_dict.get('reference', None)
    version  = property_dict.get('version', None)
    language  = property_dict.get('language', None)
    if portal_type and reference and version and language:
243
      portal_catalog = portal.portal_catalog
Nicolas Delaby's avatar
Nicolas Delaby committed
244
      document = portal_catalog.getResultValue(portal_type=portal_type,
Nicolas Delaby's avatar
Nicolas Delaby committed
245 246 247
                                               reference=reference,
                                               version=version,
                                               language=language)
248

Nicolas Delaby's avatar
Nicolas Delaby committed
249 250 251 252 253 254
      if document is not None:
        # document is already uploaded. So overrides file.
        if not _checkPermission(Permissions.ModifyPortalContent, document):
          raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % document.getId()
        document.edit(file=kw['file'])
        return document
255 256 257
    # Temp objects use the standard newContent from Folder
    if temp_object:
      # For temp_object creation, use the standard method
258
      return BaseTool.newContent(self, portal_type=portal_type, **kw)
259

260
    # Then put the file inside ourselves for a short while
261
    document = self._setObject(document_id, None, portal_type=portal_type,
Nicolas Delaby's avatar
Nicolas Delaby committed
262
                               user_login=user_login, container=container,
263
                               discover_metadata=discover_metadata,
Nicolas Delaby's avatar
Nicolas Delaby committed
264 265
                               filename=filename,
                               input_parameter_dict=input_parameter_dict
266
                               )
267
    object_id = document.getId()
268
    document = self._getOb(object_id) # Call _getOb to purge cache
269

Nicolas Delaby's avatar
Nicolas Delaby committed
270
    kw['filename'] = filename # Override filename property
271
    # Then edit the document contents (so that upload can happen)
272
    document._edit(**kw)
273 274
    if url:
      document.fromURL(url)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
275

276
    # Allow reindexing, reindex it and return the document
Romain Courteaud's avatar
Romain Courteaud committed
277
    try:
278
      del document.isIndexable
Romain Courteaud's avatar
Romain Courteaud committed
279 280 281
    except AttributeError:
      # Document does not have such attribute
      pass
282
    document.reindexObject()
283 284
    if REQUEST is not None:
      return REQUEST.RESPONSE.redirect(self.absolute_url())
285 286
    return document

287
  security.declareProtected( Permissions.AddPortalContent, 'newXML' )
288 289 290 291 292 293 294
  def newXML(self, xml):
    """
      Create a new content based on XML data. This is intended for contributing
      to ERP5 from another application.
    """
    pass

Nicolas Delaby's avatar
Nicolas Delaby committed
295 296 297
  security.declareProtected(Permissions.ModifyPortalContent,
                            'getMatchedFilenamePatternDict')
  def getMatchedFilenamePatternDict(self, filename):
298
    """
299
      Get matched group dict of file name parsing regular expression.
300
    """
301
    property_dict = {}
302

Nicolas Delaby's avatar
Nicolas Delaby committed
303
    if filename is None:
304 305
      return property_dict

Nicolas Delaby's avatar
Nicolas Delaby committed
306 307
    regex_text = self.portal_preferences.\
                                getPreferredDocumentFilenameRegularExpression()
308
    if regex_text in ('', None):
309 310
      return property_dict

311 312 313
    if regex_text:
      pattern = re.compile(regex_text)
      if pattern is not None:
314
        try:
Nicolas Delaby's avatar
Nicolas Delaby committed
315
          property_dict = pattern.match(filename).groupdict()
316 317
        except AttributeError: # no match
          pass
318 319
    return property_dict

Nicolas Delaby's avatar
Nicolas Delaby committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333
  # backward compatibility
  security.declareProtected(Permissions.ModifyPortalContent,
                            'getMatchedFileNamePatternDict')
  def getMatchedFileNamePatternDict(self, filename):
    """
    (deprecated) use getMatchedFilenamePatternDict() instead.
    """
    warnings.warn('getMatchedFileNamePatternDict() is deprecated. '
                  'use getMatchedFilenamePatternDict() instead.')
    return self.getMatchedFilenamePatternDict(filename)

  security.declareProtected(Permissions.ModifyPortalContent,
                            'getPropertyDictFromFilename')
  def getPropertyDictFromFilename(self, filename):
334 335 336 337
    """
      Gets properties from filename. File name is parsed with a regular expression
      set in preferences. The regexp should contain named groups.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
338
    if filename is None:
339
      return {}
Nicolas Delaby's avatar
Nicolas Delaby committed
340
    property_dict = self.getMatchedFilenamePatternDict(filename)
341 342
    try:
      method = self._getTypeBasedMethod('getPropertyDictFromFilename',
Nicolas Delaby's avatar
Nicolas Delaby committed
343
             fallback_script_id='ContributionTool_getPropertyDictFromFilename')
344 345 346
    except AttributeError: # Try to use previous naming convention
      method = self._getTypeBasedMethod('getPropertyDictFromFileName',
             fallback_script_id='ContributionTool_getPropertyDictFromFileName')
Nicolas Delaby's avatar
Nicolas Delaby committed
347
    property_dict = method(filename, property_dict)
348 349
    return property_dict

Nicolas Delaby's avatar
Nicolas Delaby committed
350 351 352 353 354 355 356 357 358 359 360
  # backward compatibility
  security.declareProtected(Permissions.ModifyPortalContent,
                            'getPropertyDictFromFileName')
  def getPropertyDictFromFileName(self, filename):
    """
    (deprecated) use getPropertyDictFromFilename() instead.
    """
    warnings.warn('getPropertyDictFromFileName() is deprecated. '
                  'use getPropertyDictFromFilename() instead.')
    return self.getPropertyDictFromFilename(filename)

361
  # WebDAV virtual folder support
Nicolas Delaby's avatar
Nicolas Delaby committed
362 363 364
  def _setObject(self, id, ob, portal_type=None, user_login=None,
                 container=None, discover_metadata=True, filename=None,
                 input_parameter_dict=None):
365
    """
366
      portal_contribution_registry will find appropriate portal type
Nicolas Delaby's avatar
Nicolas Delaby committed
367
      name by filename and content itself.
368 369 370 371 372

      The ContributionTool instance must be configured in such
      way that _verifyObjectPaste will return TRUE.

    """
373 374 375 376 377
    # _setObject is called by constructInstance at a time
    # when the object has no portal_type defined yet. It
    # will be removed later on. We can safely store the
    # document inside us at this stage. Else we
    # must find out where to store it.
378
    if ob is not None:
379 380 381 382 383
      # Called from webdav API
      # Object is already created by PUT_factory
      # fill the volatile cache _v_document_cache
      # then return the document
      document = ob
384
    else:
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      if not portal_type:
        document = BaseTool.newContent(self, id=id,
                                      portal_type=portal_type,
                                      is_indexable=0)
      elif ob is None:
        # We give the system a last chance to analyse the
        # portal_type based on the document content
        # (ex. a Memo is a kind of Text which can be identified
        # by the fact it includes some specific content)

        # Now we know the portal_type, let us find the module
        # to which we should move the document to
        if container is None:
          module = self.getDefaultModule(portal_type)
        else:
          module = container
        # There is no preexisting document - we can therefore
        # set the new object
        new_content_kw = {'portal_type': portal_type,
                          'is_indexable': False}
        if id is not None:
          new_content_kw['id'] = id
        document = module.newContent(**new_content_kw)
        # We can now discover metadata
        if discover_metadata:
          # Metadata disovery is done as an activity by default
          # If we need to discoverMetadata synchronously, it must
          # be for user interface and should thus be handled by
          # ZODB scripts
          document.activate(after_path_and_method_id=(document.getPath(),
415 416
            ('convertToBaseFormat', 'Document_tryToConvertToBaseFormat',
             'immediateReindexObject', 'recursiveImmediateReindexObject')))\
417 418 419 420 421 422 423 424 425 426
          .discoverMetadata(filename=filename,
                            user_login=user_login,
                            input_parameter_dict=input_parameter_dict)
    # Keep the document close to us - this is only useful for
    # file upload from webdav
    volatile_cache = getattr(self, '_v_document_cache', None)
    if volatile_cache is None:
      self._v_document_cache = {}
      volatile_cache = self._v_document_cache
    volatile_cache[document.getId()] = document.getRelativeUrl()
427 428
    # Return document to newContent method
    return document
429

430 431 432 433 434
  def _getOb(self, id, default=_marker):
    """
    Check for volatile temp object info first
    and try to find it
    """
435 436
    # Use the document cache if possible and return result immediately
    # this is only useful for webdav
Nicolas Delaby's avatar
Nicolas Delaby committed
437 438 439
    volatile_cache = getattr(self, '_v_document_cache', None)
    if volatile_cache is not None:
      document_url = volatile_cache.get(id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
440
      if document_url is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
441
        del volatile_cache[id]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
442 443
        return self.getPortalObject().unrestrictedTraverse(document_url)

444 445 446 447 448 449 450 451 452 453 454 455
    # Try first to return the real object inside
    # This is much safer than trying to access objects displayed by listDAVObjects
    # because the behaviour of catalog is unpredicatble if a string is passed
    # for a UID. For example 
    #   select path from catalog where uid = "001193.html";
    # will return the same as
    #   select path from catalog where uid = 1193;
    # This was the source of an error in which the contribution tool
    # was creating a web page and was returning a Base Category
    # when
    #   o = folder._getOb(id)
    # was called in DocumentConstructor
456 457 458 459 460 461 462
    if default is _marker:
      result = BaseTool._getOb(self, id)
    else:
      result = BaseTool._getOb(self, id, default=default)
    if result is not None:
      # if result is None, ignore it at this stage
      # we can be more lucky with portal_catalog
463 464 465
      return result

    # Return an object listed by listDAVObjects
466 467 468
    # ids are concatenation of uid + '-' + standard file name of documents
    # get the uid
    uid = str(id).split('-', 1)[0]
469 470
    object = self.getPortalObject().portal_catalog.unrestrictedGetResultValue(uid=uid)
    if object is not None:
471
      return object.getObject() # Make sure this does not break security. XXX
472 473
    if default is not _marker:
      return default
474 475 476
    # Raise an AttributeError the same way as in OFS.ObjectManager._getOb
    raise AttributeError, id

477

Bartek Górny's avatar
Bartek Górny committed
478
  def listDAVObjects(self):
479 480 481
    """
      Get all contents contributed by the current user. This is
      delegated to a script in order to help customisation.
482
    XXX Killer feature, it is not scalable
483 484 485 486 487 488 489 490 491 492 493 494 495
    """
    method = getattr(self, 'ContributionTool_getMyContentList', None)
    if method is not None:
      object_list = method()
    else:
      sm = getSecurityManager()
      user = sm.getUser()
      object_list = self.portal_catalog(portal_type=self.getPortalMyDocumentTypeList(),
                                        owner=str(user))

    def wrapper(o_list):
      for o in o_list:
        o = o.getObject()
Nicolas Delaby's avatar
Nicolas Delaby committed
496
        id = '%s-%s' % (o.getUid(), o.getStandardFilename(),)
497
        yield o.asContext(id=id)
498 499

    return wrapper(object_list)
Bartek Górny's avatar
Bartek Górny committed
500

Jean-Paul Smets's avatar
Jean-Paul Smets committed
501
  security.declareProtected(Permissions.AddPortalContent, 'crawlContent')
502
  def crawlContent(self, content, container=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
503 504 505 506 507 508
    """
      Analyses content and download linked pages

      XXX: missing is the conversion of content local href to something
      valid.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
509 510
    portal = self.getPortalObject()
    url_registry_tool = portal.portal_url_registry
Jean-Paul Smets's avatar
Jean-Paul Smets committed
511
    depth = content.getCrawlingDepth()
512 513 514 515 516 517 518 519
    if depth < 0:
      # Do nothing if crawling depth is reached
      # (this is not a duplicate code but a way to prevent
      # calling isIndexContent unnecessarily)
      return
    if not content.isIndexContent(): # Decrement depth only if it is a content document
      depth = depth - 1
    if depth < 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
520 521
      # Do nothing if crawling depth is reached
      return
Nicolas Delaby's avatar
Nicolas Delaby committed
522
    url_list = content.getContentNormalisedURLList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
523
    for url in set(url_list):
524
      # LOG('trying to crawl', 0, url)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
525
      # Some url protocols should not be crawled
Nicolas Delaby's avatar
Nicolas Delaby committed
526
      if urlparse.urlsplit(url)[0] in no_crawl_protocol_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
527
        continue
528 529 530 531
      if container is None:
        #if content.getParentValue()
        # in place of not ?
        container = content.getParentValue()
Nicolas Delaby's avatar
Nicolas Delaby committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
      try:
        url_registry_tool.getReferenceFromURL(url, context=container)
      except KeyError:
        pass
      else:
        # url already crawled
        continue
      # XXX - This call is not working due to missing group_method_id
      # therefore, multiple call happen in parallel and eventually fail
      # (the same URL is created multiple times)
      # LOG('activate newContentFromURL', 0, url)
      self.activate(activity="SQLQueue").newContentFromURL(
                                  container_path=container.getRelativeUrl(),
                                  url=url, crawling_depth=depth)
      # Url is not known yet but register right now to avoid
      # creation of duplicated crawled content
      # An activity will later setup the good reference for it.
      url_registry_tool.registerURL(url, None, context=container)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550 551

  security.declareProtected(Permissions.AddPortalContent, 'updateContentFromURL')
552 553
  def updateContentFromURL(self, content, repeat=MAX_REPEAT, crawling_depth=0,
                           repeat_interval=1, batch_mode=True):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
554 555 556
    """
      Updates an existing content.
    """
557 558 559 560 561 562 563 564 565
    # First, test if the document is updatable according to
    # its workflow states (if it has a workflow associated with)
    if content.isUpdatable():
      # Step 0: update crawling_depth if required
      if crawling_depth > content.getCrawlingDepth():
        content._setCrawlingDepth(crawling_depth)
      # Step 1: download new content
      try:
        url = content.asURL()
Nicolas Delaby's avatar
Nicolas Delaby committed
566
        file_object, filename, content_type = self._openURL(url)
567
      except urllib2.URLError, error:
568
        if repeat == 0 or not batch_mode:
569
          # XXX - Call the extendBadURLList method,--NOT Implemented--
Jérome Perrin's avatar
Jérome Perrin committed
570
          raise
571
        content.activate(at_date=DateTime() + repeat_interval).updateContentFromURL(repeat=repeat - 1)
572 573
        return

Nicolas Delaby's avatar
Nicolas Delaby committed
574 575
      content._edit(file=file_object, content_type=content_type)
                              # Please make sure that if content is the same
576 577 578
                              # we do not update it
                              # This feature must be implemented by Base or File
                              # not here (look at _edit in Base)
Nicolas Delaby's avatar
Nicolas Delaby committed
579 580 581 582 583 584 585
      # Step 2: convert to base format
      if content.isSupportBaseDataConversion():
        content.activate().Document_tryToConvertToBaseFormat()
      # Step 3: run discoverMetadata
      content.activate(after_path_and_method_id=(content.getPath(),
            ('convertToBaseFormat', 'Document_tryToConvertToBaseFormat'))) \
          .discoverMetadata(filename=filename)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
586
      # Step 4: activate populate (unless interaction workflow does it)
587
      content.activate().populateContent()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
588
      # Step 5: activate crawlContent
589 590 591
      depth = content.getCrawlingDepth()
      if depth > 0:
        content.activate().crawlContent()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
592 593

  security.declareProtected(Permissions.AddPortalContent, 'newContentFromURL')
594 595
  def newContentFromURL(self, url, container_path=None, id=None, repeat=MAX_REPEAT,
                        repeat_interval=1, batch_mode=True, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
596 597 598 599 600 601 602 603 604
    """
      A wrapper method for newContent which provides extra safety
      in case or errors (ie. download, access, conflict, etc.).
      The method is able to handle a certain number of exceptions
      and can postpone itself through an activity based on
      the type of exception (ex. for a 404, postpone 1 day), using
      the at_date parameter and some standard values.

      NOTE: implementation needs to be done.
Nicolas Delaby's avatar
Nicolas Delaby committed
605
      id parameter is ignored
Jean-Paul Smets's avatar
Jean-Paul Smets committed
606
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
607
    document = None
608
    try:
Nicolas Delaby's avatar
Nicolas Delaby committed
609
      document = self.newContent(container_path=container_path, url=url, **kw)
610 611 612 613 614 615
      if document.isIndexContent() and document.getCrawlingDepth() >= 0:
        # If this is an index document, keep on crawling even if crawling_depth is 0
        document.activate().crawlContent()
      elif document.getCrawlingDepth() > 0:
        # If this is an index document, stop crawling if crawling_depth is 0
        document.activate().crawlContent()
616
    except urllib2.HTTPError, error:
617
      if repeat == 0 or not batch_mode:
618 619 620
        # here we must call the extendBadURLList method,--NOT Implemented--
        # which had to add this url to bad URL list, so next time we avoid
        # crawling bad URL
621
        raise
622 623 624 625
      if repeat > 0:
        # Catch any HTTP error
        self.activate(at_date=DateTime() + repeat_interval,
                      activity="SQLQueue").newContentFromURL(
Nicolas Delaby's avatar
Nicolas Delaby committed
626
                        container_path=container_path, url=url,
627 628
                        repeat=repeat - 1,
                        repeat_interval=repeat_interval, **kw)
629
    return document
Jean-Paul Smets's avatar
Jean-Paul Smets committed
630

Nicolas Delaby's avatar
Nicolas Delaby committed
631 632 633
  security.declareProtected(Permissions.AccessContentsInformation,
                            'guessMimeTypeFromFilename')
  def guessMimeTypeFromFilename(self, filename):
634
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
635
      get mime type from file name
636
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
637 638 639 640
    if not filename:
      return
    portal = self.getPortalObject()
    content_type = portal.mimetypes_registry.lookupExtension(filename)
641 642
    if content_type:
      return str(content_type)
Nicolas Delaby's avatar
Nicolas Delaby committed
643 644 645 646 647 648 649 650
    return content_type

  def _openURL(self, url):
    """Download content from url,
    read filename and content_type
    return file_object, filename, content_type tuple
    """
    # Quote path part of url
651
    url = reencodeUrlEscapes(url)
Nicolas Delaby's avatar
Nicolas Delaby committed
652
    # build a new file from the url
653 654
    url_file = urllib2.urlopen(urllib2.Request(url,
                                               headers={'Accept':'*/*'}))
Nicolas Delaby's avatar
Nicolas Delaby committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    data = url_file.read() # time out must be set or ... too long XXX
    file_object = cStringIO.StringIO()
    file_object.write(data)
    file_object.seek(0)
    # if a content-disposition header is present,
    # try first to read the suggested filename from it.
    header_info = url_file.info()
    content_disposition = header_info.getheader('content-disposition', '')
    filename = parse_header(content_disposition)[1].get('filename')
    if not filename:
      # Now read the filename from url.
      # In case of http redirection, the real url must be read
      # from file object returned by urllib2.urlopen.
      # It can happens when the header 'Location' is present in request.
      # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
      url = url_file.geturl()
      # Create a file name based on the URL and quote it
      filename = urlparse.urlsplit(url)[-3]
      filename = os.path.basename(filename)
      filename = urllib.quote(filename, safe='')
      filename = filename.replace('%', '')
    content_type = header_info.gettype()
    return file_object, filename, content_type
678

Ivan Tyagov's avatar
Ivan Tyagov committed
679
InitializeClass(ContributionTool)