class Connection(Shared.DC.ZRDB.Connection.Connection): _isAnSQLConnection = 1 manage_options = Shared.DC.ZRDB.Connection.Connection.manage_options + ( { 'label': 'Browse', 'action': 'manage_browse' }, # {'label': 'Design', 'action':'manage_tables'}, ) manage_tables = HTMLFile('tables', globals()) manage_browse = HTMLFile('browse', globals()) info = None def tpValues(self): #if hasattr(self, '_v_tpValues'): return self._v_tpValues r = [] # self._v_tables=tables=TableBrowserCollection() #tables=tables.__dict__ c = self._v_database_connection try: for d in c.tables(rdb=0): try: name = d['TABLE_NAME'] b = TableBrowser() b.__name__ = name b._d = d b._c = c #b._columns=c.columns(name) b.icon = table_icons.get(d['TABLE_TYPE'], 'text') r.append(b) # tables[name]=b except: # print d['TABLE_NAME'], sys.exc_type, sys.exc_value pass finally: pass #print sys.exc_type, sys.exc_value #self._v_tpValues=r return r def __getitem__(self, name): if name == 'tableNamed': if not hasattr(self, '_v_tables'): self.tpValues() return self._v_tables.__of__(self) raise KeyError, name def manage_wizard(self, tables): " " def manage_join(self, tables, select_cols, join_cols, REQUEST=None): """Create an SQL join""" def manage_insert(self, table, cols, REQUEST=None): """Create an SQL insert""" def manage_update(self, table, keys, cols, REQUEST=None): """Create an SQL update"""
class Connection(Shared.DC.ZRDB.Connection.Connection): _isAnSQLConnection = 1 manage_options = Shared.DC.ZRDB.Connection.Connection.manage_options + ( { 'label': 'Browse', 'action': 'manage_browse' }, ) manage_tables = HTMLFile('dtml/tables', globals()) manage_browse = HTMLFile('dtml/browse', globals()) def tpValues(self): r = [] if not hasattr(self, '_v_database_connection'): return r c = self._v_database_connection for d in c.tables(rdb=0): r.append(TableBrowser(d, c)) for d in c.procedures(): r.append(ProcedureBrowser(d)) for d in c.generators(): r.append(GeneratorBrowser(d)) return r def __getitem__(self, name): if name == 'tableNamed': if not hasattr(self, '_v_tables'): self.tpValues() return self._v_tables.__of__(self) raise KeyError(name)
class TableBrowser(BrowserBase, Implicit): icon = 'what' check = '' info = HTMLFile('www/table_info', globals()) def tpValues(self): v = values() v._f = self.tpValues_ return v def tpValues_(self): r = [] tname = self._d['table_name'] for d in self._c.columns(tname): b = ColumnBrowser() b._d = d b.icon = d['icon'] b.table_name = tname r.append(b) return r def tpId(self): return self._d['table_name'] def tpURL(self): return 'Table/%s' % self._d['table_name'] def name(self): return self._d['table_name'] def type(self): return self._d['table_type'] def description(self): return self._d['description']
def __get__(self, instance, owner): f = None cls = self.cls path = self.path theme = cls.get().get('zmi.theme', 'dtml') try: if instance is not None: instance_zmi_theme = getattr(instance, 'zmi_theme', None) if instance_zmi_theme is not None: theme = instance_zmi_theme elif getattr(instance, 'meta_type', None) == 'ZMS': theme = instance.getConfProperty('zmi.theme', 'dtml') except: print "### self=", self print "### instance=", instance print "### owner=", owner import sys, traceback, string type, val, tb = sys.exc_info() sys.stderr.write( string.join(traceback.format_exception(type, val, tb), '')) del type, val, tb if theme == 'zpt': if path.find('/') > 0: path = 'zpt/%s' % path f = PageTemplateFile(path, globals()) else: if path.find('/') > 0: path = 'dtml/%s' % path f = HTMLFile(path, globals()) return f
def reportPage(self): """ """ request = self.REQUEST jsonObj = json.loads(request['userid']) user_id = str(jsonObj[0]) getreport = self.zsqls.selectMyPurchase(user_id=user_id) report_html = HTMLFile("views/report", globals()) return report_html(standard_html_header='', standard_html_footer='', getreport=getreport)
class Connection(DABase.Connection): """MySQL Connection Object """ database_type = database_type id = '%s_database_connection' % database_type meta_type = title = 'Z %s Database Connection' % database_type icon = 'misc_/Z%sDA/conn' % database_type security = ClassSecurityInfo() manage_properties = HTMLFile('connectionEdit', globals()) connect_on_load = False def factory(self): return DB security.declarePrivate('manage_beforeDelete') def manage_beforeDelete(self, item, container): database_connection_pool.get(self._p_oid, {}).pop(self._p_jar, None) def connect(self, s): self._v_connected = '' if not self._p_oid: transaction.savepoint(optimistic=True) pool = database_connection_pool[self._p_oid] connection = pool.get(self._p_jar) DB = self.factory() if connection.__class__ is not DB or connection._connection != s: connection = pool[self._p_jar] = DB(s) self._v_database_connection = connection # XXX If date is used as such, it can be wrong because an existing # connection may be reused. But this is suposedly only used as a # marker to know if connection was successfull. self._v_connected = DateTime() return self def sql_quote__(self, v, escapes={}): try: connection = self._v_database_connection except AttributeError: # The volatile attribute sometimes disappears. # In this case, re-assign it by calling the connect method. # Note that we don't call sql_quote__ recursively by intention, # because if connect fails to assign the volatile attribute for # any reason, that would generate an infinite loop. self.connect(self.connection_string) connection = self._v_database_connection return connection.string_literal(v)
def generateReports(self): """ """ request = self.REQUEST jsonObj = json.loads(request['repObj']) user_id = str(jsonObj[0]) product = str(jsonObj[1]) start_date = str(jsonObj[2]) end_date = str(jsonObj[3]) getreport = self.zsqls.selectMonthlyReport(user_id=user_id, product=product, start_date=start_date, end_date=end_date) report_html = HTMLFile("views/report", globals()) return report_html(standard_html_header='', standard_html_footer='', getreport=getreport)
class Connection(DABase.Connection): " " database_type = database_type id = "%s_database_connection" % database_type meta_type = title = "Z %s Database Connection" % database_type zmi_icon = "fa fa-database" manage_properties = HTMLFile("dtml/connectionEdit", globals(), data_sources=data_sources) def connected(self): if hasattr(self, "_v_database_connection"): return self._v_database_connection.opened return "" def title_and_id(self): s = _Connection.inheritedAttribute("title_and_id")(self) if (hasattr(self, "_v_database_connection") and self._v_database_connection.opened): s = "%s, which is connected" % s else: s = "%s, which is <font color=red> not connected</font>" % s return s def title_or_id(self): s = _Connection.inheritedAttribute("title_and_id")(self) if (hasattr(self, "_v_database_connection") and self._v_database_connection.opened): s = "%s (connected)" % s else: s = "%s (<font color=red> not connected</font>)" % s return s def data_dir(self): return standard.data_dir def connect(self, s): _connections_lock.acquire() try: c = _connections page_charset = getattr(self, "management_page_charset", "utf-8") self._v_database_connection = c[s] = db.DB(s, page_charset) return self finally: _connections_lock.release()
class Connection(DABase.Connection): " " database_type = database_type id = '%s_database_connection' % database_type meta_type = title = 'Z %s Database Connection' % database_type icon = 'misc_/Z%sDA/conn' % database_type manage_properties = HTMLFile('dtml/connectionEdit', globals(), data_sources=data_sources) def connected(self): if hasattr(self, '_v_database_connection'): return self._v_database_connection.opened return '' def title_and_id(self): s = _Connection.inheritedAttribute('title_and_id')(self) if (hasattr(self, '_v_database_connection') and self._v_database_connection.opened): s = "%s, which is connected" % s else: s = "%s, which is <font color=red> not connected</font>" % s return s def title_or_id(self): s = _Connection.inheritedAttribute('title_and_id')(self) if (hasattr(self, '_v_database_connection') and self._v_database_connection.opened): s = "%s (connected)" % s else: s = "%s (<font color=red> not connected</font>)" % s return s def connect(self, s): _connections_lock.acquire() try: c = _connections page_charset = getattr(self, 'management_page_charset', 'utf-8') self._v_database_connection = c[s] = DB(s, page_charset) return self finally: _connections_lock.release()
def validateLogin(self): """ Login Validation """ request = self.REQUEST USER_ID = request.USER_ID PASSWORD = request.PASSWORD existinguser = self.zsqls.selectUser(USER_ID=USER_ID) if existinguser: if existinguser[0]['USER_ID'] == USER_ID and existinguser[0]['PASSWORD'] == PASSWORD: if existinguser[0]['role'] == 'Y': report_html = HTMLFile("views/generatUserReports", globals()) return report_html(standard_html_header='', standard_html_footer='',USER_ID=USER_ID) else: item_list = self.views.itemlist return item_list(standard_html_header='', standard_html_footer='', USER_ID=USER_ID) else: return "User does not exists. Please Register."
class TableBrowser(Browser, Acquisition.Implicit): info = HTMLFile('dtml/table_info', globals()) def tpValues(self): r = [] for d in self._c.columns(self.TABLE_NAME): r.append(ColumnBrowser(d)) consts = self._c.constraints(self.TABLE_NAME) for d in consts: r.append(ConstraintBrowser(consts[d])) check_consts = self._c.check_constraints(self.TABLE_NAME) for d in check_consts: r.append(CheckConstraintBrowser(check_consts[d])) for d in self._c.triggers(self.TABLE_NAME): r.append(TriggerBrowser(d)) r.append(SourceBrowser(self.VIEW_SOURCE)) return r def tpId(self): return self.TABLE_NAME def icon(self): if self.VIEW_SOURCE: return 'view' + '.gif' elif self.SYSTEM_FLAG: return 'stable' + '.gif' else: return 'table' + '.gif' def Type(self): if self.VIEW_SOURCE: return 'VIEW' elif self.SYSTEM_FLAG: return 'SYSTEM_TABLE' else: return 'TABLE'
""" Event subscriber for (un)registering a CC as a before traverse hook. """ if not ICookieCrumbler.providedBy(ob): return if IObjectMovedEvent.providedBy(event): if event.newParent is not None: # register before traverse hook handle = ob.meta_type + '/' + ob.getId() nc = BeforeTraverse.NameCaller(ob.getId()) BeforeTraverse.registerBeforeTraverse(event.newParent, nc, handle) elif IObjectWillBeMovedEvent.providedBy(event): if event.oldParent is not None: # unregister before traverse hook handle = ob.meta_type + '/' + ob.getId() BeforeTraverse.unregisterBeforeTraverse(event.oldParent, handle) manage_addCCForm = HTMLFile('dtml/addCC', globals()) manage_addCCForm.__name__ = 'addCC' def manage_addCC(dispatcher, id, REQUEST=None): ' ' ob = CookieCrumbler() ob.id = id dispatcher._setObject(ob.getId(), ob) ob = getattr(dispatcher.this(), ob.getId()) if REQUEST is not None: return dispatcher.manage_main(dispatcher, REQUEST)
class AccessManager(AccessableContainer): # -------------------------------------------------------------------------- # AccessManager.getRoleName # -------------------------------------------------------------------------- def getRoleName(self, role): langKey = 'ROLE_%s' % role.upper() langStr = self.getZMILangStr(langKey) if langKey == langStr: return role return langStr # -------------------------------------------------------------------------- # AccessManager.getValidUserids: # -------------------------------------------------------------------------- def getValidUserids(self, search_term='', without_node_check=True): local_userFldr = self.getUserFolder() valid_userids = [] c = 0 for userFldr in self.getUserFolders(): doc_elmnts = userFldr.aq_parent.objectValues(['ZMS']) if doc_elmnts: doc_elmnt = doc_elmnts[0] sec_users = doc_elmnt.getConfProperty('ZMS.security.users') if userFldr.meta_type == 'LDAPUserFolder': if c == 0: search_param = self.getConfProperty( 'LDAPUserFolder.login_attr', userFldr.getProperty('_login_attr')) exact = False if search_term == '': search_terms = sec_users.keys() exact = True else: search_terms = [search_term] for st in search_terms: users = userFldr.findUser( search_param=search_param, search_term=st) for user in users: name = user[search_param] if not exact or name == st: d = {} d['localUserFldr'] = userFldr d['name'] = name for extra in ['givenName', 'sn']: try: d[extra] = user[extra] except: pass valid_userids.append(d) else: node_prefix = '{$%s@' % self.getHome().id for sec_user in sec_users: nodes = doc_elmnt.getUserAttr(sec_user, 'nodes') if str(nodes).find(node_prefix) >= 0: d = {} d['localUserFldr'] = userFldr d['name'] = sec_user valid_userids.append(d) elif userFldr.meta_type != 'LDAPUserFolder': for userName in userFldr.getUserNames(): if without_node_check or ( local_userFldr == userFldr ) or self.get_local_roles_for_userid(userName): if search_term == '' or search_term == userName: d = {} d['localUserFldr'] = userFldr d['name'] = userName valid_userids.append(d) c += 1 return valid_userids # -------------------------------------------------------------------------- # AccessManager.setUserAttr: # -------------------------------------------------------------------------- def setUserAttr(self, user, name, value): user = getUserId(user) d = self.getConfProperty('ZMS.security.users', {}) i = d.get(user, {}) i[name] = value d[user] = i.copy() self.setConfProperty('ZMS.security.users', d.copy()) # -------------------------------------------------------------------------- # AccessManager.getLDAPUserAttr: # -------------------------------------------------------------------------- def getLDAPUserAttr(self, user, name): user = getUserId(user) userFldr = self.getUserFolder() if userFldr.meta_type == 'LDAPUserFolder': userObj = userFldr.getUserByAttr( userFldr.getProperty('_login_attr'), user, pwd=None, cache=1) if userObj is not None: if name in userObj._properties: value = userObj.getProperty(name) return value elif name == 'email': for key in userObj._properties: value = userObj.getProperty(key) if value.find('@') > 0 and value.rfind( '.') > 0 and value.find('@') < value.rfind( '.'): return value return None # -------------------------------------------------------------------------- # AccessManager.getUserAttr: # -------------------------------------------------------------------------- def getUserAttr(self, user, name=None, default=None, flag=0): user = getUserId(user) if name not in ['nodes']: v = self.getLDAPUserAttr(user, name) if v is not None: return v d = self.getConfProperty('ZMS.security.users', {}) if name is None: v = d.get(user, None) else: i = d.get(user, {}) v = i.get(name, default) # Process master. if flag == 0: portalMaster = self.getPortalMaster() if portalMaster is not None: w = portalMaster.getUserAttr(user, name, default, 1) if type(w) in StringTypes: if type(v) in StringTypes: if len(v) == 0: v = w # Process clients. if flag == 0: for portalClient in self.getPortalClients(): w = portalClient.getUserAttr(user, name, default) if type(w) is dict: if v is None: v = w elif type(v) is dict: v = v.copy() for node in w.keys(): ob = portalClient.getLinkObj(node) newNode = self.getRefObjPath(ob) v[newNode] = w[node] return v # -------------------------------------------------------------------------- # AccessManager.delUserAttr: # -------------------------------------------------------------------------- def delUserAttr(self, user): user = getUserId(user) d = self.getConfProperty('ZMS.security.users', {}) try: del d[user] self.setConfProperty('ZMS.security.users', d) except: _globals.writeError(self, '[delUserAttr]: user=%s not deleted!' % user) # -------------------------------------------------------------------------- # AccessManager.initRoleDefs: # # Init Role-Definitions and Permission Settings # -------------------------------------------------------------------------- def initRoleDefs(self): # Init Roles. for role in role_defs.keys(): role_def = role_defs[role] # Add Local Role. if not role in self.valid_roles(): self._addRole(role) # Set permissions for Local Role. self.manage_role(role_to_manage=role, permissions=role_permissions(self, role)) # Clear acquired permissions. self.manage_acquiredPermissions([]) # Grant public access. self.synchronizePublicAccess() # -------------------------------------------------------------------------- # AccessManager.findUser: # -------------------------------------------------------------------------- def findUser(self, name): for userFldr in self.getUserFolders(): userObj = None if userFldr.meta_type == 'LDAPUserFolder': if self.getConfProperty('LDAPUserFolder.login_attr', '') == 'dn': userObj = userFldr.getUserByDN(name) else: ldapUsersObjs = userFldr.findUser( search_param=userFldr.getProperty('_login_attr'), search_term=name) if len(ldapUsersObjs) == 1: userObj = ldapUsersObjs[0] userObj['__id__'] = userObj[userFldr.getProperty( '_login_attr')] else: userObj = userFldr.getUser(name) if userObj is not None: return userObj return None # -------------------------------------------------------------------------- # AccessManager.getUserFolder: # -------------------------------------------------------------------------- def getUserFolder(self): homeElmnt = self.getHome() userFldrs = homeElmnt.objectValues(user_folder_meta_types) if len(userFldrs) == 0: portalMaster = self.getPortalMaster() if portalMaster is not None: userFldr = portalMaster.getUserFolder() else: userFldr = UserFolder() homeElmnt._setObject(userFldr.id, userFldr) else: userFldr = userFldrs[0] return userFldr # -------------------------------------------------------------------------- # AccessManager.getUserFolders: # -------------------------------------------------------------------------- def getUserFolders(self): userFolders = [] ob = self depth = 0 while True: if depth > sys.getrecursionlimit(): raise zExceptions.InternalError( "Maximum recursion depth exceeded") depth = depth + 1 if ob is None: break try: localUserFolders = ob.objectValues(user_folder_meta_types) if len(localUserFolders) == 1: localUserFolder = localUserFolders[0] if localUserFolder not in userFolders: userFolders.append(localUserFolder) ob = ob.aq_parent except: ob = None return userFolders ############################################################################ ### ### Local Users ### ############################################################################ # ------------------------------------------------------------------------------ # AccessManager.purgeLocalUsers # ------------------------------------------------------------------------------ def purgeLocalUsers(self, ob=None, valid_userids=[], invalid_userids=[]): rtn = "" if ob is None: ob = self for local_role in ob.get_local_roles(): delLocalRoles = False userid = local_role[0] userroles = local_role[1] if 'Owner' not in userroles: if userid not in valid_userids and userid not in invalid_userids: userob = ob.findUser(userid) if userob is None: invalid_userids.append(userid) else: valid_userids.append(userid) if userid in valid_userids: nodes = self.getUserAttr(userid, 'nodes', {}) if len( filter( lambda x: (x == "{$}" and ob.id == "content") or x == "{$%s}" % ob.id or x.endswith("/%s}" % ob.id), nodes.keys())) == 0: delLocalRoles = True elif userid in invalid_userids: delLocalRoles = True if delLocalRoles: rtn += ob.absolute_url() + " " + userid + " " + str( userroles) + "<br/>" ob.manage_delLocalRoles(userids=[userid]) # Process subtree. for subob in ob.objectValues(ob.dGlobalAttrs.keys()): rtn += self.purgeLocalUsers(subob, valid_userids, invalid_userids) return rtn # -------------------------------------------------------------------------- # AccessManager.setLocalUser: # -------------------------------------------------------------------------- def setLocalUser(self, id, node, roles, langs): # Insert node to user-properties. nodes = self.getUserAttr(id, 'nodes', {}) nodes[node] = {'langs': langs, 'roles': roles} nodes = nodes.copy() self.setUserAttr(id, 'nodes', nodes) roles = list(roles) if 'ZMSAdministrator' in roles: roles.append('Manager') # Set local roles in node. ob = self.getLinkObj(node, self.REQUEST) if ob is not None: ob.manage_setLocalRoles(id, roles) # -------------------------------------------------------------------------- # AccessManager.delLocalUser: # -------------------------------------------------------------------------- def delLocalUser(self, id, node): # Delete node from user-properties. nodes = self.getUserAttr(id, 'nodes', {}) if nodes.has_key(node): del nodes[node] nodes = nodes.copy() self.setUserAttr(id, 'nodes', nodes) # Delete local roles in node. ob = self.getLinkObj(node, self.REQUEST) if ob is not None: ob.manage_delLocalRoles(userids=[id]) ############################################################################ ### ### Properties ### ############################################################################ # Management Interface. # --------------------- manage_users = _confmanager.ConfDict.template('ZMS/manage_users') manage_users_sitemap = HTMLFile('dtml/ZMS/manage_users_sitemap', globals()) ############################################################################ # AccessManager.manage_roleProperties: # # Change or delete roles. ############################################################################ def manage_roleProperties(self, btn, key, lang, REQUEST, RESPONSE=None): """ AccessManager.manage_roleProperties """ message = '' id = REQUEST.get('id', '') # Cancel. # ------- if btn in [ self.getZMILangStr('BTN_CANCEL'), self.getZMILangStr('BTN_BACK') ]: id = '' # Insert. # ------- if btn == self.getZMILangStr('BTN_INSERT'): if key == 'obj': #-- Add local role. id = REQUEST.get('newId').strip() if id not in self.valid_roles(): self._addRole(role=id, REQUEST=REQUEST) #-- Prepare nodes from config-properties. security_roles = self.getConfProperty('ZMS.security.roles', {}) security_roles[id] = {} security_roles = security_roles.copy() self.setConfProperty('ZMS.security.roles', security_roles) #-- Assemble message. message = self.getZMILangStr( 'MSG_INSERTED') % self.getZMILangStr('ATTR_ROLE') elif key == 'attr': #-- Insert node to config-properties. node = REQUEST.get('node') roles = REQUEST.get('roles', []) if not type(roles) is list: roles = [roles] security_roles = self.getConfProperty('ZMS.security.roles', {}) dict = security_roles.get(id, {}) dict[node] = {'roles': roles} security_roles[id] = dict security_roles = security_roles.copy() self.setConfProperty('ZMS.security.roles', security_roles) #-- Set permissions in node. ob = self.getLinkObj(node, REQUEST) permissions = [] for role in roles: permissions = ob.concat_list( permissions, role_permissions(self, role.replace(' ', ''))) ob.manage_role(role_to_manage=id, permissions=permissions) #-- Assemble message. message = self.getZMILangStr( 'MSG_INSERTED') % self.getZMILangStr('ATTR_NODE') # Delete. # ------- elif btn in ['delete', self.getZMILangStr('BTN_DELETE')]: if key == 'obj': #-- Delete local role. self._delRoles(roles=[id], REQUEST=REQUEST) #-- Delete nodes from config-properties. security_roles = self.getConfProperty('ZMS.security.roles', {}) if security_roles.has_key(id): del security_roles[id] security_roles = security_roles.copy() self.setConfProperty('ZMS.security.roles', security_roles) id = '' elif key == 'attr': #-- Delete node from config-properties. node = REQUEST.get('nodekey') security_roles = self.getConfProperty('ZMS.security.roles', {}) dict = security_roles.get(id, {}) if dict.has_key(node): del dict[node] security_roles[id] = dict security_roles = security_roles.copy() self.setConfProperty('ZMS.security.roles', security_roles) #-- Delete permissions in node. permissions = [] ob = self.getLinkObj(node, REQUEST) if ob is not None: ob.manage_role(role_to_manage=id, permissions=permissions) #-- Assemble message. message = self.getZMILangStr('MSG_DELETED') % int(1) # Return with message. if RESPONSE: message = urllib.quote(message) return RESPONSE.redirect( 'manage_users?lang=%s&manage_tabs_message=%s&id=%s' % (lang, message, id)) ############################################################################ # AccessManager.manage_userProperties: # # Change or delete users. ############################################################################ def manage_userProperties(self, btn, key, lang, REQUEST, RESPONSE=None): """ AccessManager.manage_userProperties """ message = '' id = REQUEST.get('id', '') # Cancel. # ------- if btn in [ self.getZMILangStr('BTN_CANCEL'), self.getZMILangStr('BTN_BACK') ]: id = '' # Insert. # ------- if btn == self.getZMILangStr('BTN_INSERT'): if key == 'obj': #-- Insert user. newId = REQUEST.get('newId', '').strip() newPassword = REQUEST.get('newPassword', '').strip() newConfirm = REQUEST.get('newConfirm', '').strip() newEmail = REQUEST.get('newEmail', '').strip() id = insertUser(self, newId, newPassword, newEmail, REQUEST) #-- Assemble message. message = self.getZMILangStr( 'MSG_INSERTED') % self.getZMILangStr('ATTR_USER') elif key == 'attr': #-- Insert local user. langs = REQUEST.get('langs', []) if not type(langs) is list: langs = [langs] roles = REQUEST.get('roles', []) if not type(roles) is list: roles = [roles] node = REQUEST.get('node') ob = self.getLinkObj(node, REQUEST) docElmnt = ob.getDocumentElement() node = docElmnt.getRefObjPath(ob) docElmnt.setLocalUser(id, node, roles, langs) #-- Assemble message. message = self.getZMILangStr( 'MSG_INSERTED') % self.getZMILangStr('ATTR_NODE') # Change. # ------- elif btn == self.getZMILangStr('BTN_SAVE'): userObj = self.findUser(id) if key == 'obj': password = REQUEST.get('password', '******') confirm = REQUEST.get('confirm', '') if password != '******' and password == confirm: try: userFldr = self.getUserFolder() roles = userObj.getRoles() domains = userObj.getDomains() userFldr.userFolderEditUser(id, password, roles, domains) except: _globals.writeError( self, '[manage_user]: can\'t change password') self.setUserAttr(id, 'email', REQUEST.get('email', '').strip()) self.setUserAttr(id, 'profile', REQUEST.get('profile', '').strip()) elif key == 'attr': pass #-- Assemble message. message = self.getZMILangStr('MSG_CHANGED') # Delete. # ------- elif btn in ['delete', self.getZMILangStr('BTN_DELETE')]: if key == 'obj': #-- Delete user. deleteUser(self, id) id = '' #-- Assemble message. message = self.getZMILangStr('MSG_DELETED') % int(1) elif key == 'attr': #-- Delete local user. node = REQUEST.get('nodekey') try: self.delLocalUser(id, node) except: pass try: docElmnt = self.getDocumentElement() ob = self.getLinkObj(node, REQUEST) if ob is not None: docElmnt = ob.getDocumentElement() node = docElmnt.getRefObjPath(ob) docElmnt.delLocalUser(id, node) except: pass #-- Assemble message. message = self.getZMILangStr('MSG_DELETED') % int(1) # Invite. # ------- elif btn == self.getZMILangStr('BTN_INVITE'): if key == 'obj': email = self.getUserAttr(id, 'email', '') nodekeys = REQUEST.get('nodekeys', []) if len(email) > 0 and len(nodekeys) > 0: # Send notification. # ------------------ #-- Recipient mto = email #-- Body userObj = self.findUser(id) mbody = [] mbody.append( self.getTitle(REQUEST) + ' ' + self.getHref2IndexHtml(REQUEST)) mbody.append('\n') mbody.append('\n%s: %s' % (self.getZMILangStr('ATTR_ID'), id)) mbody.append('\n') for nodekey in nodekeys: ob = self.getLinkObj(nodekey, REQUEST) mbody.append('\n * ' + ob.getTitlealt(REQUEST) + ' [' + ob.display_type(REQUEST) + ']: ' + ob.absolute_url() + '/manage') mbody.append('\n') mbody.append('\n' + self.getZMILangStr('WITH_BEST_REGARDS')) mbody.append('\n' + str(REQUEST['AUTHENTICATED_USER'])) mbody.append('\n-------------------------------') mbody = ''.join(mbody) #-- Subject msubject = '%s (invitation)' % self.getTitlealt(REQUEST) #-- Send self.sendMail(mto, msubject, mbody, REQUEST) #-- Assemble message. message = self.getZMILangStr('MSG_CHANGED') # Return with message. if RESPONSE: message = urllib.quote(message) return RESPONSE.redirect( 'manage_users?lang=%s&manage_tabs_message=%s&id=%s' % (lang, message, id)) ################################################################################
class AccessableObject: # -------------------------------------------------------------------------- # AccessableObject.getUsers: # -------------------------------------------------------------------------- def getUsers(self, REQUEST): users = {} d = self.getConfProperty('ZMS.security.users', {}) for user in d.keys(): roles = self.getUserRoles(user, aq_parent=0) langs = self.getUserLangs(user, aq_parent=0) if len(roles) > 0 and len(langs) > 0: users[user] = {'roles': roles, 'langs': langs} return users # -------------------------------------------------------------------------- # AccessableObject.hasAccess: # -------------------------------------------------------------------------- def hasAccess(self, REQUEST): auth_user = REQUEST.get('AUTHENTICATED_USER') access = auth_user.has_permission('View', self) in [1, True] if not access: access = access or self.hasPublicAccess() return access # -------------------------------------------------------------------------- # AccessableObject.getUserRoles: # -------------------------------------------------------------------------- def getUserRoles(self, userObj, aq_parent=1): roles = [] try: roles.extend(list(userObj.getRolesInContext(self))) if 'Manager' in roles: roles = self.concat_list(roles, [ 'ZMSAdministrator', 'ZMSEditor', 'ZMSAuthor', 'ZMSSubscriber', 'ZMSUserAdministrator' ]) except: pass nodes = self.getUserAttr(userObj, 'nodes', {}) ob = self depth = 0 while ob is not None: if depth > sys.getrecursionlimit(): raise zExceptions.InternalError( "Maximum recursion depth exceeded") depth = depth + 1 nodekey = self.getRefObjPath(ob) if nodekey in nodes.keys(): roles = self.concat_list(roles, nodes[nodekey]['roles']) break if aq_parent: ob = ob.getParentNode() else: ob = None # Resolve security_roles. security_roles = self.getConfProperty('ZMS.security.roles', {}) for id in filter(lambda x: x in security_roles.keys(), roles): dict = security_roles.get(id, {}) for v in dict.values(): for role in map(lambda x: x.replace(' ', ''), v.get('roles', [])): if role not in roles: roles.append(role) return roles # -------------------------------------------------------------------------- # AccessableObject.getUserLangs: # -------------------------------------------------------------------------- def getUserLangs(self, userObj, aq_parent=1): langs = [] try: langs.extend(list(getattr(userObj, 'langs', ['*']))) except: pass nodes = self.getUserAttr(userObj, 'nodes', {}) ob = self depth = 0 while ob is not None: if depth > sys.getrecursionlimit(): raise zExceptions.InternalError( "Maximum recursion depth exceeded") depth = depth + 1 nodekey = self.getRefObjPath(ob) if nodekey in nodes.keys(): langs = nodes[nodekey]['langs'] break if aq_parent: ob = ob.getParentNode() else: ob = None return langs ############################################################################ ### ### Public Access (Subscribers) ### ############################################################################ # -------------------------------------------------------------------------- # AccessableObject.hasRestrictedAccess: # -------------------------------------------------------------------------- def hasRestrictedAccess(self): restricted = False if 'attr_dc_accessrights_restricted' in self.getObjAttrs().keys(): req = {'lang': self.getPrimaryLanguage()} restricted = restricted or self.getObjProperty( 'attr_dc_accessrights_restricted', req) in [1, True] return restricted # -------------------------------------------------------------------------- # AccessableObject.hasPublicAccess: # -------------------------------------------------------------------------- def hasPublicAccess(self): if 'attr_dc_accessrights_public' in self.getObjAttrs().keys(): req = {'lang': self.getPrimaryLanguage()} if self.getObjProperty('attr_dc_accessrights_public', req) in [1, True]: return True public = not self.hasRestrictedAccess() parent = self.getParentNode() if parent is not None and isinstance(parent, AccessableObject): public = public and parent.hasPublicAccess() return public # -------------------------------------------------------------------------- # AccessableObject.synchronizePublicAccess: # -------------------------------------------------------------------------- def synchronizePublicAccess(self): # This is ugly, but necessary since ZMSObject is inherited from # AccessableObject and ZMSContainerObject is inherited from # AccessableContainer! restricted = self.hasRestrictedAccess() if self.meta_id == 'ZMSLinkElement' and self.isEmbedded(self.REQUEST): ob = self.getRefObj() if ob is not None: for item in ob.breadcrumbs_obj_path(): restricted = restricted or item.hasRestrictedAccess() if restricted: break else: ob = self if isinstance(ob, AccessableContainer): if restricted: self.revokePublicAccess() else: self.grantPublicAccess() ############################################################################ ### ### Properties ### ############################################################################ ############################################################################ # AccessableObject.manage_user: # # Change user. ############################################################################ manage_userForm = HTMLFile('dtml/ZMS/manage_user', globals()) def manage_user(self, btn, lang, REQUEST, RESPONSE): """ AccessManager.manage_user """ message = '' # Change. # ------- if btn == self.getZMILangStr('BTN_SAVE'): id = getUserId(REQUEST['AUTHENTICATED_USER']) userObj = self.findUser(id) password = REQUEST.get('password', '******') confirm = REQUEST.get('confirm', '') if password != '******' and password == confirm: for userFldr in self.getUserFolders(): if id in userFldr.getUserNames(): try: roles = userObj.getRoles() domains = userObj.getDomains() userFldr.userFolderEditUser( id, password, roles, domains) message += self.getZMILangStr( 'ATTR_PASSWORD') + ': ' except: message += _globals.writeError( self, '[manage_user]: can\'t change password') break self.setUserAttr(userObj, 'email', REQUEST.get('email', '').strip()) #-- Assemble message. message += self.getZMILangStr('MSG_CHANGED') #-- Build json. RESPONSE.setHeader('Content-Type', 'text/plain; charset=utf-8') RESPONSE.setHeader('Cache-Control', 'no-cache') RESPONSE.setHeader('Pragma', 'no-cache') return self.str_json(message)
# manage_addTool() can then grab it. constructors=(manage_addToolForm, manage_addTool, self), icon=self.icon) if self.icon: icon = os_path.split(self.icon)[1] else: icon = None for tool in self.tools: tool.__factory_meta_type__ = self.meta_type tool.icon = 'misc_/%s/%s' % (self.product_name, icon) InitializeClass(ToolInit) addInstanceForm = HTMLFile('dtml/addInstance', globals()) def manage_addToolForm(self, REQUEST): """ Show the add tool form. """ # self is a FactoryDispatcher. toolinit = self.toolinit tl = [] for tool in toolinit.tools: tl.append(tool.meta_type) return addInstanceForm(addInstanceForm, self, REQUEST, factory_action='manage_addTool', factory_meta_type=toolinit.meta_type,
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from AccessControl import ClassSecurityInfo from Products.ERP5Type import Permissions, PropertySheet from App.special_dtml import HTMLFile from Products.ERP5Type.XMLObject import XMLObject from Products.PythonScripts.PythonScript import \ PythonScript as ZopePythonScript from Products.ERP5.mixin.expression import ExpressionMixin # Only needed until skin tool is migrated manage_addPythonScriptFormThroughZMI = \ HTMLFile("../dtml/addPythonScriptThroughZMIForm", globals()) def addPythonScriptThroughZMI(self, id, title="", REQUEST=None): """Add a Python script to a folder. """ type_info = self.getPortalObject().portal_types.getTypeInfo("Python Script") type_info.constructInstance( container=self, id=id) if REQUEST is not None: try: u = self.DestinationURL() except: u = REQUEST['URL1'] REQUEST.RESPONSE.redirect(u+'/manage_main') class PythonScriptThroughZMI(XMLObject): """ Dummy class only used to do construction through zmi of PythonScript
from ExtensionClass import Base from DateTime import DateTime # import psycopg and functions/singletons needed for date/time conversions import psycopg2 from psycopg2 import NUMBER, STRING, ROWID, DATETIME from psycopg2.extensions import INTEGER, FLOAT, BOOLEAN, DATE from psycopg2.extensions import TIME from psycopg2.extensions import new_type import psycopg2.extensions DEFAULT_TILEVEL = psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ # add a new connection to a folder manage_addZPsycopgConnectionForm = HTMLFile('dtml/add', globals()) def manage_addZPsycopgConnection(self, id, title, connection_string, zdatetime=None, tilevel=DEFAULT_TILEVEL, encoding='', check=None, REQUEST=None): """Add a DB connection to a folder.""" self._setObject(id, Connection(id, title, connection_string, zdatetime, check, tilevel, encoding)) if REQUEST is not None: return self.manage_main(self, REQUEST) # the connection object class Connection(Shared.DC.ZRDB.Connection.Connection):
class ZMSAttributeContainer(Folder, _objattrs.ObjAttrs, _pathhandler.PathHandler): # Properties. # ----------- meta_type = 'ZMSAttributeContainer' # Management Options. # ------------------- manage_options = ( { 'label': 'Contents', 'action': 'manage_main' }, { 'label': 'Properties', 'action': 'manage_propertiesForm' }, ) # Management Interface. # --------------------- manage_propertiesForm = HTMLFile('dtml/objattrs/manage_propertiesform', globals()) """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"" Constructor """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" "" def __init__(self, id): self.id = id # ---------------------------------------------------------------------------- # ZMSAttributeContainer.getObjAttrs: # # Delegates getObjAttrs to parent. # ---------------------------------------------------------------------------- def getObjAttrs(self, meta_type=None): return self.aq_parent.getObjAttrs(meta_type) # ---------------------------------------------------------------------------- # ZMSAttributeContainer.getObjVersion: # # Overrides method from _versionmanager.VersionManager. # ---------------------------------------------------------------------------- def getObjVersion(self, REQUEST={}): return self # ---------------------------------------------------------------------------- # ZMSAttributeContainer.getParentNode: # # Delegates getParentNode to parent. # ---------------------------------------------------------------------------- getParentNode__roles__ = None def getParentNode(self): """ Delegates getParentNode to parent. """ return self.aq_parent.getParentNode() # ---------------------------------------------------------------------------- # ZMSAttributeContainer.getChildNodes: # ---------------------------------------------------------------------------- def getChildNodes(self, REQUEST={}, meta_types=None, reid=None): return [] ############################################################################## # ZMSAttributeContainer.manage_changeProperties: # # Change properties. ############################################################################## def manage_changeProperties(self, REQUEST, RESPONSE): """ ZMSAttributeContainer.manage_changeProperties """ message = '' for key in self.getObjAttrs().keys(): obj_attr = self.getObjAttr(key) if obj_attr['multilang']: for lang in self.getLangIds(): REQUEST.set('lang', lang) self.setReqProperty(key, REQUEST, 1) else: REQUEST.set('lang', self.getPrimaryLanguage()) self.setReqProperty(key, REQUEST, 1) # Return with message. return RESPONSE.redirect( 'manage_propertiesForm?manage_tabs_message=%s' % (urllib.quote(message)))
from ZODB.DB import DB from Products.TemporaryFolder.mount import MountPoint ADD_TEMPORARY_FOLDER_PERM = "Add Temporary Folder" def constructTemporaryFolder(self, id, title=None, REQUEST=None): """ """ ms = MountedTemporaryFolder(id, title) self._setObject(id, ms) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1) constructTemporaryFolderForm = HTMLFile('dtml/addTemporaryFolder', globals()) class SimpleTemporaryContainer(Folder): # dbtab-style container class meta_type = 'Temporary Folder' icon = 'misc_/TemporaryFolder/tempfolder.gif' class MountedTemporaryFolder(MountPoint, Item): """ A mounted RAM database with a basic interface for displaying the reason the database did not connect. XXX this is only here for backwards compatibility purposes: DBTab uses the SimpleTemporaryContainer class instead.
self.resp = resp def __del__(self): # Free the references. # # No errors of any sort may propagate, and we don't care *what* # they are, even to log them. try: del self.resp.unauthorized except: pass try: del self.resp._unauthorized except: pass try: del self.resp except: pass manage_addCCForm = HTMLFile('dtml/addCC', globals()) manage_addCCForm.__name__ = 'addCC' def _create_forms(ob): ''' Create default forms inside ob ''' import os from OFS.DTMLMethod import addDTMLMethod dtmldir = os.path.join(os.path.dirname(__file__), 'dtml') for fn in ('index_html', 'logged_in', 'logged_out', 'login_form', 'standard_login_footer', 'standard_login_header'): filename = os.path.join(dtmldir, fn + '.dtml') f = open(filename, 'rt') try: data = f.read() finally: f.close() addDTMLMethod(ob, fn, file=data)
class ZLDAPConnection(Acquisition.Implicit, Persistent, OFS.SimpleItem.Item, LDCAccessors.LDAPConnectionAccessors, AccessControl.Role.RoleManager): '''LDAP Connection Object''' isPrincipiaFolderish = 1 meta_type = 'LDAP Connection' manage_options = ( { 'label': 'Connection Properties', 'action': 'manage_main' }, { 'label': 'Open/Close', 'action': 'manage_connection' }, { 'label': 'Browse', 'action': 'manage_browse' }, { 'label': 'Security', 'action': 'manage_access' }, ) __ac_permissions__ = ( ( 'Access contents information', ('canBrowse', ), ), ('View management screens', ('manage_tabs', 'manage_main'), ('Manager', )), ('Edit connection', ('manage_edit', ), ('Manager', )), ('Change permissions', ('manage_access', )), ('Open/Close Connection', ( 'manage_connection', 'manage_open', 'manage_close', ), ('Manager', )), ( 'Browse Connection Entries', ('manage_browse', ), ('Manager', ), ), ) manage_browse = HTMLFile('browse', globals()) manage_connection = HTMLFile('connection', globals()) ### dealing with browseability on the root. def canBrowse(self): """ Returns true if the connection is open *and* the '_canBrowse' property is set to true """ return self.shouldBeOpen() and self.getBrowsable() ### constructor def __init__(self, id, title, host, port, basedn, bind_as, pw, openc, transactional=1): "init method" self._v_conn = None self._v_delete = [] self._v_openc = openc self.openc = openc self.setId(id) self.setTitle(title) self.setHost(host) self.setPort(port) self.setBindAs(bind_as) self.setPW(pw) self.setDN(basedn) self.setOpenConnection(openc) self.setTransactional(transactional) # if connection is specified to be open, open it up if openc: self._open() ### upgrade path... def __setstate__(self, state): # Makes sure we have an Entry class now self._refreshEntryClass() Persistent.__setstate__(self, state) ### Entry Factory stuff def _refreshEntryClass(self): """ This class sets up the Entry class used to return results. """ transactional = self.getTransactional() if transactional: EntryBase = TransactionalEntry else: EntryBase = GenericEntry class LdapEntry(EntryBase, ZopeEntry): pass self._v_entryclass = LdapEntry return LdapEntry def _EntryFactory(self): """ Stamps out an Entry class to be used for every entry returned, taking into account transactional versus non-transactional """ return getattr(aq_base(self), '_v_entryclass', self._refreshEntryClass()) ### Tree stuff def __bobo_traverse__(self, REQUEST, key): key = urllib.unquote(key) if getattr(self, key, None) is not None: return getattr(self, key) return self.getRoot()[key] def tpId(self): return self.id def tpURL(self): return self.id def tpValues(self): if self.canBrowse(): return self.getRoot().tpValues() else: return [] #### TransactionalObjectManager stuff ##### def tpc_begin(self, *ignored): #make sure we're open! if not self.__ping(): #we're not open raise ConnectionError('LDAP Connection is not open for commiting') self._v_okobjects = [] def commit(self, o, *ignored): ' o = object to commit ' # check to see if object exists oko = [] if self.hasEntry(o.dn): oko.append(o) elif o._isNew or o._isDeleted: oko.append(o) self._v_okobjects = oko def tpc_finish(self, *ignored): " really really commit and DON'T FAIL " oko = self._v_okobjects self._isCommitting = 1 d = getattr(self, '_v_delete', []) for deldn in d: self._deleteEntry(deldn) self._v_delete = [] for o in oko: try: if o._isDeleted: pass # we shouldn't need to do anything now that # the mass delete has happened elif o._isNew: self._addEntry(o.dn, o._data.items()) o._isNew = 0 del self._v_add[o.dn] else: o._modify() o._registered = 0 except: pass #XXX We should log errors here del self._v_okobjects del self._isCommitting self.GetConnection().destroy_cache() def tpc_abort(self, *ignored): " really really rollback and DON'T FAIL " try: self._abort() except: pass #XXX We should also log errors here def abort(self, o, *ignored): if o.dn in getattr(self, '_v_delete', ()): self._v_delete.remove(o.dn) if o._isDeleted: o.undelete() o._rollback() o._registered = 0 if o._isNew: if o.dn in getattr(self, '_v_add', {}).keys(): del self._v_add[o.dn] self.GetConnection().destroy_cache() def _abort(self): oko = self._v_okobjects for o in oko: self.abort(o) self.GetConnection().destroy_cache() def tpc_vote(self, *ignored): pass ### getting entries and attributes def hasEntry(self, dn): if getattr(self, '_v_add', {}).has_key(dn): #object is marked for adding return 1 elif dn in getattr(self, '_v_delete', ()): #object is marked for deletion return 0 try: e = self._connection().search_s(dn, ldap.SCOPE_BASE, 'objectclass=*') if e: return 1 except ldap.NO_SUCH_OBJECT: return 0 return 0 def getRawEntry(self, dn): " return raw entry from LDAP module " if getattr(self, '_v_add', {}).has_key(dn): return (dn, self._v_add[dn]._data) elif dn in getattr(self, '_v_delete', ()): raise ldap.NO_SUCH_OBJECT("Entry '%s' has been deleted" % dn) try: e = self._connection().search_s(dn, ldap.SCOPE_BASE, 'objectclass=*') if e: return e[0] except: raise ldap.NO_SUCH_OBJECT("Cannot retrieve entry '%s'" % dn) def getEntry(self, dn, o=None): " return **unwrapped** Entry object, unless o is specified " Entry = self._EntryFactory() if getattr(self, '_v_add', {}).has_key(dn): e = self._v_add[dn] else: e = self.getRawEntry(dn) e = Entry(e[0], e[1], self) if o is not None: return e.__of__(o) else: return e def getRoot(self): " return root entry object " return self.getEntry(self.dn, self) def getAttributes(self, dn): " get raw attributes from entry from LDAP module " return self.getRawEntry(dn)[1] ### listing subentries def getRawSubEntries(self, dn): " get the raw entry objects of entry dn's immediate children " # XXX Do something soon to account for added but noncommited..? if dn in getattr(self, '_v_delete', ()): raise ldap.NO_SUCH_OBJECT results = self._connection().search_s(dn, ldap.SCOPE_ONELEVEL, 'objectclass=*') r = [] for entry in results: #make sure that the subentry isn't marked for deletion if entry[0] not in getattr(self, '_v_delete', ()): r.append(entry) return r def getSubEntries(self, dn, o=None): Entry = self._EntryFactory() r = [] se = self.getRawSubEntries(dn) for entry in se: e = Entry(entry[0], entry[1], self) if o is not None: e = e.__of__(o) r.append(e) return r ### modifying entries def _modifyEntry(self, dn, modlist): if not getattr(self, '_isCommitting', 0): raise AccessError('Cannot modify unless in a commit') #someone's trying to be sneaky and modify an object #outside of a commit. We're not going to allow that! c = self._connection() c.modify_s(dn, modlist) ### deleting entries def _registerDelete(self, dn): " register DN for deletion " d = getattr(self, '_v_delete', []) if dn not in d: d.append(dn) self._v_delete = d def _unregisterDelete(self, dn): " unregister DN for deletion " d = getattr(self, '_v_delete', []) if dn in d: d.remove(dn) self._v_delete = d self._unregisterAdd(dn) def _deleteEntry(self, dn): if not getattr(self, '_isCommitting', 0): raise AccessError('Cannot delete unless in a commit') c = self._connection() c.delete_s(dn) ### adding entries def _registerAdd(self, o): a = getattr(self, '_v_add', {}) if not a.has_key(o.dn): a[o.dn] = o self._v_add = a def _unregisterAdd(self, o=None, dn=None): a = getattr(self, '_v_add', {}) if o and o in a.values(): del a[o.dn] elif dn and a.has_key(dn): del a[dn] self._v_add = a def _addEntry(self, dn, attrs): if not getattr(self, '_isCommitting', 0): raise AccessError('Cannot add unless in a commit') c = self._connection() c.add_s(dn, attrs) ### other stuff def title_and_id(self): "title and id, with conn state" s = ZLDAPConnection.inheritedAttribute('title_and_id')(self) if self.shouldBeOpen(): s = "%s (connected)" % s else: s = '%s (<font color="red"> not connected</font>)' % s return s ### connection checking stuff def _connection(self): if self.getOpenConnection(): if not self.isOpen(): self._open() return self._v_conn else: raise ConnectionError('Connection Closed') GetConnection = _connection def getForcedConnection(self): if self.getOpenConnection(): self._open() return self._v_conn else: raise ConnectionError('Connection Closed') def isOpen(self): " quickly checks to see if the connection's open " if getattr(aq_base(self), '_v_conn', None) is None: self._v_conn = None if self._v_conn is None or not self.shouldBeOpen(): return 0 else: return 1 def __ping(self): " more expensive check on the connection and validity of conn " try: self._connection().whoami_s() return 1 except: self._close() return 0 def _open(self): """ open a connection """ try: self._close() except: pass self._v_conn = ldap.open(self.host, self.port) #Nicolas the version of pythonldap doesn't use the enable_cache method #self._v_conn.enable_cache() try: self._v_conn.simple_bind_s(self.bind_as, self.pw) except ldap.NO_SUCH_OBJECT: return """ Error: LDAP Server returned `no such object' for %s. Possibly the bind string or password are incorrect""" % (self.bind_as) self._v_openc = 1 def manage_open(self, REQUEST=None): """ open a connection. """ self.setOpenConnection(1) ret = self._open() if not getattr(self, '_v_openc', 0): return ret if REQUEST is not None: m = 'Connection has been opened.' return self.manage_connection(self, REQUEST, manage_tabs_message=m) def _close(self): """ close a connection """ if self.getOpenConnection() is None: #I'm already closed, but someone is still trying to close me self._v_conn = None self._v_openc = 0 else: try: self._v_conn.unbind_s() except AttributeError: pass self._v_conn = None self._v_openc = 0 def manage_close(self, REQUEST=None): """ close a connection. """ self._close() if REQUEST is not None: m = 'Connection has been closed.' return self.manage_connection(self, REQUEST, manage_tabs_message=m) def manage_clearcache(self, REQUEST=None): """ clear the cache """ self._connection().destroy_cache() if REQUEST is not None: m = 'Cache has been cleared.' return self.manage_connection(self, REQUEST, manage_tabs_message=m) manage_main = HTMLFile("edit", globals()) def manage_edit(self, title, hostport, basedn, bind_as, pw, openc=0, canBrowse=0, transactional=1, REQUEST=None): """ handle changes to a connection """ self.title = title host, port = splitHostPort(hostport) if self.host != host: self._close() self.setHost(host) if self.port != port: self._close() self.setPort(port) if self.bind_as != bind_as: self._close() self.setBindAs(bind_as) if self.pw != pw: self._close() self.setPW(pw) if openc and not self.getOpenConnection(): self.setOpenConnection(1) ret = self._open() if not self._v_openc: return ret if not openc and self.getOpenConnection(): self.setOpenConnection(0) self._close() self.setBrowsable(canBrowse) self.setTransactional(transactional) self.setDN(basedn) if REQUEST is not None: return MessageDialog( title='Edited', message='<strong>%s</strong> has been edited.' % self.id, action='./manage_main', ) def _isAnLDAPConnection(self): return 1
from __future__ import absolute_import __version__ = "$Revision: 1.11 $"[11:-2] import Acquisition, AccessControl, OFS, string from Acquisition import aq_base from App.special_dtml import HTMLFile from App.Dialogs import MessageDialog from Persistence import Persistent import ldap, urllib from . import LDCAccessors from .Entry import ZopeEntry, GenericEntry, TransactionalEntry ConnectionError = 'ZLDAP Connection Error' manage_addZLDAPConnectionForm = HTMLFile('add', globals()) class NoBrainer: """ Empty class for mixin to EntryFactory """ class ZLDAPConnection(Acquisition.Implicit, Persistent, OFS.SimpleItem.Item, LDCAccessors.LDAPConnectionAccessors, AccessControl.Role.RoleManager): '''LDAP Connection Object''' isPrincipiaFolderish = 1 meta_type = 'LDAP Connection'
class ZMSItem( OFS.ObjectManager.ObjectManager, OFS.SimpleItem.Item, Persistent, # Persistent. Implicit, # Acquisition. ): # Documentation string. __doc__ = """ZMS product module.""" # Version string. __version__ = '0.1' # Management Permissions. # ----------------------- __authorPermissions__ = ('manage_page_request', 'manage_page_header', 'manage_page_footer', 'manage_tabs', 'manage_tabs_sub', 'manage_bodyTop', 'manage_main_iframe') __viewPermissions__ = ('manage_menu', ) __ac_permissions__ = ( ('ZMS Author', __authorPermissions__), ('View', __viewPermissions__), ) # Templates. # ---------- f_bodyContent = HTMLFile('dtml/object/f_bodycontent', globals()) # Template: Body-Content / Element manage = HTMLFile('dtml/object/manage', globals()) manage_workspace = HTMLFile('dtml/object/manage', globals()) # ZMI Manage manage_main = HTMLFile('dtml/ZMSObject/manage_main', globals()) manage_tabs = HTMLFile('dtml/object/manage_tabs', globals()) # ZMI Tabulators manage_tabs_sub = HTMLFile('dtml/object/manage_tabs_sub', globals()) # ZMI Tabulators (Sub) manage_bodyTop = HTMLFile('dtml/object/manage_bodytop', globals()) # ZMI bodyTop manage_page_request = HTMLFile('dtml/object/manage_page_request', globals()) # ZMI Page Request manage_page_header = HTMLFile('dtml/object/manage_page_header', globals()) # ZMI Page Header manage_page_footer = HTMLFile('dtml/object/manage_page_footer', globals()) # ZMI Page Footer manage_main_iframe = HTMLFile('dtml/ZMSObject/manage_main_iframe', globals()) # ZMI Iframe # -------------------------------------------------------------------------- # ZMSItem.display_icon: # # @param REQUEST # -------------------------------------------------------------------------- def display_icon(self, REQUEST, meta_type=None, key='icon', zpt=None): if meta_type is None: return self.icon else: return self.aq_parent.display_icon(REQUEST, meta_type, key, zpt) # -------------------------------------------------------------------------- # ZMSItem.getTitlealt # -------------------------------------------------------------------------- def getTitlealt(self, REQUEST): return self.getZMILangStr(self.meta_type) # -------------------------------------------------------------------------- # ZMSItem.breadcrumbs_obj_path: # -------------------------------------------------------------------------- def breadcrumbs_obj_path(self, portalMaster=True): return self.aq_parent.breadcrumbs_obj_path(portalMaster) ################################################################################
class TableBrowser(Browser, Acquisition.Implicit): icon = 'what' Description = check = '' info = HTMLFile('table_info', globals()) menu = HTMLFile('table_menu', globals()) def tpValues(self): v = values() v._f = self.tpValues_ return v def tpValues_(self): r = [] tname = self.__name__ for d in self._c.columns(tname): b = ColumnBrowser() b._d = d b.icon = d['Icon'] b.TABLE_NAME = tname r.append(b) return r def tpId(self): return self._d['TABLE_NAME'] def tpURL(self): return "Table/%s" % self._d['TABLE_NAME'] def Name(self): return self._d['TABLE_NAME'] def Type(self): return self._d['TABLE_TYPE'] manage_designInput = HTMLFile('designInput', globals()) def manage_buildInput(self, id, source, default, REQUEST=None): "Create a database method for an input form" args = [] values = [] names = [] columns = self._columns for i in range(len(source)): s = source[i] if s == 'Null': continue c = columns[i] d = default[i] t = c['Type'] n = c['Name'] names.append(n) if s == 'Argument': values.append("<!--#sql-value %s type=%s-->'" % (n, vartype(t))) a = '%s%s' % (n, boboType(t)) if d: a = "%s=%s" % (a, d) args.append(a) elif s == 'Property': values.append("<!--#sql-value %s type=%s-->'" % (n, vartype(t))) else: if isStringType(t): if find(d, "\'") >= 0: d = join(split(d, "\'"), "''") values.append("'%s'" % d) elif d: values.append(str(d)) else: raise ValueError, ('no default was given for <em>%s</em>' % n)
class Connection(Shared.DC.ZRDB.Connection.Connection): """ZPsycopg Connection.""" _isAnSQLConnection = 1 id = 'Psycopg2_database_connection' database_type = 'Psycopg2' meta_type = title = 'Z Psycopg 2 Database Connection' zmi_icon = "fas fa-database" def __init__(self, id, title, connection_string, zdatetime, check=None, tilevel=DEFAULT_TILEVEL, encoding='UTF-8'): self.zdatetime = zdatetime self.id = str(id) self.edit(title, connection_string, zdatetime, check=check, tilevel=tilevel, encoding=encoding) def factory(self): return DB ## connection parameters editing ## def edit(self, title, connection_string, zdatetime, check=None, tilevel=DEFAULT_TILEVEL, encoding='UTF-8'): self.title = title self.connection_string = connection_string self.zdatetime = zdatetime self.tilevel = tilevel self.encoding = encoding if check: self.connect(self.connection_string) manage_properties = HTMLFile('dtml/edit', globals()) def manage_edit(self, title, connection_string, zdatetime=None, check=None, tilevel=DEFAULT_TILEVEL, encoding='UTF-8', REQUEST=None): """Edit the DB connection.""" self.edit(title, connection_string, zdatetime, check=check, tilevel=tilevel, encoding=encoding) if REQUEST is not None: msg = "Connection edited." return self.manage_main(self, REQUEST, manage_tabs_message=msg) def connect(self, s): try: self._v_database_connection.close() except: pass # check psycopg version and raise exception if does not match check_psycopg_version(psycopg2.__version__) self._v_connected = '' dbf = self.factory() # TODO: let the psycopg exception propagate, or not? self._v_database_connection = dbf( self.connection_string, self.tilevel, self.get_type_casts(), self.encoding) self._v_database_connection.open() self._v_connected = DateTime() return self def get_type_casts(self): # note that in both cases order *is* important if self.zdatetime: return ZDATETIME, ZDATE, ZTIME else: return DATETIME, DATE, TIME ## browsing and table/column management ## manage_options = Shared.DC.ZRDB.Connection.Connection.manage_options # + ( # {'label': 'Browse', 'action':'manage_browse'},) #manage_tables = HTMLFile('dtml/tables', globals()) #manage_browse = HTMLFile('dtml/browse', globals()) info = None def table_info(self): return self._v_database_connection.table_info() def __getitem__(self, name): if name == 'tableNamed': if not hasattr(self, '_v_tables'): self.tpValues() return self._v_tables.__of__(self) raise KeyError(name) def tpValues(self): res = [] conn = self._v_database_connection for d in conn.tables(rdb=0): try: name = d['TABLE_NAME'] b = TableBrowser() b.__name__ = name b._d = d b._c = conn try: b.icon = table_icons[d['TABLE_TYPE']] except: pass res.append(b) except: pass return res
Instead of providing xml files in GenericSetup profiles for our, workflows we prepare our own Zope2 style factories for registration in the Workflow Tool. """ assert not _workflow_factories.get(id), ( 'Workflow factory with id %r already exists.' % id) _workflow_factories[id] = { 'factory': factory, 'id': id, 'title': title, } # Workflow Creation DTML manage_addWorkflowFormDtml = HTMLFile('dtml/addWorkflow', globals()) def _generateWorkflowConstructors(factory_info): """ Generate a "addWorkflow_?" and "addWorkflowForm_?" methods specific for each workflow factory. """ FACTORY_FORM_PREFIX = 'addWorkflowForm_' FACTORY_ACTION_PREFIX = 'addWorkflow_' workflow_factory_id = factory_info['id'] workflow_factory_title = factory_info['title'] # the method names (last url segments) constructor_form_name = FACTORY_FORM_PREFIX + workflow_factory_id constructor_action_name = FACTORY_ACTION_PREFIX + workflow_factory_id
$Id: DA.py,v 1.10 2009/08/08 08:18:24 nakagami Exp $''' % database_type __version__ = '$Revision: 1.10 $'[11:-2] from db import DB, manage_DataSources import sys, DABase from App.special_dtml import HTMLFile import Shared.DC.ZRDB.Connection, ThreadLock _Connection = Shared.DC.ZRDB.Connection.Connection _connections = {} _connections_lock = ThreadLock.allocate_lock() data_sources = manage_DataSources addConnectionForm = HTMLFile('dtml/connectionAdd', globals()) def manage_addZSQLiteConnection(self, id, title, connection, REQUEST=None): """Add a DB connection to a folder""" # Note - ZSQLiteDA's connect immediately check is alway false self._setObject(id, Connection(id, title, connection, None)) if REQUEST is not None: return self.manage_main(self, REQUEST) class Connection(DABase.Connection): " " database_type = database_type id = '%s_database_connection' % database_type meta_type = title = 'Z %s Database Connection' % database_type
class TableBrowser(Browser, Acquisition.Implicit): icon = 'what' Description = check = '' info = HTMLFile('table_info', globals()) menu = HTMLFile('table_menu', globals()) def tpValues(self): v = values() v._f = self.tpValues_ return v def tpValues_(self): r = [] tname = self.__name__ for d in self._c.columns(tname): b = ColumnBrowser() b._d = d try: b.icon = field_icons[d['Type']] except: pass b.TABLE_NAME = tname r.append(b) return r def tpId(self): return self._d['TABLE_NAME'] def tpURL(self): return "Table/%s" % self._d['TABLE_NAME'] def Name(self): return self._d['TABLE_NAME'] def Type(self): return self._d['TABLE_TYPE'] manage_designInput = HTMLFile('designInput', globals()) @staticmethod def vartype(inVar): """Get a type name for a variable suitable for use with dtml-sqlvar""" outVar = type(inVar) if outVar == 'str': outVar = 'string' return outVar def manage_buildInput(self, id, source, default, REQUEST=None): """Create a database method for an input form""" args = [] values = [] names = [] columns = self._columns for i in range(len(source)): s = source[i] if s == 'Null': continue c = columns[i] d = default[i] t = c['Type'] n = c['Name'] names.append(n) if s == 'Argument': values.append("<dtml-sqlvar %s type=%s>'" % (n, self.vartype(t))) a = '%s%s' % (n, self.vartype(t).title()) if d: a = "%s=%s" % (a, d) args.append(a) elif s == 'Property': values.append("<dtml-sqlvar %s type=%s>'" % (n, self.vartype(t))) else: if isinstance(t, str): if d.find("\'") >= 0: d = "''".join(d.split("\'")) values.append("'%s'" % d) elif d: values.append(str(d)) else: raise ValueError( 'no default was given for <em>%s</em>' % n)
def manage_changeLangDictProperties(self, lang, REQUEST, RESPONSE): """ MultiLanguageManager.manage_changeLangDictProperties """ # Delete. # ------- if REQUEST['btn'] == self.getZMILangStr('BTN_DELETE'): ids = REQUEST.get('ids',[]) dict = self.get_lang_dict() lang_dict = {} for id in dict.keys(): if not id in ids: lang_dict[id] = dict[id] self.setConfProperty('ZMS.custom.langs.dict',lang_dict.copy()) # Change. # ------- elif REQUEST['btn'] == self.getZMILangStr('BTN_SAVE'): d = self.get_lang_dict() lang_dict = {} for key in d.keys(): for lang_id in self.getLangIds(): lang_dict[key] = lang_dict.get(key,{}) enabled = lang_id not in d[key].get('acquired',[]) if enabled: lang_dict[key][lang_id] = REQUEST['%s_value_%s'%(key,lang_id)].strip() # Insert key = REQUEST['_key'].strip() if len(key) > 0: lang_dict = self.get_lang_dict() lang_dict[key] = {} for lang_id in self.getLangIds(): lang_dict[key][lang_id] = REQUEST['_value_%s'%lang_id].strip() self.setConfProperty('ZMS.custom.langs.dict',lang_dict.copy()) # Export. # ------- elif REQUEST['btn'] == self.getZMILangStr('BTN_EXPORT'): value = [] ids = REQUEST.get('ids',[]) dict = self.get_lang_dict() for id in dict.keys(): item = dict[id].copy() item['key'] = id if id in ids or len(ids) == 0: value.append(item) REQUEST.set('context',self) REQUEST.set('value',value) tmplt = HTMLFile('dtml/ZMS/manage_exportlanguages', globals()) export = tmplt(self,REQUEST) return export # Import. # ------- elif REQUEST['btn'] == self.getZMILangStr('BTN_IMPORT'): f = REQUEST['file'] if f: filename = f.filename importXml(self,xml=f) else: filename = REQUEST['init'] createIfNotExists = 1 self.importConf(filename, REQUEST, createIfNotExists) message = self.getZMILangStr('MSG_IMPORTED')%('<i>%s</i>'%filename) # Return with message. message = urllib.quote(self.getZMILangStr('MSG_CHANGED')) return RESPONSE.redirect('manage_customizeLanguagesForm?lang=%s&manage_tabs_message=%s#langdict'%(lang,message))
class SyndicationTool(UniqueObject, SimpleItem): """ The syndication tool manages the site-wide policy for syndication of folder content as RSS. """ implements(ISyndicationTool) id = 'portal_syndication' meta_type = 'Default Syndication Tool' security = ClassSecurityInfo() #Default Sitewide Values isAllowed = 0 syUpdatePeriod = 'daily' syUpdateFrequency = 1 syUpdateBase = DateTime() max_items = 15 #ZMI Methods manage_options = ( ( { 'label' : 'Overview' , 'action' : 'overview' , 'help' : ( 'CMFDefault' , 'Syndication-Tool_Overview.stx' ) } ,{ 'label' : 'Properties' , 'action' : 'propertiesForm' , 'help' : ( 'CMFDefault' , 'Syndication-Tool_Properties.stx' ) } ,{ 'label' : 'Policies' , 'action' : 'policiesForm' , 'help' : ( 'CMFDefault' , 'Syndication-Tool_Policies.stx' ) } ,{ 'label' : 'Reports' , 'action' : 'reportForm' , 'help' : ( 'CMFDefault' , 'Syndication-Tool_Reporting.stx' ) } ) ) security.declareProtected(ManagePortal, 'overview') overview = HTMLFile('synOverview', _dtmldir) security.declareProtected(ManagePortal, 'propertiesForm') propertiesForm = HTMLFile('synProps', _dtmldir) security.declareProtected(ManagePortal, 'policiesForm') policiesForm = HTMLFile('synPolicies', _dtmldir) security.declareProtected(ManagePortal, 'reportForm') reportForm = HTMLFile('synReports', _dtmldir) security.declareProtected(ManagePortal, 'editProperties') def editProperties( self , updatePeriod=None , updateFrequency=None , updateBase=None , isAllowed=None , max_items=None , REQUEST=None ): """ Edit the properties for the SystemWide defaults on the SyndicationTool. """ if isAllowed is not None: self.isAllowed = isAllowed if updatePeriod is not None: self.syUpdatePeriod = updatePeriod else: try: del self.syUpdatePeriod except (AttributeError, KeyError): pass if updateFrequency is not None: self.syUpdateFrequency = int(updateFrequency) else: try: del self.syUpdateFrequency except (AttributeError, KeyError): pass if updateBase is not None: if type( updateBase ) is type( '' ): updateBase = DateTime( updateBase ) self.syUpdateBase = updateBase else: try: del self.syUpdateBase except (AttributeError, KeyError): pass if max_items is not None: self.max_items = int(max_items) else: try: del self.max_items except (AttributeError, KeyError): pass if REQUEST is not None: REQUEST['RESPONSE'].redirect( self.absolute_url() + '/propertiesForm' + '?manage_tabs_message=Tool+Updated.' ) security.declarePublic( 'editSyInformationProperties' ) def editSyInformationProperties( self , obj , updatePeriod=None , updateFrequency=None , updateBase=None , max_items=None , REQUEST=None ): """ Edit syndication properties for the obj being passed in. These are held on the syndication_information object. Not Sitewide Properties. """ if not _checkPermission( ManageProperties, obj ): raise AccessControl_Unauthorized syInfo = getattr(obj, 'syndication_information', None) if syInfo is None: raise 'Syndication is Disabled' if updatePeriod is not None: syInfo.syUpdatePeriod = updatePeriod else: syInfo.syUpdatePeriod = self.syUpdatePeriod if updateFrequency is not None: syInfo.syUpdateFrequency = int(updateFrequency) else: syInfo.syUpdateFrequency = self.syUpdateFrequency if updateBase is not None: if type( updateBase ) is type( '' ): updateBase = DateTime( updateBase ) syInfo.syUpdateBase = updateBase else: syInfo.syUpdateBase = self.syUpdateBase if max_items is not None: syInfo.max_items = int(max_items) else: syInfo.max_items = self.max_items security.declarePublic('enableSyndication') def enableSyndication(self, obj): """ Enable syndication for the obj """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is Disabled' if hasattr(aq_base(obj), 'syndication_information'): raise 'Syndication Information Exists' syInfo = SyndicationInformation() obj._setObject('syndication_information', syInfo) syInfo = obj._getOb('syndication_information') syInfo.syUpdatePeriod = self.syUpdatePeriod syInfo.syUpdateFrequency = self.syUpdateFrequency syInfo.syUpdateBase = self.syUpdateBase syInfo.max_items = self.max_items syInfo.description = "Channel Description" security.declarePublic('disableSyndication') def disableSyndication(self, obj): """ Disable syndication for the obj; and remove it. """ syInfo = getattr(obj, 'syndication_information', None) if syInfo is None: raise 'This object does not have Syndication Information' obj._delObject('syndication_information') security.declarePublic('getSyndicatableContent') def getSyndicatableContent(self, obj): """ An interface for allowing folderish items to implement an equivalent of PortalFolderBase.contentValues() """ if hasattr(obj, 'synContentValues'): values = obj.synContentValues() else: values = PortalFolderBase.contentValues(obj) return values security.declarePublic('buildUpdatePeriods') def buildUpdatePeriods(self): """ Return a list of possible update periods for the xmlns: sy """ updatePeriods = ( ('hourly', 'Hourly') , ('daily', 'Daily') , ('weekly', 'Weekly') , ('monthly', 'Monthly') , ('yearly', 'Yearly') ) return updatePeriods security.declarePublic('isSiteSyndicationAllowed') def isSiteSyndicationAllowed(self): """ Return sitewide syndication policy """ return self.isAllowed security.declarePublic('isSyndicationAllowed') def isSyndicationAllowed(self, obj=None): """ Check whether syndication is enabled for the site. This provides for extending the method to check for whether a particular obj is enabled, allowing for turning on only specific folders for syndication. """ syInfo = getattr(aq_base(obj), 'syndication_information', None) if syInfo is None: return 0 else: return self.isSiteSyndicationAllowed() security.declarePublic('getUpdatePeriod') def getUpdatePeriod( self, obj=None ): """ Return the update period for the RSS syn namespace. This is either on the object being passed or the portal_syndication tool (if a sitewide value or default is set) NOTE: Need to add checks for sitewide policies!!! """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is Not Allowed' if obj is None: return self.syUpdatePeriod syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: return syInfo.syUpdatePeriod else: return 'Syndication is Not Allowed' security.declarePublic('getUpdateFrequency') def getUpdateFrequency(self, obj=None): """ Return the update frequency (as a positive integer) for the syn namespace. This is either on the object being pass or the portal_syndication tool (if a sitewide value or default is set). Note: Need to add checks for sitewide policies!!! """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is not Allowed' if obj is None: return self.syUpdateFrequency syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: return syInfo.syUpdateFrequency else: return 'Syndication is not Allowed' security.declarePublic('getUpdateBase') def getUpdateBase(self, obj=None): """ Return the base date to be used with the update frequency and the update period to calculate a publishing schedule. Note: I'm not sure what's best here, creation date, last modified date (of the folder being syndicated) or some arbitrary date. For now, I'm going to build a updateBase time from zopetime and reformat it to meet the W3CDTF. Additionally, sitewide policy checks might have a place here... """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is not Allowed' if obj is None: when = self.syUpdateBase return when.ISO() syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: when = syInfo.syUpdateBase return when.ISO() else: return 'Syndication is not Allowed' security.declarePublic('getHTML4UpdateBase') def getHTML4UpdateBase(self, obj=None): """ Return HTML4 formated UpdateBase DateTime """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is not Allowed' if obj is None: when = self.syUpdateBase return when.HTML4() syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: when = syInfo.syUpdateBase return when.HTML4() else: return 'Syndication is not Allowed' def getMaxItems(self, obj=None): """ Return the max_items to be displayed in the syndication """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is not Allowed' if obj is None: return self.max_items syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: return syInfo.max_items else: return 'Syndication is not Allowed'
listFolderHierarchy(ob, '', rval, adding_meta_type) rval.sort() return rval security.declareProtected(ACI, 'getDirPath') def getDirPath(self): return self.__dict__['_real']._dirpath security.declarePublic('getId') def getId(self): return self.id InitializeClass(DirectoryViewSurrogate) manage_addDirectoryViewForm = HTMLFile('dtml/addFSDirView', globals()) def createDirectoryView(parent, reg_key, id=None): """ Add either a DirectoryView or a derivative object. """ info = _dirreg.getDirectoryInfo(reg_key) if info is None: reg_key = _dirreg.getCurrentKeyFormat(reg_key) info = _dirreg.getDirectoryInfo(reg_key) warn('createDirectoryView() called with deprecated reg_key format. ' 'Support for old key formats will be removed in CMF 2.3. Please ' 'use the new key format <product>:<subdir> instead.', DeprecationWarning, stacklevel=2) if not id: id = reg_key.split('/')[-1] else: