Esempio n. 1
0
        # check if the id already exists
        documents = self.getParentDatabase().documents
        try:
            documents._checkId(new_id)
        except BadRequestException:
            new_id = self._findUniqueId(new_id)
        return new_id

    def __nonzero__(self):
        # Needed for Plone 3 compliancy
        # (as BTreeFolder2 1.0 does not define __nonzero__)
        return True


InitializeClass(PlominoDocument)
addPlominoDocument = Factory(PlominoDocument)
addPlominoDocument.__name__ = "addPlominoDocument"


def getTemporaryDocument(db, form, REQUEST, doc=None, validation_mode=False):
    if hasattr(doc, 'real_id'):
        return doc
    else:
        target = TemporaryDocument(db,
                                   form,
                                   REQUEST,
                                   real_doc=doc,
                                   validation_mode=validation_mode).__of__(db)
        return target
Esempio n. 2
0
            return 0

        return 1

    @security.protected(ManagePortal)
    def getTypeLabel(self):
        """
            Return a human-readable label for the predicate type.
        """
        return self.PREDICATE_TYPE

    security.declareProtected(ManagePortal, 'predicateWidget')
    predicateWidget = DTMLFile('majorMinorWidget', _dtmldir)


InitializeClass(MajorMinorPredicate)


@implementer(IContentTypeRegistryPredicate)
class ExtensionPredicate(SimpleItem):
    """
        Predicate matching on filename extensions.
    """

    extensions = None
    PREDICATE_TYPE = 'extension'

    security = ClassSecurityInfo()

    def __init__(self, id):
        self.id = id
Esempio n. 3
0
                RESPONSE.setHeader('Content-Length', self.size)
                return result

        data = self.data
        if isinstance(data, str):
            RESPONSE.setBase(None)
            return data

        while data is not None:
            RESPONSE.write(data.data)
            data = data.next

        return ''


InitializeClass(File)

manage_addImageForm = DTMLFile('dtml/imageAdd',
                               globals(),
                               Kind='Image',
                               kind='image')


def manage_addImage(self,
                    id,
                    file,
                    title='',
                    precondition='',
                    content_type='',
                    REQUEST=None):
    """
Esempio n. 4
0
        return transactions

    @security.public
    def undo(self, object, transaction_info):
        """
            Undo the list of transactions passed in 'transaction_info',
            first verifying that the current user is allowed to undo them.
        """
        # Belt and suspenders:  make sure that the user is actually
        # allowed to undo the transation(s) in transaction_info.

        xids = {}  # set of allowed transaction IDs

        allowed = self.listUndoableTransactionsFor(object)

        for xid in [x['id'] for x in allowed]:
            xids[xid] = 1

        if isinstance(transaction_info, str):
            transaction_info = [transaction_info]

        for tinfo in transaction_info:
            if not xids.get(tinfo, None):
                raise AccessControl_Unauthorized

        object.manage_undo_transactions(transaction_info)


InitializeClass(UndoTool)
registerToolInterface('portal_undo', IUndoTool)
        This is used by housekeeping methods (like clearEpired)
        and stored in reset request records."""
        return (datetime.datetime.utcnow() +
                datetime.timedelta(days=self._timedelta))

    @security.private
    def getValidUser(self, userid):
        """Returns the member with 'userid' if available and None otherwise."""
        if get_member_by_login_name:
            registry = getUtility(IRegistry)
            settings = registry.forInterface(ISecuritySchema, prefix='plone')
            if settings.use_email_as_login:
                return get_member_by_login_name(self,
                                                userid,
                                                raise_exceptions=False)
        membertool = getToolByName(self, 'portal_membership')
        return membertool.getMemberById(userid)

    @security.private
    def expired(self, dt, now=None):
        """Tells whether a DateTime or timestamp 'datetime' is expired
        with regards to either 'now', if provided, or the current
        time."""
        if not now:
            now = datetime.datetime.utcnow()
        return now >= dt


InitializeClass(PasswordResetTool)
Esempio n. 6
0
                        max_results=None, **kw):
        """Group enumeration.

        This method adds a workaround to enforce LDAPUserFolder to return a
        list of all groups. This is desirable for LDAP environments where only
        a few groups are present. In Plone we know this in advance thanks to
        the 'many groups' setting.
        """
        if not id and not kw:
            kw["cn"]=""
        return ActiveDirectoryMultiPlugin.enumerateGroups(self, id,
                exact_match, sort_by, max_results, **kw)


classImplements(
    PloneActiveDirectoryMultiPlugin,
    IAuthenticationPlugin,
    ICredentialsResetPlugin,
    IGroupEnumerationPlugin,
    IGroupIntrospection,
    IGroupsPlugin,
    IMutablePropertiesPlugin,
    IPropertiesPlugin,
    IRoleEnumerationPlugin,
    IRolesPlugin,
    IUserEnumerationPlugin,
    *implementedBy(ActiveDirectoryMultiPlugin)
    )

InitializeClass(PloneActiveDirectoryMultiPlugin)
        return creds

    @security.private
    def challenge(self, request, response, **kw):
        """ Challenge the user for credentials.
        """
        realm = response.realm
        if realm:
            response.addHeader('WWW-Authenticate', 'basic realm="%s"' % realm)
        m = '<strong>You are not authorized to access this resource.</strong>'

        if not response.body:
            response.setBody(m, is_error=1)
        response.setStatus(401)
        return 1

    @security.private
    def resetCredentials(self, request, response):
        """ Raise unauthorized to tell browser to clear credentials.
        """
        # ???:  Does this need to check whether we have an HTTP response?
        response.unauthorized()


classImplements(HTTPBasicAuthHelper, IHTTPBasicAuthHelper,
                ILoginPasswordHostExtractionPlugin, IChallengePlugin,
                ICredentialsResetPlugin)

InitializeClass(HTTPBasicAuthHelper)
Esempio n. 8
0
            r = results[0]
            # if hasattr(self, 'aq_parent'): r=r.__of__(self.aq_parent)
            return r

        self._arg[key]  # raise KeyError if not an arg
        return Traverse(self, {}, key)

    def connectionIsValid(self):
        return (hasattr(self, self.connection_id)
                and hasattr(getattr(self, self.connection_id), 'connected'))

    def connected(self):
        return getattr(getattr(self, self.connection_id), 'connected')()


InitializeClass(DA)

ListType = type([])


class Traverse(Base):
    """Helper class for 'traversing' searches during URL traversal
    """
    _da = None

    def __init__(self, da, args, name=None):
        self._r = None
        self._da = da
        self._args = args
        self._name = name
Esempio n. 9
0
            else:
                raise CopyError(MessageDialog(
                    title = 'Insufficient Privileges',
                    message = ('You do not possess the %s permission in the '
                               'context of the container into which you are '
                               'pasting, thus you are not able to perform '
                               'this operation.' % mt_permission),
                    action = 'manage_main'))
        else:
            raise CopyError(MessageDialog(
                title = 'Not Supported',
                message = ('The object <em>%s</em> does not support this '
                           'operation.' % escape(absattr(object.id))),
                action = 'manage_main'))

InitializeClass(CopyContainer)


