Esempio n. 1
0
    def test_factory_location(self):
        # Given an object that is a location,
        # it is not proxied
        @interface.implementer(ILocation)
        class LocatedTarget(Target):
            __name__ = None
            __parent__ = None

        getAnnotation = factory(LocatedTarget)

        context = Context()
        target = getAnnotation(context)

        key = 'zope.annotation.tests.test_factory.LocatedTarget'
        self.assertEqual([key], list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), LocatedTarget)

        # Third, the returned object is an ILocation, rooted at the
        # parent and having the given name.
        self.assertTrue(ILocation.providedBy(target))
        self.assertIs(target.__parent__, context)
        self.assertEqual(target.__name__, key)

        # And it's not a proxy.
        self.assertEqual(type(target), LocatedTarget)
        self.assertTrue(ITarget.providedBy(target))
        self.assertIs(target, context[key])
Esempio n. 2
0
    def test_factory_no_location(self):

        getAnnotation = factory(Target)

        context = Context()
        target = getAnnotation(context)

        # Several things have happened now.
        # First, we have an annotation, derived from
        # our class name
        key = 'zope.annotation.tests.test_factory.Target'
        self.assertEqual([key], list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), Target)

        # Third, the returned object is an ILocation, rooted at the
        # parent and having the given name.
        self.assertTrue(ILocation.providedBy(target))
        self.assertIs(target.__parent__, context)
        self.assertEqual(target.__name__, key)

        # But it's a proxy.
        self.assertNotEqual(type(target), Target)
        self.assertTrue(ITarget.providedBy(target))
    def test_factory_no_location(self):

        getAnnotation = factory(Target)

        context = Context()
        target = getAnnotation(context)

        # Several things have happened now.
        # First, we have an annotation, derived from
        # our class name
        key = 'zope.annotation.tests.test_factory.Target'
        self.assertEqual([key],
                         list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), Target)

        # Third, the returned object is an ILocation, rooted at the
        # parent and having the given name.
        self.assertTrue(ILocation.providedBy(target))
        self.assertIs(target.__parent__, context)
        self.assertEqual(target.__name__, key)

        # But it's a proxy.
        self.assertNotEqual(type(target), Target)
        self.assertTrue(ITarget.providedBy(target))
Esempio n. 4
0
def note_factory(klass, key):
    """\
    Named Annotation Factory maker specific for PMR2 annotations
    """

    key = PREFIX + key
    return factory(klass, key)
    def test_factory_location(self):
        # Given an object that is a location,
        # it is not proxied
        @interface.implementer(ILocation)
        class LocatedTarget(Target):
            __name__ = None
            __parent__ = None

        getAnnotation = factory(LocatedTarget)

        context = Context()
        target = getAnnotation(context)

        key = 'zope.annotation.tests.test_factory.LocatedTarget'
        self.assertEqual([key],
                         list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), LocatedTarget)

        # Third, the returned object is an ILocation, rooted at the
        # parent and having the given name.
        self.assertTrue(ILocation.providedBy(target))
        self.assertIs(target.__parent__, context)
        self.assertEqual(target.__name__, key)

        # And it's not a proxy.
        self.assertEqual(type(target), LocatedTarget)
        self.assertTrue(ITarget.providedBy(target))
        self.assertIs(target, context[key])
Esempio n. 6
0
def settings_factory(klass, name, title=None, fields=None):
    key = PREFIX + name
    result = factory(klass, key)
    result.name = result.title = name
    if title is not None:
        result.title = title
    result.fields = fields
    return result
Esempio n. 7
0
    def test_factory_with_key(self):

        key = 'testkey'
        getAnnotation = factory(Target, key)

        context = Context()
        getAnnotation(context)

        self.assertEqual([key], list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), Target)
    def test_factory_with_key(self):

        key = 'testkey'
        getAnnotation = factory(Target, key)

        context = Context()
        getAnnotation(context)

        self.assertEqual([key],
                         list(context))

        # Second, a target object is stored at that location.
        self.assertEqual(type(context[key]), Target)
Esempio n. 9
0
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.annotation import factory
from zope import component
from zope import interface
from zope import schema

from collective.rcse.settings import getDefaultSettings


class ISettings(interface.Interface):
    settings = schema.Dict(
        title=u"Settings",
        key_type=schema.ASCIILine(),
        value_type=schema.ASCIILine()
    )


class Settings(object):
    interface.implements(ISettings)
    component.adapts(IAttributeAnnotatable)

    def __init__(self):
        self.settings = getDefaultSettings()


SettingsFactory = factory(Settings)
Esempio n. 10
0
    banner_elements = ['title', 'text', 'image']
    width = None
    height = None
    pager_template = '@@pager-numbers'
    element_id = 'carousel-default'
    transition_type = 'fade'
    transition_speed = 0.5
    transition_delay = 8.0
    default_page_only = True
    lazyload = False
    random_order = False

    def __init__(self):
        self.element_id = 'carousel-%s' % hash(time())

CarouselSettingsFactory = factory(CarouselSettings)


class AppearanceGroup(group.Group):
    """
    Appearance options.
    """

    label = _('Appearance')
    fields = field.Fields(ICarouselSettings).select(
        'banner_template', 'banner_elements', 'width', 'height',
        'pager_template', 'element_id', 'lazyload', 'random_order')
    fields['banner_elements'].widgetFactory = CheckBoxFieldWidget
    fields['lazyload'].widgetFactory = SingleCheckBoxFieldWidget
    fields['random_order'].widgetFactory = SingleCheckBoxFieldWidget
Esempio n. 11
0
# 2010 Ilshad Khabibullin <*****@*****.**>

from persistent import Persistent
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.annotation import factory
from zope.schema.fieldproperty import FieldProperty
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import PrincipalLookupError
from interfaces import IResponsibility
from interfaces import IIssue

class Responsibility(Persistent):
    implements(IResponsibility)
    adapts(IIssue)

    responsible = FieldProperty(IResponsibility["responsible"])

    def get_principal(self):
        auth = getUtility(IAuthentication)
        if self.responsible is None:
            return None
        try:
            return auth.getPrincipal(self.responsible)
        except PrincipalLookupError:
            return None
    
annotation_factory = factory(Responsibility)
class ICommentExtenderFields(Interface):
    attachment = NamedBlobFile(
        title=_(u"Attachment"),
        description=_(u""),
        required=False,
    )


class CommentExtenderFields(Persistent):
    interface.implements(ICommentExtenderFields)
    adapts(Comment)
    attachment = u""


CommentExtenderFactory = factory(CommentExtenderFields)


class CommentExtender(extensible.FormExtender):
    adapts(Interface, IDefaultBrowserLayer, CommentForm)

    fields = Fields(ICommentExtenderFields)

    def __init__(self, context, request, form):
        self.context = context
        self.request = request
        self.form = form

    def update(self):
        self.add(ICommentExtenderFields, prefix="")
        self.move('attachment', after='text', prefix="")

class IExtraBehavior(Interface):
    foo = schema.TextLine(title=u"Foo")
    bar = schema.TextLine(title=u"Bar")


class ExtraBehavior(Persistent):
    implements(IExtraBehavior)
    adapts(NewsletterSubcriber)

    foo = u""
    bar = u""


ExtraBehavior = factory(ExtraBehavior)
provideAdapter(ExtraBehavior)
provideAdapter(AttributeAnnotations)


class ExtraBehaviorExtender(extensible.FormExtender):
    adapts(Interface, IDefaultBrowserLayer, NewsletterSubscriberForm)

    def __init__(self, context, request, form):
        self.context = context
        self.request = request
        self.form = form

    def update(self):
        if 'extra.foo' not in self.form.fields.keys():
            self.add(IExtraBehavior, prefix="extra")
Esempio n. 14
0
from plone.z3cform.fieldsets import extensible

from plone.app.discussion.browser.comments import CommentForm
from plone.app.discussion.comment import Comment
from plone.app.discussion.interfaces import IDiscussionSettings, ICaptcha


class Captcha(Persistent):
    """Captcha input field.
    """
    interface.implements(ICaptcha)
    adapts(Comment)
    captcha = u""


Captcha = factory(Captcha)


class CaptchaExtender(extensible.FormExtender):
    """Extends the comment form with a Captcha. This Captcha extender is only
    registered when a plugin is installed that provides the
    "plone.app.discussion-captcha" feature.
    """
    adapts(Interface, IDefaultBrowserLayer,
           CommentForm)  # context, request, form

    fields = Fields(ICaptcha)

    def __init__(self, context, request, form):
        self.context = context
        self.request = request
Esempio n. 15
0
    width = None
    height = None
    pager_template = u"@@pager-numbers"
    element_id = u"carousel-default"
    transition_type = u"fade"
    transition_speed = 0.5
    transition_delay = 8.0
    default_page_only = True
    lazyload = False
    random_order = False

    def __init__(self):
        self.element_id = u"carousel-%s" % hash(time())


CarouselSettingsFactory = factory(CarouselSettings)


class AppearanceGroup(group.Group):
    """
    Appearance options.
    """

    label = _(u"Appearance")
    fields = field.Fields(ICarouselSettings).select(
        "banner_template",
        "banner_elements",
        "width",
        "height",
        "pager_template",
        "element_id",
Esempio n. 16
0
        if not email_list:
            return

        if not emails:
            # remove all user's email addresses.
            emails = list(email_list)

        for email in emails:
            try:
                self._email_to_login.pop(email, None)
                email_list.remove(email)
            except ValueError:
                pass

    def get_emails_for(self, login):
        """
        Return all emails for this login.
        """

        return sorted(self._user_email_lists.get(login, []))

    def get_login_for(self, email):
        """
        Return the login for this email address.
        """

        return self._email_to_login.get(email, None)


EmailManagerFactory = factory(EmailManager)
        """Make the adapter penetratable for the vocabulary to find the cat"""
        return getToolByName(getSite(), 'portal_catalog')

    @property
    def portal_url(self):
        """Make the adapter penetratable for the vocabulary to find the cat"""
        return getToolByName(getSite(), 'portal_url')

    urls = []


class LinkList(LinkListBase):
    implements(ILinkList, ILinkListDocument)
    adapts(IATDocument)

linklist_adapter_document = factory(LinkList)


class LinkListFolder(LinkListBase):
    implements(ILinkList, ILinkListFolder)
    adapts(IATFolder)

linklist_adapter_folder = factory(LinkListFolder)


class LinkCollectionForm(form.PageEditForm):
    form_fields = form.Fields(ILinkList)
    label = u"Add Content Objects to point to"
    form_fields['urls'].custom_widget = UberMultiSelectionWidget

    @form.action(_("Apply"))
Esempio n. 18
0
# -*- coding: utf-8 --
import logging
from persistent import Persistent
from zope import component, schema
from zope.interface import implementer, provider
from zope.component import adapter
from zope.annotation import factory
from Products.CMFCore.interfaces import ISiteRoot
import interfaces

LOG = logging.getLogger(__name__)


@implementer(interfaces.IOdooPasSettings)
@adapter(ISiteRoot)
class OdooPasSettingsAdapter(Persistent):
    def __init__(self, **kwargs):
        iface = interfaces.IOdooPasSettings
        for field in [
                iface.get(name) for name in iface.names()
                if schema.interfaces.IField.providedBy(iface.get(name))
        ]:
            setattr(self, field.__name__,
                    kwargs.get(field.__name__, field.default))


OdooPasSettings = factory(OdooPasSettingsAdapter)
Esempio n. 19
0

class IRecaptchaInfo(Interface):
    error = schema.TextLine()
    verified = schema.Bool()


class RecaptchaInfoAnnotation(object):
    implements(IRecaptchaInfo)
    adapts(IBrowserRequest)

    def __init__(self):
        self.error = None
        self.verified = False

RecaptchaInfo = factory(RecaptchaInfoAnnotation)


class RecaptchaView(BrowserView):

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.settings = getRecaptchaSettings()

    def image_tag(self):
        portal_state = queryMultiAdapter(
            (self.context, self.request), name=u'plone_portal_state')
        if portal_state is not None:
            lang = portal_state.language()[:2]
        else:
Esempio n. 20
0
# 2010 Ilshad Khabibullin <*****@*****.**>

from persistent import Persistent
from zope.component import adapts, hooks
from zope.component.interfaces import ISite
from zope.schema.fieldproperty import FieldProperty
from zope.interface import implements
from zope.annotation import factory

from tackle.interfaces import IInstalledContent


class InstalledContent(Persistent):
    implements(IInstalledContent)
    adapts(ISite)

    contents = FieldProperty(IInstalledContent['contents'])


annotation_factory = factory(InstalledContent)


def content_removed(ob, event):
    annotation = IInstalledContent(getSite())
    keys = annotation.contents
    name = event.oldName
    if name in keys:
        x = keys.pop(keys.index(name))
Esempio n. 21
0
                              value_type=schema.TextLine(title=u"User ID"))


class FavoritingStorage(object):
    interface.implements(IFavoritingStorage)
    component.adapts(IAttributeAnnotatable)

    def __init__(self):
        """
        Note that the annotation implementation does not expect any arguments
        to its `__init__`. Otherwise it's basically an adapter.
        """
        self.favoritedby = []


FavoritingStorageFactory = factory(FavoritingStorage)


class FavoritingManager(BrowserView):
    """implementation of IFavoriting using annotation + portal_catalog"""
    interface.implements(IFavoritingManager)

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.userid = None
        self.membership = None
        self.catalog = None
        self.favorites = []
        self.storage = None
Esempio n. 22
0
    image = NamedBlobImage(
        title=_(u"Upload an image"),
        required=False,
    )

    file = NamedBlobFile(
        title=_(u"Upload a file"),
        required=False,
    )


@adapter(Comment)
@implementer(ICommentFormExtender)
class CommentFormAdapter(object):
    """ CommentFormAdapter fields.
    """


CommentFormAdapter = factory(CommentFormAdapter)


@implementer(IFormExtender)
@adapter(Interface, ILMUCommentFormLayer, CommentForm)
class CommentFormExtender(FormExtender):
    ''' Extend the comment form with additional extra fields
    '''
    fields = Fields(ICommentFormExtender)

    def update(self):
        self.add(self.fields)
Esempio n. 23
0
from cellml.theme.vocab import get_layout


class LayoutSettings(Persistent):
    """
    Maps between the two thing,
    """

    interface.implements(ILayoutSettings)
    component.adapts(interface.Interface)

    layout = fieldproperty.FieldProperty(ILayoutSettings['layout'])

    def get_layout(self, sl, sr):
        """
        Return the layout name.
        """

        leftcolumn, rightcolumn, bothcolumns = get_layout(self.layout)

        # a simple truth table to figure this out.
        return {
            (False, False): u'layoutZero',
            (True, False): leftcolumn,
            (False, True): rightcolumn,
            (True, True): bothcolumns,
        }[(sl, sr)]


LayoutSettingsFactory = factory(LayoutSettings)
Esempio n. 24
0
                return self._schema[key].default
        else:
            raise AttributeError

    def __setattr__(self, key, value):
        if key in self._schema:
            bound = self._schema[key].bind(self)
            bound.validate(value)
            self._data[key] = value
        else:
            raise AttributeError
    
class PersistentConfig(Persistent):
    implements(IPersistentConfig)
    adapts(ISite)

    def __init__(self):
        self.data = OOBTree()

    def get_config(self, key):
        try:
            c = self.data[key]
        except KeyError:
            c = self.data[key] = OOBucket()
        return _config(c, getUtility(IPersistentConfigType, key))

annotation_factory = factory(PersistentConfig)

def persistent_config(k):
    return IPersistentConfig(hooks.getSite()).get_config(k)
Esempio n. 25
0
            defn.scoreSystem.getNumericalValue(rating.value)
            for rating in ratings
        ])
        try:
            return total / len(ratings)
        except ZeroDivisionError:
            return -1

    def countScores(self, id, dtMin=None, dtMax=None):
        """See interfaces.IRatingsManager"""
        defn = self._getDefinition(id)
        ratings = list(self._storage.get(id, {}).values())
        value_count = {}
        for rating in ratings:
            value_count.setdefault(rating.value, 0)
            value_count[rating.value] += 1

        return [(score, value_count.get(score[0], 0))
                for score in defn.scoreSystem.scores]

    def countAmountRatings(self, id, dtMin=None, dtMax=None):
        """See interfaces.IRatingManager"""
        ratings = list(self._storage.get(id, {}).values())
        return len(ratings)

    def __repr__(self):
        return '<%s for %r>' % (self.__class__.__name__, self.__parent__)


