class FakeXMLReferenceUpdater(grok.Adapter): grok.context(FakeEntry) grok.implements(zeit.cms.content.interfaces.IXMLReferenceUpdater) def update(self, node, suppress_errors=False): pass
class CSSInjector(grok.Adapter): grok.context(zeit.content.modules.interfaces.IRawText) grok.implements(ICSS) @cachedproperty def vivi_css(self): import cssutils embed = self.context.text_reference if not zeit.content.text.interfaces.IEmbed.providedBy(embed): return None if not embed.vivi_css: return None module = self.context.__name__ css = cssutils.parseString(embed.vivi_css) for rule in css: if not isinstance(rule, cssutils.css.CSSStyleRule): continue selectors = [x.selectorText for x in rule.selectorList] while rule.selectorList: del rule.selectorList[0] for selector in selectors: # zeit.content.article rule.selectorList.append(u'#%s %s' % (module, selector)) # zeit.content.cp rule.selectorList.append(u'.%s %s' % (module, selector)) return u'<style>\n%s\n</style>' % css.cssText
class PreDeployHookOpenVZ(GlobalUtility): implements(IPreDeployHook) name('pre-deploy-openvz') @defer.inlineCallbacks def execute(self, context, *args, **kw): @db.ro_transact def check_backend(context): return context.__parent__.backend != 'openvz' if (yield check_backend(context)): return cmd = args[0] vm_parameters = args[1] ctid = yield get_current_ctid() if ctid is not None: log.msg('Deploying %s to %s: hinting CTID (%s)' % (context, context.__parent__, ctid), system='deploy-hook-openvz') vm_parameters.update({'ctid': ctid + 1}) else: self._action_log( cmd, 'Information about current global CTID is unavailable yet, ' 'will let it use HN-local value instead', system='deploy-hook-openvz')
class Converter(grok.Adapter): """This adapter works a bit differently: It adapts its context to a separately _configured_ `interface`, and declines if that is not possible; but all adapters are _registered_ for the same basic ICMSContent interface. This way we can retrieve data stored in various DAVPropertyAdapters. """ grok.baseclass() grok.context(zeit.cms.interfaces.ICMSContent) grok.implements(zeit.retresco.interfaces.ITMSRepresentation) interface = NotImplemented # Subclasses need to register as named adapters to work with # `TMSRepresentation`, e.g. by specifying `grok.name(interface.__name__)` def __new__(cls, context): adapted = cls.interface(context, None) if adapted is None: return None instance = super(Converter, cls).__new__(cls, None) instance.context = adapted instance.content = context return instance def __init__(self, context): pass # self.context has been set by __new__() already. def __call__(self): return {'payload': {}}
class TMSRepresentation(grok.Adapter): grok.context(zeit.cms.interfaces.ICMSContent) grok.implements(zeit.retresco.interfaces.ITMSRepresentation) def __call__(self): result = {} for name, converter in sorted( zope.component.getAdapters( (self.context, ), zeit.retresco.interfaces.ITMSRepresentation)): if not name: # The unnamed adapter is the one which runs all the named # adapters, i.e. this one. continue merge_and_skip_empty(converter(), result) if not self._validate(result): return None return result REQUIRED_FIELDS = ( 'doc_id', 'title', 'teaser', # For completeness, but these cannot be empty with our implementation. 'doc_type', 'url', 'date', ) def _validate(self, data): return all([data.get(x) for x in self.REQUIRED_FIELDS])
class EventDescription(EventDescriptionBase, grok.Adapter): """Adapter from IEvent to IEventDescription needed by renderer.""" grok.context(icemac.ab.calendar.interfaces.IBaseEvent) grok.implements(IEventDescription) def __init__(self, context): super(EventDescription, self).__init__(context) self.prio = 0 self.whole_day = context.whole_day_event self.special_event = None calendar = icemac.ab.calendar.interfaces.ICalendar(context) # Without the following line we get a ForbidenError for # `__getitem__` when accessing the annotations where # `ICalendarDisplaySettings` are stored. As only authorized users # are able to access this adapter, this is no security hole. unsave_calendar = zope.security.proxy.getObject(calendar) # Making a copy so changing is not possible: self._info_fields = copy.copy( icemac.ab.calendar.interfaces.ICalendarDisplaySettings( unsave_calendar).event_additional_fields) @hyphenated def getText(self, lang=None): return self._text @hyphenated def getInfo(self, lang=None): return self._get_info_from_fields(self._info_fields)
class PasswdCmd(Cmd): implements(ICmdArgumentsSyntax) command('passwd') def arguments(self): parser = VirtualConsoleArgumentParser() parser.add_argument('password') parser.add_argument('-u', help='User name', required=False, default=None) parser.add_argument('-g', help="group(s): comma separated list of " "groups the user belongs to", required=False, default=None) return parser @require_admins_or_same_user def execute(self, args): try: update_passwd(args.u or self.user.id, password=args.password, group=args.g) except UserManagementError as e: self.write('%s\n' % str(e))
class OncViewFactory(Adapter): implements(IHttpRestSubViewFactory) context(OncPlugin) def resolve(self, path, request): if request.method.lower() != 'get': raise MethodNotAllowed('Method not allowed', ('GET', )) if path == []: path = ['index.html'] relative_path = os.path.join(*(['../..'] + path)) filename = pkg_resources.resource_filename(__name__, relative_path) if os.path.join(*path) == 'config.js': return OncConfigView(filename) resource = File(filename) if not resource.exists(): return # make sure fonts are servers with a correct mime type resource.contentTypes['.woff'] = 'application/x-font-woff' return OncView(resource)
class Reference(zeit.cms.content.reference.Reference): grok.implements(zeit.content.author.interfaces.IAuthorReference) grok.provides(zeit.content.author.interfaces.IAuthorReference) grok.name('author') location = zeit.cms.content.property.ObjectPathProperty('.location')
class BioReference(zeit.cms.content.reference.Reference): grok.implements(zeit.content.author.interfaces.IAuthorBioReference) grok.provides(zeit.content.author.interfaces.IAuthorBioReference) grok.name('authorbio') biography = zeit.cms.content.property.ObjectPathProperty('.biography')
class Home(Container): implements(IHome) __contains__ = UserProfile __name__ = 'home' def _new_id(self): raise TypeError('This container does not support generated IDs')
class Home(grok.MultiAdapter): grok.adapts(Cave, Fireplace) grok.implements(IHome) def __init__(self, cave, fireplace): self.cave = cave self.fireplace = fireplace
class StopAllVmsCmd(Cmd): implements(ICmdArgumentsSyntax) command('stopvms') def arguments(self): parser = VirtualConsoleArgumentParser() parser.add_argument('-u', help="Stop all VMs belonging to the user") return parser @db.ro_transact def get_computes(self, args): computes = db.get_root()['oms_root']['computes'] user_vms = [] for c in map(follow_symlinks, computes.listcontent()): if not IVirtualCompute.providedBy(c): continue if c.__owner__ == args.u: user_vms.append(c) return user_vms @require_admins_only @defer.inlineCallbacks def execute(self, args): log.msg('Stopping all VMs of "%s"...' % args.u, system='stopallvms') computes = yield self.get_computes(args) for c in computes: self.write("Stopping %s...\n" % c) yield ShutdownComputeAction(c).execute(DetachedProtocol(), object()) self.write("Stopping done. %s VMs stopped\n" % (len(computes))) log.msg('Stopping done. %s VMs of "%s" stopped' % (len(computes), args.u), system='stopallvms')
class LocalSublocations(grok.Adapter): grok.context(zeit.content.image.interfaces.ILocalImageGroup) grok.implements(zope.location.interfaces.ISublocations) def sublocations(self): return []
class Dependencies(grok.Adapter): """Adapter to find the publication dependencies of an object.""" grok.context(zeit.cms.interfaces.ICMSContent) grok.implements(zeit.workflow.interfaces.IPublicationDependencies) def get_dependencies(self): dependencies = set() for adapter in self._find_adapters(): dependencies.update(adapter.get_dependencies()) return sorted(dependencies, key=lambda x: x.uniqueId) def get_retract_dependencies(self): dependencies = set() for adapter in self._find_adapters(): if adapter.retract_dependencies: dependencies.update(adapter.get_dependencies()) return sorted(dependencies, key=lambda x: x.uniqueId) def _find_adapters(self): for name, adapter in zope.component.getAdapters( (self.context, ), zeit.workflow.interfaces.IPublicationDependencies): if not name: # This is actually this adapter continue yield adapter
class CollectionTextLine(grok.MultiAdapter): grok.adapts( zope.schema.interfaces.ICollection, zope.schema.interfaces.ITextLine, zeit.retresco.interfaces.IElasticDAVProperties) grok.implements(zeit.cms.content.interfaces.IDAVPropertyConverter) # Taken from zeit.cms.content.dav.CollectionTextLineProperty def __init__(self, context, value_type, content): self.context = context self.value_type = value_type self.content = content self._type = context._type if isinstance(self._type, tuple): # XXX this is way hacky self._type = self._type[0] def fromProperty(self, value): typ = zope.component.getMultiAdapter( (self.value_type, self.content), zeit.cms.content.interfaces.IDAVPropertyConverter) return self._type([typ.fromProperty(x) for x in value]) def toProperty(self, value): typ = zope.component.getMultiAdapter( (self.value_type, self.content), zeit.cms.content.interfaces.IDAVPropertyConverter) return [typ.toProperty(x) for x in value]
class AddUserCmd(Cmd): implements(ICmdArgumentsSyntax) command('adduser') def arguments(self): parser = VirtualConsoleArgumentParser() parser.add_argument('user') parser.add_argument('password') parser.add_argument('-g', help="group(s): comma separated list of " "groups the user belongs to", required=False, default=None) parser.add_argument('-i', '--uid', help="user ID", required=False, default=0) return parser @require_admins_only def execute(self, args): try: add_user(args.user, args.password, group=args.g, uid=args.uid) except UserManagementError as e: self.write('%s\n' % str(e))
class RootContainerInjector(Subscription): implements(IContainerInjector) context(OmsRoot) def inject(self): return { 'search': SearchContainer(), }
class CaveHomeFactory(object): grok.implements(IHome) def __init__(self, id): self.id = id def __call__(self, context): return Home(self.id)
class Int(grok.Adapter): grok.context(IInt) grok.implements(IJSONGenerator) def output(self, value): return value def input(self, item): return item
class SetAclCmd(Cmd, SetAclMixin): implements(ICmdArgumentsSyntax) command('setfacl') def arguments(self): parser = VirtualConsoleArgumentParser() parser.add_argument('paths', nargs='+') parser.add_argument('-R', '--recursive', action='store_true', help='Apply permissions recursively') group = parser.add_mutually_exclusive_group(required=True) group.add_argument( '-i', '--inherit', action='store_true', help='Set object to inherit permissions from its parent(s)', default=False) group.add_argument( '-m', action='append', help="add an Allow ace: {u:[user]:permspec|g:[group]:permspec}") group.add_argument( '-d', action='append', help="add an Deny ace: {u:[user]:permspec|g:[group]:permspec}") group.add_argument( '-x', action='append', help="remove an ace: {u:[user]:permspec|g:[group]:permspec}") return parser @db.transact def execute(self, args): try: for path in args.paths: obj = self.traverse(path) if obj.__transient__: self.write( "Transient object %s always inherits permissions from its parent\n" % path) log.warning( "Transient object %s always inherits permissions from its parent", path) continue with self.protocol.interaction: self.set_acl(obj, args.inherit, args.m, args.d, args.x, recursive=args.recursive) except NoSuchPermission as e: self.write("No such permission '%s'\n" % (e.message)) transaction.abort()
class OmsRootLocation(Adapter): implements(ILocation) context(opennode.oms.model.model.root.OmsRoot) def get_path(self): return [''] def get_url(self): return '/'
class Home3(grok.MultiAdapter): grok.adapts(Cave, Fireplace) grok.implements(IHome, IFireplace) grok.provides(IHome) grok.name('home3') def __init__(self, cave, fireplace): self.cave = cave self.fireplace = fireplace
class SetOrMkCmdDynamicArguments(Adapter): """Dynamically creates the key=value arguments for the `set` and `mk` commands depending on the object or type being edited or created. """ implements(IContextualCmdArgumentsSyntax) baseclass() @db.transact def arguments(self, parser, args, rest): parser.declare_argument('keywords', {}) model_or_obj, args_required = ((creatable_models.get(args.type), True) if self.context.name == 'mk' else (self.context.traverse(args.path), False)) schema_fields = get_schema_fields(model_or_obj, marker=getattr( self.context.current_obj, '__contains__', None)) for name, field, schema in schema_fields: if field.readonly: continue field = field.bind(model_or_obj) choices = ([i.value.encode('utf-8') for i in field.vocabulary] if isinstance(field, zope.schema.Choice) else None) type = (int if isinstance(field, zope.schema.Int) else None) kwargs = {} if isinstance(field, Path): kwargs['is_path'] = True base_path = '.' if field.relative_to == Path.PARENT: if self.context.name == 'mk': base_path = self.context.protocol._cwd() else: base_path = canonical_path(model_or_obj.__parent__) kwargs['base_path'] = os.path.join(base_path, field.base_path) parser.add_argument('=%s' % name, required=(args_required and field.required), type=type, action=GroupDictAction, group='keywords', help=field.title.encode('utf8'), choices=choices, **kwargs) return parser
class UserStatsLogger(GlobalUtility): implements(IUserStatisticsLogger) name('user-stats-logger') def __init__(self): self.slog = logging.getLogger("%s.userstats" % __name__) def log(self, user, stats_data): data = {'username': user, 'stats': stats_data} self.slog.info('%s' % data, extra=data)
class DependencyBase(grok.Adapter): grok.implements(zeit.workflow.interfaces.IPublicationDependencies) grok.name('must be set in subclass') grok.baseclass() retract_dependencies = False def get_dependencies(self): return ()
class Sleep(grok.MultiSubscription): grok.implements(IActivity) grok.adapts(Office, Mammoth) def __init__(self, where, who): self.where = where self.who = who def do(self): print '%s is sleeping at %s.' % (self.who.name, self.where.name)
class DefaultUserPreferredLanguages(component.Adapter): """ A very simple adapter that return the user preferred language with the browser information (Accept-Language). """ component.context(IRequest) component.implements(IUserPreferredLanguages) def getPreferredLanguages(self): return self.context.accept_language
class CustomInfoPlugin(PluginInfo): implements(IPlugin, ICustomInfoPlugin) def __init__(self, *args): super(CustomInfoPlugin, self).__init__(*args) self.custom_attribute = 'test' def initialize(self): print "[CustomInfoPlugin] initializing plugin"
class FolderPrincipalRoleMap(grok.Adapter): """Roles for a principal on a folder depending on their keywords.""" grok.context(icemac.ab.document.interfaces.IFolder) grok.implements(zope.securitypolicy.interfaces.IPrincipalRoleMap) def getPrincipalsForRole(self, role_id): """Get the principals that have been granted a role.""" raise NotImplementedError() def getRolesForPrincipal(self, principal_id): """Get the roles granted to a principal.""" principal_folder = zope.component.getUtility( zope.pluggableauth.interfaces.IAuthenticatorPlugin, name=u'icemac.addressbook.principals') try: principal = principal_folder[principal_id] except KeyError: keywords = set() else: keywords = set(principal.person.keywords) roles = [] if keywords.intersection(self.context.read_only): setting = zope.securitypolicy.interfaces.Allow else: subfolder_keywords = itertools.chain( *self._keywords_of_subfolders(self.context)) if keywords.intersection(subfolder_keywords): setting = zope.securitypolicy.interfaces.Allow else: setting = zope.securitypolicy.interfaces.Deny roles.append((u'icemac.ab.document.Visitor', setting)) if keywords.intersection(self.context.read_write): roles.append((u'icemac.ab.document.Editor', zope.securitypolicy.interfaces.Allow)) return roles def _keywords_of_subfolders(self, parent): """Generator containing sets of keywords of the subfolders.""" for folder in icemac.addressbook.utils.iter_by_interface( parent, icemac.ab.document.interfaces.IFolder): yield set(folder.read_only) # XXX `yield from` would be nice! for keywords in self._keywords_of_subfolders(folder): yield keywords def getSetting(self, role_id, principal_id, default=None): """Return the setting for this principal, role combination.""" raise NotImplementedError() def getPrincipalsAndRoles(self): """Get all settings.""" raise NotImplementedError()