info = loadJsonFile("%s/applications/wizard_info/%s.json" % (self.path, self.tipo_app)).result wfInfo = iDoc.wfInfo() if doc.portal_type == 'PlominoForm': result["state"] = info["initial_state"] result["actions"] = info["initial_actions"] else: result["state"] = wfInfo["wf_state"] result["actions"] = wfInfo["wf_actions"] for v in info["states"]: cls_list = list() if not iDoc.isActionSupported(v["action"]): cls_list.append('link-disabled') action = "" else: action = v["action"] if result["state"] == v["state"]: cls_list.append("active") i = { "label": v["label"], "class": " ".join(cls_list), "action": action } result["forms"].append(i) return result InitializeClass(IolApp)
creds['login'] = name creds['password'] = password creds['remote_host'] = request.get('REMOTE_HOST', '') try: creds['remote_address'] = request.getClientAddr() except AttributeError: creds['remote_address'] = request.get('REMOTE_ADDR', '') return creds classImplements(DumbHTTPExtractor, ILoginPasswordHostExtractionPlugin) InitializeClass(DumbHTTPExtractor) class EmergencyUserAuthenticator(Implicit): security = ClassSecurityInfo() security.declarePrivate('authenticateCredentials') def authenticateCredentials(self, credentials): """ Check credentials against the emergency user. """ if isinstance(credentials, dict): eu = emergency_user eu_name = eu.getUserName()
def unindexObject(self, object): """Remove from catalog. """ url = self.__url(object) self.uncatalog_object(url) security.declarePrivate('reindexObject') def reindexObject(self, object, idxs=[], update_metadata=1, uid=None): """Update catalog after object data has changed. The optional idxs argument is a list of specific indexes to update (all of them by default). The update_metadata flag controls whether the object's metadata record is updated as well. If a non-None uid is passed, it will be used as the catalog uid for the object instead of its physical path. """ if uid is None: uid = self.__url(object) if idxs != []: # Filter out invalid indexes. valid_indexes = self._catalog.indexes.keys() idxs = [i for i in idxs if i in valid_indexes] self.catalog_object(object, uid, idxs, update_metadata) InitializeClass(CatalogTool)
else: self.default_expr = None g = Guard() if g.changeFromProperties(props or REQUEST): self.info_guard = g else: self.info_guard = None self.for_catalog = bool(for_catalog) self.for_status = bool(for_status) self.update_always = bool(update_always) if REQUEST is not None: return self.manage_properties(REQUEST, 'Properties changed.') InitializeClass(VariableDefinition) class Variables(ContainerTab): """A container for variable definitions""" meta_type = 'Workflow Variables' all_meta_types = ({ 'name': VariableDefinition.meta_type, 'action': 'addVariable', 'permission': ManagePortal, }, ) _manage_variables = DTMLFile('variables', _dtmldir)
begin = DateTime('%d/%02d/%02d 00:00:00' % (year, month, day)) end = DateTime('%d/%02d/%02d 23:59:59' % (year, month, day)) return (begin, end) security.declarePublic('getNextEvent') def getNextEvent(self, start_date=None): """ Get the next event that starts after start_date start_date is expected to be a DateTime instance """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool if start_date is None: start_date = DateTime() ctool = getToolByName(self, 'portal_catalog') query = ctool( portal_type=self.getCalendarTypes(), review_state=self.getCalendarStates(), start={'query': start_date, 'range': 'min'}, sort_on='start') results = unique_results(query) if results: results.sort(sort_by_date) return results[0] InitializeClass(CalendarTool)
if not bool(previewable) is self.is_previewable(): self.set_previewable(bool(previewable)) msg += "Previewable setting changed. " if not bool(usable) is self.is_usable(): self.set_usable(bool(usable)) msg += "Usability setting changed. " if layout_id and layout_id != self._layout_id: self._layout_id = layout_id msg += "Layout object id changed. " return self.editSQLSource(manage_tabs_message=msg) InitializeClass(SQLSource) manage_addSQLSourceForm = PageTemplateFile( "www/sqlSourceAdd", globals(), __name__='manage_addSQLSourceForm') def manage_addSQLSource(context, id, title=None, REQUEST=None): """Add a SQLSource object """ source = SQLSource(id) title = unicode(title, source.management_page_charset) source.title = title context._setObject(id, source) source = context._getOb(id) source._set_statement('SELECT <dtml-var columns> FROM <dtml-var table>') # parameters form
from Products.validation.service import Service from Acquisition import Implicit from App.class_init import InitializeClass from AccessControl import ClassSecurityInfo from AccessControl import ModuleSecurityInfo # make validator service public security = ModuleSecurityInfo('Products.validation.config') security.declarePublic('validation') class ZService(Service, Implicit): """Service running in a zope site - exposes some methods""" security = ClassSecurityInfo() security.declarePublic('validate') security.declarePublic('__call__') security.declarePublic('validatorFor') InitializeClass(ZService)
return True def retrieveSubstitute(self, history_id, selector, default=None): """Retrives the next older version If there isn't a next older one returns the next newer one. """ selector = int(selector) storage = getToolByName(self, 'portal_historiesstorage') savedSelector = selector while selector: selector -= 1 data = storage.retrieve(history_id, selector, substitute=False) if data.isValid(): return data selector = savedSelector while True: selector += 1 try: data = storage.retrieve(history_id, selector, substitute=False) except storage.StorageRetrieveError: break if data.isValid(): return data return default InitializeClass(KeepLastNVersionsTool)
m_to = message_obj['To'] m_from = message_obj['From'] host = getToolByName(self, 'MailHost') host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True) return self.mail_password_response(self, self.REQUEST) RegistrationTool.__doc__ = BaseTool.__doc__ InitializeClass(RegistrationTool) _TESTS = ( (re.compile("^[0-9a-zA-Z\.\-\_\+\']+\@[0-9a-zA-Z\.\-]+$"), True, "Failed a"), (re.compile("^[^0-9a-zA-Z]|[^0-9a-zA-Z]$"), False, "Failed b"), (re.compile("([0-9a-zA-Z_]{1})\@."), True, "Failed c"), (re.compile(".\@([0-9a-zA-Z]{1})"), True, "Failed d"), (re.compile(".\.\-.|.\-\..|.\.\..|.!(xn)\-\-."), False, "Failed e"), (re.compile(".\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_."), False, "Failed f"), (re.compile("(.\.([a-zA-Z]{2,}))$|(.\.(xn--[0-9a-z]+))$"), True, "Failed g"), ) def _checkEmail(address):
yield { 'category': action_icon.getCategory(), 'action_id': action_icon.getActionId(), 'title': action_icon.getTitle(), 'priority': action_icon.getPriority(), 'icon_expr': action_icon.getExpression(), } security.declarePrivate('_getExportTemplate') def _getExportTemplate(self): return PageTemplateFile('aitExport.xml', _xmldir) InitializeClass(ActionIconsToolExportConfigurator) class ActionIconsToolImportConfigurator(ImportConfiguratorBase): def _getImportMapping(self): return { 'action-icons': { 'action-icon': { KEY: 'action_icons', DEFAULT: () }, 'i18n:domain': {}, 'xmlns:i18n': {}, }, 'action-icon': { 'category': {},
# # IGroupsPlugin implementation # security.declarePrivate( 'getGroupsForPrincipal' ) def getGroupsForPrincipal( self, user, request=None ): set = list( user.getGroups() ) seen = [] parent = aq_parent( self ) while set: test = set.pop(0) if test in seen: continue seen.append( test ) new_groups = parent._getGroupsForPrincipal( PropertiedUser( test ).__of__(parent), ignore_plugins=( self.getId(), ) ) if new_groups: set.extend( new_groups ) return tuple( seen ) classImplements( RecursiveGroupsPlugin , IRecursiveGroupsPlugin , IGroupsPlugin ) InitializeClass(RecursiveGroupsPlugin)
# immediate_view else finally return the 'base_view' string which is a # autogenerated form from Archetypes. default_view = getattr(aq_base(self), 'default_view', None) if default_view: return default_view immediate_view = getattr(self.getTypeInfo(), 'immediate_view', None) if immediate_view: return immediate_view return 'base_view' def getTemplateFor(self, pt, default='base_view'): # Let the SkinManager handle this. # But always try to show something. pt = getattr(self, pt, None) if not pt: # default is the value of obj.default_view or base_view default_pt = getattr(self, 'default_view', None) if not default_pt: default_pt = default return getattr(self, default_pt) else: return pt InitializeClass(TemplateMixin) # BBB backward compatibility schema = TemplateMixinSchema getTemplateFor = TemplateMixin.getTemplateFor __all__ = ('TemplateMixinSchema', 'TemplateMixin', )
log('ZopeFind: catched MissingBinary exception') security.declareProtected(View, 'objectItems') def objectItems(self, *args, **kwargs): """Don't break ZopeFind feature when a transform can't be loaded """ try: return Folder.objectItems(self, *args, **kwargs) except MissingBinary: log('objectItems: catched MissingBinary exception') return [] # available mimetypes #################################################### def listAvailableTextInputs(self): """Returns a list of mimetypes that can be used as input for textfields by building a list of the inputs beginning with "text/" of all transforms. """ available_types = [] candidate_transforms = [object[1] for object in self.objectItems()] for candidate in candidate_transforms: for input in candidate.inputs: if input.startswith("text/") and input not in available_types: available_types.append(input) return available_types InitializeClass(TransformTool) registerToolInterface('portal_transforms', IPortalTransformsTool)
if self.minor and not minor in self.minor: return 0 return 1 @security.protected(ManagePortal) def getTypeLabel(self): """ Return a human-readable label for the predicate type. """ return self.PREDICATE_TYPE security.declareProtected(ManagePortal, 'predicateWidget') predicateWidget = DTMLFile('majorMinorWidget', _dtmldir) InitializeClass(MajorMinorPredicate) @implementer(IContentTypeRegistryPredicate) class ExtensionPredicate(SimpleItem): """ Predicate matching on filename extensions. """ extensions = None PREDICATE_TYPE = 'extension' security = ClassSecurityInfo() def __init__(self, id):
'id': identity_userid, 'login': identity.userid, 'pluginid': pluginid, }) if max_results and len(ret) >= max_results: break if sort_by in ['id', 'login']: return sorted(ret, key=itemgetter(sort_by)) return ret @security.private def getRolesForPrincipal(self, user, request=None): """ Fullfill RolesPlugin requirements """ identity = self._useridentities_by_userid.get(user.getId(), None) if not identity: return () keys = [key for key in identity._identities.keys()] provider_id = keys[0] if 'roles' in identity._identities[provider_id].keys(): roles = identity._identities[provider_id]['roles'] if isinstance(roles, list): return tuple(roles) else: return () else: return () InitializeClass(AuthomaticPlugin)
directlyProvides( self, *(list(curr_interfaces - del_interfaces)) ) security.declareProtected( ManageUsers, 'manage_updateInterfaces' ) def manage_updateInterfaces( self, interfaces, RESPONSE=None ): """ For ZMI update of interfaces. """ pas_instance = self._getPAS() plugins = pas_instance._getOb( 'plugins' ) new_interfaces = [] for interface in interfaces: new_interfaces.append( plugins._getInterfaceFromName( interface ) ) klass_interfaces = [x for x in implementedBy(ScriptablePlugin)] directlyProvides( self, *(klass_interfaces + new_interfaces) ) if RESPONSE is not None: RESPONSE.redirect('%s/manage_workspace' '?manage_tabs_message=' 'Interfaces+updated.' % self.absolute_url()) classImplements( ScriptablePlugin , IScriptablePlugin , *(implementedBy(Folder) + implementedBy(BasePlugin)) ) InitializeClass(ScriptablePlugin)
_types_list = [ 'Analysis', 'ReferenceAnalysis', 'DuplicateAnalysis', ] bika_catalog_analysis_listing_definition = { CATALOG_ANALYSIS_LISTING: { 'types': _types_list, 'indexes': _indexes_dict, 'columns': _columns_list, } } class BikaAnalysisCatalog(BikaCatalogTool): """ Catalog for Analysis content types """ implements(IBikaAnalysisCatalog) def __init__(self): BikaCatalogTool.__init__(self, CATALOG_ANALYSIS_LISTING, 'Bika Analysis Catalog', 'BikaAnalysisCatalog') InitializeClass(BikaAnalysisCatalog) """ """
from Products.LinguaPlone.I18NBaseObject import I18NBaseObject class I18NOnlyBaseBTreeFolder(I18NBaseObject): """Base class for translatable objects.""" security = ClassSecurityInfo() def __nonzero__(self): return 1 def manage_beforeDelete(self, item, container): I18NBaseObject.manage_beforeDelete(self, item, container) InitializeClass(I18NOnlyBaseBTreeFolder) class I18NBaseBTreeFolder(I18NOnlyBaseBTreeFolder, BaseBTreeFolder): """Base class for translatable objects.""" security = ClassSecurityInfo() def manage_beforeDelete(self, item, container): I18NOnlyBaseBTreeFolder.manage_beforeDelete(self, item, container) BaseBTreeFolder.manage_beforeDelete(self, item, container) InitializeClass(I18NBaseBTreeFolder)
return data def _setOldCacheHeaders(self): # return False to disable this simple caching behaviour return _FSCacheHeaders(self) security.declareProtected(View, 'getContentType') def getContentType(self): """Get the content type of a file or image. Returns the content type (MIME type) of a file or image. """ self._updateFromFS() return self.content_type security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = index_html InitializeClass(FSFile) registerFileExtension('doc', FSFile) registerFileExtension('txt', FSFile) registerFileExtension('pdf', FSFile) registerFileExtension('swf', FSFile) registerFileExtension('jar', FSFile) registerFileExtension('cab', FSFile) registerFileExtension('ico', FSFile) registerFileExtension('js', FSFile) registerFileExtension('css', FSFile) registerMetaType('File', FSFile)
response._locked_status = True response.setBody = self._setBody # Keep response.exception return True # Methods to override on response def _setBody(self, body, *args, **kw): pass classImplements( InlineAuthHelper , IInlineAuthHelper , ILoginPasswordHostExtractionPlugin , IChallengePlugin ) InitializeClass(InlineAuthHelper) BASIC_LOGIN_FORM = """<html> <head> <title> Login Form </title> </head> <body> <h3> Please log in </h3> <form method="post"> <table cellpadding="2"> <tr> <td><b>Login:</b> </td>
:param kwargs: """ raise NotImplementedError def marshall(self, instance, **kwargs): """marshall. :param instance: :param kwargs: """ raise NotImplementedError def initializeField(self, instance, field): """initializeField. :param instance: :param field: """ pass def cleanupField(self, instance, field): """cleanupField. :param instance: :param field: """ pass InitializeClass(Marshaller)
security = ClassSecurityInfo() security.declarePrivate('manage_addProperty') security.declarePrivate('manage_delProperties') security.declarePrivate('manage_changePropertyTypes') def manage_propertiesForm(self, REQUEST, *args, **kw): """ An override that makes the schema fixed. """ my_kw = kw.copy() my_kw['property_extensible_schema__'] = 0 form = PropertyManager.manage_propertiesForm.__of__(self) return form(self, REQUEST, *args, **my_kw) InitializeClass(SimpleItemWithProperties) # # "Omnibus" factory framework for tools. # class ToolInit: """ Utility class for generating the factories for several tools. """ __name__ = 'toolinit' security = ClassSecurityInfo() security.declareObjectPrivate() # equivalent of __roles__ = () def __init__(self, meta_type, tools, product_name=None, icon=None): self.meta_type = meta_type
key = str(key).strip() if key: ks.append(key) self._cache_namespace_keys = tuple(ks) if REQUEST is not None: return self.ZCacheable_manage(self, REQUEST) # Zope 2.3.x way: def validate(self, inst, parent, name, value, md=None): return getSecurityManager().validate(inst, parent, name, value) if bbb.HAS_ZSERVER: security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = get_unbound_function(DTMLMethod.manage_FTPget) security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = get_unbound_function( DTMLMethod.PrincipiaSearchSource) security.declareProtected(ViewManagementScreens, 'document_src') document_src = get_unbound_function(DTMLMethod.document_src) security.declareProtected(ViewManagementScreens, 'manage_haveProxy') manage_haveProxy = get_unbound_function(DTMLMethod.manage_haveProxy) InitializeClass(FSDTMLMethod) registerFileExtension('dtml', FSDTMLMethod) registerMetaType('DTML Method', FSDTMLMethod)
description='', contributors=(), effective_date=None, expiration_date=None, format='text/html', language='en-US', rights='', ): """ used to be: editMetadata = WorkflowAction(_editMetadata) Need to add check for webDAV locked resource for TTW methods. """ self.failIfLocked() self._editMetadata(title=title, subject=subject, description=description, contributors=contributors, effective_date=effective_date, expiration_date=expiration_date, format=format, language=language, rights=rights, ) self.reindexObject() InitializeClass(ExtensibleMetadata) ExtensibleMetadataSchema = ExtensibleMetadata.schema __all__ = ('ExtensibleMetadata', 'ExtensibleMetadataSchema', )
# Delete members' local roles. if delete_localroles: self.deleteLocalRoles(getUtility(ISiteRoot), member_ids, reindex=1, recursive=1) return tuple(member_ids) security.declarePublic('getHomeFolder') def getHomeFolder(self, id=None, verifyPermission=0): """Returns a member's home folder object or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None security.declarePublic('getHomeUrl') def getHomeUrl(self, id=None, verifyPermission=0): """Returns the URL to a member's home folder or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None InitializeClass(MembershipTool)
""" if not self._default_cataloging: return if hasattr(aq_base(ob), 'reindexObject'): # XXX We only need the keys here, no need to compute values. mapping = self.getCatalogVariablesFor(ob) or {} vars = mapping.keys() ob.reindexObject(idxs=vars) # Reindex security of subobjects. if hasattr(aq_base(ob), 'reindexObjectSecurity'): ob.reindexObjectSecurity() InitializeClass(WorkflowTool) registerToolInterface('portal_workflow', IWorkflowTool) class DefaultWorkflowStatus(object): implements(IWorkflowStatus) adapts(IWorkflowAware, IWorkflowDefinition) def __init__(self, context, workflow): self.context = aq_base(context) self.wf_id = workflow.getId() def get(self): history = getattr(self.context, 'workflow_history', {}) wfh = history.get(self.wf_id) if wfh:
return self.getModTime() security.declareProtected(View, 'getContentType') def getContentType(self): """Get the content type of a file or image. Returns the content type (MIME type) of a file or image. """ self._updateFromFS() return self.content_type security.declareProtected(View, 'get_size') def get_size(self): """ Return the size of the image. """ self._updateFromFS() return self._data and len( self._data ) or 0 security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = index_html InitializeClass(FSImage) registerFileExtension('gif', FSImage) registerFileExtension('jpg', FSImage) registerFileExtension('jpeg', FSImage) registerFileExtension('png', FSImage) registerFileExtension('bmp', FSImage) registerMetaType('Image', FSImage)
u'webDAV.')) return 0 # # Contentish interface methods # security.declareProtected(View, 'SearchableText') def SearchableText(self): """ Returns a concatination of all searchable text. Should be overriden by portal objects. """ return "%s %s" % (self.Title(), self.Description()) def __call__(self): """ Invokes the default view. """ ti = self.getTypeInfo() method_id = ti and ti.queryMethodID('(Default)', context=self) if method_id and method_id!='(Default)': method = getattr(self, method_id) if getattr(aq_base(method), 'isDocTemp', 0): return method(self, self.REQUEST, self.REQUEST['RESPONSE']) else: return method() else: raise NotFound( 'Cannot find default view for "%s"' % '/'.join( self.getPhysicalPath() ) ) InitializeClass(PortalContent)
]: try: defaultppolicy = agent.conn.search_s( 'cn=defaultppolicy,ou=pwpolicies,o=EIONET,' 'l=Europe', SCOPE_BASE) p_length = defaultppolicy[0][1]['pwdMinLength'][0] message = '%s (min. %s characters)' % ( e.message['info'], p_length) except NO_SUCH_OBJECT: message = e.message['info'] else: message = e.message['info'] _set_session_message(REQUEST, 'error', message) location = (self.absolute_url() + '/confirm_email?token=' + token) else: del self._tokens[token] location = (self.absolute_url() + '/messages_html?msg=password-reset') REQUEST.RESPONSE.redirect(location) security.declareProtected(view, 'can_edit_users') def can_edit_users(self): user = self.REQUEST.AUTHENTICATED_USER return bool(user.has_permission(ldap_edit_users, self)) InitializeClass(PasswordResetTool)
review_state. ''' review_state = self.getReviewStateOf(ob) if review_state == 'private': anon_view = 0 owner_modify = 1 reviewer_view = 0 elif review_state == 'pending': anon_view = 0 owner_modify = 0 # Require a retraction for editing. reviewer_view = 1 elif review_state == 'published': anon_view = 1 owner_modify = 0 reviewer_view = 1 else: # This object is in an unknown state anon_view = 0 owner_modify = 1 reviewer_view = 0 # Modify role to permission mappings directly. new_map = { View: {'Anonymous': anon_view, 'Reviewer': reviewer_view, 'Owner': 1} , ModifyPortalContent: {'Owner': owner_modify} } return _modifyPermissionMappings(ob, new_map) InitializeClass(DefaultWorkflowDefinition)