getRatingsManager = annotation.factory(RatingsManager)
Esempio n. 26
0
    def add(self, subscription):
        self.subscriptions[self._next_id] = subscription
        self._next_id += 1

    def remove(self, n):
        del self.subscriptions[n]

    def list_with_keys(self):
        for n, subscription in self.subscriptions.iteritems():
            yield n, subscription

    def __iter__(self):
        for subscription in self.subscriptions.itervalues():
            yield subscription

subscription_container_factory = annotation.factory(SubscriptionContainer)

class AccountSubscription(object):
    interface.implements(ISubscription)

    def __init__(self, user_id, notif_type, lang):
        self.user_id = user_id
        self.lang = lang
        self.notif_type = notif_type

    def check_permission(self, obj):
        acl_users = obj.getSite().getAuthenticationTool()
        user = acl_users.get_user_with_userid(self.user_id)

        if user is None:
            return False
Esempio n. 27
0
        self.email = kw.pop('email')
        self.first_name = kw.get('first_name')
        self.last_name = kw.get('last_name')
        self.organisation = kw.get('organisation')
        self.country = kw.get('country')
        self.notif_type = kw.pop('notif_type')
        self.lang = kw.pop('lang')
        self.content_types = kw.pop('content_types')
        self.location = kw.pop('location')
        self.key = sha("%s%s" % (time(),
                                     random.randrange(1, 10000))).hexdigest()
        self.__dict__.update(kw)
        self.datetime = datetime.now()

    def check_permission(self, obj):
        user = obj.unrestrictedTraverse('/acl_users')._nobody
        return bool(user.has_permission(view, obj))

    def get_email(self, obj):
        return self.email

    def to_string(self, obj):
        if getattr(self, 'organisation', ''):
            return u'%s (%s)' % (self.organisation, self.email)
        else:
            return u'%s' % self.email

#The key is the old location of the class
subscription_container_factory = annotation.factory(SubscriptionContainer,
"Products.NaayaCore.NotificationTool.NotificationTool.SubscriptionContainer")
Esempio n. 28
0
    )


class FavoritingStorage(object):
    interface.implements(IFavoritingStorage)
    component.adapts(IAttributeAnnotatable)

    def __init__(self):
        """
        Note that the annotation implementation does not expect any arguments
        to its `__init__`. Otherwise it's basically an adapter.
        """
        self.favoritedby = []


FavoritingStorageFactory = factory(FavoritingStorage)


class FavoritingManager(BrowserView):
    """implementation of IFavoriting using annotation + portal_catalog"""
    interface.implements(IFavoritingManager)

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.userid = None
        self.membership = None
        self.catalog = None
        self.favorites = []
        self.storage = None
Esempio n. 29
0
from zope.interface import implements
from zope.annotation import factory

from tackle.interfaces import ISubscription, ISubscribable
from tackle.profile import get_profile
from tackle.smtp import send_mail

class Subscription(Persistent):
    implements(ISubscription)
    adapts(ISubscribable)

    def __init__(self):
        self.subscribers = OOTreeSet()

    def subscribe(self, principal_id):
        self.subscribers.insert(principal_id)

    def unsubscribe(self, principal_id):
        self.subscribers.remove(principal_id)

    def send(self, message, subject):
        for pid in self.subscribers.keys():
            profile = get_profile(pid, "basic")
            send_mail(message, subject, profile.email)

annotation_factory = factory(Subscription)

def subscribe(ob, event):
    subscription = ISubscription(event.context)
    subscription.send(event.message)
Esempio n. 30
0
    listField = FieldProperty(interfaces.IAllFields['listField'])
    objectField = FieldProperty(interfaces.IAllFields['objectField'])
    passwordField = FieldProperty(interfaces.IAllFields['passwordField'])
    setField = FieldProperty(interfaces.IAllFields['setField'])
    sourceTextField = FieldProperty(interfaces.IAllFields['sourceTextField'])
    textField = FieldProperty(interfaces.IAllFields['textField'])
    textLineField = FieldProperty(interfaces.IAllFields['textLineField'])
    timeField = FieldProperty(interfaces.IAllFields['timeField'])
    timedeltaField = FieldProperty(interfaces.IAllFields['timedeltaField'])
    tupleField = FieldProperty(interfaces.IAllFields['tupleField'])
    uriField = FieldProperty(interfaces.IAllFields['uriField'])
    hiddenField = FieldProperty(interfaces.IAllFields['hiddenField'])


# register the AllField class as a annotation adapter
getAllFields = factory(AllFields)


