""" Very simple volatile-attribute-based caching. Especially useful to cache processed pseudo-constants in PythonScripts: cached value will be set as a volatile on the PythonScript, so it gets flushed when script is edited. For such use, it would be even better to be able to put evaluate-once code in PythonScripts (ie, make python scripts really become Python *Scripts*, not "python-function-body-and-parameters"). NOTE: This patches OFS.Item.SimpleItem as it's the lowest patchable class before persistence.Persistent, where this patch would actually belong. """ security = ClassSecurityInfo() security.declarePublic('volatileCached') def volatileCached(self, func): """ Cache "func()" return value using a volatile on self. Return that value, calling func only if needed. Usual volatile rules apply: - outlives transaction duration - bound to a thread only while a transaction is executed (ie, it can be reused by a different thread on next processed transaction) - destroyed when object is modified by another transaction - destroyed when object is modified by transaction and transaction gets aborted - destroyed when connection cache is minimized and holder (self) is pruned
res = ex.getResult() else: if hasattr(aq_base(instance), 'reindexObject'): instance.reindexObject() else: res = wf.wrapWorkflowMethod(instance, self._id, self._m, (instance, ) + args, kw) from Products.CMFCore import WorkflowCore # BBB: WorkflowMethod has been removed from CMFCore 2 WorkflowCore.WorkflowAction = WorkflowMethod # XXX: Kept here instead of ERP5Type.Tool.WorkflowTool because not used in # erp5.git: is it used in projects? security.declarePublic('canDoActionFor') def canDoActionFor(self, ob, action, wf_id=None, guard_kw={}): """ Check we can perform the given workflow action on 'ob'. """ if wf_id is None: workflow_list = self.getWorkflowValueListFor(ob) or () else: workflow = self._getOb(wf_id, None) if workflow: workflow_list = (workflow, ) else: workflow_list = () for workflow in workflow_list:
# not in cache, ask LDAPUserFolder zope_user = self._get_zope_user(user_id) if zope_user is None: raise LDAPUserNotFound(user_id) return user_info_from_zope_user(self, zope_user, self.default_encoding) def has_user(self, user_id): if ldap_cache.has(self._user_dn_from_id(user_id)): return True elif self._get_zope_user(user_id) is not None: return True else: return False security.declarePublic("interface_html") interface_html = PageTemplateFile("plugLDAPUserFolder", globals()) security.declarePublic("section_manage_all_html") section_manage_all_html = PageTemplateFile("plugLDAPUserFolderManage", globals()) security.declarePublic("section_assign_to_users_html") section_assign_to_users_html = PageTemplateFile("plugLDAPUserFolderAssignUsers", globals()) security.declarePublic("section_assign_to_groups_html") section_assign_to_groups_html = PageTemplateFile("plugLDAPUserFolderAssignGroups", globals()) security.declarePublic("section_group_members_html") section_group_members_html = PageTemplateFile("plugLDAPUserFolderGroupMembers", globals()) security.declareProtected(manage_users, "pickroles_html")
""" Very simple volatile-attribute-based caching. Especially useful to cache processed pseudo-constants in PythonScripts: cached value will be set as a volatile on the PythonScript, so it gets flushed when script is edited. For such use, it would be even better to be able to put evaluate-once code in PythonScripts (ie, make python scripts really become Python *Scripts*, not "python-function-body-and-parameters"). NOTE: This patches OFS.Item.SimpleItem as it's the lowest patchable class before persistence.Persistent, where this patch would actually belong. """ security = ClassSecurityInfo() security.declarePublic('volatileCached') def volatileCached(self, func): """ Cache "func()" return value using a volatile on self. Return that value, calling func only if needed. Usual volatile rules apply: - outlives transaction duration - bound to a thread only while a transaction is executed (ie, it can be reused by a different thread on next processed transaction) - destroyed when object is modified by another transaction - destroyed when object is modified by transaction and transaction gets aborted - destroyed when connection cache is minimized and holder (self) is pruned (minimization can be triggered in many places...)
from Acquisition import aq_base, aq_inner, aq_parent from AccessControl import Unauthorized from Products.CMFPlone.utils import _createObjectByType from zope.event import notify from zope.lifecycleevent import ObjectCreatedEvent from zope.component import createObject from Products.Archetypes.event import ObjectInitializedEvent, ObjectEditedEvent from ubify.recyclebin import movetotrash security = ClassSecurityInfo() # This is public because we don't know what permissions the user # has on the objects to be deleted. The restrictedTraverse and # manage_delObjects calls should handle permission checks for us. security.declarePublic('deleteObjectsByPaths') def deleteObjectsByPaths(context,paths, handle_errors=True, REQUEST=None): failure = {} success = [] # use the portal for traversal in case we have relative paths portal = getToolByName(context, 'portal_url').getPortalObject() traverse = portal.restrictedTraverse for path in paths: # Skip and note any errors if handle_errors: sp = transaction.savepoint(optimistic=True) try: obj = traverse(path) obj_parent = aq_parent(aq_inner(obj)) movetotrash(obj) obj_parent.manage_delObjects([obj.getId()])
WorkflowTool.getFutureStateSetFor = lambda self, wf_id, *args, **kw: \ self[wf_id].getFutureStateSet(*args, **kw) def WorkflowTool_isTransitionPossible(self, ob, transition_id, wf_id=None): """Test if the given transition exist from the current state. """ for workflow in (wf_id and (self[wf_id], ) or self.getWorkflowsFor(ob)): state = workflow._getWorkflowStateOf(ob) if state and transition_id in state.transitions: return 1 return 0 security.declarePublic('isTransitionPossible') WorkflowTool.isTransitionPossible = WorkflowTool_isTransitionPossible def WorkflowTool_getWorkflowChainDict(self, sorted=True): """Returns workflow chain compatible with workflow_chain_dict signature""" chain = self._chains_by_type.copy() return_dict = {} for portal_type, workflow_id_list in chain.iteritems(): if sorted: workflow_id_list = list(workflow_id_list) workflow_id_list.sort() return_dict['chain_%s' % portal_type] = ', '.join(workflow_id_list) return return_dict
Generic, Indexed, _CompositeQuery, LiteralResultSet, ) from eval import eval as _eval from ranking import RankByQueries_Sum, RankByQueries_Max ############################################################################ ## Security _allow_module("Products.AdvancedQuery") _s = ClassSecurityInfo() _s.declarePublic("addSubquery") _CompositeQuery._s = _s InitializeClass(_CompositeQuery) ############################################################################ ## ZCatalog extension def _makeAdvancedQuery(self, catalogSearchSpec): """advanced query corresponding to *catalogSearchSpec* (a dictionary).""" q = And() get = catalogSearchSpec.get for i in self.Indexes.objectIds(): vi = get(i) if vi is None or vi == "": continue if not (isinstance(vi, dict) and vi.get("query") is not None or getattr(vi, "query", None) is not None):
from Acquisition import aq_base, aq_inner, aq_parent from AccessControl import Unauthorized from Products.CMFPlone.utils import _createObjectByType from zope.event import notify from zope.lifecycleevent import ObjectCreatedEvent from zope.component import createObject from Products.Archetypes.event import ObjectInitializedEvent, ObjectEditedEvent from ubify.recyclebin import movetotrash security = ClassSecurityInfo() # This is public because we don't know what permissions the user # has on the objects to be deleted. The restrictedTraverse and # manage_delObjects calls should handle permission checks for us. security.declarePublic('deleteObjectsByPaths') def deleteObjectsByPaths(context, paths, handle_errors=True, REQUEST=None): failure = {} success = [] # use the portal for traversal in case we have relative paths portal = getToolByName(context, 'portal_url').getPortalObject() traverse = portal.restrictedTraverse for path in paths: # Skip and note any errors if handle_errors: sp = transaction.savepoint(optimistic=True) try: obj = traverse(path) obj_parent = aq_parent(aq_inner(obj))
WorkflowTool.setStatusOf = WorkflowTool_setStatusOf WorkflowTool.getFutureStateSetFor = lambda self, wf_id, *args, **kw: \ self[wf_id].getFutureStateSet(*args, **kw) def WorkflowTool_isTransitionPossible(self, ob, transition_id, wf_id=None): """Test if the given transition exist from the current state. """ for workflow in (wf_id and (self[wf_id],) or self.getWorkflowsFor(ob)): state = workflow._getWorkflowStateOf(ob) if state and transition_id in state.transitions: return 1 return 0 security.declarePublic('isTransitionPossible') WorkflowTool.isTransitionPossible = WorkflowTool_isTransitionPossible def WorkflowTool_getWorkflowChainDict(self, sorted=True): """Returns workflow chain compatible with workflow_chain_dict signature""" chain = self._chains_by_type.copy() return_dict = {} for portal_type, workflow_id_list in chain.iteritems(): if sorted: workflow_id_list = list(workflow_id_list) workflow_id_list.sort() return_dict['chain_%s' % portal_type] = ', '.join(workflow_id_list) return return_dict security.declareProtected(Permissions.ManagePortal, 'getWorkflowChainDict') WorkflowTool.getWorkflowChainDict = WorkflowTool_getWorkflowChainDict
for id in ids: self.deleteDocument(self.getDocument(id)) security.declareProtected( config.REMOVE_PERMISSION, 'manage_deleteDocuments') def manage_deleteDocuments(self, REQUEST): """ Delete documents action. """ strids = REQUEST.get('deldocs', None) if strids is not None: ids = [i for i in strids.split('@') if i is not ''] self.deleteDocuments(ids=ids, massive=False) # Trigger events REQUEST.RESPONSE.redirect('.') security.declarePublic('getIndex') def getIndex(self): """ Return the database index. """ return getattr(self, 'plomino_index') security.declarePublic('getAllDocuments') def getAllDocuments(self, getObject=True): """ Return all the database documents. """ if getObject is False: # XXX: TODO: Return brains pass return self.documents.values()
from Globals import InitializeClass from AdvancedQuery import Eq, In, Le, Ge, \ MatchGlob, MatchRegexp, \ Between, Not, And, Or, Generic, Indexed, \ _CompositeQuery, LiteralResultSet from eval import eval as _eval from ranking import RankByQueries_Sum, RankByQueries_Max ############################################################################ ## Security _allow_module('Products.AdvancedQuery') _s = ClassSecurityInfo() _s.declarePublic('addSubquery') _CompositeQuery._s = _s InitializeClass(_CompositeQuery) ############################################################################ ## ZCatalog extension def _makeAdvancedQuery(self, catalogSearchSpec): '''advanced query corresponding to *catalogSearchSpec* (a dictionary).''' q = And() get = catalogSearchSpec.get for i in self.Indexes.objectIds(): vi = get(i) if vi is None or vi == '': continue if not (isinstance(vi, dict) and vi.get('query') is not None or getattr(vi, 'query', None) is not None):
if HAS_PEF3: from Products.PloneExFile.ExFile import PloneExFile # PloneArticle 3.x support try: from Products.PloneArticle.PloneArticle import PloneArticle HAS_PA3 = True except ImportError, e: HAS_PA3 = False security = ClassSecurityInfo() # Make fckAbsUrl importable TTW security.declarePublic('fckAbsUrl') def fckAbsUrl(obj_url, portal_url, server_url, text): """ Find real absolute url for href and img """ # obj_url = self.absolute_url() html = text portal_path = portal_url.replace(server_url,'') # Method to replace src and href link by new one def replace_locale_url(match): """Compute local url """ url = str(match.group('url')) attribute = str(match.group('attribute')) if match.group('protocol') is not None:
from AccessControl import ClassSecurityInfo from App.special_dtml import DTMLFile from App.Management import Navigation from OFS.ObjectManager import ObjectManager import Products import os security = ClassSecurityInfo() security.declarePublic("manage_zmi_logout") LOGO_HTML = """\ <div style="margin: 22px 0 22px 0"> <a href="<dtml-var "REQUEST.SERVER_URL" html_quote>"><img src="<dtml-var "REQUEST.SERVER_URL" html_quote>/++resource++plone-logo.png"></a> </div> """ ZMI_WARNING_HTML = """\ <div class="alert alert-error"><strong>Warning:</strong> <span>The Zope Management Interface (ZMI) is a very dangerous place to be. It provides direct access to Zope database (ZODB) objects. As such, you should not attempt to edit, cut, copy, paste, add, or remove content or change any settings here, unless you know exactly what you are doing. You have been warned! Changing these settings will void any and all Plone warranties, both written and implied. Please do not contact the Plone team about any damage caused by ZMI changes. </div></tr><tr> """
except ImportError: from Globals import InitializeClass from AdvancedQuery import Eq, In, Le, Ge, \ MatchGlob, MatchRegexp, \ Between, Not, And, Or, Generic, Indexed, \ _CompositeQuery, LiteralResultSet from eval import eval as _eval from ranking import RankByQueries_Sum, RankByQueries_Max ############################################################################ ## Security _allow_module('Products.AdvancedQuery') _s = ClassSecurityInfo(); _s.declarePublic('addSubquery') _CompositeQuery._s = _s; InitializeClass(_CompositeQuery) ############################################################################ ## ZCatalog extension def _makeAdvancedQuery(self,catalogSearchSpec): '''advanced query corresponding to *catalogSearchSpec* (a dictionary).''' q = And(); get = catalogSearchSpec.get for i in self.Indexes.objectIds(): vi = get(i) if vi is None or vi == '': continue if not (isinstance(vi, dict) and vi.get('query') is not None or getattr(vi, 'query', None) is not None): usage = get(i+'_usage') if usage is not None:
WorkflowTool.setStatusOf = WorkflowTool_setStatusOf WorkflowTool.getFutureStateSetFor = lambda self, wf_id, *args, **kw: self[wf_id].getFutureStateSet(*args, **kw) def WorkflowTool_isTransitionPossible(self, ob, transition_id, wf_id=None): """Test if the given transition exist from the current state. """ for workflow in wf_id and (self[wf_id],) or self.getWorkflowsFor(ob): state = workflow._getWorkflowStateOf(ob) if state and transition_id in state.transitions: return 1 return 0 security.declarePublic("isTransitionPossible") WorkflowTool.isTransitionPossible = WorkflowTool_isTransitionPossible def WorkflowTool_getWorkflowChainDict(self, sorted=True): """Returns workflow chain compatible with workflow_chain_dict signature""" chain = self._chains_by_type.copy() return_dict = {} for portal_type, workflow_id_list in chain.iteritems(): if sorted: workflow_id_list = list(workflow_id_list) workflow_id_list.sort() return_dict["chain_%s" % portal_type] = ", ".join(workflow_id_list) return return_dict
# not in cache, ask LDAPUserFolder zope_user = self._get_zope_user(user_id) if zope_user is None: raise LDAPUserNotFound(user_id) return user_info_from_zope_user(self, zope_user, self.default_encoding) def has_user(self, user_id): if ldap_cache.has(self._user_dn_from_id(user_id)): return True elif self._get_zope_user(user_id) is not None: return True else: return False security.declarePublic('interface_html') interface_html = PageTemplateFile('plugLDAPUserFolder', globals()) security.declarePublic('section_manage_all_html') section_manage_all_html = PageTemplateFile('plugLDAPUserFolderManage', globals()) security.declarePublic('section_assign_to_users_html') section_assign_to_users_html = PageTemplateFile( 'plugLDAPUserFolderAssignUsers', globals()) security.declarePublic('section_assign_to_groups_html') section_assign_to_groups_html = PageTemplateFile( 'plugLDAPUserFolderAssignGroups', globals()) security.declarePublic('section_group_members_html')
from AccessControl import ClassSecurityInfo security = ClassSecurityInfo() PROJECTNAME = 'CMFPlomino' VERSION = '1.13' security.declarePublic('ADD_DESIGN_PERMISSION') ADD_DESIGN_PERMISSION = 'CMFPlomino: Add Plomino design elements' security.declarePublic('ADD_CONTENT_PERMISSION') ADD_CONTENT_PERMISSION = 'CMFPlomino: Add Plomino content' security.declarePublic('READ_PERMISSION') READ_PERMISSION = 'CMFPlomino: Read documents' security.declarePublic('EDIT_PERMISSION') EDIT_PERMISSION = 'CMFPlomino: Edit documents' security.declarePublic('CREATE_PERMISSION') CREATE_PERMISSION = 'CMFPlomino: Create documents' security.declarePublic('REMOVE_PERMISSION') REMOVE_PERMISSION = 'CMFPlomino: Remove documents' security.declarePublic('DESIGN_PERMISSION') DESIGN_PERMISSION = 'CMFPlomino: Modify Database design' security.declarePublic('ACL_PERMISSION') ACL_PERMISSION = 'CMFPlomino: Control Database ACL' FIELD_TYPES = { "TEXT": ["Text", "FieldIndex"], "NUMBER": ["Number", "FieldIndex"], #"FLOAT": ["Float", "FieldIndex"], "RICHTEXT": ["Rich text", "ZCTextIndex"], "DATETIME": ["Date/Time", "DateIndex"],
for id in ids: self.deleteDocument(self.getDocument(id)) security.declareProtected(config.REMOVE_PERMISSION, 'manage_deleteDocuments') def manage_deleteDocuments(self, REQUEST): """ Delete documents action. """ strids = REQUEST.get('deldocs', None) if strids is not None: ids = [i for i in strids.split('@') if i is not ''] self.deleteDocuments(ids=ids, massive=False) # Trigger events REQUEST.RESPONSE.redirect('.') security.declarePublic('getIndex') def getIndex(self): """ Return the database index. """ return getattr(self, 'plomino_index') security.declarePublic('getAllDocuments') def getAllDocuments(self, getObject=True): """ Return all the database documents. """ if getObject is False: # XXX: TODO: Return brains pass return self.documents.values()