def setUp(self):
     self._epoch = DateTime('1970/01/01')
Beispiel #2
0
 def getCreationTime(self):
     return DateTime(self._created)
Beispiel #3
0
 def test_ExpirationDate_with_explicit_timezone(self):
     item = self._makeDummyContent('item')
     item.expiration_date = DateTime('2007-01-01T12:00:00Z')
     self.assertEqual(item.ExpirationDate('US/Eastern'),
                      '2007-01-01 07:00:00')
 def test_bobobase_modification_time(self):
     script = self._makeOne('test1', 'test1.py')
     self.assertTrue(isinstance(script.bobobase_modification_time(),
                                DateTime))
     self.assertEqual(script.bobobase_modification_time(),
                      DateTime(os.stat(script._filepath).st_mtime))
Beispiel #5
0
 def get_birthdate(self):
     bd = self._getProperty("birthdate")
     return None if bd == DateTime(
         "1900/01/01 00:00:00") else bd.asdatetime().date()
    def getHeaders(self, expr_context):
        """
            Does this request match our predicate?  If so, return a
            sequence of caching headers as ( key, value ) tuples.
            Otherwise, return an empty sequence.
        """
        headers = []

        if self.testPredicate(expr_context):

            if self.getLastModified():
                mtime = self._mtime_func(expr_context)
                if type(mtime) is type(''):
                    mtime = DateTime(mtime)
                if mtime is not None:
                    mtime_str = rfc1123_date(mtime.timeTime())
                    headers.append(('Last-modified', mtime_str))

            control = []

            if self.getMaxAgeSecs() is not None:
                now = expr_context.vars['time']
                exp_time_str = rfc1123_date(now.timeTime() +
                                            self._max_age_secs)
                headers.append(('Expires', exp_time_str))
                control.append('max-age=%d' % self._max_age_secs)

            if self.getSMaxAgeSecs() is not None:
                control.append('s-maxage=%d' % self._s_max_age_secs)

            if self.getNoCache():
                control.append('no-cache')
                # The following is for HTTP 1.0 clients
                headers.append(('Pragma', 'no-cache'))

            if self.getNoStore():
                control.append('no-store')

            if self.getPublic():
                control.append('public')

            if self.getPrivate():
                control.append('private')

            if self.getMustRevalidate():
                control.append('must-revalidate')

            if self.getProxyRevalidate():
                control.append('proxy-revalidate')

            if self.getNoTransform():
                control.append('no-transform')

            pre_check = self.getPreCheck()
            if pre_check is not None:
                control.append('pre-check=%d' % pre_check)

            post_check = self.getPostCheck()
            if post_check is not None:
                control.append('post-check=%d' % post_check)

            if control:
                headers.append(('Cache-control', ', '.join(control)))

            if self.getVary():
                headers.append(('Vary', self._vary))

            if self.getETagFunc():
                headers.append(('ETag', self._etag_func(expr_context)))

        return headers
Beispiel #7
0
 def _makeAndIndexOneDoc(self, index):
     from DateTime.DateTime import DateTime
     doc = self._makeDoc(type='fluke', date=DateTime('1/1/2004'))
     return index.index_object(1, doc)
Beispiel #8
0
def _checkConditionalGET(obj, extra_context):
    """A conditional GET is done using one or both of the request
       headers:

       If-Modified-Since: Date
       If-None-Match: list ETags (comma delimited, sometimes quoted)

       If both conditions are present, both must be satisfied.

       This method checks the caching policy manager to see if
       a content object's Last-modified date and ETag satisfy
       the conditional GET headers.

       Returns the tuple (last_modified, etag) if the conditional
       GET requirements are met and None if not.

       It is possible for one of the tuple elements to be None.
       For example, if there is no If-None-Match header and
       the caching policy does not specify an ETag, we will
       just return (last_modified, None).
       """

    REQUEST = getattr(obj, 'REQUEST', None)
    if REQUEST is None:
        return False

    # check whether we need to suppress subtemplates
    call_count = getattr(REQUEST, SUBTEMPLATE, 0)
    setattr(REQUEST, SUBTEMPLATE, call_count + 1)
    if call_count != 0:
        return False

    if_modified_since = REQUEST.getHeader('If-Modified-Since', None)
    if_none_match = REQUEST.getHeader('If-None-Match', None)

    if if_modified_since is None and if_none_match is None:
        # not a conditional GET
        return False

    manager = queryUtility(ICachingPolicyManager)
    if manager is None:
        return False

    ret = manager.getModTimeAndETag(aq_parent(obj), obj.getId(), extra_context)
    if ret is None:
        # no appropriate policy or 304s not enabled
        return False

    (content_mod_time, content_etag, set_last_modified_header) = ret
    if content_mod_time:
        mod_time_secs = int(content_mod_time.timeTime())
    else:
        mod_time_secs = None

    if if_modified_since:
        # from CMFCore/FSFile.py:
        if_modified_since = if_modified_since.split(';')[0]
        # Some proxies seem to send invalid date strings for this
        # header. If the date string is not valid, we ignore it
        # rather than raise an error to be generally consistent
        # with common servers such as Apache (which can usually
        # understand the screwy date string as a lucky side effect
        # of the way they parse it).
        try:
            if_modified_since = int(DateTime(if_modified_since).timeTime())
        except Exception:
            if_modified_since = None

    client_etags = None
    if if_none_match:
        client_etags = parse_etags(if_none_match)

    if not if_modified_since and not client_etags:
        # not a conditional GET, or headers are messed up
        return False

    if if_modified_since:
        if not content_mod_time or \
           mod_time_secs < 0 or \
           mod_time_secs > if_modified_since:
            return False

    if client_etags:
        if not content_etag or \
           (content_etag not in client_etags and '*' not in client_etags):
            return False
    else:
        # If we generate an ETag, don't validate the conditional GET unless
        # the client supplies an ETag
        # This may be more conservative than the spec requires, but we are
        # already _way_ more conservative.
        if content_etag:
            return False

    response = REQUEST.RESPONSE
    if content_mod_time and set_last_modified_header:
        response.setHeader('Last-modified', str(content_mod_time))
    if content_etag:
        response.setHeader('ETag', content_etag, literal=1)
    response.setStatus(304)
    delattr(REQUEST, SUBTEMPLATE)

    return True
Beispiel #9
0
    def ZopeFindAndApply(self,
                         obj,
                         obj_ids=None,
                         obj_metatypes=None,
                         obj_searchterm=None,
                         obj_expr=None,
                         obj_mtime=None,
                         obj_mspec=None,
                         obj_permission=None,
                         obj_roles=None,
                         search_sub=0,
                         REQUEST=None,
                         result=None,
                         pre='',
                         apply_func=None,
                         apply_path=''):
        """Zope Find interface and apply

        This is a *great* hack.  Zope find just doesn't do what we
        need here; the ability to apply a method to all the objects
        *as they're found* and the need to pass the object's path into
        that method.
        """

        if result is None:
            result = []

            if obj_metatypes and 'all' in obj_metatypes:
                obj_metatypes = None

            if obj_mtime and isinstance(obj_mtime, str):
                obj_mtime = DateTime(obj_mtime).timeTime()

            if obj_permission:
                obj_permission = getPermissionIdentifier(obj_permission)

            if obj_roles and isinstance(obj_roles, str):
                obj_roles = [obj_roles]

            if obj_expr:
                # Setup expr machinations
                md = td()
                obj_expr = (Eval(obj_expr), md, md._push, md._pop)

        base = aq_base(obj)

        if not hasattr(base, 'objectItems'):
            return result
        try:
            items = obj.objectItems()
        except Exception:
            return result

        try:
            add_result = result.append
        except Exception:
            raise AttributeError(repr(result))

        for id, ob in items:
            if pre:
                p = "%s/%s" % (pre, id)
            else:
                p = id

            dflag = 0
            if hasattr(ob, '_p_changed') and (ob._p_changed is None):
                dflag = 1

            bs = aq_base(ob)

            if ((not obj_ids or absattr(bs.id) in obj_ids) and
                (not obj_metatypes or
                 (hasattr(bs, 'meta_type') and bs.meta_type in obj_metatypes))
                    and
                (not obj_searchterm or
                 (hasattr(ob, 'PrincipiaSearchSource')
                  and ob.PrincipiaSearchSource().find(obj_searchterm) >= 0)
                 )  # noqa: E501
                    and (not obj_expr or expr_match(ob, obj_expr)) and
                (not obj_mtime or mtime_match(ob, obj_mtime, obj_mspec))
                    and ((not obj_permission or not obj_roles)
                         or role_match(ob, obj_permission, obj_roles))):
                if apply_func:
                    apply_func(ob, (apply_path + '/' + p))
                else:
                    add_result((p, ob))
                    dflag = 0

            if search_sub and hasattr(bs, 'objectItems'):
                self.ZopeFindAndApply(ob, obj_ids, obj_metatypes,
                                      obj_searchterm, obj_expr, obj_mtime,
                                      obj_mspec, obj_permission, obj_roles,
                                      search_sub, REQUEST, result, p,
                                      apply_func, apply_path)
            if dflag:
                ob._p_deactivate()

        return result
Beispiel #10
0
    def test_search_restrict_visible(self):
        from DateTime.DateTime import DateTime
        catalog = self._makeOne()
        catalog.addIndex('allowedRolesAndUsers', 'KeywordIndex')
        catalog.addIndex('effective', 'DateIndex')
        catalog.addIndex('expires', 'DateIndex')
        catalog.addIndex('meta_type', 'FieldIndex')

        now = DateTime()
        dummy = self._makeContent(catalog=1)
        dummy.allowedRolesAndUsers = ('Blob', )

        self.loginWithRoles('Blob')

        # visible
        dummy.effective = now - 2
        dummy.expires = now + 2
        catalog.catalog_object(dummy, '/dummy')
        query = {'meta_type': 'Dummy'}
        self.assertEqual(1, len(catalog._catalog.searchResults(query)))
        self.assertEqual(1, len(catalog.searchResults(query)))

        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': now - 1,
                    'range': 'min'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': now - 1,
                    'range': 'max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': now + 1,
                    'range': 'min'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': now + 1,
                    'range': 'max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': (now - 1, now + 1),
                    'range': 'min:max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': (now - 1, now + 1),
                    'range': 'minmax'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 2,
                    'range': None
                })))

        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': now - 3,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': now - 3,
                    'range': 'max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': now + 3,
                    'range': 'min'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': now + 3,
                    'range': 'max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': (now - 3, now + 3),
                    'range': 'min:max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': (now - 3, now + 3),
                    'range': 'minmax'
                })))

        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 1,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now - 1,
                    'range': 'max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now + 1,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now + 1,
                    'range': 'max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': (now - 1, now + 1),
                    'range': 'min:max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': (now - 1, now + 1),
                    'range': 'minmax'
                })))

        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 3,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now - 3,
                    'range': 'max'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now + 3,
                    'range': 'min'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now + 3,
                    'range': 'max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': (now - 3, now + 3),
                    'range': 'min:max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': (now - 3, now + 3),
                    'range': 'minmax'
                })))

        self.assertEqual(
            1,
            len(
                catalog.searchResults(effective={
                    'query': now - 1,
                    'range': 'max'
                },
                                      expires={
                                          'query': now + 1,
                                          'range': 'min'
                                      })))

        self.assertEqual(
            0,
            len(
                catalog.searchResults(effective={
                    'query': now + 1,
                    'range': 'max'
                },
                                      expires={
                                          'query': now + 3,
                                          'range': 'min'
                                      })))
 def modified(self):
     return DateTime(_FILE_MOD_TIME)