class AllFieldsForm(form.EditForm):
    """A form showing all fields."""
    fields = field.Fields(interfaces.IAllFields).omit('dictField',
                                                      'objectField')
    fields['checkboxBoolField'].widgetFactory = \
                                              checkbox.SingleCheckBoxFieldWidget
    label = 'Widgets Demo'

    def getContent(self):
        return interfaces.IAllFields(self.context)

    def updateWidgets(self):
        self.widgets = zope.component.getMultiAdapter(
    zope.component.adapts(interfaces.IHasEditorialStatus)

    def getCurrentEditorialStatus(self):
        try:
            return self.items()[-1][1]
        except IndexError:
            return None

    @property
    def locked(self):
        cur = self.getCurrentEditorialStatus()
        if cur is None:
            return False
        vocReg = getVocabularyRegistry()
        voc = vocReg.get(cur, 'quotationtool.editorial.Status')
        return voc.getTermByToken(cur.status).locked


editorialHistoryAnnotation = factory(EditorialHistory)


class EditorialStatusNameChooser(NameChooser):
    """ A name chooser for editorial status objects."""

    zope.component.adapts(interfaces.IEditorialHistory)
    
    def chooseName(self, name, obj):
        name = str(obj.date)
        self.checkName(name, obj)
        return name
Esempio n. 32
0
import orm

from schema import metadata

from domain import User, Minister
from domain import (GroupMembership, Group, Government, Parliament,
    PoliticalParty, Ministry, Committee, CommitteeType, CommitteeTypeStatus
)
from domain import (GroupSitting, GroupSittingType, GroupSittingAttendance,
    AttendanceType
)
from domain import ParliamentSession, PoliticalGroup
from domain import (Question, QuestionVersion, QuestionChange, QuestionType, 
    ResponseType
)
from domain import Motion, MotionVersion, MotionChange
from domain import Bill, BillVersion, BillChange, BillType
from domain import Constituency, Parliament
from domain import Country, Region, Province
from domain import MemberOfParliament, MemberElectionType
from domain import TitleType, MemberTitle
from domain import ItemSchedule

from domain import AddressType, GroupAddress, UserAddress, PostalAddressType

from zope.annotation import factory
from zope import component
from roles import SubRoleAnnotations
component.provideAdapter(factory(SubRoleAnnotations))
Esempio n. 33
0
        email_list = self._user_email_lists.get(login, ())
        if not email_list:
            return

        if not emails:
            # remove all user's email addresses.
            emails = list(email_list)

        for email in emails:
            try:
                self._email_to_login.pop(email, None)
                email_list.remove(email)
            except ValueError:
                pass

    def get_emails_for(self, login):
        """
        Return all emails for this login.
        """

        return sorted(self._user_email_lists.get(login, []))

    def get_login_for(self, email):
        """
        Return the login for this email address.
        """

        return self._email_to_login.get(email, None)

EmailManagerFactory = factory(EmailManager)
Esempio n. 34
0
from tackle.interfaces import ISubscription, ISubscribable
from tackle.profile import get_profile
from tackle.smtp import send_mail


class Subscription(Persistent):
    implements(ISubscription)
    adapts(ISubscribable)

    def __init__(self):
        self.subscribers = OOTreeSet()

    def subscribe(self, principal_id):
        self.subscribers.insert(principal_id)

    def unsubscribe(self, principal_id):
        self.subscribers.remove(principal_id)

    def send(self, message, subject):
        for pid in self.subscribers.keys():
            profile = get_profile(pid, "basic")
            send_mail(message, subject, profile.email)


annotation_factory = factory(Subscription)


def subscribe(ob, event):
    subscription = ISubscription(event.context)
    subscription.send(event.message)
    public_key = schema.TextLine(title=_(u'Site Key'))

    private_key = schema.TextLine(title=_(u'Secret Key'))


class RecaptchaSettingsAnnotations(Persistent):
    implements(IRecaptchaSettings)
    adapts(IAttributeAnnotatable)

    def __init__(self):
        self.public_key = None
        self.private_key = None


RecaptchaSettings = factory(RecaptchaSettingsAnnotations)


def getRecaptchaSettings():
    site = getSite()
    return IRecaptchaSettings(site)


class RecaptchaSettingsForm(EditForm):
    schema = IRecaptchaSettings
    label = _(u"Recaptcha settings")

    if FormFields:
        # formlib missing (Plone 5?)
        form_fields = FormFields(IRecaptchaSettings)
Esempio n. 36
0
Created by Kapil Thangavelu on 2007-11-22.
"""

import orm

from schema import metadata

from domain import User, Minister
from domain import (GroupMembership, Group, Government, Parliament,
                    PoliticalParty, Ministry, Committee, CommitteeType,
                    CommitteeTypeStatus)
from domain import (GroupSitting, GroupSittingType, GroupSittingAttendance,
                    AttendanceType)
from domain import ParliamentSession, PoliticalGroup
from domain import (Question, QuestionVersion, QuestionChange, QuestionType,
                    ResponseType)
from domain import Motion, MotionVersion, MotionChange
from domain import Bill, BillVersion, BillChange, BillType
from domain import Constituency, Parliament
from domain import Country, Region, Province
from domain import MemberOfParliament, MemberElectionType
from domain import TitleType, MemberTitle
from domain import ItemSchedule

from domain import AddressType, GroupAddress, UserAddress, PostalAddressType

from zope.annotation import factory
from zope import component
from roles import SubRoleAnnotations
component.provideAdapter(factory(SubRoleAnnotations))
Esempio n. 37
0
from plone.memoize.ram import global_cache
from plone.app.layout.navigation.defaultpage import isDefaultPage
from Solgema.RichMenu.interfaces import ISolgemaRichMenuAttributes, ISolgemaRichMenuMarker
from Solgema.RichMenu.config import _
LOG = logging.getLogger('Solgema.RichMenu')

class SolgemaRichMenuAttributesAdapter(Persistent):

    implements(ISolgemaRichMenuAttributes)
    component.adapts(interface.Interface)
    def __init__(self):
        for iface in list(directlyProvidedBy(self)):
            for field in [iface.get(name) for name in iface.names() if schema.interfaces.IField.providedBy(iface.get(name))]:
                setattr(self, field.__name__, field.default)

SolgemaRichMenuAttributes = factory(SolgemaRichMenuAttributesAdapter)

class z3cManageSolgemaRichMenuAttributes(form.EditForm):
    
    label = _('Rich Menu parameters')

    @property
    def fields(self):
        fields = field.Fields(ISolgemaRichMenuAttributes)
        portal_quickinstaller = getToolByName(self.context, 'portal_quickinstaller')
        if has_p5 and has_rel and portal_quickinstaller.isProductInstalled('plone.app.widgets'):
            fields['section_menu_item'].widgetFactory[INPUT_MODE] = RelatedItemsFieldWidget
        elif not has_p5 and not has_rel and has_ctree:
            fields['section_menu_item'].widgetFactory[INPUT_MODE] = ContentTreeFieldWidget
        return fields
    
Esempio n. 38
0
from persistent import Persistent

from zope.annotation import factory
from zope.component import adapts
from zope.interface import implements

from collective.mediaelementjs.interfaces import IVideo, IMediaInfo, IAudio


class VideoInfo(Persistent):
    implements(IMediaInfo)
    adapts(IVideo)

    def __init__(self):
        self.height = None
        self.width = None
        self.duration = None

VideoInfoAdapter = factory(VideoInfo)


class AudioInfo(Persistent):
    implements(IMediaInfo)
    adapts(IAudio)

    def __init__(self):
        self.duration = None

AudioInfoAdapter = factory(AudioInfo)
 def _wrapper(cls):
     adapter_ = factory(adapter(*ifaces)(cls), key=TIMELINE_ANNOTATIONS_KEY)
     provideAdapter(adapter_)
     return cls
        super(StagingRelationValue, self).__init__(to_id)
        self.staging_properties = PersistentDict()
        # remember the creator
        portal = getUtility(ISiteRoot)
        mstool = getToolByName(portal, 'portal_membership')
        self.creator = mstool.getAuthenticatedMember().getId()


class Storage(Persistent):
    implements(IWCAnnotator)
    adapts(IDexterityContent)

    def __init__(self):
        super(Storage, self).__init__()
        self._data = None

    def set_relation(self, value):
        # dewrap __parent__ attribute,
        # CMFEdition cannot pickle wrapped objects
        value.__parent__ = aq_base(value.__parent__)
        self._data = value

    def get_relation(self):
        return self._data

    def delete(self):
        self._data = None


WCAnnotator = factory(Storage)
Esempio n. 41
0
# -*- coding: utf-8 --
import logging
from persistent import Persistent
from zope import component, schema
from zope.interface import implementer, provider
from zope.component import adapter
from zope.annotation import factory
from Products.CMFCore.interfaces import ISiteRoot
import interfaces

LOG = logging.getLogger(__name__)

@implementer(interfaces.IOdooPasSettings)
@adapter(ISiteRoot)
class OdooPasSettingsAdapter(Persistent):
  
    def __init__(self, **kwargs):
        iface = interfaces.IOdooPasSettings
        for field in [iface.get(name) for name in iface.names() if schema.interfaces.IField.providedBy(iface.get(name))]:
            setattr(self, field.__name__, kwargs.get(field.__name__, field.default))

OdooPasSettings = factory(OdooPasSettingsAdapter)
Esempio n. 42
0
                                'location is not a workspace container')
            else:
                raise TypeError('the content returned is not a user workspace '
                                'container')
        return obj

    def getExposureContainer(self):
        return self.siteManagerUnrestrictedTraverse(
            self.default_exposure_subpath)

    def siteManagerUnrestrictedTraverse(self, subpath):
        sm = getSiteManager(self)
        path = '../%s' % subpath
        return sm.unrestrictedTraverse(str(path), None)

PMR2GlobalSettings = factory(PMR2GlobalSettingsAnnotation)


def _make_default_path():
    # While ${SOFTWARE_HOME} is typically standard "default" location
    # for application specific files, this product is normally installed 
    # via buildout, hence this directory will be recreated on each 
    # reinstall.  This basically makes it a bad choice for storing any
    # persistent information as they will be unlinked every upgrade.
    # The ${CLIENT_HOME} is more stable, however it might not exist, so
    # we will have fallback.

    suffix = 'pmr2'
    envvar = ['CLIENT_HOME', 'SOFTWARE_HOME']

    for v in envvar:
Esempio n. 43
0
import zope.interface
import zope.component
from zope.schema import fieldproperty
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.annotation import factory
from zope.container.contained import Contained
from persistent import Persistent

from pmr2.virtuoso.interfaces import IWorkspaceRDFInfo


@zope.component.adapter(IAttributeAnnotatable)
@zope.interface.implementer(IWorkspaceRDFInfo)
class WorkspaceRDFInfo(Persistent, Contained):

    paths = fieldproperty.FieldProperty(IWorkspaceRDFInfo['paths'])


WorkspaceRDFInfoFactory = factory(WorkspaceRDFInfo)
Esempio n. 44
0
    """

    attribution_factory = BTrees.family32.OO.TreeSet


class AttributionAnnotation(PersistentAttribution, Location):
    """ An attribution implemented as a persistent annotation to
    ICategorizable objects.

    """

    zope.interface.implements(interfaces.IAttribution)
    zope.component.adapts(interfaces.ICategorizable)


attribution_annotation_factory = factory(AttributionAnnotation,
                                         ATTRIBUTION_KEY)


@zope.component.adapter(interfaces.IAttributionModifiedEvent)
def attributionModifiedDispatcher(event):
    """ Dispatch AttributionModifiedEvent to ObjectModifiedEvent on
    categorizable (attributed) object."""
    zope.event.notify(ObjectModifiedEvent(event.attribution.__parent__))


class AttributionIndexer(ValueIndexer):
    """ Value indexer that indexes attributions of categorizable
    objects."""

    indexName = ATTRIBUTION_INDEX  # it is a SetIndex
Esempio n. 45
0
from zope import interface
from zope import component
from zope import annotation
from zope.deprecation import deprecated
from persistent.dict import PersistentDict

from gu.repository.content.interfaces import IRepositoryMetadata
#

ANNO_KEY = 'gu.repository'

#


#
deprecated('RepositoryMetadata', 'Not useful anymore')
class RepositoryMetadata(PersistentDict):
    interface.implements(IRepositoryMetadata)
    component.adapts(annotation.IAttributeAnnotatable)

#
deprecated('RepositoryMetadataAdapter', 'Not useful anymore')
RepositoryMetadataAdapter = annotation.factory(RepositoryMetadata, key=ANNO_KEY)
Esempio n. 46
0

class IExtraBehavior(Interface):
    foo = schema.TextLine(title=u"Foo")
    bar = schema.TextLine(title=u"Bar")


@implementer(IExtraBehavior)
@adapter(NewsletterSubcriber)
class ExtraBehavior(Persistent):

    foo = u""
    bar = u""


ExtraBehavior = factory(ExtraBehavior)
provideAdapter(ExtraBehavior)
provideAdapter(AttributeAnnotations)


@adapter(Interface, IDefaultBrowserLayer, NewsletterSubscriberForm)
class ExtraBehaviorExtender(extensible.FormExtender):
    def __init__(self, context, request, form):
        self.context = context
        self.request = request
        self.form = form

    def update(self):
        if 'extra.foo' not in self.form.fields.keys():
            self.add(IExtraBehavior, prefix="extra")
Esempio n. 47
0
from persistent import Persistent
from zope.component import adapts
from zope.interface import implements
from zope.container import btree
from zope.annotation import factory
from zope.schema.fieldproperty import FieldProperty
from interfaces import ITODOAnnotatable, ITODO, IItem


class TODO(btree.BTreeContainer):
    implements(ITODO)
    adapts(ITODOAnnotatable)

    @property
    def progress(self):
        try:
            return len([x
                        for x in self.values() if x.closed]) / len(self) * 100
        except ZeroDivisionError:
            return 0


class Item(Persistent):
    implements(IItem)

    subject = FieldProperty(IItem['subject'])
    closed = FieldProperty(IItem['closed'])


annotation_factory = factory(TODO)
Esempio n. 48
0
KEY = 'collective.compositepage.layout'


class LayoutManager(object):
    interface.implements(ILayoutManager)
    component.adapts(IComposable)

    def __init__(self):
        # Does not expect argument as usual adapters
        # You can access annotated object through ``self.__parent__``
        # Let's use a PersistentDict since we do not know how it may evolve
        # and if we'll need more attributes to store.
        self._data = PersistentDict({'html': ''})
        self._old_data = PersistentDict({'html': ''})

    def html(self, html=None):
        current = self._data['html']
        if html is None:
            return current
        # else store a new value
        # but keep previous version
        self._old_data['html'] = current
        self._data['html'] = html

    def old_version(self):
        return self._data['html']


manager = annotation.factory(LayoutManager, key=KEY)
Esempio n. 49
0
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.annotation import factory
from zope import component
from zope import interface
from zope import schema

from collective.rcse.settings import getDefaultSettings


class ISettings(interface.Interface):
    settings = schema.Dict(title=u"Settings",
                           key_type=schema.ASCIILine(),
                           value_type=schema.ASCIILine())


class Settings(object):
    interface.implements(ISettings)
    component.adapts(IAttributeAnnotatable)

    def __init__(self):
        self.settings = getDefaultSettings()


SettingsFactory = factory(Settings)
Esempio n. 50
0
        created_at, userid, target = token

        if created_at + self.ttl < time():
            # Expired token, by removing it also.
            self._keys.pop(key, None)
            # Others will not be removed, figure out how to prune later.
            return None

        server_url = request.get('SERVER_URL', '')
        actual_url = request.get('ACTUAL_URL', '')

        if target[:1] == '/':
            target = server_url + target

        if not (actual_url and actual_url.startswith(target)):
            return None

        return userid

    def validateByCredentials(self, key, credentials):
        """
        For the PAS plugin.
        """

        if not credentials.get('_temp_auth'):
            return None
        return self.validateAccess(key, credentials)

TemporaryAuthFactory = factory(TemporaryAuth)
Esempio n. 51
0
from persistent import Persistent
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.annotation import factory
from zope.schema.fieldproperty import FieldProperty
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import PrincipalLookupError
from interfaces import IResponsibility
from interfaces import IIssue


class Responsibility(Persistent):
    implements(IResponsibility)
    adapts(IIssue)

    responsible = FieldProperty(IResponsibility["responsible"])

    def get_principal(self):
        auth = getUtility(IAuthentication)
        if self.responsible is None:
            return None
        try:
            return auth.getPrincipal(self.responsible)
        except PrincipalLookupError:
            return None


annotation_factory = factory(Responsibility)
    
    banner_template = schema.Choice(
     title=_(u'Banner Type'),
        description=_(u'The banner is the part of the Carousel that rotates.'
            ' Choose Default for the standard Carousel banner.'),
        vocabulary='msd.landingpage.BannerTemplates',
    )
    
    
class LandingPageCarouselSettings(CarouselSettings):
    implements(ILandingPageCarouselSettings)
    adapts(ICarouselBlock)
    
    pager_template = None
    
LandingPageCarouselSettingsFactory = factory(LandingPageCarouselSettings)

class AppearanceGroup(group.Group):
    """
    Appearance options. Just so we can override banner_template vocabulary and hide some fields
    """

    label = _(u'Appearance')
    fields = field.Fields(ILandingPageCarouselSettings).select(
        'banner_template', 'banner_elements', 'width', 'height',
         'element_id')
    fields['banner_elements'].widgetFactory = CheckBoxFieldWidget
    fields["banner_template"].vocabularyName ='msd.landingpage.BannerTemplates'

class LandingPageCarouselSettingsForm(CarouselSettingsForm):
    """
Esempio n. 53
0
# 2010 Ilshad Khabibullin <*****@*****.**>

from persistent import Persistent
from zope.component import adapts
from zope.interface import implements
from zope.container import btree
from zope.annotation import factory
from zope.schema.fieldproperty import FieldProperty
from interfaces import ITODOAnnotatable, ITODO, IItem

class TODO(btree.BTreeContainer):
    implements(ITODO)
    adapts(ITODOAnnotatable)

    @property
    def progress(self):
        try:
            return len(
                [x for x in self.values() if x.closed]) / len(
                self) * 100
        except ZeroDivisionError:
            return 0

class Item(Persistent):
    implements(IItem)

    subject = FieldProperty(IItem['subject'])
    closed = FieldProperty(IItem['closed'])

annotation_factory = factory(TODO)
Esempio n. 54
0
from zope.interface import implements
from zope.component import adapts

from zope.annotation import factory

from collective.flowplayer.interfaces import IVideo, IAudio, IMediaInfo


class VideoInfo(Persistent):
    implements(IMediaInfo)
    adapts(IVideo)

    def __init__(self):
        self.height = None
        self.width = None
        self.audio_only = False


VideoInfoAdapter = factory(VideoInfo)


class AudioInfo(object):
    implements(IMediaInfo)
    adapts(IAudio)

    def __init__(self, context):
        self.audio_only = True
        self.width = None
        self.height = None
Esempio n. 55
0
from zope import interface
from zope.annotation import factory
from zope.component import adapts
from zope.component import queryUtility
from zope.interface import Interface
from zope.publisher.interfaces.browser import IDefaultBrowserLayer


@interface.implementer(ICaptcha)
class Captcha(Persistent):
    """Captcha input field.
    """
    adapts(Comment)
    captcha = u""

Captcha = factory(Captcha)


class CaptchaExtender(extensible.FormExtender):
    """Extends the comment form with a Captcha. This Captcha extender is only
    registered when a plugin is installed that provides the
    "plone.app.discussion-captcha" feature.
    """
    # context, request, form
    adapts(Interface, IDefaultBrowserLayer, CommentForm)

    fields = Fields(ICaptcha)

    def __init__(self, context, request, form):
        self.context = context
        self.request = request
Esempio n. 56
0

class IRecaptchaInfo(Interface):
    error = schema.TextLine()
    verified = schema.Bool()


@adapter(IBrowserRequest)
@implementer(IRecaptchaInfo)
class RecaptchaInfoAnnotation(object):
    def __init__(self):
        self.error = None
        self.verified = False


RecaptchaInfo = factory(RecaptchaInfoAnnotation)


class RecaptchaView(BrowserView):
    def __init__(self, context, request):
        self.context = context
        self.request = request
        registry = queryUtility(IRegistry)
        self.settings = registry.forInterface(IReCaptchaSettings)

    def image_tag(self):
        if not self.settings.public_key:
            return """No recaptcha public key configured.
                Go to <a href="{}/@@recaptcha-settings" target=_blank>
                Recaptcha Settings</a> to configure.""".format(
                getSite().absolute_url())  # noqa: E501
Esempio n. 57
0
    form.fieldset('tagging', label=u"Tagging", fields=['enabled', 'tags'])
    
    enabled = schema.Bool(title=u"Tagging enabled",
                          required=False,
                          default=True)
    
    tags = schema.List(title=u"Tags",
                       description=u"Tags for this object",
                       value_type=schema.Choice(values=["Tag 1", "Tag 2", "Tag 3"]),
                       required=False)

alsoProvides(ITagging, form.IFormFieldProvider)

class TaggingAnnotations(Persistent):
    """Persistent storage for tags in annotations. This uses the "persistent 
    adapter" pattern seen in zope.annotation's README.txt. Of course, a
    regular adapter from context to ITagging would work just as well, but 
    there'd be more work persisting values. If you use a simple adapter,
    don't forget to make __init__() take a 'context' parameter.
    """
    
    implements(ITagging)
    adapts(IAnnotatable)
    
    def __init__(self):
        self.enabled = True
        self.tags = OOSet()

# Use the factory from zope.annotation to support persistent storage of tag data.
Tagging = factory(TaggingAnnotations)
Esempio n. 58
0
    public_key = schema.TextLine(title=_(u"Public Key"))

    private_key = schema.TextLine(title=_(u"Private Key"))


class RecaptchaSettingsAnnotations(Persistent):
    implements(IRecaptchaSettings)
    adapts(IAttributeAnnotatable)

    def __init__(self):
        self.public_key = None
        self.private_key = None


RecaptchaSettings = factory(RecaptchaSettingsAnnotations)


def getRecaptchaSettings():
    registry = getUtility(IRegistry)
    if TRY_REGISTRY:
        # if plone.formwidget.recaptcha is installed, try getting
        # its settings from the registry
        try:
            settings = registry.forInterface(IReCaptchaSettings)
            if settings.public_key and settings.private_key:
                return settings
        except:
            pass
    # try getting settings from the registry first
    try: