class Menu(collections.abc.Iterable): grok.name('base menu') grok.context(Interface) grok.provides(IMenu) grok.baseclass() def __init__(self, context, request, view): self.context = context self.request = request self.view = view def available(self): return True def __iter__(self): entries = grokcore.component.sort_components(( e for name, e in getAdapters( (self, self.context, self.request, self.view), IMenuEntry))) for e in entries: e.__parent__ = self if zope.security.canAccess(e, 'available') and e.available(): yield e def update(self): self.entries = list(iter(self))
class YoutubeHosted(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IEmbeddableContentHostingService) grok.name('youtube') YOUTUBE_PARAMETERS = "&hl=en_US&fs=1&enablejsapi=1&showinfo=0&modestbranding=1&autoplay=1&playerapiid=ytplayerembed&origin=%(origin)s" # NOQA EMBED_TEMPLATE = '<iframe id="ytplayerembed" class="youtube-player" width="%(width)d" height="%(height)d" src="http://www.youtube.com/embed/%(id)s?%(params)s" style="border: 0">\n</iframe>' # NOQA CONTROLS_HEIGHT = 25.0 ASPECT_RATIO = 16.0 / 9.0 DEFAULT_WIDTH = 640 @no_call_on_empty def link_code(self, media_id): return ('<a href="http://www.youtube.com/watch?v=%s">' 'YouTube</a>') % media_id.strip() def embed_code(self, request, media_id, max_width=DEFAULT_WIDTH, max_height=None): width, height = calculate_embed_size(self.ASPECT_RATIO, self.CONTROLS_HEIGHT, max_width) origin = urlparse.urlparse(request.getApplicationURL()).netloc parameters = self.YOUTUBE_PARAMETERS % {'origin': origin} return self.EMBED_TEMPLATE % { 'id': media_id.strip(), 'width': width, 'height': height, 'params': parameters, }
class PortalMembership(grok.Adapter): grok.provides(IHomeFolderManager) grok.context(uvcsite.interfaces.IUVCSite) owner_roles = [u'uvc.User', u'uvc.Editor', u'uvc.MasterUser'] content_factory = HomeFolder @property def container(self): return self.context['members'] def create(self, uid): home = self.container[uid] = self.content_factory() principal_roles = IPrincipalRoleManager(home) for role in self.owner_roles: principal_roles.assignRoleToPrincipal(role, uid) return home def __delitem__(self, uid): del self.container[uid] def __getitem__(self, uid): if uid in self.container: return self.container[uid] raise KeyError('Unknown homefolder.') def get(self, uid, default=None): try: return self[uid] except KeyError: return default
class ToplevelAuthenticatorPlugin(grok.GlobalUtility): """toplevel authentication plugin for the PluggableAuthentication used at the application level, to manage meetings """ grok.provides(IAuthenticatorPlugin) grok.name('app_admin') def authenticateCredentials(self, credentials): if not isinstance(credentials, dict): return None if not ('login' in credentials and 'password' in credentials): return None # hardcoded admin account TODO Arghhh if credentials['login'] != 'admin' or credentials[ 'password'] != 'barcamp': return None # grant permission to the hardcoded admin IPrincipalPermissionManager(grok.getSite()).grantPermissionToPrincipal( 'zope.ManageContent', 'admin') IPrincipalPermissionManager(grok.getSite()).grantPermissionToPrincipal( 'afpy.barcamp.managemeetings', 'admin') IPrincipalPermissionManager(grok.getSite()).grantPermissionToPrincipal( 'afpy.barcamp.editseance', 'admin') IPrincipalPermissionManager(grok.getSite()).grantPermissionToPrincipal( 'afpy.barcamp.seances.list', 'admin') return PrincipalInfo(id='admin', title=_(u'admin'), description=_(u'admin')) def principalInfo(self, id): return PrincipalInfo(id='admin', title=_(u'admin'), description=_(u'admin'))
class DemosceneTV(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IEmbeddableContentHostingService) grok.name('demoscenetv') EMBED_TEMPLATE = """ <embed src="http://www.demoscene.tv/mediaplayer.swf?id=%(id_file)s_%(id_prod)s_%(id_app)s" width="%(width)s" height="%(height)s" allowfullscreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />""" # NOQA CONTROLS_HEIGHT = 20.0 ASPECT_RATIO = 16.0 / 9.0 DEFAULT_WIDTH = 512 def _get_vars(self, media_id): return dict( map(lambda x: (x[0], x[1][0]), cgi.parse_qs(media_id).items())) @no_call_on_empty def link_code(self, media_id): media_vars = self._get_vars(media_id) return ('<a href="http://demoscene.tv/prod.php?id_prod=%s">' 'DTV</a>') % media_vars['id_prod'] def embed_code(self, request, media_id, max_width=DEFAULT_WIDTH, max_height=None): media_vars = self._get_vars(media_id) width = int(media_vars['width']) height = int(media_vars['height']) aspect = float(width) / height new_width, new_height = calculate_embed_size(aspect, 0, max_width) media_vars['width'] = new_width media_vars['height'] = new_height return self.EMBED_TEMPLATE % media_vars
class CMSProfile(grok.Adapter): grok.context(CMS) grok.provides(asm.cms.interfaces.IProfileSelection) def set_name(self, value): value = zope.component.getUtility(asm.cms.interfaces.IProfile, name=value) sm = self.context.getSiteManager() bases = (x for x in sm.__bases__ if not asm.cms.interfaces.IProfile.providedBy(x)) sm.__bases__ = (value, ) + tuple(bases) def get_name(self): sm = self.context.getSiteManager() for profile in sm.__bases__: if not asm.cms.interfaces.IProfile.providedBy(profile): continue break else: return None for name, reg_profile in zope.component.getUtilitiesFor( asm.cms.interfaces.IProfile): if reg_profile is profile: return name name = property(fget=get_name, fset=set_name)
class Home3(grok.MultiAdapter): grok.adapts(Cave, Fireplace) grok.provides(IHome) grok.name('home3') def __init__(self, cave, fireplace): self.cave = cave self.fireplace = fireplace
class Plugin(grok.GlobalUtility): grok.baseclass() grok.provides(IPlugin) title = None description = u"" status = Status(state=flags.States.NOT_INSTALLED) actions = None
class ViewLayout(mars.template.LayoutFactory): grok.template('templates/complex.pt') # required grok.context(MammothView) # define the adapted view grok.name('complex') # view must use named adapter lookup grok.provides(IMyPageTemplate) # view must use this interface to lookup mars.template.macro('body') # define the macro to use mars.template.content_type('text/html') # define the contentType grok.layer(DirLayer) # registered on this layer.
class MySessionCredentialsPlugin(grok.GlobalUtility, SessionCredentialsPlugin): """credentials plugin for the PluggableAuthentication """ grok.provides(ICredentialsPlugin) grok.name('credentials') loginpagename = 'login' loginfield = 'form.login' passwordfield = 'form.password'
class SingleAdapter(grok.Adapter): grok.context(Calculator) grok.adapts(Calculator) # generally allowed, but not in this case, because there's already grok.context grok.implements(ISomething) # if this is not specified, app breaks grok.provides(ISomething) # if adapter implements more than one interface grok.name('') # this is actually the default def something(self): """self.context is automatically provided""" return self.context.foo
class RetailPreferredLanguages(grok.Adapter): grok.context(zope.publisher.interfaces.browser.IBrowserRequest) grok.provides(zope.i18n.interfaces.IUserPreferredLanguages) def __init__(self, request): self.request = request def getPreferredLanguages(self): return get_language_preferences(self.request)
class UVCSiteTalesAdapter(grok.Adapter, ZopeTalesAPI): """extend the zope implementation by providing additional dublin core """ grok.provides(IPathAdapter) grok.context(IRequest) grok.name('uvcsite') @property def homefolder(self): hf_url = uvcsite.IGetHomeFolderUrl(self.context).getURL() return hf_url
class DownloadURLService(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IContentHostingService) grok.name('download') DEFAULT_LINK_TEXT = u"Download" @no_call_on_empty def link_code(self, media_id_data): link_address, link_text = get_media_info(media_id_data, self.DEFAULT_LINK_TEXT) return u'<a href="%s">%s</a>' % (link_address, link_text)
class PouetNet(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IContentHostingService) grok.name('pouet') POUET_LINK = ( '<a href="http://www.pouet.net/prod.php?which=%s">pouet.net</a>') @no_call_on_empty def link_code(self, media_id): return self.POUET_LINK % media_id.strip()
class PluginConfigurationNamespace(grok.MultiAdapter): grok.name('plugins') grok.provides(ITraversable) grok.adapts(Interface, Interface) def __init__(self, context, request): self.context = context self.request = request def traverse(self, name, ignore): return get_plugin_configuration(request=self.request, name=name)
class LDAPPrincipalPermissionMap(grok.Adapter): grok.context(LDAPApp) grok.provides(zope.securitypolicy.interfaces.IPrincipalPermissionMap) def getPrincipalsForPermission(permission_id): return None def getPermissionsForPrincipal(principal_id): return None def getPrincipalsAndPermissions(): return None def getSetting(self, permission_id, principal_id, default=Unset): # bootstrapper-y: an unconfigured application must allow access if not self.context.ldap_view_group or not self.context.ldap_admin_group: return Allow # Allow access if the LDAP server is down try: view_group_names = self.context['groups'][ self.context.ldap_view_group].uids admin_group_names = self.context['groups'][ self.context.ldap_admin_group].uids sysadmin_group_names = self.context['groups'][ self.context.ldap_sysadmin_group].uids except ldapadapter.interfaces.ServerDown: return Allow name = principal_id.split('.')[-1] # View permission if permission_id == u'gum.View': try: if name in self.context['groups'][ self.context.ldap_view_group].uids: return Allow except ldapadapter.interfaces.NoSuchObject, ldapadapter.interfaces.InvalidCredentials: return Allow # Add/Edit/EditGroup permissions if permission_id in [ u'gum.Add', u'gum.Edit', u'gum.EditGroup', ]: try: if name in self.context['groups'][ self.context.ldap_admin_group].uids: return Allow except ldapadapter.interfaces.NoSuchObject, ldapadapter.interfaces.InvalidCredentials: return Allow
class plain(grok.MultiAdapter): grok.name('text/plain') grok.provides(zope.interface.Interface) grok.adapts(IPlugin, IDefaultBrowserLayer, Result) def __init__(self, plugin, request, result): self.plugin = plugin self.request = request self.result = result def __call__(self): return u'<pre>%s</pre>' % self.result.value
class BannerAnnotation(grok.Annotation): grok.implements(asm.banner.interfaces.IBanner) grok.provides(asm.banner.interfaces.IBanner) grok.context(asm.cms.interfaces.IEdition) area = None def copyFrom(self, other): self.area = other.area def __eq__(self, other): return self.area == other.area
class ApplicationRoot(grok.GlobalUtility): grok.provides(site.interfaces.IRootFolder) grok.baseclass() __name__ = None __parent__ = None def getSiteManager(self): gsm = component.getGlobalSiteManager() return gsm def setSiteManager(self, sm): pass
class JSON(grok.MultiAdapter): grok.name('application/json') grok.provides(zope.interface.Interface) grok.adapts(IPlugin, IDefaultBrowserLayer, Result) def __init__(self, plugin, request, result): self.plugin = plugin self.request = request self.result = result def __call__(self): return u'<pre>%s</pre>' % json.dumps( self.result.value, indent=4, sort_keys=True)
class SceneOrgDownload(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IContentHostingService) grok.name('sceneorg') DEFAULT_LINK_TEXT = u"scene.org" @no_call_on_empty def link_code(self, media_id_data): media_id, link_text = get_media_info(media_id_data, self.DEFAULT_LINK_TEXT) return (u'<a href="http://www.scene.org/file.php?file=%s">%s</a>' % (urllib.quote_plus(media_id.strip()), link_text))
class Service(grok.MultiAdapter): grok.baseclass() grok.adapts(IApplication, IHTTPRequest) grok.implements(IPublishTraverse, IService) grok.provides(IService) layer = None def __init__(self, context, request): self.context = context self.request = request def publishTraverse(self, request, name): raise NotImplementedError("implement me")
class ENMSHomeFolderTraverser(grok.MultiAdapter): grok.context(IHomeFolder) grok.name('enms') grok.provides(ITraversable) grok.adapts(IHomeFolder, Interface) def __init__(self, context, request): self.context = context self.request = request def traverse(self, name, ignore): lister = ENMSLister(self.context, 'enms') if not name: return lister return lister.get(name)
class TeaserAnnotation(grok.Annotation): grok.implements(INewsFields) grok.provides(INewsFields) grok.context(asm.cms.interfaces.IEdition) teaser = u'' def copyFrom(self, other): self.teaser = other.teaser self.image = other.image def __eq__(self, other): return (self.teaser == other.teaser, self.image == other.image) def set_image(self, value): if value is None: return edition = self.__parent__ if not 'teaser-image' in edition.page: image = asm.cms.page.Page('asset') edition.page['teaser-image'] = image image = edition.page['teaser-image'] image_edition = image.getEdition(edition.parameters, create=True) image_edition.content = value def _get_image_asset(self): edition = self.__parent__ if not 'teaser-image' in edition.page: return None image = edition.page['teaser-image'] image_edition = image.getEdition(self.__parent__.parameters, create=True) return image_edition def get_image(self): asset = self._get_image_asset() if asset is None: return None return asset.content image = property(fget=get_image, fset=set_image) @property def content_type(self): asset = self._get_image_asset() if asset is None: return None return asset.content_type
class DataUriAnnotation(grok.Annotation): grok.implements(asm.cms.interfaces.IDataUri) grok.provides(asm.cms.interfaces.IDataUri) grok.context(asm.cms.interfaces.IAsset) _datauri = None @property def datauri(self): if self._datauri is None: return None return self._datauri.open().read() def copyFrom(self, other): self._datauri = other._datauri def __eq__(self, other): return (self._datauri == other._datauri)
class Vimeo(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IEmbeddableContentHostingService) grok.name('vimeo') EMBED_TEMPLATE = """<iframe src="http://player.vimeo.com/video/%(id)s?autoplay=1" width="%(width)d" height="%(height)d" frameborder="0"></iframe>""" # NOQA CONTROLS_HEIGHT = 0.0 DEFAULT_ASPECT_RATIO = 16.0 / 9.0 DEFAULT_WIDTH = 400 def _get_aspect_ratio(self, aspect_str): width, height = aspect_str.strip().split(":") return float(width) / float(height) def _get_media_data(self, media_id_data): if "," in media_id_data: media_id, aspect_ratio_str = media_id_data.split(",") aspect_ratio = self._get_aspect_ratio(aspect_ratio_str) else: media_id = media_id_data aspect_ratio = self.DEFAULT_ASPECT_RATIO return media_id, aspect_ratio @no_call_on_empty def link_code(self, media_id_data): media_id, _ = self._get_media_data(media_id_data) return "<a href='http://vimeo.com/%s'>Vimeo</a>" % media_id.strip() def embed_code(self, request, media_id_data, max_width=DEFAULT_WIDTH, max_height=None): media_id, aspect_ratio = self._get_media_data(media_id_data) width, height = calculate_embed_size(aspect_ratio, self.CONTROLS_HEIGHT, max_width) return self.EMBED_TEMPLATE % { 'id': media_id.strip(), 'width': width, 'height': height }
class ServicesNamespace(grok.MultiAdapter): grok.name('services') grok.provides(ITraversable) grok.adapts(uvcsite.IUVCSite, IHTTPRequest) def __init__(self, context, request): self.context = context self.request = request def traverse(self, name, ignore): if not name: raise NotImplementedError('Please specify a service.') service = getMultiAdapter((self.context, self.request), IService, name=name) if service.layer is not None: applySkin(self.request, service.layer) return LocationProxy(service, self.context, "++services++%s" % name)
class FolderIndexForContent(grok.Adapter): """Adapt possible folder to folder. """ grok.context(interfaces.IContent) grok.provides(interfaces.IIndexFolder) def __init__(self, context): self.context = context def setFolderIndex(self, item=None): # remove any current index for page in self.context.values(): if interfaces.IFolderIndex.providedBy(page): zope.interface.directlyProvides(page, zope.interface.directlyProvidedBy(page) - \ interfaces.IFolderIndex) # set the index page if item is not None: zope.interface.directlyProvides( item, interfaces.IFolderIndex, zope.interface.directlyProvidedBy(item))
class Image(grok.GlobalUtility): grok.provides(asm.mediagallery.interfaces.IEmbeddableContentHostingService) grok.name('image') EMBED_TEMPLATE = """<img src="%(id)s" alt="%(image_text)s" />""" DEFAULT_TEXT = "Gallery image." @no_call_on_empty def link_code(self, media_id): return None def embed_code(self, request, media_id_data, max_width=None, max_height=None): media_id, image_text = get_media_info(media_id_data, self.DEFAULT_TEXT) return self.EMBED_TEMPLATE % { 'id': media_id.strip(), 'image_text': cgi.escape(image_text.strip(), quote=True) }