class CopySource(Base):

    """Interface for objects which allow themselves to be copied."""

    implements(ICopySource)

    # declare a dummy permission for Copy or Move here that we check
    # in cb_isCopyable.
    security = ClassSecurityInfo()
    security.setPermissionDefault(copy_or_move, ('Anonymous', 'Manager'))

    def _canCopy(self, op=0):
        """Called to make sure this object is copyable.
Esempio n. 10
0
        },
        {
            'id': 'ordering',
            'type': 'float',
            'mode': 'w'
        },
    )

    _relations = (("zenMenus",
                   ToOne(ToManyCont, 'Products.ZenModel.ZenMenu',
                         'zenMenuItems')), ) + ZenPackable._relations

    security = ClassSecurityInfo()

    def getMenuItemOwner(self):
        parent = self.primaryAq()
        for unused in range(4):
            parent = aq_parent(parent)
        return parent

    def __cmp__(self, other):
        if isinstance(other, ZenMenuItem):
            if other and other.ordering:
                return cmp(other.ordering, self.ordering)
            else:
                return cmp(0.0, self.ordering)
        return cmp(id(self), id(other))


InitializeClass(ZenMenuItem)
Esempio n. 11
0
    def getDescription(self):
        return '%s %s' % (self.value, self.legend)

    def getType(self):
        return 'AREA'

    def getGraphCmds(self,
                     cmds,
                     context,
                     rrdDir,
                     addSummary,
                     idx,
                     multiid=-1,
                     prefix=''):
        ''' Build the graphing commands for this graphpoint
        '''
        unused(multiid, rrdDir)
        gopts = 'AREA:%s%s' % (self.addPrefix(prefix,
                                              self.value), self.getColor(idx))

        if self.legend or self.stacked:
            legend = self.talesEval(self.legend, context)
            legend = self.escapeForRRD(legend)
            gopts += ':%s' % legend
        if self.stacked:
            gopts += ':STACK'
        return cmds + [gopts]


InitializeClass(AreaGraphPoint)
Esempio n. 12
0
            return
        for prop in props:
            self._setProperty(prop.new_id, prop.new_value, prop.new_type)
        if REQUEST is not None:
            return self.manage_propertiesForm(self, REQUEST)

    security.declareProtected(manage_properties, 'manage_delProperties')
    def manage_delProperties(self, ids=None, REQUEST=None):
        """Delete one or more properties specified by 'ids'."""
        if REQUEST:
            # Bugfix for property named "ids" (Casey)
            if ids == self.getProperty('ids', None):
                ids = None
            ids = REQUEST.get('_ids', ids)
        if ids is None:
            raise BadRequest('No property specified.')
        propdict = self.propdict()
        nd = self._reserved_names
        for id in ids:
            if not hasattr(aq_base(self), id):
                raise BadRequest(
                    'The property <em>%s</em> does not exist' % escape(id))
            if ('d' not in propdict[id].get('mode', 'wd')) or (id in nd):
                raise BadRequest('Cannot delete %s' % id)
            self._delProperty(id)

        if REQUEST is not None:
            return self.manage_propertiesForm(self, REQUEST)

InitializeClass(PropertyManager)
Esempio n. 13
0
            self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
            body = REQUEST.get('BODY', '')
            self._validateProxy(REQUEST)
            self.munge(body)
            self.ZCacheable_invalidate()
            RESPONSE.setStatus(204)
            return RESPONSE

        @security.protected(ftp_access)
        def manage_FTPget(self):
            """ Get source for FTP download.
            """
            return self.read()


InitializeClass(DTMLMethod)

token = "[a-zA-Z0-9!#$%&'*+\-.\\\\^_`|~]+"
hdr_start = re.compile(r'(%s):(.*)' % token).match


def decapitate(html, RESPONSE=None):
    headers = []
    spos = 0
    eolen = 1
    while 1:
        m = hdr_start(html, spos)
        if not m:
            if html[spos:spos + 2] == '\r\n':
                eolen = 2
                break
Esempio n. 14
0
        """Return the name at the remote end of our relationship."""
        schema = self.__primary_parent__.lookupSchema(self.id)
        return schema.remoteName

    def getPrimaryParent(self):
        """Return our parent object by our primary path"""
        return self.__primary_parent__.primaryAq()

    def getRelationshipManagerClass(self):
        """
        Return the local class of this relationship. For all relationshps
        this is the class of our __primary_parent___.
        """
        return self.__primary_parent__.__class__

    def cb_isCopyable(self):
        """Don't let relationships move off their managers"""
        return 0

    def cb_isMoveable(self):
        """Don't let relationships move off their managers"""
        return 0

    def checkRelation(self, repair=False):
        """Check to make sure that relationship bidirectionality is ok.
        """
        return


InitializeClass(RelationshipBase)
Esempio n. 15
0
            return value
        if isinstance(value, (str, datetime)):
            dt_obj = DateTime(value)
            value = dt_obj.millis() / 1000 / 60  # flatten to minutes
        elif isinstance(value, DateTime):
            value = value.millis() / 1000 / 60  # flatten to minutes
        if value > MAX32 or value < -MAX32:
            # t_val must be integer fitting in the 32bit range
            raise OverflowError('%s is not within the range of dates allowed'
                                'by a DateRangeIndex' % value)
        value = int(value)
        # handle values outside our specified range
        if value > self.ceiling_value:
            return None
        elif value < self.floor_value:
            return None
        return value

InitializeClass(DateRangeIndex)

manage_addDateRangeIndexForm = DTMLFile('addDateRangeIndex', _dtmldir)


def manage_addDateRangeIndex(self, id, extra=None,
        REQUEST=None, RESPONSE=None, URL3=None):
    """Add a date range index to the catalog, using the incredibly icky
       double-indirection-which-hides-NOTHING.
    """
    return self.manage_addIndex(id, 'DateRangeIndex', extra,
        REQUEST, RESPONSE, URL3)
Esempio n. 16
0
        descriptions = []
        for tid in transaction_info:
            tid = tid.split()
            if tid:
                tids.append(decode64(tid[0]))
                descriptions.append(tid[-1])

        if tids:
            transaction.get().note("Undo %s" % ' '.join(descriptions))
            self._p_jar.db().undoMultiple(tids)

        if REQUEST is not None:
            REQUEST.RESPONSE.redirect("%s/manage_UndoForm" % REQUEST['URL1'])


InitializeClass(UndoSupport)

# Blech, need this cause binascii.b2a_base64 is too pickly


def encode64(s, b2a=binascii.b2a_base64):
    if len(s) < 58:
        return b2a(s).decode('ascii')
    r = []
    a = r.append
    for i in range(0, len(s), 57):
        a(b2a(s[i:i + 57])[:-1])
    return (b''.join(r)).decode('ascii')


def decode64(s, a2b=binascii.a2b_base64):
    def getOwner(self, info=0):
        """Gets the owner of the executable object.

        This method is required of all objects that go into
        the security context stack.  Since this object came from the
        filesystem, it is owned by no one managed by Zope.
        """
        return None

    def __getstate__(self):
        from ZODB.POSException import StorageError
        raise StorageError, ("Instance of AntiPersistent class %s "
                             "cannot be stored." % self.__class__.__name__)


InitializeClass(PageTemplateFile)

XML_PREFIXES = [
    "<?xml",  # ascii, utf-8
    "\xef\xbb\xbf<?xml",  # utf-8 w/ byte order mark
    "\0<\0?\0x\0m\0l",  # utf-16 big endian
    "<\0?\0x\0m\0l\0",  # utf-16 little endian
    "\xfe\xff\0<\0?\0x\0m\0l",  # utf-16 big endian w/ byte order mark
    "\xff\xfe<\0?\0x\0m\0l\0",  # utf-16 little endian w/ byte order mark
]

XML_PREFIX_MAX_LENGTH = max(map(len, XML_PREFIXES))


def sniff_type(text):
    for prefix in XML_PREFIXES:
Esempio n. 18
0
            security.removeContext(self)

        have_key = RESPONSE.headers.has_key
        if not (have_key('content-type') or have_key('Content-Type')):
            if self.__dict__.has_key('content_type'):
                c = self.content_type
            else:
                c, e = guess_content_type(self.__name__, r)
            RESPONSE.setHeader('Content-Type', c)
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result


InitializeClass(DTMLDocument)

default_dd_html = """<html>
  <head><title><dtml-var title_or_id></title>
  </head>
  <body bgcolor="#FFFFFF">
    <h2><dtml-var title_or_id></h2>
<p>
This is the <dtml-var id> Document.
</p>
</body>
</html>"""

addForm = DTMLFile('dtml/documentAdd', globals())

Esempio n. 19
0
    @security.protected(AddPortalMember)
    def isMemberIdAllowed(self, id):
        """Returns 1 if the ID is not in use and is not reserved.
        """
        if len(id) < 1 or id == 'Anonymous User':
            return 0
        if not self._ALLOWED_MEMBER_ID_PATTERN.match(id):
            return 0
        mtool = getUtility(IMembershipTool)
        if mtool.getMemberById(id) is not None:
            return 0
        return 1

    @security.public
    def afterAdd(self, member, id, password, properties):
        """Called by portal_registration.addMember()
        after a member has been added successfully."""
        pass

    @security.protected(MailForgottenPassword)
    def mailPassword(self, forgotten_userid, REQUEST):
        """Email a forgotten password to a member.  Raises an exception
        if user ID is not found.
        """
        raise NotImplementedError


InitializeClass(RegistrationTool)
registerToolInterface('portal_registration', IRegistrationTool)
Esempio n. 20
0
class CMFBTreeFolder(BTreeFolder2Base, PortalFolderBase):

    """BTree folder for CMF sites.
    """

    security = ClassSecurityInfo()

    def __init__(self, id, title=''):
        PortalFolderBase.__init__(self, id, title)
        BTreeFolder2Base.__init__(self, id)

    def _checkId(self, id, allow_dup=0):
        PortalFolderBase._checkId(self, id, allow_dup)
        BTreeFolder2Base._checkId(self, id, allow_dup)

    @security.protected(AddPortalFolders)
    def manage_addPortalFolder(self, id, title='', REQUEST=None):
        """Add a new PortalFolder object with id *id*.
        """
        ob = PortalFolder(id, title)
        self._setObject(id, ob, suppress_events=True)
        if REQUEST is not None:
            return self.folder_contents(  # XXX: ick!
                self, REQUEST, portal_status_message='Folder added')


InitializeClass(CMFBTreeFolder)

CMFBTreeFolderFactory = Factory(CMFBTreeFolder)
Esempio n. 21
0
                time_offset = '%.2fs' % t
            divs.append({
                'store_len': store_len,
                'load_len': load_len,
                'trans_len': max(segment_height - store_len - load_len, 0),
                'store_count': div['stores'],
                'load_count': div['loads'],
                'connections': div['connections'],
                'start': div['start'],
                'end': div['end'],
                'time_offset': time_offset,
                })

        if analysis:
            start_time = DateTime(divs[0]['start']).aCommonZ()
            end_time = DateTime(divs[-1]['end']).aCommonZ()
        else:
            start_time = ''
            end_time = ''

        res = {'start_time': start_time,
               'end_time': end_time,
               'divs': divs,
               'total_store_count': total_store_count,
               'total_load_count': total_load_count,
               'total_connections': total_connections,
               }
        return res

InitializeClass(CacheManager)
Esempio n. 22
0
        PropertyManager,
        RoleManager,
        Collection,
        Item,
        FindSupport,
):
    """Folders are basic container objects that provide a standard
    interface for object management. Folder objects also implement
    a management interface and can have arbitrary properties.
    """

    implements(IFolder)
    meta_type = 'Folder'

    _properties = ({'id': 'title', 'type': 'string', 'mode': 'wd'}, )

    manage_options = (ObjectManager.manage_options + ({
        'label': 'View',
        'action': ''
    }, ) + PropertyManager.manage_options + RoleManager.manage_options +
                      Item.manage_options + FindSupport.manage_options)

    __ac_permissions__ = ()

    def __init__(self, id=None):
        if id is not None:
            self.id = str(id)


InitializeClass(Folder)
Esempio n. 23
0
    def __call__(self, econtext):
        if not self.text.strip():
            return ''
        compiled = self._v_compiled
        if compiled is None:
            compiled = self._v_compiled = getEngine().compile(self.text)
        # ?? Maybe expressions should manipulate the security
        # context stack.
        res = compiled(econtext)
        if isinstance(res, Exception):
            raise res
        return res


InitializeClass(Expression)


def getExprContext(context, object=None):
    request = getRequest()
    if request:
        cache = request.get('_ec_cache', None)
        if cache is None:
            request['_ec_cache'] = cache = {}
        ec = cache.get(id(object), None)
    else:
        ec = None
    if ec is None:
        try:
            utool = getUtility(IURLTool)
        except ComponentLookupError:
Esempio n. 24
0
                if provider_name == 'portal_actions':
                    actions.extend(
                        provider.listActionInfos(
                            object=object,
                            ignore_categories=ignore_categories))
                else:
                    actions.extend(provider.listActionInfos(object=object))

        # Include actions from object.
        if object is not None:
            if IActionProvider.providedBy(object):
                actions.extend(object.listActionInfos(object=object))

        # Reorganize the actions by category.
        filtered_actions = {
            'user': [],
            'folder': [],
            'object': [],
            'global': [],
            'workflow': [],
        }

        for action in actions:
            catlist = filtered_actions.setdefault(action['category'], [])
            catlist.append(action)

        return filtered_actions


InitializeClass(ActionsTool)
Esempio n. 25
0
            s = '_'.join((prefix, base))
        s = self.scrubForRRD(s)
        return s

    def scrubForRRD(self, value, namespace=None):
        ''' scrub value so it is a valid rrd variable name.  If namespace
        is provided then massage value as needed to avoid name conflicts
        with items in namespace.
        '''
        import string
        import itertools
        validRRDchars = set(string.ascii_letters + string.digits + '_-')
        value = ''.join(c if c in validRRDchars else '_' for c in value)
        if namespace:
            postfixIter = itertools.count(2)
            candidate = value
            while candidate in namespace:
                candidate = value + str(postfixIter.next())
            value = candidate
        return value

    def escapeForRRD(self, value):
        '''
        Escapes characters like colon ':' for use by RRDTool which would
        '''
        value = value.replace(":", "\:")[:198]
        return value