Beispiel #12
0
    def test_search_restrict_manager(self):
        from DateTime.DateTime import DateTime
        catalog = self._makeOne()
        catalog.addIndex('allowedRolesAndUsers', 'KeywordIndex')
        catalog.addIndex('effective', 'DateIndex')
        catalog.addIndex('expires', 'DateIndex')
        catalog.addIndex('meta_type', 'FieldIndex')
        now = DateTime()
        dummy = self._makeContent(catalog=1)

        self.loginManager()

        # already expired
        dummy.effective = now - 4
        dummy.expires = now - 2
        catalog.catalog_object(dummy, '/dummy')
        query = {'meta_type': 'Dummy'}
        self.assertEqual(1, len(catalog._catalog.searchResults(query)))
        self.assertEqual(1, len(catalog.searchResults(query)))

        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 3,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now - 1,
                    'range': 'min'
                })))
        self.assertEqual(
            0,
            len(
                catalog.searchResults(expires={
                    'query': now - 3,
                    'range': 'max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 1,
                    'range': 'max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': (now - 3, now - 1),
                    'range': 'min:max'
                })))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': (now - 3, now - 1),
                    'range': 'minmax'
                })))
        self.assertEqual(
            1, len(catalog.searchResults(expires={'query': now - 2})))
        self.assertEqual(
            1,
            len(
                catalog.searchResults(expires={
                    'query': now - 2,
                    'range': None
                })))
Beispiel #13
0
  def test_TypeChecking(self):
    fi= self.fi; obj= self.obj2
    # numeric
    fi.TermType= 'numeric'
    obj.id= 1; self.assertEqual(fi._evaluate(obj),1)
    obj.id= '1'; self.assertEqual(fi._evaluate(obj),1)
    obj.id= '1.0'; self.assertEqual(fi._evaluate(obj),1.0)
    obj.id= '1.0+'; self.assertRaises(Exception,fi._evaluate,obj)
    # string
    fi.TermType= 'string'
    obj.id= 1; self.assertEqual(fi._evaluate(obj),'1')
    obj.id= '1'; self.assertEqual(fi._evaluate(obj),'1')
    obj.id= obj; self.assertRaises(Exception,fi._evaluate,obj)
    # unicode
    fi.TermType= 'ustring'
    obj.id= u'1'; self.assertEqual(fi._evaluate(obj),u'1')
    obj.id= '1'; self.assertEqual(fi._evaluate(obj),u'1')
    # integer
    fi.TermType= 'integer'
    obj.id= 1; self.assertEqual(fi._evaluate(obj),1)
    obj.id= '1'; self.assertEqual(fi._evaluate(obj),1)
    obj.id= 1.1; self.assertEqual(fi._evaluate(obj),1)
    # DateTime
    fi.TermType= 'DateTime'; now= DateTime()
    obj.id= now; self.assertEqual(fi._evaluate(obj),now)
    obj.id= 'xyzZYX'; self.assertRaises(Exception,fi._evaluate,obj)
    # DateTimeInteger
    fi.TermType= 'DateTimeInteger'
    obj.id= now; v = fi._evaluate(obj)
    self.assert_(isinstance(v, int))
    self.assert_(abs(v-now._t) <= 1)
    # DateInteger
    fi.TermType= 'DateInteger'
    obj.id = DateTime('1000-01-01')
    v = fi._evaluate(obj)
    self.assert_(isinstance(v, int))
    self.assertEqual(v, 400000)
    # tuple
    fi.TermType= 'tuple'
    fi.TermTypeExtra= 'n(su)d'
    obj.id= (1,('1',u'1'),now); self.assertEqual(fi._evaluate(obj),obj.id)
    fi.TermTypeExtra+= 'n'
    self.assertRaises(Exception,fi._evaluate,obj)
    fi.TermTypeExtra= fi.TermTypeExtra[:-2]
    self.assertRaises(Exception,fi._evaluate,obj)
    # instance
    fi.TermType= 'instance'
    b= obj.aq_base; cl= b.__class__
    fi.TermTypeExtra= '%s.%s' % (cl.__module__,cl.__name__)
    obj.id= b; self.assertEqual(fi._evaluate(obj),b)
    obj.id= '1'; self.assertRaises(Exception,fi._evaluate,obj)
    # expression
    fi.TermType= 'expression checked'
    fi.TermTypeExtra= 'python: 1'
    self.assertEqual(fi._evaluate(obj),1)
    fi.TermTypeExtra= 'python: lambda v: 1'
    self.assertEqual(fi._evaluate(obj),1)

    ## term copy
    fi.TermType= 'instance'
    fi.TermTypeExtra= '%s._Object' % __name__
    b= _Object()
    obj.id= b; self.assert_(fi._evaluate(obj) is b)
    fi.TermCopy= 'shallow'
    v= fi._evaluate(obj)
    self.assertEqual(v,b)
    self.assert_(v is not b)
    fi.TermCopy= 'deep'
    b.l= []
    v= fi._evaluate(obj)
    self.assertEqual(v,b)
    self.assert_(v.l is not b.l)
Beispiel #14
0
def _mungeHeaders(messageText,
                  mto=None,
                  mfrom=None,
                  subject=None,
                  charset=None,
                  msg_type=None):
    """Sets missing message headers, and deletes Bcc.
       returns fixed message, fixed mto and fixed mfrom"""
    # If we have been given unicode fields, attempt to encode them
    if isinstance(messageText, unicode):
        messageText = _try_encode(messageText, charset)
    if isinstance(mto, unicode):
        mto = _try_encode(mto, charset)
    if isinstance(mfrom, unicode):
        mfrom = _try_encode(mfrom, charset)
    if isinstance(subject, unicode):
        subject = _try_encode(subject, charset)

    if isinstance(messageText, Message):
        # We already have a message, make a copy to operate on
        mo = deepcopy(messageText)
    else:
        # Otherwise parse the input message
        mo = message_from_string(messageText)

    if msg_type and not mo.get('Content-Type'):
        # we don't use get_content_type because that has a default
        # value of 'text/plain'
        mo.set_type(msg_type)

    charset = _set_recursive_charset(mo, charset=charset)

    # Parameters given will *always* override headers in the messageText.
    # This is so that you can't override or add to subscribers by adding
    # them to # the message text.
    if subject:
        # remove any existing header otherwise we get two
        del mo['Subject']
        # Perhaps we should ignore errors here and pass 8bit strings
        # on encoding errors
        mo['Subject'] = Header(subject, charset, errors='replace')
    elif not mo.get('Subject'):
        mo['Subject'] = '[No Subject]'

    if mto:
        if isinstance(mto, basestring):
            mto = [formataddr(addr) for addr in getaddresses((mto, ))]
        if not mo.get('To'):
            mo['To'] = ', '.join(
                str(_encode_address_string(e, charset)) for e in mto)
    else:
        # If we don't have recipients, extract them from the message
        mto = []
        for header in ('To', 'Cc', 'Bcc'):
            v = ','.join(mo.get_all(header) or [])
            if v:
                mto += [formataddr(addr) for addr in getaddresses((v, ))]
        if not mto:
            raise MailHostError("No message recipients designated")

    if mfrom:
        # XXX: do we really want to override an explicitly set From
        # header in the messageText
        del mo['From']
        mo['From'] = _encode_address_string(mfrom, charset)
    else:
        if mo.get('From') is None:
            raise MailHostError("Message missing SMTP Header 'From'")
        mfrom = mo['From']

    if mo.get('Bcc'):
        del mo['Bcc']

    if not mo.get('Date'):
        mo['Date'] = DateTime().rfc822()

    return mo.as_string(), mto, mfrom
 def getLastModified(self, path):
     try:
         zip_info = self._archive.getinfo(path)
     except KeyError:
         return None
     return DateTime(*zip_info.date_time)
Beispiel #16
0
    				    ),
    ))


#################################
## Base Fields
#################################


EffectiveDateSchema =  Schema((

    DateTimeField('effectiveDate',
                  searchable=True,
		  accessor="EffectiveDate",
		  mutator="setEffectiveDate",
		  default=DateTime(),
		  required=True,
		  isMetadata=True,
		  widget=CalendarWidget(label='Effective Date',
		                        description='Date when the content should become available on the public site',
					label_msgid='label_effective_date',
					description_msgid='help_effective_date',
					i18n_domain='plone')
					),																			  
    ))

TextSchema = Schema ((

    TextField('text',
              required=False,
	      searchable=True,
Beispiel #17
0
class DefaultDublinCoreImpl(PropertyManager):
    """
        Mix-in class which provides Dublin Core methods
    """
    __implements__ = DublinCore, CatalogableDublinCore, MutableDublinCore

    security = ClassSecurityInfo()

    def __init__(self,
                 title='',
                 subject=(),
                 description='',
                 contributors=(),
                 effective_date=None,
                 expiration_date=None,
                 format='text/html',
                 language='',
                 rights=''):
        now = DateTime()
        self.creation_date = now
        self.modification_date = now
        self._editMetadata(title, subject, description, contributors,
                           effective_date, expiration_date, format, language,
                           rights)

    #
    #  Set-modification-date-related methods.
    #  In DefaultDublinCoreImpl for lack of a better place.
    #

    # Class variable default for an upgrade.
    modification_date = None

    security.declarePrivate('notifyModified')

    def notifyModified(self):
        """
        Take appropriate action after the resource has been modified.
        For now, change the modification_date.
        """
        # XXX This could also store the id of the user doing modifications.
        self.setModificationDate()

    # XXX Could this be simply protected by ModifyPortalContent ?
    security.declarePrivate('setModificationDate')

    def setModificationDate(self, modification_date=None):
        """
            Set the date when the resource was last modified.
            When called without an argument, sets the date to now.
        """
        if modification_date is None:
            self.modification_date = DateTime()
        else:
            self.modification_date = self._datify(modification_date)

    #
    #  DublinCore interface query methods
    #
    security.declarePublic('Title')

    def Title(self):
        "Dublin Core element - resource name"
        return self.title

    security.declarePublic('Creator')

    def Creator(self):
        # XXX: fixme using 'portal_membership' -- should iterate over
        #       *all* owners
        "Dublin Core element - resource creator"
        owner_tuple = self.getOwnerTuple()
        if owner_tuple:
            return owner_tuple[1]
        return 'No owner'

    security.declarePublic('Subject')

    def Subject(self):
        "Dublin Core element - resource keywords"
        return getattr(self, 'subject', ())  # compensate for *old* content

    security.declarePublic('Publisher')

    def Publisher(self):
        "Dublin Core element - resource publisher"
        portal_metadata = getToolByName(self, 'portal_metadata', None)

        if portal_metadata is not None:
            return portal_metadata.getPublisher()

        return 'No publisher'

    security.declarePublic('Description')

    def Description(self):
        "Dublin Core element - resource summary"
        return self.description

    security.declarePublic('Contributors')

    def Contributors(self):
        "Dublin Core element - additional contributors to resource"
        # XXX: fixme
        return self.contributors

    security.declarePublic('Date')

    def Date(self):
        "Dublin Core element - default date"
        # Return effective_date if set, modification date otherwise
        date = getattr(self, 'effective_date', None)
        if date is None:
            date = self.modified()
        return date.ISO()

    security.declarePublic('CreationDate')

    def CreationDate(self):
        """
            Dublin Core element - date resource created.
        """
        # return unknown if never set properly
        return self.creation_date and self.creation_date.ISO() or 'Unknown'

    security.declarePublic('EffectiveDate')

    def EffectiveDate(self):
        """
            Dublin Core element - date resource becomes effective.
        """
        ed = getattr(self, 'effective_date', None)
        return ed and ed.ISO() or 'None'

    security.declarePublic('ExpirationDate')

    def ExpirationDate(self):
        """
            Dublin Core element - date resource expires.
        """
        ed = getattr(self, 'expiration_date', None)
        return ed and ed.ISO() or 'None'

    security.declarePublic('ModificationDate')

    def ModificationDate(self):
        """
            Dublin Core element - date resource last modified.
        """
        return self.modified().ISO()

    security.declarePublic('Type')

    def Type(self):
        "Dublin Core element - Object type"
        if hasattr(aq_base(self), 'getTypeInfo'):
            ti = self.getTypeInfo()
            if ti is not None:
                return ti.Title()
        return self.meta_type

    security.declarePublic('Format')

    def Format(self):
        """
            Dublin Core element - resource format
        """
        return self.format

    security.declarePublic('Identifier')

    def Identifier(self):
        "Dublin Core element - Object ID"
        # XXX: fixme using 'portal_metadata' (we need to prepend the
        #      right prefix to self.getPhysicalPath().
        return self.absolute_url()

    security.declarePublic('Language')

    def Language(self):
        """
            Dublin Core element - resource language
        """
        return self.language

    security.declarePublic('Rights')

    def Rights(self):
        """
            Dublin Core element - resource copyright
        """
        return self.rights

    #
    #  DublinCore utility methods
    #
    def content_type(self):
        """
            WebDAV needs this to do the Right Thing (TM).
        """
        return self.Format()

    __FLOOR_DATE = DateTime(1970, 0)  # always effective

    security.declarePublic('isEffective')

    def isEffective(self, date):
        """
            Is the date within the resource's effective range?
        """
        pastEffective = (self.effective_date is None
                         or self.effective_date <= date)
        beforeExpiration = (self.expiration_date is None
                            or self.expiration_date >= date)
        return pastEffective and beforeExpiration

    #
    #  CatalogableDublinCore methods
    #
    security.declarePublic('created')

    def created(self):
        """
            Dublin Core element - date resource created,
              returned as DateTime.
        """
        # allow for non-existent creation_date, existed always
        date = getattr(self, 'creation_date', None)
        return date is None and self.__FLOOR_DATE or date

    security.declarePublic('effective')

    def effective(self):
        """
            Dublin Core element - date resource becomes effective,
              returned as DateTime.
        """
        marker = []
        date = getattr(self, 'effective_date', marker)
        if date is marker:
            date = getattr(self, 'creation_date', None)
        return date is None and self.__FLOOR_DATE or date

    __CEILING_DATE = DateTime(9999, 0)  # never expires

    security.declarePublic('expires')

    def expires(self):
        """
            Dublin Core element - date resource expires,
              returned as DateTime.
        """
        date = getattr(self, 'expiration_date', None)
        return date is None and self.__CEILING_DATE or date

    security.declarePublic('modified')

    def modified(self):
        """
            Dublin Core element - date resource last modified,
              returned as DateTime.
        """
        date = self.modification_date
        if date is None:
            # Upgrade.
            date = self.bobobase_modification_time()
            self.modification_date = date
        return date

    security.declarePublic('getMetadataHeaders')

    def getMetadataHeaders(self):
        """
            Return RFC-822-style headers.
        """
        hdrlist = []
        hdrlist.append(('Title', self.Title()))
        hdrlist.append(('Subject', string.join(self.Subject(), ', ')))
        hdrlist.append(('Publisher', self.Publisher()))
        hdrlist.append(('Description', self.Description()))
        hdrlist.append(('Contributors', string.join(self.Contributors(),
                                                    '; ')))
        hdrlist.append(('Effective_date', self.EffectiveDate()))
        hdrlist.append(('Expiration_date', self.ExpirationDate()))
        hdrlist.append(('Type', self.Type()))
        hdrlist.append(('Format', self.Format()))
        hdrlist.append(('Language', self.Language()))
        hdrlist.append(('Rights', self.Rights()))
        return hdrlist

    #
    #  MutableDublinCore methods
    #
    security.declarePrivate('_datify')

    def _datify(self, attrib):
        if attrib == 'None':
            attrib = None
        elif not isinstance(attrib, DateTime):
            if attrib is not None:
                attrib = DateTime(attrib)
        return attrib

    security.declareProtected(ModifyPortalContent, 'setTitle')

    def setTitle(self, title):
        "Dublin Core element - resource name"
        self.title = title

    security.declareProtected(ModifyPortalContent, 'setSubject')

    def setSubject(self, subject):
        "Dublin Core element - resource keywords"
        self.subject = tuplize('subject', subject)

    security.declareProtected(ModifyPortalContent, 'setDescription')

    def setDescription(self, description):
        "Dublin Core element - resource summary"
        self.description = description

    security.declareProtected(ModifyPortalContent, 'setContributors')

    def setContributors(self, contributors):
        "Dublin Core element - additional contributors to resource"
        # XXX: fixme
        self.contributors = tuplize('contributors', contributors, semi_split)

    security.declareProtected(ModifyPortalContent, 'setEffectiveDate')

    def setEffectiveDate(self, effective_date):
        """
            Dublin Core element - date resource becomes effective.
        """
        self.effective_date = self._datify(effective_date)

    security.declareProtected(ModifyPortalContent, 'setExpirationDate')

    def setExpirationDate(self, expiration_date):
        """
            Dublin Core element - date resource expires.
        """
        self.expiration_date = self._datify(expiration_date)

    security.declareProtected(ModifyPortalContent, 'setFormat')

    def setFormat(self, format):
        """
            Dublin Core element - resource format
        """
        self.format = format

    security.declareProtected(ModifyPortalContent, 'setLanguage')

    def setLanguage(self, language):
        """
            Dublin Core element - resource language
        """
        self.language = language

    security.declareProtected(ModifyPortalContent, 'setRights')

    def setRights(self, rights):
        """
            Dublin Core element - resource copyright
        """
        self.rights = rights

    #
    #  Management tab methods
    #

    security.declarePrivate('_editMetadata')

    def _editMetadata(self,
                      title=_marker,
                      subject=_marker,
                      description=_marker,
                      contributors=_marker,
                      effective_date=_marker,
                      expiration_date=_marker,
                      format=_marker,
                      language=_marker,
                      rights=_marker):
        """
            Update the editable metadata for this resource.
        """
        if title is not _marker:
            self.setTitle(title)
        if subject is not _marker:
            self.setSubject(subject)
        if description is not _marker:
            self.setDescription(description)
        if contributors is not _marker:
            self.setContributors(contributors)
        if effective_date is not _marker:
            self.setEffectiveDate(effective_date)
        if expiration_date is not _marker:
            self.setExpirationDate(expiration_date)
        if format is not _marker:
            self.setFormat(format)
        if language is not _marker:
            self.setLanguage(language)
        if rights is not _marker:
            self.setRights(rights)

    security.declareProtected(ModifyPortalContent, 'manage_metadata')
    manage_metadata = DTMLFile('zmi_metadata', _dtmldir)

    security.declareProtected(ModifyPortalContent, 'manage_editMetadata')

    def manage_editMetadata(self, title, subject, description, contributors,
                            effective_date, expiration_date, format, language,
                            rights, REQUEST):
        """
            Update metadata from the ZMI.
        """
        self._editMetadata(title, subject, description, contributors,
                           effective_date, expiration_date, format, language,
                           rights)
        REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_metadata' +
                                     '?manage_tabs_message=Metadata+updated.')

    security.declareProtected(ModifyPortalContent, 'editMetadata')

    def editMetadata(self,
                     title='',
                     subject=(),
                     description='',
                     contributors=(),
                     effective_date=None,
                     expiration_date=None,
                     format='text/html',
                     language='en-US',
                     rights=''):
        """
        used to be:  editMetadata = WorkflowAction(_editMetadata)
        Need to add check for webDAV locked resource for TTW methods.
        """
        # as per bug #69, we cant assume they use the webdav
        # locking interface, and fail gracefully if they dont
        if hasattr(self, 'failIfLocked'):
            self.failIfLocked()

        self._editMetadata(title=title,
                           subject=subject,
                           description=description,
                           contributors=contributors,
                           effective_date=effective_date,
                           expiration_date=expiration_date,
                           format=format,
                           language=language,
                           rights=rights)
        self.reindexObject()
Beispiel #18
0
class DefaultDublinCoreImpl(PropertyManager):
    """
        Mix-in class which provides Dublin Core methods
    """
    __implements__ = DublinCore, CatalogableDublinCore, MutableDublinCore

    security = ClassSecurityInfo()

    def __init__(self,
                 title='',
                 subject=(),
                 description='',
                 contributors=(),
                 effective_date=None,
                 expiration_date=None,
                 format='text/html',
                 language='',
                 rights=''):
        self.creation_date = DateTime()
        self._editMetadata(title, subject, description, contributors,
                           effective_date, expiration_date, format, language,
                           rights)

    #
    #  DublinCore interface query methods
    #
    security.declarePublic('Title')

    def Title(self):
        "Dublin Core element - resource name"
        return self.title

    security.declarePublic('Creator')

    def Creator(self):
        # XXX: fixme using 'portal_membership' -- should iterate over
        #       *all* owners
        "Dublin Core element - resource creator"
        owner = self.getOwner()
        if hasattr(owner, 'getUserName'):
            return owner.getUserName()
        return 'No owner'

    security.declarePublic('Subject')

    def Subject(self):
        "Dublin Core element - resource keywords"
        return self.subject

    security.declarePublic('Publisher')

    def Publisher(self):
        "Dublin Core element - resource publisher"
        # XXX: fixme using 'portal_metadata'
        return 'No publisher'

    security.declarePublic('Description')

    def Description(self):
        "Dublin Core element - resource summary"
        return self.description

    security.declarePublic('Contributors')

    def Contributors(self):
        "Dublin Core element - additional contributors to resource"
        # XXX: fixme
        return self.contributors

    security.declarePublic('Date')

    def Date(self):
        "Dublin Core element - default date"
        # Return effective_date if set, modification date otherwise
        date = getattr(self, 'effective_date', None)
        if date is None:
            date = self.bobobase_modification_time()
        return date.ISO()

    security.declarePublic('CreationDate')

    def CreationDate(self):
        """
            Dublin Core element - date resource created.
        """
        return self.creation_date.ISO()

    security.declarePublic('EffectiveDate')

    def EffectiveDate(self):
        """
            Dublin Core element - date resource becomes effective.
        """
        return self.effective_date and self.effective_date.ISO() or 'None'

    security.declarePublic('ExpirationDate')

    def ExpirationDate(self):
        """
            Dublin Core element - date resource expires.
        """
        return self.expiration_date and self.expiration_date.ISO() or 'None'

    security.declarePublic('ModificationDate')

    def ModificationDate(self):
        """
            Dublin Core element - date resource last modified.
        """
        return self.bobobase_modification_time().ISO()

    security.declarePublic('Type')

    def Type(self):
        "Dublin Core element - Object type"
        if hasattr(aq_base(self), 'getTypeInfo'):
            ti = self.getTypeInfo()
            if ti is not None:
                return ti.Type()
        return self.meta_type

    security.declarePublic('Format')

    def Format(self):
        """
            Dublin Core element - resource format
        """
        return self.format

    security.declarePublic('Identifier')

    def Identifier(self):
        "Dublin Core element - Object ID"
        # XXX: fixme using 'portal_metadata' (we need to prepend the
        #      right prefix to self.getPhysicalPath().
        return self.absolute_url()

    security.declarePublic('Language')

    def Language(self):
        """
            Dublin Core element - resource language
        """
        return self.language

    security.declarePublic('Rights')

    def Rights(self):
        """
            Dublin Core element - resource copyright
        """
        return self.rights

    #
    #  DublinCore utility methods
    #
    def content_type(self):
        """
            WebDAV needs this to do the Right Thing (TM).
        """
        return self.Format()

    security.declarePublic('isEffective')

    def isEffective(self, date):
        """
            Is the date within the resource's effective range?
        """
        pastEffective = (self.effective_date is None
                         or self.effective_date <= date)
        beforeExpiration = (self.expiration_date is None
                            or self.expiration_date >= date)
        return pastEffective and beforeExpiration

    #
    #  CatalogableDublinCore methods
    #
    security.declarePublic('created')

    def created(self):
        """
            Dublin Core element - date resource created,
              returned as DateTime.
        """
        return self.creation_date

    __FLOOR_DATE = DateTime(1000, 0)  # alwasy effective

    security.declarePublic('effective')

    def effective(self):
        """
            Dublin Core element - date resource becomes effective,
              returned as DateTime.
        """
        marker = []
        date = getattr(self, 'effective_date', marker)
        if date is marker:
            date = getattr(self, 'creation_date', None)
        return date is None and self.__FLOOR_DATE or date

    __CEILING_DATE = DateTime(9999, 0)  # never expires

    security.declarePublic('expires')

    def expires(self):
        """
            Dublin Core element - date resource expires,
              returned as DateTime.
        """
        date = getattr(self, 'expiration_date', None)
        return date is None and self.__CEILING_DATE or date

    security.declarePublic('modified')

    def modified(self):
        """
            Dublin Core element - date resource last modified,
              returned as DateTime.
        """
        return self.bobobase_modification_time()

    security.declarePublic('getMetadataHeaders')

    def getMetadataHeaders(self):
        """
            Return RFC-822-style headers.
        """
        hdrlist = []
        hdrlist.append(('Title', self.Title()))
        hdrlist.append(('Subject', string.join(self.Subject(), ', ')))
        hdrlist.append(('Publisher', self.Publisher()))
        hdrlist.append(('Description', self.Description()))
        hdrlist.append(('Contributors', string.join(self.Contributors(),
                                                    '; ')))
        hdrlist.append(('Effective_date', self.EffectiveDate()))
        hdrlist.append(('Expiration_date', self.ExpirationDate()))
        hdrlist.append(('Type', self.Type()))
        hdrlist.append(('Format', self.Format()))
        hdrlist.append(('Language', self.Language()))
        hdrlist.append(('Rights', self.Rights()))
        return hdrlist

    #
    #  MutableDublinCore methods
    #
    security.declarePrivate('_datify')

    def _datify(self, attrib):
        if attrib == 'None':
            attrib = None
        elif not isinstance(attrib, DateTime):
            if attrib is not None:
                attrib = DateTime(attrib)
        return attrib

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setTitle')

    def setTitle(self, title):
        "Dublin Core element - resource name"
        self.title = title

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setSubject')

    def setSubject(self, subject):
        "Dublin Core element - resource keywords"
        self.subject = tuplize('subject', subject)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setDescription')

    def setDescription(self, description):
        "Dublin Core element - resource summary"
        self.description = description

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setContributors')

    def setContributors(self, contributors):
        "Dublin Core element - additional contributors to resource"
        # XXX: fixme
        self.contributors = tuplize('contributors', contributors, semi_split)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setEffectiveDate')

    def setEffectiveDate(self, effective_date):
        """
            Dublin Core element - date resource becomes effective.
        """
        self.effective_date = self._datify(effective_date)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setExpirationDate')

    def setExpirationDate(self, expiration_date):
        """
            Dublin Core element - date resource expires.
        """
        self.expiration_date = self._datify(expiration_date)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setFormat')

    def setFormat(self, format):
        """
            Dublin Core element - resource format
        """
        self.format = format

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setLanguage')

    def setLanguage(self, language):
        """
            Dublin Core element - resource language
        """
        self.language = language

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'setRights')

    def setRights(self, rights):
        """
            Dublin Core element - resource copyright
        """
        self.rights = rights

    #
    #  Management tab methods
    #

    security.declarePrivate('_editMetadata')

    def _editMetadata(self,
                      title='',
                      subject=(),
                      description='',
                      contributors=(),
                      effective_date=None,
                      expiration_date=None,
                      format='text/html',
                      language='en-US',
                      rights=''):
        """
            Update the editable metadata for this resource.
        """
        self.setTitle(title)
        self.setSubject(subject)
        self.setDescription(description)
        self.setContributors(contributors)
        self.setEffectiveDate(effective_date)
        self.setExpirationDate(expiration_date)
        self.setFormat(format)
        self.setLanguage(language)
        self.setRights(rights)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'manage_metadata')
    manage_metadata = DTMLFile('zmi_metadata', _dtmldir)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'manage_editMetadata')

    def manage_editMetadata(self, title, subject, description, contributors,
                            effective_date, expiration_date, format, language,
                            rights, REQUEST):
        """
            Update metadata from the ZMI.
        """
        self._editMetadata(title, subject, description, contributors,
                           effective_date, expiration_date, format, language,
                           rights)
        REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_metadata' +
                                     '?manage_tabs_message=Metadata+updated.')

    security.declareProtected(CMFCorePermissions.ModifyPortalContent,
                              'editMetadata')

    def editMetadata(self,
                     title='',
                     subject=(),
                     description='',
                     contributors=(),
                     effective_date=None,
                     expiration_date=None,
                     format='text/html',
                     language='en-US',
                     rights=''):
        """
        used to be:  editMetadata = WorkflowAction(_editMetadata)
        Need to add check for webDAV locked resource for TTW methods.
        """
        self.failIfLocked()
        self._editMetadata(title=title,
                           subject=subject,
                           description=description,
                           contributors=contributors,
                           effective_date=effective_date,
                           expiration_date=expiration_date,
                           format=format,
                           language=language,
                           rights=rights)
        self.reindexObject()
    def test15_storageStatistics(self):
        self.maxDiff = None
        portal_storage = self.portal.portal_historiesstorage

        cmf_uid = 1
        obj1 = CMFDummy('obj', cmf_uid)
        obj1.text = 'v1 of text'
        portal_storage.register(cmf_uid,
                                ObjectData(obj1),
                                metadata=self.buildMetadata('saved v1'))

        obj2 = CMFDummy('obj', cmf_uid)
        obj2.text = 'v2 of text'
        portal_storage.save(cmf_uid,
                            ObjectData(obj2),
                            metadata=self.buildMetadata('saved v2'))

        obj3 = CMFDummy('obj', cmf_uid)
        obj3.text = 'v3 of text'
        portal_storage.save(cmf_uid,
                            ObjectData(obj3),
                            metadata=self.buildMetadata('saved v3'))

        obj4 = CMFDummy('obj', cmf_uid)
        obj4.text = 'v4 of text'
        self.portal._setObject('obj', obj4)
        self.portal.portal_catalog.indexObject(self.portal.obj)
        portal_storage.save(cmf_uid,
                            ObjectData(obj4),
                            metadata=self.buildMetadata('saved v4'))

        cmf_uid = 2
        tomorrow = DateTime() + 1
        obj5 = CMFDummy('tomorrow', cmf_uid, effective=tomorrow)
        obj5.allowedRolesAndUsers = ['Anonymous']
        self.portal._setObject('tomorrow', obj5)
        self.portal.portal_catalog.indexObject(self.portal.tomorrow)
        portal_storage.register(
            cmf_uid,
            ObjectData(obj5),
            metadata=self.buildMetadata('effective tomorrow'))

        cmf_uid = 3
        yesterday = DateTime() - 1
        obj6 = CMFDummy('yesterday', cmf_uid, expires=yesterday)
        obj6.allowedRolesAndUsers = ['Anonymous']
        self.portal._setObject('yesterday', obj6)
        self.portal.portal_catalog.indexObject(self.portal.yesterday)
        portal_storage.register(
            cmf_uid,
            ObjectData(obj6),
            metadata=self.buildMetadata('expired yesterday'))

        cmf_uid = 4
        obj7 = CMFDummy('public', cmf_uid)
        obj7.text = 'visible for everyone'
        obj7.allowedRolesAndUsers = ['Anonymous']
        self.portal._setObject('public', obj7)
        self.portal.portal_catalog.indexObject(self.portal.public)
        portal_storage.register(cmf_uid,
                                ObjectData(obj7),
                                metadata=self.buildMetadata('saved public'))

        got = portal_storage.zmi_getStorageStatistics()
        expected = {
            'deleted': [],
            'summaries': {
                'totalHistories': 4,
                'deletedVersions': 0,
                'existingVersions': 7,
                'deletedHistories': 0,
                # time may easily be different
                # 'time': '0.00',
                'totalVersions': 7,
                'existingAverage': '1.8',
                'existingHistories': 4,
                'deletedAverage': 'n/a',
                'totalAverage': '1.8'
            },
            'existing': [{
                'url': 'http://nohost/plone/obj',
                'history_id': 1,
                'length': 4,
                'path': '/obj',
                'sizeState': 'approximate',
                'portal_type': 'Dummy',
            }, {
                'url': 'http://nohost/plone/tomorrow',
                'history_id': 2,
                'length': 1,
                'path': '/tomorrow',
                'sizeState': 'approximate',
                'portal_type': 'Dummy',
            }, {
                'url': 'http://nohost/plone/yesterday',
                'history_id': 3,
                'length': 1,
                'path': '/yesterday',
                'sizeState': 'approximate',
                'portal_type': 'Dummy',
            }, {
                'url': 'http://nohost/plone/public',
                'history_id': 4,
                'length': 1,
                'path': '/public',
                'sizeState': 'approximate',
                'portal_type': 'Dummy',
            }]
        }
        self.assertEqual(expected['deleted'], got['deleted'])
        self.assertTrue('summaries' in got)
        self.assertTrue('time' in got['summaries'])
        for key, value in expected['summaries'].items():
            self.assertEqual(value, got['summaries'][key])
        self.assertEqual(len(expected['existing']), len(got['existing']))
        for idx in range(len(expected['existing'])):
            exp = expected['existing'][idx]
            actual = got['existing'][idx]
            for key, value in exp.items():
                self.assertEqual(actual[key], value)
            # The actual size is not important and we want robust tests,
            # s. https://github.com/plone/Products.CMFEditions/issues/31
            self.failUnless(actual['size'] > 0)
Beispiel #20
0
    def modifyRequest(self, req, resp):
        """Copies cookie-supplied credentials to the basic auth fields.

        Returns a flag indicating what the user is trying to do with
        cookies: ATTEMPT_NONE, ATTEMPT_LOGIN, or ATTEMPT_RESUME.  If
        cookie login is disabled for this request, raises
        CookieCrumblerDisabled.
        """
        if (req.__class__ is not HTTPRequest
                or not req['REQUEST_METHOD'] in ('HEAD', 'GET', 'PUT', 'POST')
                or req.environ.has_key('WEBDAV_SOURCE_PORT')):
            raise CookieCrumblerDisabled

        # attempt may contain information about an earlier attempt to
        # authenticate using a higher-up cookie crumbler within the
        # same request.
        attempt = getattr(req, '_cookie_auth', ATTEMPT_NONE)

        if attempt == ATTEMPT_NONE:
            if req._auth:
                # An auth header was provided and no cookie crumbler
                # created it.  The user must be using basic auth.
                raise CookieCrumblerDisabled

            if req.has_key(self.pw_cookie) and req.has_key(self.name_cookie):
                # Attempt to log in and set cookies.
                attempt = ATTEMPT_LOGIN
                name = req[self.name_cookie]
                pw = req[self.pw_cookie]
                ac = encodestring('%s:%s' % (name, pw)).rstrip()
                self._setAuthHeader(ac, req, resp)
                if req.get(self.persist_cookie, 0):
                    # Persist the user name (but not the pw or session)
                    expires = (DateTime() + 365).toZone('GMT').rfc822()
                    resp.setCookie(self.name_cookie,
                                   name,
                                   path=self.getCookiePath(),
                                   expires=expires)
                else:
                    # Expire the user name
                    resp.expireCookie(self.name_cookie,
                                      path=self.getCookiePath())
                method = self.getCookieMethod('setAuthCookie',
                                              self.defaultSetAuthCookie)
                method(resp, self.auth_cookie, quote(ac))
                self.delRequestVar(req, self.name_cookie)
                self.delRequestVar(req, self.pw_cookie)

            elif req.has_key(self.auth_cookie):
                # Attempt to resume a session if the cookie is valid.
                # Copy __ac to the auth header.
                ac = unquote(req[self.auth_cookie])
                if ac and ac != 'deleted':
                    try:
                        decodestring(ac)
                    except:
                        # Not a valid auth header.
                        pass
                    else:
                        attempt = ATTEMPT_RESUME
                        self._setAuthHeader(ac, req, resp)
                        self.delRequestVar(req, self.auth_cookie)
                        method = self.getCookieMethod('twiddleAuthCookie',
                                                      None)
                        if method is not None:
                            method(resp, self.auth_cookie, quote(ac))

        req._cookie_auth = attempt
        return attempt
 def test_getModTime(self):
     script = self._makeOne('test1', 'test1.py')
     self.assertTrue(isinstance(script.getModTime(), DateTime))
     self.assertEqual(script.getModTime(),
                      DateTime(os.stat(script._filepath).st_mtime))
Beispiel #22
0
from Products.CMFCore.interfaces.DublinCore \
        import DublinCore as z2IDublinCore
from Products.CMFCore.interfaces.DublinCore \
        import MutableDublinCore as z2IMutableDublinCore

from permissions import ModifyPortalContent
from permissions import View
from utils import tuplize
from utils import _dtmldir
from utils import semi_split

_marker=[]

# For http://www.zope.org/Collectors/CMF/325
# We only really need this once, at startup.
_zone = DateTime().timezone()


class DefaultDublinCoreImpl( PropertyManager ):

    """ Mix-in class which provides Dublin Core methods.
    """

    implements(IDublinCore, ICatalogableDublinCore, IMutableDublinCore)
    __implements__ = (z2IDublinCore, z2ICatalogableDublinCore,
                      z2IMutableDublinCore)

    security = ClassSecurityInfo()

    def __init__( self
                , title=''
Beispiel #23
0
    def _range_request_handler(self, REQUEST, RESPONSE):
        # HTTP Range header handling: return True if we've served a range
        # chunk out of our data.
        range = REQUEST.get_header('Range', None)
        request_range = REQUEST.get_header('Request-Range', None)
        if request_range is not None:
            # Netscape 2 through 4 and MSIE 3 implement a draft version
            # Later on, we need to serve a different mime-type as well.
            range = request_range
        if_range = REQUEST.get_header('If-Range', None)
        if range is not None:
            ranges = HTTPRangeSupport.parseRange(range)

            if if_range is not None:
                # Only send ranges if the data isn't modified, otherwise send
                # the whole object. Support both ETags and Last-Modified dates!
                if len(if_range) > 1 and if_range[:2] == 'ts':
                    # ETag:
                    if if_range != self.http__etag():
                        # Modified, so send a normal response. We delete
                        # the ranges, which causes us to skip to the 200
                        # response.
                        ranges = None
                else:
                    # Date
                    date = if_range.split(';')[0]
                    try:
                        mod_since = long(DateTime(date).timeTime())
                    except:
                        mod_since = None
                    if mod_since is not None:
                        if self._p_mtime:
                            last_mod = long(self._p_mtime)
                        else:
                            last_mod = long(0)
                        if last_mod > mod_since:
                            # Modified, so send a normal response. We delete
                            # the ranges, which causes us to skip to the 200
                            # response.
                            ranges = None

            if ranges:
                # Search for satisfiable ranges.
                satisfiable = 0
                for start, end in ranges:
                    if start < self.size:
                        satisfiable = 1
                        break

                if not satisfiable:
                    RESPONSE.setHeader('Content-Range',
                                       'bytes */%d' % self.size)
                    RESPONSE.setHeader('Accept-Ranges', 'bytes')
                    RESPONSE.setHeader('Last-Modified',
                                       rfc1123_date(self._p_mtime))
                    RESPONSE.setHeader('Content-Type', self.content_type)
                    RESPONSE.setHeader('Content-Length', self.size)
                    RESPONSE.setStatus(416)
                    return True

                ranges = HTTPRangeSupport.expandRanges(ranges, self.size)

                if len(ranges) == 1:
                    # Easy case, set extra header and return partial set.
                    start, end = ranges[0]
                    size = end - start

                    RESPONSE.setHeader('Last-Modified',
                                       rfc1123_date(self._p_mtime))
                    RESPONSE.setHeader('Content-Type', self.content_type)
                    RESPONSE.setHeader('Content-Length', size)
                    RESPONSE.setHeader('Accept-Ranges', 'bytes')
                    RESPONSE.setHeader(
                        'Content-Range',
                        'bytes %d-%d/%d' % (start, end - 1, self.size))
                    RESPONSE.setStatus(206)  # Partial content

                    data = self.data
                    if isinstance(data, str):
                        RESPONSE.write(data[start:end])
                        return True

                    # Linked Pdata objects. Urgh.
                    pos = 0
                    while data is not None:
                        l = len(data.data)
                        pos = pos + l
                        if pos > start:
                            # We are within the range
                            lstart = l - (pos - start)

                            if lstart < 0: lstart = 0

                            # find the endpoint
                            if end <= pos:
                                lend = l - (pos - end)

                                # Send and end transmission
                                RESPONSE.write(data[lstart:lend])
                                break

                            # Not yet at the end, transmit what we have.
                            RESPONSE.write(data[lstart:])

                        data = data.next

                    return True

                else:
                    boundary = choose_boundary()

                    # Calculate the content length
                    size = (
                        8 + len(boundary) +  # End marker length
                        len(ranges) * (  # Constant lenght per set
                            49 + len(boundary) + len(self.content_type) +
                            len('%d' % self.size)))
                    for start, end in ranges:
                        # Variable length per set
                        size = (size + len('%d%d' % (start, end - 1)) + end -
                                start)

                    # Some clients implement an earlier draft of the spec, they
                    # will only accept x-byteranges.
                    draftprefix = (request_range is not None) and 'x-' or ''

                    RESPONSE.setHeader('Content-Length', size)
                    RESPONSE.setHeader('Accept-Ranges', 'bytes')
                    RESPONSE.setHeader('Last-Modified',
                                       rfc1123_date(self._p_mtime))
                    RESPONSE.setHeader(
                        'Content-Type', 'multipart/%sbyteranges; boundary=%s' %
                        (draftprefix, boundary))
                    RESPONSE.setStatus(206)  # Partial content

                    data = self.data
                    # The Pdata map allows us to jump into the Pdata chain
                    # arbitrarily during out-of-order range searching.
                    pdata_map = {}
                    pdata_map[0] = data

                    for start, end in ranges:
                        RESPONSE.write('\r\n--%s\r\n' % boundary)
                        RESPONSE.write('Content-Type: %s\r\n' %
                                       self.content_type)
                        RESPONSE.write(
                            'Content-Range: bytes %d-%d/%d\r\n\r\n' %
                            (start, end - 1, self.size))

                        if isinstance(data, str):
                            RESPONSE.write(data[start:end])

                        else:
                            # Yippee. Linked Pdata objects. The following
                            # calculations allow us to fast-forward through the
                            # Pdata chain without a lot of dereferencing if we
                            # did the work already.
                            first_size = len(pdata_map[0].data)
                            if start < first_size:
                                closest_pos = 0
                            else:
                                closest_pos = ((
                                    (start - first_size) >> 16 << 16) +
                                               first_size)
                            pos = min(closest_pos, max(pdata_map.keys()))
                            data = pdata_map[pos]

                            while data is not None:
                                l = len(data.data)
                                pos = pos + l
                                if pos > start:
                                    # We are within the range
                                    lstart = l - (pos - start)

                                    if lstart < 0: lstart = 0

                                    # find the endpoint
                                    if end <= pos:
                                        lend = l - (pos - end)

                                        # Send and loop to next range
                                        RESPONSE.write(data[lstart:lend])
                                        break

                                    # Not yet at the end, transmit what we have.
                                    RESPONSE.write(data[lstart:])

                                data = data.next
                                # Store a reference to a Pdata chain link so we
                                # don't have to deref during this request again.
                                pdata_map[pos] = data

                    # Do not keep the link references around.
                    del pdata_map

                    RESPONSE.write('\r\n--%s--\r\n' % boundary)
                    return True
Beispiel #24
0
class DefaultDublinCoreImpl( PropertyManager ):

    """ Mix-in class which provides Dublin Core methods.
    """

    implements(IDublinCore, ICatalogableDublinCore, IMutableDublinCore)
    __implements__ = (z2IDublinCore, z2ICatalogableDublinCore,
                      z2IMutableDublinCore)

    security = ClassSecurityInfo()

    def __init__( self
                , title=''
                , subject=()
                , description=''
                , contributors=()
                , effective_date=None
                , expiration_date=None
                , format='text/html'
                , language=''
                , rights=''
                ):
        now = DateTime()
        self.creation_date = now
        self.modification_date = now
        self.creators = ()
        self._editMetadata( title
                          , subject
                          , description
                          , contributors
                          , effective_date
                          , expiration_date
                          , format
                          , language
                          , rights
                          )

    #
    #  Set-modification-date-related methods.
    #  In DefaultDublinCoreImpl for lack of a better place.
    #

    # Class variable default for an upgrade.
    modification_date = None

    security.declarePrivate('notifyModified')
    def notifyModified(self):
        """ Take appropriate action after the resource has been modified.

        Update creators and modification_date.
        """
        self.addCreator()
        self.setModificationDate()

    security.declareProtected(ModifyPortalContent, 'addCreator')
    def addCreator(self, creator=None):
        """ Add creator to Dublin Core creators.
        """
        if creator is None:
            mtool = queryUtility(IMembershipTool)
            creator = mtool and mtool.getAuthenticatedMember().getId()

        # call self.listCreators() to make sure self.creators exists
        if creator and not creator in self.listCreators():
            self.creators = self.creators + (creator, )

    security.declareProtected(ModifyPortalContent, 'setModificationDate')
    def setModificationDate(self, modification_date=None):
        """ Set the date when the resource was last modified.

        When called without an argument, sets the date to now.
        """
        if modification_date is None:
            self.modification_date = DateTime()
        else:
            self.modification_date = self._datify(modification_date)

    #
    #  DublinCore interface query methods
    #
    security.declareProtected(View, 'Title')
    def Title( self ):
        """ Dublin Core Title element - resource name.
        """
        return self.title

    security.declareProtected(View, 'listCreators')
    def listCreators(self):
        """ List Dublin Core Creator elements - resource authors.
        """
        if not hasattr(aq_base(self), 'creators'):
            # for content created with CMF versions before 1.5
            owner_tuple = self.getOwnerTuple()
            if owner_tuple:
                self.creators = (owner_tuple[1],)
            else:
                self.creators = ()
        return self.creators

    security.declareProtected(View, 'Creator')
    def Creator(self):
        """ Dublin Core Creator element - resource author.
        """
        creators = self.listCreators()
        return creators and creators[0] or ''

    security.declareProtected(View, 'Subject')
    def Subject( self ):
        """ Dublin Core Subject element - resource keywords.
        """
        return getattr( self, 'subject', () ) # compensate for *old* content

    security.declareProtected(View, 'Description')
    def Description( self ):
        """ Dublin Core Description element - resource summary.
        """
        return self.description

    security.declareProtected(View, 'Publisher')
    def Publisher( self ):
        """ Dublin Core Publisher element - resource publisher.
        """
        tool = queryUtility(IMetadataTool)

        if tool is not None:
            return tool.getPublisher()

        return 'No publisher'

    security.declareProtected(View, 'listContributors')
    def listContributors(self):
        """ Dublin Core Contributor elements - resource collaborators.
        """
        return self.contributors

    security.declareProtected(View, 'Contributors')
    def Contributors(self):
        """ Deprecated alias of listContributors.
        """
        return self.listContributors()

    security.declareProtected(View, 'Date')
    def Date( self ):
        """ Dublin Core Date element - default date.
        """
        # Return effective_date if set, modification date otherwise
        date = getattr(self, 'effective_date', None )
        if date is None:
            date = self.modified()
        return date.toZone(_zone).ISO()

    security.declareProtected(View, 'CreationDate')
    def CreationDate( self ):
        """ Dublin Core Date element - date resource created.
        """
        # return unknown if never set properly
        if self.creation_date:
            return self.creation_date.toZone(_zone).ISO()
        else:
            return 'Unknown'

    security.declareProtected(View, 'EffectiveDate')
    def EffectiveDate( self ):
        """ Dublin Core Date element - date resource becomes effective.
        """
        ed = getattr( self, 'effective_date', None )
        return ed and ed.toZone(_zone).ISO() or 'None'

    security.declareProtected(View, 'ExpirationDate')
    def ExpirationDate( self ):
        """ Dublin Core Date element - date resource expires.
        """
        ed = getattr( self, 'expiration_date', None )
        return ed and ed.toZone(_zone).ISO() or 'None'

    security.declareProtected(View, 'ModificationDate')
    def ModificationDate( self ):
        """ Dublin Core Date element - date resource last modified.
        """
        return self.modified().toZone(_zone).ISO()

    security.declareProtected(View, 'Type')
    def Type( self ):
        """ Dublin Core Type element - resource type.
        """
        ti = self.getTypeInfo()
        return ti is not None and ti.Title() or 'Unknown'

    security.declareProtected(View, 'Format')
    def Format( self ):
        """ Dublin Core Format element - resource format.
        """
        return self.format

    security.declareProtected(View, 'Identifier')
    def Identifier( self ):
        """ Dublin Core Identifier element - resource ID.
        """
        # XXX: fixme using 'portal_metadata' (we need to prepend the
        #      right prefix to self.getPhysicalPath().
        return self.absolute_url()

    security.declareProtected(View, 'Language')
    def Language( self ):
        """ Dublin Core Language element - resource language.
        """
        return self.language

    security.declareProtected(View, 'Rights')
    def Rights( self ):
        """ Dublin Core Rights element - resource copyright.
        """
        return self.rights

    #
    #  DublinCore utility methods
    #
    def content_type( self ):
        """ WebDAV needs this to do the Right Thing (TM).
        """
        return self.Format()

    __FLOOR_DATE = DateTime( 1970, 0 ) # always effective

    security.declareProtected(View, 'isEffective')
    def isEffective( self, date ):
        """ Is the date within the resource's effective range?
        """
        pastEffective = ( self.effective_date is None
                       or self.effective_date <= date )
        beforeExpiration = ( self.expiration_date is None
                          or self.expiration_date >= date )
        return pastEffective and beforeExpiration

    #
    #  CatalogableDublinCore methods
    #
    security.declareProtected(View, 'created')
    def created( self ):
        """ Dublin Core Date element - date resource created.
        """
        # allow for non-existent creation_date, existed always
        date = getattr( self, 'creation_date', None )
        return date is None and self.__FLOOR_DATE or date

    security.declareProtected(View, 'effective')
    def effective( self ):
        """ Dublin Core Date element - date resource becomes effective.
        """
        marker = []
        date = getattr( self, 'effective_date', marker )
        if date is marker:
            date = getattr( self, 'creation_date', None )
        return date is None and self.__FLOOR_DATE or date

    __CEILING_DATE = DateTime( 2500, 0 ) # never expires

    security.declareProtected(View, 'expires')
    def expires( self ):
        """ Dublin Core Date element - date resource expires.
        """
        date = getattr( self, 'expiration_date', None )
        return date is None and self.__CEILING_DATE or date

    security.declareProtected(View, 'modified')
    def modified( self ):
        """ Dublin Core Date element - date resource last modified.
        """
        date = self.modification_date
        if date is None:
            # Upgrade.
            date = self.bobobase_modification_time()
            self.modification_date = date
        return date

    security.declareProtected(View, 'getMetadataHeaders')
    def getMetadataHeaders( self ):
        """ Return RFC-822-style headers.
        """
        hdrlist = []
        hdrlist.append( ( 'Title', self.Title() ) )
        hdrlist.append( ( 'Subject', ', '.join( self.Subject() ) ) )
        hdrlist.append( ( 'Publisher', self.Publisher() ) )
        hdrlist.append( ( 'Description', self.Description() ) )
        hdrlist.append( ( 'Contributors', '; '.join( self.Contributors() ) ) )
        hdrlist.append( ( 'Effective_date', self.EffectiveDate() ) )
        hdrlist.append( ( 'Expiration_date', self.ExpirationDate() ) )
        hdrlist.append( ( 'Type', self.Type() ) )
        hdrlist.append( ( 'Format', self.Format() ) )
        hdrlist.append( ( 'Language', self.Language() ) )
        hdrlist.append( ( 'Rights', self.Rights() ) )
        return hdrlist

    #
    #  MutableDublinCore methods
    #
    security.declarePrivate( '_datify' )
    def _datify( self, attrib ):
        if attrib == 'None':
            attrib = None
        elif not isinstance( attrib, DateTime ):
            if attrib is not None:
                attrib = DateTime( attrib )
        return attrib

    security.declareProtected(ModifyPortalContent, 'setTitle')
    def setTitle( self, title ):
        """ Set Dublin Core Title element - resource name.
        """
        self.title = title

    security.declareProtected(ModifyPortalContent, 'setCreators')
    def setCreators(self, creators):
        """ Set Dublin Core Creator elements - resource authors.
        """
        self.creators = tuplize('creators', creators)

    security.declareProtected(ModifyPortalContent, 'setSubject')
    def setSubject( self, subject ):
        """ Set Dublin Core Subject element - resource keywords.
        """
        self.subject = tuplize( 'subject', subject )

    security.declareProtected(ModifyPortalContent, 'setDescription')
    def setDescription( self, description ):
        """ Set Dublin Core Description element - resource summary.
        """
        self.description = description

    security.declareProtected(ModifyPortalContent, 'setContributors')
    def setContributors( self, contributors ):
        """ Set Dublin Core Contributor elements - resource collaborators.
        """
        # XXX: fixme
        self.contributors = tuplize('contributors', contributors, semi_split)

    security.declareProtected(ModifyPortalContent, 'setEffectiveDate')
    def setEffectiveDate( self, effective_date ):
        """ Set Dublin Core Date element - date resource becomes effective.
        """
        self.effective_date = self._datify( effective_date )

    security.declareProtected(ModifyPortalContent, 'setExpirationDate')
    def setExpirationDate( self, expiration_date ):
        """ Set Dublin Core Date element - date resource expires.
        """
        self.expiration_date = self._datify( expiration_date )

    security.declareProtected(ModifyPortalContent, 'setFormat')
    def setFormat( self, format ):
        """ Set Dublin Core Format element - resource format.
        """
        self.format = format

    security.declareProtected(ModifyPortalContent, 'setLanguage')
    def setLanguage( self, language ):
        """ Set Dublin Core Language element - resource language.
        """
        self.language = language

    security.declareProtected(ModifyPortalContent, 'setRights')
    def setRights( self, rights ):
        """ Set Dublin Core Rights element - resource copyright.
        """
        self.rights = rights

    #
    #  Management tab methods
    #

    security.declarePrivate( '_editMetadata' )
    def _editMetadata( self
                     , title=_marker
                     , subject=_marker
                     , description=_marker
                     , contributors=_marker
                     , effective_date=_marker
                     , expiration_date=_marker
                     , format=_marker
                     , language=_marker
                     , rights=_marker
                     ):
        """ Update the editable metadata for this resource.
        """
        if title is not _marker:
            self.setTitle( title )
        if subject is not _marker:
            self.setSubject( subject )
        if description is not _marker:
            self.setDescription( description )
        if contributors is not _marker:
            self.setContributors( contributors )
        if effective_date is not _marker:
            self.setEffectiveDate( effective_date )
        if expiration_date is not _marker:
            self.setExpirationDate( expiration_date )
        if format is not _marker:
            self.setFormat( format )
        if language is not _marker:
            self.setLanguage( language )
        if rights is not _marker:
            self.setRights( rights )

    security.declareProtected(ModifyPortalContent, 'manage_metadata')
    manage_metadata = DTMLFile( 'zmi_metadata', _dtmldir )

    security.declareProtected(ModifyPortalContent, 'manage_editMetadata')
    def manage_editMetadata( self
                           , title
                           , subject
                           , description
                           , contributors
                           , effective_date
                           , expiration_date
                           , format
                           , language
                           , rights
                           , REQUEST
                           ):
        """ Update metadata from the ZMI.
        """
        self._editMetadata( title, subject, description, contributors
                          , effective_date, expiration_date
                          , format, language, rights
                          )
        REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
                                + '/manage_metadata'
                                + '?manage_tabs_message=Metadata+updated.' )

    security.declareProtected(ModifyPortalContent, 'editMetadata')
    def editMetadata(self
                   , title=''
                   , subject=()
                   , description=''
                   , contributors=()
                   , effective_date=None
                   , expiration_date=None
                   , format='text/html'
                   , language='en-US'
                   , rights=''
                    ):
        """
        Need to add check for webDAV locked resource for TTW methods.
        """
        # as per bug #69, we cant assume they use the webdav
        # locking interface, and fail gracefully if they dont
        if hasattr(self, 'failIfLocked'):
            self.failIfLocked()

        self._editMetadata(title=title
                     , subject=subject
                     , description=description
                     , contributors=contributors
                     , effective_date=effective_date
                     , expiration_date=expiration_date
                     , format=format
                     , language=language
                     , rights=rights
                     )
        self.reindexObject()
