Example #1
0
def registerPermission(id, title, roles=()):
    def _registerPermission():
        permission = Permission(id, title, '')
        config.registerUtility(permission, IPermission, id)

        z2_permission = str(title)
        if roles:
            addPermission(z2_permission, default_roles=tuple(roles))
        else:
            addPermission(z2_permission)

    config.action(_registerPermission, __frame=sys._getframe(1))
Example #2
0
def registerConfiglet(
    name, schema=None, klass=None, title="", description="", category="Products", permission="Manage portal"
):

    if not title:
        title = name

    ConfigletClass = ConfigletType(str(name), schema, klass, title, description)
    interface.classImplements(ConfigletClass, schema)

    ConfigletClass.permission = permission

    def completeRegistration():
        # configlet instance
        inst = ConfigletClass()

        # register configlet as utility
        config.registerUtility(inst, schema, "")
        config.registerUtility(inst, IConfiglet, name)

        # register plone configlet
        ai = PloneConfiglet(
            name,
            id=name,
            title=title,
            description=description,
            permissions=(permission,),
            action=Expression(text=u"python:'%%s/++cp++%s/'%%%s" % (name, "portal_url")),
            category=category,
        )

        config.registerUtility(ai, IPloneConfiglet, name)

    frame = sys._getframe(1)

    config.action(
        completeRegistration,
        __frame=frame,
        __discriminator=("memphis.content:configlet", name),
        __order=(config.moduleNum(frame.f_locals["__name__"]), 992),
    )
Example #3
0
from zope import event
from zope.schema import getFieldsInOrder
from zope.interface import providedBy, implementedBy
from zope.component import getSiteManager, getUtility, queryUtility, getMultiAdapter
from zope.lifecycleevent import ObjectRemovedEvent

from memphis import config, view, form
from memphisttw.schema.interfaces import _
from memphisttw.schema.interfaces import IField, IFieldFactory
from memphisttw.schema.interfaces import ISchema, ISchemaManagement

import pagelets, ttwschema
from configlet import SchemaFactory


config.action(view.registerDefaultView, "index.html", IField)

config.action(view.registerDefaultView, "index.html", ISchema)

config.action(view.registerDefaultView, "index.html", ISchemaManagement)


config.action(
    view.registerActions,
    ("index.html", IField, _("Edit"), _("Field edit form."), 10),
    ("preview.html", IField, _("Preview"), _("Field preview."), 20),
    ("../index.html", IField, _("Schema"), _("Return back to schema."), 30),
)


config.action(
Example #4
0
import sqlalchemy
from zope import interface
from memphis import storage, config
from memphis.contenttype.interfaces import IBehaviorType
from memphis.versions.interfaces import \
    IVersionItem, IVersionsRelation, IVersionsSchema, IVersionsBehavior


config.action(
    storage.registerRelation,
    'content.versions', IVersionsRelation)


config.action(
    storage.registerSchema,
    'content.versions', IVersionsSchema,
    title = u'Versions')


class VersionItem(storage.BehaviorBase):
    storage.behavior('content.version-item', IVersionItem)


class VersionsBehavior(storage.BehaviorBase):
    interface.implements(IVersionsBehavior)
    storage.behavior('content.versions', relation=IVersionsRelation,
                     type = IBehaviorType,
                     schema = IVersionsSchema,
                     title = u'Versions',
                     description = u'Data versioning support for content.')
Example #5
0
import pyramid.url
from webob.exc import HTTPFound

from zope import interface
from zope.component import getUtility, queryUtility, getSiteManager

from memphis import form, config, view, storage

from memphis.contenttype import pagelets
from memphis.contenttype.form import AddContentForm
from memphis.contenttype.interfaces import _, IContent, IContentType, IDCDescriptive, IAddContentForm, IEditContentForm


config.action(view.registerDefaultView, "index.html", IContent)


config.action(
    view.registerActions,
    ("index.html", IContent, _("View"), _("View content."), 10),
    ("edit.html", IContent, _("Edit"), _("Edit content."), 20),
)


class AddContent(form.EditForm, AddContentForm, view.View):
    interface.implements(IAddContentForm)
    view.pyramidView("", IContentType)

    fields = form.Fields()
    validate = AddContentForm.validate

    @property
Example #6
0
# memphis.preferences public API

from memphis import config
from memphis.preferences.api import registerCategory
from memphis.preferences.api import registerPreference
from memphis.preferences.interfaces import _, IPreferences


config.action(
    registerCategory,
    'portal', _('Portal preferences'),
     _('These are all the preferences related to common portal settings.'))

config.action(
    registerCategory,
    'membership', _('Membership preferences'),
    _('These are all the preferences related to portal membership.'))
Example #7
0
from memphis import config

from interfaces import _, ISchema


@interface.implementer(IVocabularyFactory)
def getSchemas(context=None):
    fields = [(name, f) for name, f in component.getUtilitiesFor(ISchema)]
    fields.sort()

    return SimpleVocabulary([SimpleTerm(f, name, f.title)
                             for name, f in fields])

config.action(
    config.registerUtility,
    getSchemas, IVocabularyFactory, name='memphis.ttw-schemas')


# Static DisplayLists
dirname = os.path.dirname(globals()["__file__"])
iso3166_file = file(os.path.join(dirname, 'iso3166.txt'), 'rb')

reg = re.compile("'*(\w+)")


def countryrepl(matchobj):
    str = matchobj.group(1)
    if matchobj.group(0).startswith("'"):
        return "'" + str.lower()
    return str.lower().capitalize()
Example #8
0
from zope import interface
from pyramid import url
from memphis import config, view
from memphis.contenttype import pagelets
from memphis.contenttype.interfaces import \
    _, IContained, IContainer, \
    IContentType, IContentContainer, IDCTimes, IDCDescriptive


config.action(
    view.registerDefaultView,
    'listing.html', IContentContainer)

config.action(
    view.registerActions,
    ('listing.html', IContentContainer, 
     _('Listing'), _('Container listing.'), 11))


class Listing(view.Pagelet):
    view.pagelet(
        pagelets.IListing, IContentContainer,
        template = view.template('memphis.contenttype:templates/listing.pt'))

    def update(self):
        self.url = url.resource_url(IContained(self.context), self.request)
        self.container = IContainer(self.context)
        try:
            self.hasitems = self.container.keys().next()
        except StopIteration:
            self.hasitems = False
Example #9
0
def registerType(
    name,
    behavior = 'content.instance',
    factory = Instance,
    schemas = (),
    behaviors = (),
    title = '',
    description = '', 
    global_allow = True, 
    permission = 'View', 
    actions = None,
    **kw):

    if name in registered:
        raise ValueError('Content type "%s" already registered.'%name)

    if not title:
        title = name

    if 'add_view_expr' not in kw:
        kw['add_view_expr'] = 'string:${object_url}/++content++%s'%name

    if 'icon_expr' not in kw:
        kw['icon_expr'] = 'string:${portal_url}/document_icon.png'

    if actions is None:
        actions = (
            {'id': 'view',
             'title': 'View',
             'action': 'string:${object_url}',
             'visible': True,
             'permissions': ('View',)},
            {'id': 'edit',
             'title': 'Edit',
             'action': 'string:${object_url}/edit.html',
             'visible': True,
             'permissions': ('Modify portal content',)},
            )

    ti = ContentType(
        behavior, name, factory, 
        behaviors = behaviors,
        schemas = schemas,
        title = title,
        description = description,
        content_meta_type = name,
        global_allow = global_allow,
        permission = permission,
        actions = actions,
        **kw)

    registered[name] = ti

    def completeRegistration():
        config.registerUtility(ti, ITypeInformation, name)

        # register zope2 meta_type
        info = {'name': name,
                'action': '',
                'product': 'memphis.content',
                'permission': permission,
                'visibility': 'Global',
                'interfaces': interface.Interface,
                'instance': None,
                'container_filter': None}

        meta_types = getattr(Products, 'meta_types', ())
        meta_types += (info,)
        Products.meta_types = meta_types

        ti._complete()

    frame = sys._getframe(1)

    config.action(
        completeRegistration,
        __frame = frame,
        __info = config.getInfo(2),
        __discriminator = ('memphis.content:type', name),
        __order = (config.moduleNum(frame.f_locals['__name__']), 990))

    return ti
Example #10
0
import datetime
from zope import interface
from memphis import view, config, form, contenttype
from memphis.versions.interfaces import IVersionsBehavior, IVersionsSchema


config.action(
    view.registerActions, ("versions.html", IVersionsBehavior, "Versions", "Content versioning support.", 1000)
)


class Versions(view.View):
    view.pyramidView(
        "versions.html", IVersionsBehavior, template=view.template("memphis.versions:templates/versions.pt")
    )

    def update(self):
        self.versions = IVersionsBehavior(self.context)


class EditVersionContent(form.SubForm, view.Pagelet):
    interface.implements(form.ISubForm)
    config.adapts(IVersionsBehavior, None, contenttype.IEditContentForm, name="edit.content.version")

    fields = form.Fields(IVersionsSchema).omit("proxy", "date", "version")
    fields["commit"].widgetFactory = "singlecheckbox"

    def isAvailable(self):
        return self.parentForm.mode == form.IInputMode

    def getContent(self):
Example #11
0
""" basic views """
from zope.component import getUtility, queryUtility
from zope.schema.interfaces import IVocabularyFactory

from pyramid import security
from pyramid.config import Configurator
from pyramid.exceptions import NotFound

from memphis import view, config, form
from memphis.preferences.root import Preferences
from memphis.preferences.interfaces import IPreferences, IPreference


# layout
config.action(
    view.registerLayout,
    '', IPreferences, parent='page',
    template=view.template("memphis.preferences:templates/layout.pt"))


# /preferences/* route
def getPreferences(request):
    userid = security.authenticated_userid(request)
    if userid is None:
        raise NotFound

    return Preferences.get(userid)


def registerRoute():
    cfg = Configurator.with_context(config.getContext())
    cfg.add_route(
Example #12
0
class ChoiceList(schema.List):
    interface.implements(interfaces.IChoiceList)

    def __init__(self, values=(), *args, **kw):
        kw['default'] = []
        kw['missing_value'] = []
        kw['value_type'] = schema.Choice(values=values)

        super(ChoiceList, self).__init__(*args, **kw)

    @property
    def values(self):
        return [term.value for term in self.value_type.vocabulary]

    @setproperty
    def values(self, values):
        self.value_type.vocabulary = SimpleVocabulary.fromValues(values)


config.action(
    config.registerAdapter, 
    CheckBoxWidget, (interfaces.IChoiceList, None))

config.action(
    config.registerAdapter, 
    CheckBoxWidget, (interfaces.IChoiceList, None), name='checkbox')

config.action(
    config.registerAdapter, 
    MultiSelectWidget, (interfaces.IChoiceList, None), name='multiselect')
Example #13
0
    template = view.template("memphis.users.browser:resetpasswordmail.pt")

    def update(self):
        super(ResetPasswordTemplate, self).update()

        request = self.request

        self.date = datetime.now()

        remoteAddr = request.get("REMOTE_ADDR", "")
        forwardedFor = request.get("HTTP_X_FORWARDED_FOR", None)

        self.from_ip = forwardedFor and "%s/%s" % (remoteAddr, forwardedFor) or remoteAddr

        self.url = "%s/resetpasswordform.html?passcode=%s" % (request.application_url, self.passcode)

        info = IUserInfo(self.context)

        self.to_address = mail.formataddr((info.fullname, info.login))


config.action(
    view.registerView,
    "resetpassword.html",
    view.INavigationRoot,
    klass=ResetPassword,
    template=view.template("memphis.users.browser:resetpassword.pt"),
)

config.action(view.registerView, "resetpasswordform.html", view.INavigationRoot, klass=ResetPasswordForm)
Example #14
0
""" content type desc implementation """
from zope import interface, event
from zope.component import getAdapters, queryUtility, getUtility
from zope.lifecycleevent import ObjectCreatedEvent

from memphis import storage, config

from interfaces import _
from interfaces import IContent, IContentContainer, IFactoryProvider
from interfaces import IContentType, IContentTypeSchema, ISchemaType


config.action(
    storage.registerSchema,
    'content.item', IContent, title = 'Content item')


class Content(storage.BehaviorBase):
    interface.implements(IContent)
    storage.behavior('content.item',
                     schema = IContent,
                     title = 'Content item',
                     description = 'Base behavior for content item.')


class ContentType(storage.BehaviorBase):
    interface.implements(IContentType)
    storage.behavior('memphis.contenttype', schema=IContentTypeSchema)

    __name__ = ''
    __parent__ = None
Example #15
0
    interface.implements(form.IDataConverter)

    def __init__(self, field, widget):
        self.field = field
        self.widget = widget

    def toWidgetValue(self, value):
        if value is self.field.missing_value:
            return RichTextData(u'', self.widget.field.default_format)
        return value

    def toFieldValue(self, value):
        """See interfaces.IDataConverter"""
        return value


config.action(
    view.registerPagelet,
    form.IWidgetDisplayView, RichTextWidget,
    template=view.template("memphis.schema.richtext:widget_display.pt"))

config.action(
    view.registerPagelet,
    form.IWidgetInputView, RichTextWidget,
    template=view.template("memphis.schema.richtext:widget_input.pt"))

config.action(
    view.registerPagelet,
    form.IWidgetHiddenView, RichTextWidget,
    template=view.template("memphis.schema.richtext:widget_hidden.pt"))
Example #16
0
            wschema._InterfaceClass__attrs[name] = fld

        return wschema

    @interface.implementer(IFieldFactory)
    def getFactory(self, *args):
        return self


# Boolean
Bool = FieldFactory(
    'boolean', schema.Bool, schema.interfaces.IBool,
    title = _("Boolean"),
    description = _("Boolean field (YES or NO)."))

config.action(
    config.registerAdapter, Bool.getFactory, (ISchema,), name=Bool.name)

config.action(
    config.registerAdapter, Bool.getFactory, (schema.interfaces.IBool,))


# Integer
Int = FieldFactory(
    'int', schema.Int, schema.interfaces.IInt,
    title = _("Integer"),
    description = _("Field containing an Integer Value."))

config.action(
    config.registerAdapter, Int.getFactory, (ISchema,), name=Int.name)

config.action(
Example #17
0
    def addCategory(self, category):
        if category.__name__ in self:
            raise KeyError(category.__name__)

        category.__parent__ = self

        self[category.__name__] = category

    def __repr__(self):
        return "ControlPanel"


def registerControlPanel():
    config.registerUtility(ControlPanel(), interfaces.IControlPanel, '')

config.action(registerControlPanel)


registerCategory(
    "default", interfaces.IDefaultCategory,
    _(u"Basic configuration"))

registerCategory(
    "system", interfaces.ISystemCategory,
    _(u"System configuration"),
    _(u"This area allows you to configure system."))

registerCategory(
    "ui", interfaces.IUICategory,
    _(u"User interface configuration"),
    _(u"This area allows you to configure portal look&feel."))
Example #18
0
        datasheet.password = passwordtool.encodePassword(data['password'])

        event.notify(ObjectCreatedEvent(item))
        return item

    def setPrincipal(self, principal):
        self.principal = principal

    @button.buttonAndHandler(_(u"Register"))
    def handle_register(self, action):
        request = self.request

        data, errors = self.extractData()
        if errors:
            view.addMessage(request, self.formErrorsMessage, 'error')
            return

        self.setPrincipal(self.create(data))

        user = getUtility(IAuthentication).getUserByLogin(data['login'])
        headers = security.remember(request, user.id)

        raise HTTPFound(
            location='%s/login-success.html'%request.application_url,
            headers = headers)


config.action(
    view.registerView,
    'join.html', view.INavigationRoot, klass=Registration)
Example #19
0
import pyramid.url
from webob.exc import HTTPFound
from zope.component import getMultiAdapter

from memphis import form, config, view
from memphis.contenttype.interfaces import \
    _, IContentTypeSchema, IContentTypesConfiglet

from memphis.contenttype.configlet import ContentTypeFactory


config.action(
    view.registerDefaultView,
    'index.html', IContentTypesConfiglet)


class ConfigletView(form.Form, view.View):
    view.pyramidView(
        'index.html', IContentTypesConfiglet,
        template = view.template('memphis.contenttype:templates/configlet.pt'))

    @form.buttonAndHandler(u'Remove', name='remove')
    def removeHandler(self, action):
        pass


class AddContentTypeSchema(form.Form, view.View):
    view.pyramidView('', ContentTypeFactory)

    fields = form.Fields(IContentTypeSchema).omit(
        'schemas', 'hiddenFields', 'behaviors', 'behaviorActions', 'widgets')
Example #20
0
    interface.implements(ISchemaFieldMapper)

    def __init__(self, type, *args, **kwargs):
        self.type = type
        self.args = args
        self.kwargs = kwargs

    def __call__(self, field):
        return (
            sqlalchemy.Column(
                field.__name__, self.type(*self.args, **self.kwargs), 
                default=copy.copy(field.default)),)


config.action(
    config.registerAdapter,
    FieldMapper(sqlalchemy.Unicode), (schema.interfaces.ITextLine,))

config.action(
    config.registerAdapter,
    FieldMapper(sqlalchemy.UnicodeText), (schema.interfaces.IText,))

config.action(
    config.registerAdapter,
    FieldMapper(sqlalchemy.Unicode), (schema.interfaces.IChoice,))

config.action(
    config.registerAdapter,
    FieldMapper(sqlalchemy.Integer), (schema.interfaces.IInt,))

config.action(
Example #21
0
            context = self.context
            name = request.subpath[0]

            factory = getattr(context, '__factories__', {}).get(name)
            if factory is None:
                factory = component.queryAdapter(
                    context, interfaces.IFactory, name=name)

            if factory is None:
                for pname, provider in \
                        getAdapters((context,), interfaces.IFactoryProvider):
                    factory = provider.get(name)
                    if factory is not None:
                        break

            if factory is not None:
                return view.renderView(
                    '', LocationProxy(factory, context, name), request)

        raise NotFound


class AddContentForm(AddContentForm, view.View):
    view.pyramidView('', interfaces.IFactory)


config.action(
    view.registerPagelet,
    form.IFormActionsView, interfaces.IAddContentForm,
    template = view.template('memphis.contenttype:templates/addformactions.pt'))
Example #22
0
from zope import interface
from zope.component import getSiteManager

from memphis import view, config
from memphis.contenttype.interfaces import IContent, IDCDescriptive


# layout
class LayoutView(object):

    data = None
    title = None

    def update(self):
        super(LayoutView, self).update()

        dc = IDCDescriptive(self.maincontext, None)
        if dc is not None:
            self.title = dc.title
            self.description = dc.description


config.action(
    view.registerLayout,
    '', IContent, parent='page', klass = LayoutView,
    template=view.template("memphis.contenttype:templates/layout.pt"))
Example #23
0
class LogoutForm(object):

    def update(self):
        request = self.request
        uid = security.authenticated_userid(request)

        if uid is not None:
            headers = security.forget(request)
            raise HTTPFound(
                headers = headers,
                location = '%s/logout.html'%request.application_url)


config.action(
    view.registerView,
    'login.html', view.INavigationRoot,
    klass = LoginForm,
    template=view.template("memphis.users.browser:login.pt"))

config.action(
    view.registerView,
    'login-success.html', view.INavigationRoot,
    klass = LoginSuccess,
    template=view.template("memphis.users:browser/login-success.pt"))

config.action(
    view.registerView,
    'logout.html', view.INavigationRoot,
    klass = LogoutForm,
    template=view.template("logout.pt"))
Example #24
0
            if configlets:
                configlets.sort()
                data.append(
                    (category.title,
                     {'title': category.title,
                      'description': category.description,
                      'configlets': [c for t, c in configlets]}))

        data.sort()
        self.data = [info for t, info in data]


config.action(
    view.registerLayout,
    '', IControlPanel, parent='page', skipParent=True,
    klass = LayoutView,
    template=view.template("memphis.controlpanel:templates/layout.pt"))


# /settings/* route
def registerRoute():
    cfg = Configurator.with_context(config.getContext())
    cfg.add_route(
        'memphis.controlpanel', 'settings/*traverse',
        factory=getControlPanel, use_global_views = True)

config.action(registerRoute)


class ControlPanelView(view.View):
Example #25
0
""" config registrations for plone.supermodel """
from memphis import config
from plone.supermodel import converters, fields
from plone.supermodel import exportimport, serializer, parser


config.action(config.registerAdapter, converters.DefaultFromUnicode)
config.action(config.registerAdapter, converters.DefaultToUnicode)

config.action(config.registerAdapter, converters.DateFromUnicode)
config.action(config.registerAdapter, converters.DatetimeFromUnicode)

config.action(config.registerAdapter, converters.InterfaceFieldFromUnicode)
config.action(config.registerAdapter, converters.InterfaceFieldToUnicode)

config.action(config.registerAdapter, converters.ObjectFromUnicode)


config.action(config.registerUtility,
              fields.BytesHandler, name="zope.schema.Bytes")

config.action(config.registerUtility,
              fields.ASCIIHandler, name="zope.schema.ASCII")

config.action(config.registerUtility,
              fields.BytesLineHandler, name="zope.schema.BytesLine")

config.action(config.registerUtility,
              fields.ASCIILineHandler, name="zope.schema.ASCIILine")

config.action(config.registerUtility,
Example #26
0
    label = _("Change password")
    fields = field.Fields(SChangePasswordForm, SPasswordForm)

    def update(self, *args, **kw):
        principal = self.context.user

        info = IUserInfo(principal)

        self.principal_login = info.login
        self.principal_title = info.fullname
        return super(PrincipalPassword, self).update()

    @button.buttonAndHandler(_(u"Change password"))
    def applyChanges(self, action):
        # service = IStatusMessage(self.request)

        data, errors = self.extractData()
        if errors:
            # service.add(self.formErrorsMessage, 'error')
            self.status = self.formErrorsMessage

        elif data["password"]:
            self.context.changePassword(data["password"])
            # service.add(_('Password has been changed for ${title}.',
            #              mapping = {'title': self.principal_title}))

            self.status = _("Password has been changed for ${title}.", mapping={"title": self.principal_title})


config.action(view.registerView, "index.html", IPasswordPreference, klass=PrincipalPassword)
Example #27
0
    def __bind__(self, principal):
        clone = super(PasswordPreference, self).__bind__(principal)

        clone.user = getUtility(IAuthentication).getUser(principal.id)
        clone.ptool = getUtility(IPasswordTool)
        #clone.changer = IPasswordChanger(clone.__principal__, None)
        return clone

    def checkPassword(self, password):
        return self.ptool.checkPassword(
            IUserInfo(self.user).password, password)

    def changePassword(self, password):
        IUserInfo(self.user).password = \
            passwordTool.encodePassword(password)

    def isAvailable(self):
        if self.user is None:
            return False
        else:
            return super(PasswordPreference, self).isAvailable()


config.action(
    preferences.registerPreference,
    'membership.password', IPasswordPreference,
    klass = PasswordPreference,
    title = _('Change password'),
    description = _('You can change your password here.'))
Example #28
0
import pyramid.url
from zope import interface
from zope.component import getSiteManager, queryUtility, getUtilitiesFor
from memphis import form, config, view, storage
from memphisttw import schema
from memphis.contenttype.interfaces import _
from memphis.contenttype.interfaces import ISchemaType, IBehaviorType
from memphis.contenttype.interfaces import IContent, IContentTypeSchema


config.action(
    view.registerDefaultView,
    'index.html', IContentTypeSchema)

config.action(
    view.registerActions,
    ('index.html', IContentTypeSchema, 
     _('View'), _('View content type'), 10),
    ('edit.html', IContentTypeSchema, 
     _('Edit'), _('Edit content type'), 20),
    ('schemas.html', IContentTypeSchema, 
     _('Schemas'), _('Content type schemas'), 30),
    ('behaviors.html', IContentTypeSchema, 
     _('Behaviors'), _('Content type behaviors'), 40),
    ('actions.html', IContentTypeSchema, 
     _('Actions'), _('Content type actions'), 50))


class ContentTypeView(view.View):
    view.pyramidView(
        'index.html', IContentTypeSchema,