InitializeClass(GraphPoint)
Esempio n. 26
0
            items = obj.objectItems()
        except Exception:
            return result

        addresult = result.append
        for id, ob in items:
            if path:
                p = '%s/%s' % (path, id)
            else:
                p = id

            dflag = hasattr(ob, '_p_changed') and (ob._p_changed is None)
            bs = aq_base(ob)
            if wl_isLocked(ob):
                li = []
                addlockinfo = li.append
                for token, lock in ob.wl_lockItems():
                    addlockinfo({'owner': lock.getCreatorPath(),
                                 'token': token})
                addresult((p, li))
                dflag = 0
            if hasattr(bs, 'objectItems'):
                self._findapply(ob, result, p)
            if dflag:
                ob._p_deactivate()

        return result


InitializeClass(DavLockManager)
Esempio n. 27
0
        direct = parameters.get('allow_simple_one_argument_traversal', None)

        self.manage_edit(title, connection_id, arguments, template=data)

        self.manage_advanced(max_rows,
                             max_cache,
                             cache_time,
                             class_name,
                             class_file,
                             connection_hook=connection_hook,
                             direct=direct)

        # do we need to do anything on reparse?

    if getConfiguration().debug_mode:
        # Provide an opportunity to update the properties.
        def __of__(self, parent):
            try:
                self = ImplicitAcquisitionWrapper(self, parent)
                self._updateFromFS()
                return self
            except Exception:
                logger.exception('Error during __of__')
                raise


InitializeClass(FSZSQLMethod)

registerFileExtension('zsql', FSZSQLMethod)
registerMetaType('Z SQL Method', FSZSQLMethod)
Esempio n. 28
0
            # 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:
                mod_since = int(DateTime(header).timeTime())
            except Exception:
                mod_since = None
            if mod_since is not None:
                if getattr(self, 'lmt', None):
                    last_mod = int(self.lmt)
                else:
                    last_mod = int(0)
                if last_mod > 0 and last_mod <= mod_since:
                    RESPONSE.setHeader('Content-Length', '0')
                    RESPONSE.setStatus(304)
                    return ''

        RESPONSE.setHeader('Content-Length', str(self.size).replace('L', ''))
        return filestream_iterator(self.path, mode='rb')

    def __len__(self):
        # This is bogus and needed because of the way Python tests truth.
        return 1

    def __str__(self):
        return '<img src="%s" alt="" />' % self.__name__


InitializeClass(ImageFile)
Esempio n. 29
0
                                       'label': label,
                                       'schemata': schemata_name})
                    elif diff_type == 'variable_binary':
                        diff_type = BinaryDiff
                        if ('text/' in field.getContentType(obj1) and
                                'text/' in (obj2.getField(field.getName())
                                            .getContentType(obj2))):
                            diff_type = TextDiff
                        fields.append({'name': field.getName(),
                                       'accessor': field.accessor,
                                       'klass': diff_type,
                                       'primary': is_primary,
                                       'label': label,
                                       'schemata': schemata_name})
                    elif diff_type == 'variable_text':
                        diff_type = TextDiff
                        if ('html' in field.getContentType(obj1) and
                                'html' in (obj2.getField(field.getName())
                                           .getContentType(obj2))):
                            diff_type = CMFDTHtmlDiff
                        fields.append({'name': field.getName(),
                                       'accessor': field.accessor,
                                       'klass': diff_type,
                                       'primary': is_primary,
                                       'label': label,
                                       'schemata': schemata_name})
        return fields


InitializeClass(ATCompoundDiff)
Esempio n. 30
0
            key_bytes = [randrange(256) for i in range(kl)]
            if bytes is not str:  # Python 2
                key_bytes = b"".join(chr(b) for b in key_bytes)
            else:  # Python 3
                key_bytes = bytes(key_bytes)
        return key_bytes

    def clear_keys(self):
        del self.__keys[:]

    def new_key(self):
        self.__keys.insert(0, self._create_key())
        del self.__keys[self.KEY_NUMBER:]


InitializeClass(SimpleSpsso)


class StandaloneSimpleSpsso(SimpleSpsso):
    """a `SimpleSpsso` that works with separate plugins.

  Integration is via a (local) utility registration.
  """
    meta_type = "Saml simple spsso (standalone)"


def initialize(context):
    from dm.zope.schema.z2.constructor import add_form_factory, SchemaConfiguredZmiAddForm

    context.registerClass(
        StandaloneSimpleSpsso,