Beispiel #25
0
 def set_birthdate(self, value):
     return self._setProperty(
         "birthdate",
         DateTime(
             datetime.datetime(value.year, value.month, value.day, 0, 0)),
     )
Beispiel #26
0
   def __call__(self, *args, **kw):
       """ this is called before the commit but after the modification
           of the field data
       """

       # Notify only if it's an OIE Student Application in a state other than private and
       #    the changes were done to student-revisable fields.
       typeName = self.instance.archetype_name
       if not typeName or typeName <> 'OIE Student Application':
          return
       wf_tool = getToolByName(self.instance, 'portal_workflow', None)
       if wf_tool:
          state = wf_tool.getInfoFor(self.instance,'review_state',None)
          if state == 'private':
             return

       now = DateTime()
       username = getSecurityManager().getUser().getUserName()

       # look for changes
       changes = []
       for field in self.instance.Schema().fields():

           # skip fields that are not revisable by the student
           if field.getName() in IGNORED_FIELDS or field.write_permission <> 'UWOshOIE: Modify revisable fields':
               continue

           v = getattr(self.instance, field.accessor)()

           if v != self.d[field.getName()]:
               field_name = field.getName()
               field_type = field.getType().split('.')[-1] # dotted name

               if field_type in ('StringField', 'LinesField', 'IntField', 'BooleanField',
                                 'DateTimeField', 'DateRangesField', 'DayInMonthTimeRangeField', 'DayOfWeekTimeRangeField'):
                   changes.append((field_name, self.d[field_name], v))

               elif field_type in ('TextField',):
                   old_lines = self.d[field_name].split('\n')
                   new_lines = v.split('\n')
                   diff_lines = difflib.ndiff(old_lines, new_lines, difflib.IS_LINE_JUNK, difflib.IS_CHARACTER_JUNK)
                   changes.append((field_name, '', '\n'.join(diff_lines)))

               elif field_type in ('ImageField', 'FileField'):
                   continue

               elif field_type in ('ReferenceField',):

                   def _checkListType(inp):
                       if type(inp) not in (types.ListType, types.TupleType):
                           return [inp, ]
                       return inp

                   old_refs = [o.absolute_url(1) for o in _checkListType(self.d[field_name]) if o != None]
                   new_refs = [o.absolute_url(1) for o in _checkListType(v) if o != None]
                   changes.append((field_name, old_refs, new_refs))

               else:
                   #LOG.warn('Unhandled Field: %s %s' % (field, field.getType()))
                   LOG ("CommitHandler", WARNING, 'Unhandled Field: %s %s' % (field, field.getType()))

       if changes:
           #LOG.info('-'*60)
           LOG("CommitHandler", INFO, '-'*60)
           #LOG.info('%s(%s): %s' % (username,
           #                         self.instance.REQUEST.getClientAddr(),
           #                         self.instance.absolute_url(1)))
           LOG ("CommitHandler", INFO, '%s(%s): %s' % (username,
                                    self.instance.REQUEST.getClientAddr(),
                                    self.instance.absolute_url(1)))
           changeString = ""
           for key, old, new in changes:
               #LOG.info('%s: %s -> %s' % (key, old, new))
               changeStringLine = '%s: %s -> %s' % (key, old, new)
               LOG ("CommitHandler", INFO, changeStringLine)
               changeString += changeStringLine + "\n"

           self._sendChangeNotificationMessage(self.instance, changeString)
class UserPropertySheetTests( unittest.TestCase
                            , IPropertySheet_conformance
                            ):

    _SCHEMA = ( ( 's', 'string'  )
              , ( 'i', 'int'     )
              , ( 'f', 'float'   )
              , ( 'n', 'long'    )
              , ( 'd', 'date'    )
              , ( 'l', 'lines'   )
              , ( 't', 'lines'   )
              , ( 'b', 'boolean' )
              , ( 'img', 'image' )
              )

    _STRING_VALUE = 'string'
    _INT_VALUE = 42
    _FLOAT_VALUE = 9.8
    _LONG_VALUE = sys.maxint + 1
    _DATE_VALUE = DateTime()
    _LIST_VALUE = [ 'a', 'b', 'c' ]
    _TUPLE_VALUE = ( 'd', 'e', 'f' )
    _BOOL_VALUE = True
    _IMG_VALUE = Image('image', 'Test Image', img_file)

    def _getTargetClass( self ):

        from Products.PluggableAuthService.UserPropertySheet \
            import UserPropertySheet

        return UserPropertySheet

    def _makeOne( self, *args, **kw ):

        return self._getTargetClass()( *args, **kw )

    def test_ctor_id_noschema_novalues( self ):

        ups = self._makeOne( 'empty' )

        self.assertEqual( ups.getId(), 'empty' )

        self.failIf( ups.hasProperty( 'empty' ) )
        self.failIf( ups.hasProperty( 'foo' ) )
        self.failIf( ups.hasProperty( 'bar' ) )

        self.assertEqual( ups.getProperty( 'foo' ), None )
        self.assertEqual( ups.getPropertyType( 'foo' ), None )

        self.assertEqual( len( ups.propertyMap() ), 0 )
        self.assertEqual( len( ups.propertyIds() ), 0 )
        self.assertEqual( len( ups.propertyValues() ), 0 )
        self.assertEqual( len( ups.propertyItems() ), 0 )
        self.assertEqual( len( ups.propertyIds() ), 0 )

    def _checkStockSchema( self, ups, values_are_none=False ):

        self.failIf( ups.hasProperty( 'x' ) )
        self.failUnless( ups.hasProperty( 's' ) )
        self.failUnless( ups.hasProperty( 'i' ) )
        self.failUnless( ups.hasProperty( 'f' ) )
        self.failUnless( ups.hasProperty( 'n' ) )
        self.failUnless( ups.hasProperty( 'd' ) )
        self.failUnless( ups.hasProperty( 'l' ) )
        self.failUnless( ups.hasProperty( 't' ) )
        self.failUnless( ups.hasProperty( 'b' ) )
        self.failUnless( ups.hasProperty( 'img' ) )

        self.assertEqual( ups.getPropertyType( 's' ), 'string' )
        self.assertEqual( ups.propertyInfo( 's' )[ 'type' ], 'string' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 's' ), None )
        else:
            self.assertEqual( ups.getProperty( 's' ), self._STRING_VALUE )

        self.assertEqual( ups.getPropertyType( 'i' ), 'int' )
        self.assertEqual( ups.propertyInfo( 'i' )[ 'type' ], 'int' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 'i' ), None )
        else:
            self.assertEqual( ups.getProperty( 'i' ), self._INT_VALUE )

        self.assertEqual( ups.getPropertyType( 'f' ), 'float' )
        self.assertEqual( ups.propertyInfo( 'f' )[ 'type' ], 'float' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 'f' ), None )
        else:
            self.assertEqual( ups.getProperty( 'f' ), self._FLOAT_VALUE )

        self.assertEqual( ups.getPropertyType( 'n' ), 'long' )
        self.assertEqual( ups.propertyInfo( 'n' )[ 'type' ], 'long' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 'n' ), None )
        else:
            self.assertEqual( ups.getProperty( 'n' ), self._LONG_VALUE )

        self.assertEqual( ups.getPropertyType( 'd' ), 'date' )
        self.assertEqual( ups.propertyInfo( 'd' )[ 'type' ], 'date' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 'd' ), None )
        else:
            self.assertEqual( ups.getProperty( 'd' ), self._DATE_VALUE )

        self.assertEqual( ups.getPropertyType( 'b' ), 'boolean' )
        self.assertEqual( ups.propertyInfo( 'b' )[ 'type' ], 'boolean' )
        if values_are_none:
            self.assertEqual( ups.getProperty( 'b' ), None )
        else:
            self.assertEqual( ups.getProperty( 'b' ), self._BOOL_VALUE )

        self.assertEqual( ups.getPropertyType( 'l' ), 'lines' )
        self.assertEqual( ups.propertyInfo( 'l' )[ 'type' ], 'lines' )

        if values_are_none:
            self.assertEqual( ups.getProperty( 'l' ), None )
        else:
            got = ups.getProperty( 'l' )
            self.assertEqual( type( got ), type( () ) )
            self.assertEqual( len( got ), len( self._LIST_VALUE ) )

            for i in range( len( self._LIST_VALUE ) ):
                self.assertEqual( got[i], self._LIST_VALUE[i] )

        self.assertEqual( ups.getPropertyType( 't' ), 'lines' )
        self.assertEqual( ups.propertyInfo( 't' )[ 'type' ], 'lines' )

        if values_are_none:
            self.assertEqual( ups.getProperty( 't' ), None )
        else:
            got = ups.getProperty( 't' )
            self.assertEqual( type( got ), type( () ) )
            self.assertEqual( len( got ), len( self._TUPLE_VALUE ) )

            for i in range( len( self._TUPLE_VALUE ) ):
                self.assertEqual( got[i], self._TUPLE_VALUE[i] )

        self.assertEqual( ups.getPropertyType( 'img' ), 'image' )
        self.assertEqual( ups.propertyInfo( 'img' )[ 'type' ], 'image' )

        if values_are_none:
            self.assertEqual( ups.getProperty( 'img' ), None )
        else:
            got = ups.getProperty( 'img' )
            self.assertEqual( type( got ), Image )
            self.assertEqual( got.size, self._IMG_VALUE.size )
            self.assertEqual( got, self._IMG_VALUE )


        pmap = ups.propertyMap()
        self.assertEqual( len( pmap ), len( self._SCHEMA ) )

        for i in range( len( pmap ) ):
            info = pmap[i]
            spec = [ x for x in self._SCHEMA if x[0] == info['id' ] ][0]
            self.assertEqual( info[ 'id' ], spec[0] )
            self.assertEqual( info[ 'type' ], spec[1] )
            self.assertEqual( info[ 'mode' ], '' )  # readonly, no delete


    def test_ctor__guessSchema( self ):

        ups = self._makeOne( 'guessed'
                           , s=self._STRING_VALUE
                           , i=self._INT_VALUE
                           , f=self._FLOAT_VALUE
                           , n=self._LONG_VALUE
                           , d=self._DATE_VALUE
                           , l=self._LIST_VALUE
                           , t=self._TUPLE_VALUE
                           , b=self._BOOL_VALUE
                           , img=self._IMG_VALUE
                           )

        self._checkStockSchema( ups )


    def test_ctor_w_schema(self):

        ups = self._makeOne( 'w_schema'
                           , self._SCHEMA
                           , s=self._STRING_VALUE
                           , i=self._INT_VALUE
                           , f=self._FLOAT_VALUE
                           , n=self._LONG_VALUE
                           , d=self._DATE_VALUE
                           , l=self._LIST_VALUE
                           , t=self._TUPLE_VALUE
                           , b=self._BOOL_VALUE
                           , img=self._IMG_VALUE
                           )

        self._checkStockSchema( ups )


    def test_ctor_w_schema_no_values(self):

        ups = self._makeOne( 'w_schema'
                           , self._SCHEMA
                           )

        self._checkStockSchema( ups, values_are_none=True )
Beispiel #28
0
    def viewDay(self):
        """ Return a DateTime for a passed-in date or today
        """
        date = self.request.get('date', None) or DateTime().aCommon()[:12]

        return DateTime(date)
class UserPropertySheetTests(unittest.TestCase):

    _SCHEMA = (('s', 'string'), ('i', 'int'), ('f', 'float'), ('n', 'long'),
               ('d', 'date'), ('l', 'lines'), ('t', 'lines'))

    _STRING_VALUE = 'string'
    _INT_VALUE = 42
    _FLOAT_VALUE = 9.8
    _LONG_VALUE = 1000000000000
    _DATE_VALUE = DateTime()
    _LIST_VALUE = ['a', 'b', 'c']
    _TUPLE_VALUE = ('d', 'e', 'f')

    def _getTargetClass(self):

        from Products.PluggableAuthService.UserPropertySheet \
            import UserPropertySheet

        return UserPropertySheet

    def _makeOne(self, *args, **kw):

        return self._getTargetClass()(*args, **kw)

    def test_conformance_IPropertySheet(self):

        from Products.PluggableAuthService.interfaces.propertysheets \
            import IPropertySheet

        from Interface.Verify import verifyClass

        verifyClass(IPropertySheet, self._getTargetClass())

    def test_ctor_id_noscehma_novalues(self):

        ups = self._makeOne('empty')

        self.assertEqual(ups.getId(), 'empty')

        self.failIf(ups.hasProperty('empty'))
        self.failIf(ups.hasProperty('foo'))
        self.failIf(ups.hasProperty('bar'))

        self.assertEqual(ups.getProperty('foo'), None)
        self.assertEqual(ups.getPropertyType('foo'), None)

        self.assertEqual(len(ups.propertyMap()), 0)
        self.assertEqual(len(ups.propertyIds()), 0)
        self.assertEqual(len(ups.propertyValues()), 0)
        self.assertEqual(len(ups.propertyItems()), 0)
        self.assertEqual(len(ups.propertyIds()), 0)

    def _checkStockSchema(self, ups):

        self.failIf(ups.hasProperty('x'))
        self.failUnless(ups.hasProperty('s'))
        self.failUnless(ups.hasProperty('i'))
        self.failUnless(ups.hasProperty('f'))
        self.failUnless(ups.hasProperty('n'))
        self.failUnless(ups.hasProperty('d'))
        self.failUnless(ups.hasProperty('l'))
        self.failUnless(ups.hasProperty('t'))

        self.assertEqual(ups.getPropertyType('s'), 'string')
        self.assertEqual(ups.propertyInfo('s')['type'], 'string')
        self.assertEqual(ups.getProperty('s'), self._STRING_VALUE)

        self.assertEqual(ups.getPropertyType('i'), 'int')
        self.assertEqual(ups.propertyInfo('i')['type'], 'int')
        self.assertEqual(ups.getProperty('i'), self._INT_VALUE)

        self.assertEqual(ups.getPropertyType('f'), 'float')
        self.assertEqual(ups.propertyInfo('f')['type'], 'float')
        self.assertEqual(ups.getProperty('f'), self._FLOAT_VALUE)

        self.assertEqual(ups.getPropertyType('n'), 'long')
        self.assertEqual(ups.propertyInfo('n')['type'], 'long')
        self.assertEqual(ups.getProperty('n'), self._LONG_VALUE)

        self.assertEqual(ups.getPropertyType('d'), 'date')
        self.assertEqual(ups.propertyInfo('d')['type'], 'date')
        self.assertEqual(ups.getProperty('d'), self._DATE_VALUE)

        self.assertEqual(ups.getPropertyType('l'), 'lines')
        self.assertEqual(ups.propertyInfo('l')['type'], 'lines')

        got = ups.getProperty('l')
        self.assertEqual(type(got), type(()))
        self.assertEqual(len(got), len(self._LIST_VALUE))

        for i in range(len(self._LIST_VALUE)):
            self.assertEqual(got[i], self._LIST_VALUE[i])

        self.assertEqual(ups.getPropertyType('t'), 'lines')
        self.assertEqual(ups.propertyInfo('t')['type'], 'lines')

        got = ups.getProperty('t')
        self.assertEqual(type(got), type(()))
        self.assertEqual(len(got), len(self._TUPLE_VALUE))

        for i in range(len(self._TUPLE_VALUE)):
            self.assertEqual(got[i], self._TUPLE_VALUE[i])

        pmap = ups.propertyMap()
        self.assertEqual(len(pmap), len(self._SCHEMA))

        for i in range(len(pmap)):
            info = pmap[i]
            spec = [x for x in self._SCHEMA if x[0] == info['id']][0]
            self.assertEqual(info['id'], spec[0])
            self.assertEqual(info['type'], spec[1])
            self.assertEqual(info['mode'], '')  # readonly, no delete

    def test_ctor__guessSchema(self):

        ups = self._makeOne('guessed',
                            s=self._STRING_VALUE,
                            i=self._INT_VALUE,
                            f=self._FLOAT_VALUE,
                            n=self._LONG_VALUE,
                            d=self._DATE_VALUE,
                            l=self._LIST_VALUE,
                            t=self._TUPLE_VALUE)

        self._checkStockSchema(ups)

    def test_ctor_w_schema(self):

        ups = self._makeOne('w_schema',
                            self._SCHEMA,
                            s=self._STRING_VALUE,
                            i=self._INT_VALUE,
                            f=self._FLOAT_VALUE,
                            n=self._LONG_VALUE,
                            d=self._DATE_VALUE,
                            l=self._LIST_VALUE,
                            t=self._TUPLE_VALUE)

        self._checkStockSchema(ups)
    def setUp(self):

        self._epoch = DateTime()