Esempio n. 1
0
    def patch_class_security(self, klass, method_name, new_permission):
        """Monkey patch class security definitions to protect a method with
        a different permission.
        """
        def reset_security_for_attribute(name, klass):
            """Remove security declarations for a particular method /
            attribute by filtering declarations for that attribute from
            __ac_permissions__.
            """
            new_ac_permissions = []

            for permission_mapping in klass.__ac_permissions__:
                permission, names = permission_mapping
                if name not in names:
                    new_ac_permissions.append(permission_mapping)
                else:
                    new_names = tuple([n for n in names if n != name])
                    modified_mapping = (permission, new_names)
                    new_ac_permissions.append(modified_mapping)

            klass.__ac_permissions__ = tuple(new_ac_permissions)

        reset_security_for_attribute(method_name, klass)
        sec = ClassSecurityInfo()
        sec.declareProtected(new_permission, method_name)
        sec.apply(klass)
        InitializeClass(klass)
Esempio n. 2
0
class ZClassSecurityInfo(object):
    """Use AccessControl.ClassSecurityInfo as a function decorator."""
    def __init__(self):
        """Initialize a ZClassSecurityInfo instance."""
        self.__csi = ClassSecurityInfo()

    def private(self, f):
        """Declare the given function as private."""
        self.__csi.declarePrivate(f.func_name)
        return f

    def protected(self, permission):
        """Declare the given function as protected."""
        def wrap(f):
            self.__csi.declareProtected(permission, f.func_name)
            return f

        return wrap

    def __getattr__(self, name):
        """Return the value of the named attribute."""
        return getattr(self.__csi, name)
Esempio n. 3
0
               '') != 'CMF Skins Tool':  # It is not a skin tool we're below.
        return
    _updateCacheEntry = getattr(portal_skins.aq_base, '_updateCacheEntry',
                                None)
    if _updateCacheEntry is None:
        return
    _updateCacheEntry(self.id, id)


Folder._setOb = Folder_setOb


def Folder_isERP5SitePresent(self):
    """ Return True if a ERP5 Site is present as subobject. This is
      usefull to identify if a erp5 is present already on a Zope
      Setup.
  """
    return len(self.objectIds("ERP5 Site")) > 0


Folder.isERP5SitePresent = Folder_isERP5SitePresent

security = ClassSecurityInfo()
security.declareProtected(Permissions.ManagePortal, 'isERP5SitePresent')
Folder.security = security
InitializeClass(Folder)

# restore __repr__ after persistent > 4.4
# https://github.com/zopefoundation/Zope/issues/379
Folder.__repr__ = Item.__repr__
Esempio n. 4
0
    p = subprocess.Popen((DCWorkflowGraph.bin_search(DOT_EXE),
                          '-Nfontname=IPAexGothic', '-Nfontsize=10',
                          '-Efontname=IPAexGothic', '-Efontsize=10',
                          '-T%s' % format),
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    result = p.communicate(result)[0]

    setHeader('Content-Type', 'image/%s' % format)
  else:
    filename = wf_id or self.getId()
    setHeader('Content-Type', 'text/x-graphviz')
    setHeader('Content-Disposition', 'attachment; filename=%s.dot' % filename)

  if not result:
    LOG("ERP5Type.patches.DCWorkflowGraph", WARNING,
        "Empty %s graph file" % format)

  return result

DCWorkflowGraph.getGraph = getGraph

from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition
DCWorkflowDefinition.getGraph = getGraph
DCWorkflowDefinition.getPOT = DCWorkflowGraph.getPOT

security = ClassSecurityInfo()
security.declareProtected(Permissions.ManagePortal, 'getPOT')
security.declareProtected(Permissions.ManagePortal, 'getGraph')
DCWorkflowDefinition.security = security
InitializeClass(DCWorkflowDefinition)
Esempio n. 5
0
# BBB: A production instance used a temporary patch to speed up.
WorkflowHistoryBucketList = WorkflowHistoryList


def WorkflowTool_getChainDict(self):
    """Test if the given transition exist from the current state.
    """
    chain_dict = {}
    for portal_type, wf_id_list in self._chains_by_type.iteritems():
        for wf_id in wf_id_list:
            chain_dict.setdefault(wf_id, []).append(portal_type)
    return chain_dict


security.declareProtected(Permissions.ManagePortal, 'getChainDict')
WorkflowTool.getChainDict = WorkflowTool_getChainDict

# Backward compatibility, as WorkflowMethod has been removed in CMFCore 2.2
from MethodObject import Method


class WorkflowMethod(Method):
    """ Wrap a method to workflow-enable it.
    """
    _need__name__ = 1

    def __init__(self, method, id=None, reindex=1):
        self._m = method
        if id is None:
            id = method.__name__
Esempio n. 6
0
            if column_id in value_column_dict:
              value_column_dict[column_id].append(value)
        if len(value_column_dict[COUNT_COLUMN_TITLE]):
          try:
            Base_zInsertIntoWorklistTable(**value_column_dict)
          except (ProgrammingError, OperationalError), error_value:
            # OperationalError 1054 = unknown column
            if isinstance(error_value, OperationalError) and error_value[0] != 1054:
              raise
            LOG('WorkflowTool', 100, 'Insertion in worklist cache table ' \
                'failed. Recreating table and retrying.',
                error=sys.exc_info())
            self.Base_zCreateWorklistTable()
            Base_zInsertIntoWorklistTable(**value_column_dict)

security.declareProtected(Permissions.ManagePortal, 'refreshWorklistCache')
WorkflowTool.refreshWorklistCache = WorkflowTool_refreshWorklistCache

class WorkflowHistoryList(Persistent):
    _bucket_size = 16

    def __init__(self, iterable=None, prev=None):
        self._prev = prev
        self._slots = []
        if iterable is not None:
            for x in iterable:
                self.append(x)

    def __add__(self, iterable):
        return self.__class__(tuple(self) + tuple(iterable))
Esempio n. 7
0
LOGGER.info('Monkey patched webdav.LockItem.DEFAULTTIMEOUT')

# --------

from plone.dexterity.content import Container
# Change permission for manage_pasteObjects to "Add portal content"
# See https://dev.plone.org/ticket/9177

# XXX Find a way to do this without patching __ac_permissions__ directly

def drop_protected_attr_from_ac_permissions(attribute, classobj):
    new_mappings = []
    for mapping in Container.__ac_permissions__:
        perm, attrs = mapping
        if not attribute in attrs:
            new_mappings.append(mapping)
        else:
            modified_attrs = tuple([a for a in attrs if not a == attribute])
            modified_mapping = (perm, modified_attrs)
            new_mappings.append(modified_mapping)
    classobj.__ac_permissions__ = tuple(new_mappings)

drop_protected_attr_from_ac_permissions('manage_pasteObjects', Container)
sec = ClassSecurityInfo()
sec.declareProtected(Products.CMFCore.permissions.AddPortalContent,
                    'manage_pasteObjects')
sec.apply(Container)
InitializeClass(Container)

LOGGER.info('Monkey patched plone.dexterity.content.Container')
Esempio n. 8
0
        'object': [],
        'global': [],
        'workflow': [],
    }

    for action in actions:
        filtered_actions.setdefault(action['category'], []).append(action)

    return filtered_actions


ActionsTool.listFilteredActionsFor = listFilteredActionsFor


def reorderActions(self, REQUEST=None):
    """Reorder actions according to their priorities."""
    new_actions = self._cloneActions()
    new_actions.sort(key=lambda x: x.getPriority())
    self._actions = tuple(new_actions)

    if REQUEST is not None:
        return self.manage_editActionsForm(
            REQUEST, manage_tabs_message='Actions reordered.')


security.declareProtected(ManagePortal, 'reorderActions')
ActionsTool.reorderActions = reorderActions

ActionsTool.security = security
InitializeClass(ActionsTool)
Esempio n. 9
0
    
    security.declareProtected(PERMISSION_MANAGE_CONTENT, 'deleteFAQ')
    deleteFAQ = BaseContainer.deleteItem
            
    security.declareProtected(PERMISSION_VIEW, 'countFAQ')
    countFAQ = BaseContainer.countItems    
        
templates = ('zpt/faq/FAQManagement',
             #'zpt/faq/addPageForm',
             'zpt/faq/deleteFAQForm',
            )
addTemplates2Class(FAQContainer, templates, globals_=globals())

security = ClassSecurityInfo()
#security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'addFAQForm')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deleteFAQForm')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FAQManagement')
security.apply(FAQContainer)
InitializeClass(FAQContainer)
        
        
######################################################################
## FAQ
######################################################################
manage_addFAQForm = PTF('zpt/faq/addFAQForm', globals())
def manage_addFAQ(dispatcher, id, title,
                  abstract='', body='', publish_date=None,
                  category = None, REQUEST=None):
    """
    Create FAQ object
    """
Esempio n. 10
0
    getPages = BaseContainer.getItems
     
    security.declareProtected(PERMISSION_MANAGE_CONTENT, 'deletePage')
    deletePage = BaseContainer.deleteItem
            
    security.declareProtected(PERMISSION_VIEW, 'countPages')
    countPages = BaseContainer.countItems
    
templates = (
    'zpt/page/PagesManagementHome',
    'zpt/page/addPageForm',
    'zpt/page/deletePageForm',)            
addTemplates2Class(PageContainer, templates, globals_=globals())
                
security = ClassSecurityInfo()
security.declareProtected(PERMISSION_MANAGE_CONTENT, 'PagesManagementHome')
security.declareProtected(PERMISSION_MANAGE_CONTENT, 'addPageForm')
security.declareProtected(PERMISSION_MANAGE_CONTENT, 'deletePageForm')
security.apply(PageContainer)
InitializeClass(PageContainer)


######################################################################
## Page 
######################################################################

manage_addPageForm = PTF('zpt/page/addPageForm', globals())
def manage_addPage(context, id, title, abstract = u'',
                   body=u'',publish_date=None,
                   REQUEST=None):
    """ create """
Esempio n. 11
0
        for each in COMMON_USER_AGENTS:
            tofind, nick = each
            if user_agent.find(tofind) > -1:
                return nick

        return user_agent[:45]

    security.declareProtected(VMS, 'manage_UpdatePlogRank')

    def manage_UpdatePlogRank(self):
        """ use PlogMatrix to calculate every plogrank """
        return UpdatePlogRank(self)


zpts = (('zpt/blogcontainer_index', 'index_html'), )
addTemplates2Class(PeterbeBlogContainer, zpts, extension='zpt')

dtmls = (
    ('dtml/blogcontainer_stats', 'manage_Statistics'),
    'dtml/blogcontainer_calendar',
)
addTemplates2Class(PeterbeBlogContainer, dtmls, extension='dtml')

setattr(PeterbeBlogContainer, 'rss.xml', PeterbeBlogContainer.RSS10)

security = ClassSecurityInfo()
security.declareProtected(VMS, 'manage_Statistics')
security.apply(PeterbeBlogContainer)

InitializeClass(PeterbeBlogContainer)
Esempio n. 12
0
security = ClassSecurityInfo()

def getFolders(self): 
    return [x for x in self.objectValues(METATYPE_FOLDER) if x.submitted==1]
NyFolder.getFolders = getFolders

def hasContent(self): 
    return (len(self.getObjects()) > 0) or (len(self.objectValues(METATYPE_FOLDER)) > 0)
NyFolder.hasContent = hasContent

def getPublishedFolders(self): 
    return self.utSortObjsListByAttr([x for x in self.objectValues(METATYPE_FOLDER) if x.approved==1 and x.submitted==1], 'sortorder', 0)
NyFolder.getPublishedFolders = getPublishedFolders

security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_published_html')
def basketofapprovals_published_html(self, REQUEST=None, RESPONSE=None):
    """ """
    return self.getFormsTool().getContent({'here': self}, 'folder_basketofapprovals_published')
NyFolder.basketofapprovals_published_html = basketofapprovals_published_html

security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'basketofapprovals_duplicates_html')
def basketofapprovals_duplicates_html(self, REQUEST=None, RESPONSE=None):
    """ """
    return self.getFormsTool().getContent({'here': self}, 'folder_basketofapprovals_duplicates')
NyFolder.basketofapprovals_duplicates_html = basketofapprovals_duplicates_html

def _getDuplicatesInFolder(self, meta_type, attrs):
    """Returns an iterater with duplicate objects.

        Items with equal attrs are considered duplicated.
Esempio n. 13
0
                            'but onDelete event failed.')
                if message:
                    # Abort deletion
                    if hasattr(self, 'REQUEST'):
                        doc.writeMessageOnPage(message, self.REQUEST, False)
                        self.REQUEST.RESPONSE.redirect(doc.absolute_url())
                    return None

            self.getIndex().unindexDocument(doc)
            if self.indexInPortal:
                self.portal_catalog.uncatalog_object(
                    "/".join(self.getPhysicalPath() + (doc.id,)))
            event.notify(ObjectRemovedEvent(doc, self.documents, doc.id))
            self.documents._delOb(doc.id)

    security.declareProtected(config.REMOVE_PERMISSION, 'deleteDocuments')

    def deleteDocuments(self, ids=None, massive=True):
        """ Batch delete documents from database.
        If ``massive`` is True, the ``onDelete`` formula and index
        updating are not performed (use ``refreshDB`` to update).
        """
        if ids is None:
            ids = [doc.id for doc in self.getAllDocuments()]

        if massive:
            ObjectManager.manage_delObjects(self.documents, ids)
        else:
            for id in ids:
                self.deleteDocument(self.getDocument(id))
from AccessControl import ClassSecurityInfo
from Products.CMFCore.permissions import View
from collective.downloadtracker import add_download_record

security = ClassSecurityInfo()


security.declareProtected(View, 'index_html')
def index_html(self, instance, REQUEST=None, RESPONSE=None, **kwargs):
    """ make it directly viewable when entering the objects URL """
    blob = self.get(instance, raw=True)    # TODO: why 'raw'?
    charset = instance.getCharset()
    add_download_record(instance)
    return blob.index_html(
        REQUEST=REQUEST, RESPONSE=RESPONSE,
        charset=charset, **kwargs
        )
Esempio n. 15
0

    security.declareProtected(VMS, 'manage_UpdatePlogRank')
    def manage_UpdatePlogRank(self):
        """ use PlogMatrix to calculate every plogrank """
        return UpdatePlogRank(self)






zpts = (('zpt/blogcontainer_index', 'index_html'),)
addTemplates2Class(PeterbeBlogContainer, zpts, extension='zpt')

dtmls = (('dtml/blogcontainer_stats','manage_Statistics'),
         'dtml/blogcontainer_calendar',
         )
addTemplates2Class(PeterbeBlogContainer, dtmls, extension='dtml')

setattr(PeterbeBlogContainer, 'rss.xml', PeterbeBlogContainer.RSS10)

security = ClassSecurityInfo()
security.declareProtected(VMS, 'manage_Statistics')
security.apply(PeterbeBlogContainer)




InitializeClass(PeterbeBlogContainer)
Esempio n. 16
0
_guard_form = DTMLFile('editGuardForm', _dtmldir)
PythonScript._guard_form = _guard_form


def manage_guardForm(self, REQUEST, manage_tabs_message=None):
    '''
  '''
    return self._guard_form(
        REQUEST,
        management_view='Guard',
        manage_tabs_message=manage_tabs_message,
    )


PythonScript.manage_guardForm = manage_guardForm
security.declareProtected('View management screens', 'manage_guardForm')


def manage_setGuard(self, props=None, REQUEST=None):
    '''
  '''
    g = Guard()
    if g.changeFromProperties(props or REQUEST):
        self.guard = g
    else:
        self.guard = None
    if REQUEST is not None:
        return self.manage_guardForm(REQUEST, 'Properties changed.')


PythonScript.manage_setGuard = manage_setGuard
Esempio n. 17
0
)
PythonScript.manage_options += _guard_manage_options

_guard_form = DTMLFile(
  'editGuardForm', _dtmldir)
PythonScript._guard_form = _guard_form

def manage_guardForm(self, REQUEST, manage_tabs_message=None):
  '''
  '''
  return self._guard_form(REQUEST,
                          management_view='Guard',
                          manage_tabs_message=manage_tabs_message,
    )
PythonScript.manage_guardForm = manage_guardForm
security.declareProtected('View management screens', 'manage_guardForm')

def manage_setGuard(self, props=None, REQUEST=None):
  '''
  '''
  g = Guard()
  if g.changeFromProperties(props or REQUEST):
    self.guard = g
  else:
    self.guard = None
  if REQUEST is not None:
    return self.manage_guardForm(REQUEST, 'Properties changed.')
PythonScript.manage_setGuard = manage_setGuard
security.declareProtected('Change Python Scripts', 'manage_setGuard')

def getGuard(self):
Esempio n. 18
0
  """
  Folder_original__setOb(self, id, object)
  aq_chain = getattr(self, 'aq_chain', None)
  if aq_chain is None: # Not in acquisition context
    return
  if len(aq_chain) < 2: # Acquisition context is not deep enough for context to possibly be below portal skins.
    return
  portal_skins = aq_chain[1]
  if getattr(portal_skins, 'meta_type', '') != 'CMF Skins Tool' : # It is not a skin tool we're below.
    return
  _updateCacheEntry = getattr(portal_skins.aq_base, '_updateCacheEntry', None)
  if _updateCacheEntry is None:
    return
  _updateCacheEntry(self.id, id)

Folder._setOb = Folder_setOb

def Folder_isERP5SitePresent(self):
  """ Return True if a ERP5 Site is present as subobject. This is
      usefull to identify if a erp5 is present already on a Zope
      Setup.
  """
  return len(self.objectIds("ERP5 Site")) > 0

Folder.isERP5SitePresent = Folder_isERP5SitePresent

security = ClassSecurityInfo()
security.declareProtected(Permissions.ManagePortal, 'isERP5SitePresent')
Folder.security = security
InitializeClass(Folder)
Esempio n. 19
0
    filtered_actions={'user':[],
                      'folder':[],
                      'object':[],
                      'global':[],
                      'workflow':[],
                      }

    for action in actions:
        filtered_actions.setdefault(action['category'], []).append(action)

    return filtered_actions

ActionsTool.listFilteredActionsFor = listFilteredActionsFor


def reorderActions(self, REQUEST=None):
  """Reorder actions according to their priorities."""
  new_actions = self._cloneActions()
  new_actions.sort(key=lambda x: x.getPriority())
  self._actions = tuple( new_actions )

  if REQUEST is not None:
    return self.manage_editActionsForm(REQUEST,
        manage_tabs_message='Actions reordered.')

security.declareProtected(ManagePortal, 'reorderActions')
ActionsTool.reorderActions = reorderActions

ActionsTool.security = security
InitializeClass(ActionsTool)
Esempio n. 20
0
             'zpt/FileManagementHome',
             'zpt/search',
             'dtml/manage_MenuItems',
             ('zpt/AdvancedManagement', 'manage_AdvancedManagement'),
             'zpt/ManagementHeaderFooter',
             'zpt/DocumentManagementHome',
             ('dtml/cms.js', 'cms_js_template'),
             'zpt/page/PagesManagementHome',
             'zpt/page/deletePageForm',
             'zpt/faq/FAQManagementHome',             
            )
            
addTemplates2Class(Homepage, templates)
                
security = ClassSecurityInfo()
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'Management')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'NewsManagementHome')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'BlogManagementHome')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagementHome')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'DocumentManagementHome')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'PagesManagementHome')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FAQManagementHome')
#security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'addPageForm')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deletePageForm')
security.apply(Homepage)

setattr(Homepage, 'cms.js', Homepage.cms_js)
InitializeClass(Homepage)
        
        
#-------------------------------------------------------------------------------
Esempio n. 21
0
                    value_, label = option, option

                if compare_custom_value(value_, value, self.python_type):
                    return label

            # default
            return value
        else:
            return value


zpts = ("zpt/customfield/manage_field", "zpt/customfield/manage_validation", "zpt/customfield/index_html")
addTemplates2Class(CustomField, zpts)

security = ClassSecurityInfo()
security.declareProtected(VMS, "index_html")
security.declareProtected(VMS, "manage_field")
security.declareProtected(VMS, "manage_validation")
security.apply(CustomField)


InitializeClass(CustomField)


# ----------------------------------------------------------------------------
from OFS.SimpleItem import SimpleItem
from OFS.PropertyManager import PropertyManager


class ValidationExpression(SimpleItem, PropertyManager):
    """ a validation expression is a very simple object that consists of two
Esempio n. 22
0
                return self.editCommentsForm(self,REQUEST)
        else:
            return msg
    
templates = ('zpt/tabComments',
             'zpt/editCommentsForm',
             'zpt/mail_newCommentToWebmaster',
             'zpt/mail_newCommentToParent',
             'zpt/mail_rejectCommentToAuthor',
             'zpt/mail_deleteCommentToAuthor',
             'zpt/mail_approveCommentToAuthor',
            )
addTemplates2Class(CommentsStorage, templates, globals_=globals())

security = ClassSecurityInfo()
security.declareProtected(VMS, 'tabComments')
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'editCommentsForm')
security.declarePrivate('mail_newCommentToWebmaster')
security.declarePrivate('mail_newCommentToParent')
security.declarePrivate('mail_rejectCommentToAuthor')
security.declarePrivate('mail_deleteCommentToAuthor')
security.declarePrivate('mail_approveCommentToAuthor')
security.apply(CommentsStorage)


import unittest
import sys
class CommentsStorageTests(unittest.TestCase):
    """
    Test class for CommentsStorage class 
    """   
Esempio n. 23
0
                return True
            if q.find('/') > -1 and entry['url'].find(q) > -1:
                return True
                #print entry['url']
                #print entry['id']
                #print entry['req_html']
            
        res = [entry.copy() for entry in self._getLog() if matchingQuery(entry, q)]
    else:
        res = [entry.copy() for entry in self._getLog()]
    res.reverse()
    return res
setattr(SiteErrorLog, 'getLogEntries', getLogEntries)
                

# Add the getLogEntryErrorTypes
from Products.SiteErrorLog.SiteErrorLog import use_error_logging
security.declareProtected(use_error_logging, 'getLogEntryErrorTypes')
def getLogEntryErrorTypes(self):
    types = []
    for entry in self._getLog():
        if entry['type'] not in types:
            types.append(entry['type'])
    return types
setattr(SiteErrorLog, 'getLogEntryErrorTypes', getLogEntryErrorTypes)



# Set the security
security.apply(SiteErrorLog)
Esempio n. 24
0
        role.childs = childs
        role.cached = 1
        self._p_changed = 1
        return 1

    def getLDAPSchema(self, acl_folder):
        """ returns the schema for a LDAPUserFolder """
        return acl_folder.getLDAPSchema()

    def getPluginPath(self):
        return self.absolute_url()

    def isList(self, l):
        return isinstance(l, list)

    security.declareProtected(manage_users, "addUserRoles")

    def addUserRoles(self, name=[], roles=[], location="", user_location="", send_mail="", REQUEST=None):
        """ """
        super(plugLDAPUserFolder, self).addUserRoles(name, roles, location, user_location, send_mail, REQUEST)
        if REQUEST is not None:
            if is_ajax(REQUEST):
                url = REQUEST["HTTP_REFERER"] + ("?id=%s&s=assign_to_users" % self.id)
            else:
                url = REQUEST["HTTP_REFERER"] + "?id=" + self.id
            return REQUEST.RESPONSE.redirect(url)

    security.declareProtected(manage_users, "revokeUserRoles")

    def revokeUserRoles(self, user, location, REQUEST=None):
        """ """
Esempio n. 25
0
        role.childs = childs
        role.cached = 1
        self._p_changed = 1
        return 1

    def getLDAPSchema(self, acl_folder):
        """ returns the schema for a LDAPUserFolder """
        return acl_folder.getLDAPSchema()

    def getPluginPath(self):
        return self.absolute_url()

    def isList(self, l):
        return isinstance(l, list)

    security.declareProtected(manage_users, 'addUserRoles')

    def addUserRoles(self,
                     name=[],
                     roles=[],
                     location='',
                     user_location='',
                     send_mail='',
                     REQUEST=None):
        """ """
        super(plugLDAPUserFolder,
              self).addUserRoles(name, roles, location, user_location,
                                 send_mail, REQUEST)
        if REQUEST is not None:
            if is_ajax(REQUEST):
                url = (REQUEST['HTTP_REFERER'] +
Esempio n. 26
0
        if ICON_ASSOCIATIONS.has_key(extension):
            return '%s/%s'%(icon_location, ICON_ASSOCIATIONS[extension])
        else:
            return default

        
    
    #security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagement')

templates = ('zpt/FileManagement', 
             'zpt/deleteFileForm',
            )
addTemplates2Class(FilesContainer, templates, globals_=globals())

security = ClassSecurityInfo()
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'FileManagement')
security.apply(FilesContainer)


InitializeClass(FilesContainer)
        
        
#-------------------------------------------------------------------------------

manage_addFileForm = PTF('zpt/addFileForm', globals())

def manage_addFile(dispatcher, title, file, fileid='',
                            abstract=u'', REQUEST=None):
    """ create """

    dest = dispatcher.Destination()
Esempio n. 27
0
        self.manage_delObjects([id])
        
        if REQUEST is not None:
            msg = "News item deleted"
            url = self.absolute_url()+'/NewsManagement'
            self.http_redirect(url, msg=msg)
        

templates = ('zpt/NewsManagement',
             'zpt/deleteNewsItemForm',
            )
addTemplates2Class(NewsContainer, templates, globals_=globals())
setattr(NewsContainer, 'rss.xml', NewsContainer.RSS)

security = ClassSecurityInfo()
security.declareProtected(MANAGE_CONTENT_PERMISSIONS, 'deleteNewsItemForm')
security.apply(NewsContainer)


InitializeClass(NewsContainer)
        
        
#-------------------------------------------------------------------------------

manage_addNewsItemForm = PTF('zpt/addNewsItemForm', globals())

def manage_suggestNewsItemId(self):
    """ suggest a new id """
    return DateTime().strftime('newsitem-%d%b%Y')

Esempio n. 28
0
    p = subprocess.Popen((DCWorkflowGraph.bin_search(DOT_EXE),
                          '-Nfontname=IPAexGothic', '-Nfontsize=10',
                          '-Efontname=IPAexGothic', '-Efontsize=10',
                          '-T%s' % format),
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    result = p.communicate(pot)[0]

    setHeader('Content-Type', 'image/%s' % format)
  else:
    filename = wf_id or self.getId()
    setHeader('Content-Type', 'text/x-graphviz')
    setHeader('Content-Disposition', 'attachment; filename=%s.dot' % filename)

  if not result:
    LOG("ERP5Type.patches.DCWorkflowGraph", WARNING,
        "Empty %s graph file" % format)

  return result

DCWorkflowGraph.getGraph = getGraph

from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition
DCWorkflowDefinition.getGraph = getGraph
DCWorkflowDefinition.getPOT = DCWorkflowGraph.getPOT

security = ClassSecurityInfo()
security.declareProtected(Permissions.ManagePortal, 'getPOT')
security.declareProtected(Permissions.ManagePortal, 'getGraph')
DCWorkflowDefinition.security = security
InitializeClass(DCWorkflowDefinition)
Esempio n. 29
0
from zope.event import notify

security = ClassSecurityInfo()


def invalidateClientsCache(self, REQUEST=None):
    """ Invalidate client cache
    """
    notify(ObjectModifiedEvent(self))
    if REQUEST:
        portal_url = getToolByName(self, 'portal_url')()
        return REQUEST.RESPONSE.redirect(portal_url +
                                         '/@@invalidateClientsCache')


security.declareProtected(permissions.ManagePortal, 'manage_saveStylesheets')


def manage_saveStylesheets(self, REQUEST=None):
    """ Save stylesheets from the ZMI.
        Updates the whole sequence. For editing and reordering.
    """
    self._old_manage_saveStylesheets(REQUEST)
    invalidateClientsCache(self, REQUEST)


security.declareProtected(permissions.ManagePortal, 'manage_saveScripts')


def manage_saveScripts(self, REQUEST=None):
    """ Save scripts from the ZMI.
Esempio n. 30
0
        self.objectValues(METATYPE_FOLDER)) > 0)


NyFolder.hasContent = hasContent


def getPublishedFolders(self):
    return self.utSortObjsListByAttr([
        x for x in self.objectValues(METATYPE_FOLDER)
        if x.approved == 1 and x.submitted == 1
    ], 'sortorder', 0)


NyFolder.getPublishedFolders = getPublishedFolders

security.declareProtected(PERMISSION_PUBLISH_OBJECTS,
                          'basketofapprovals_published_html')


def basketofapprovals_published_html(self, REQUEST=None, RESPONSE=None):
    """ """
    return self.getFormsTool().getContent({'here': self},
                                          'folder_basketofapprovals_published')


NyFolder.basketofapprovals_published_html = basketofapprovals_published_html

security.declareProtected(PERMISSION_PUBLISH_OBJECTS,
                          'basketofapprovals_duplicates_html')


def basketofapprovals_duplicates_html(self, REQUEST=None, RESPONSE=None):
Esempio n. 31
0
def drop_protected_attr_from_ac_permissions(attribute, classobj):
    new_mappings = []
    for mapping in Container.__ac_permissions__:
        perm, attrs = mapping
        if attribute not in attrs:
            new_mappings.append(mapping)
        else:
            modified_attrs = tuple([a for a in attrs if not a == attribute])
            modified_mapping = (perm, modified_attrs)
            new_mappings.append(modified_mapping)
    classobj.__ac_permissions__ = tuple(new_mappings)


drop_protected_attr_from_ac_permissions("manage_pasteObjects", Container)
sec = ClassSecurityInfo()
sec.declareProtected(Products.CMFCore.permissions.AddPortalContent,
                     "manage_pasteObjects")
sec.apply(Container)
InitializeClass(Container)


def initialize(context):

    context.registerClass(
        roleplugin.CityMayorUserFactory,
        permission=add_user_folders,
        constructors=(
            roleplugin.manage_addCityMayorUserFactoryForm,
            roleplugin.manage_addCityMayorUserFactory,
        ),
        visibility=None,
    )
Esempio n. 32
0
        img = img.crop(cropbox)
        
        img.save(imagefilepath, fmt)
        
        thumbimage = open(imagefilepath, 'rb')
        ext = p.getId().split('.')[-1]
        id = 'tumnagel.%s' % ext
        self.uploadThumbnail(file=thumbimage.read(), id=id)

templates = (#'dtml/something',
             'zpt/editBustForm',
            )
addTemplates2Class(Bust, templates)
 
security = ClassSecurityInfo()
security.declareProtected(VMS, 'editBustForm')
security.apply(Bust)

InitializeClass(Bust)


#-----------------------------------------------------------------------------
        
manage_addBustFolderForm = PTF('zpt/addBustFolderForm', globals())
def manage_addBustFolder(dispatcher, id, title, REQUEST=None,
                   redirect_to=None):
    """ create instance """
    
    dest = dispatcher.Destination()
        
    instance = BustFolder(id, title)
from AccessControl import ClassSecurityInfo
from Products.CMFCore.permissions import View
from collective.downloadtracker import add_download_record

security = ClassSecurityInfo()

security.declareProtected(View, 'index_html')


def index_html(self, instance, REQUEST=None, RESPONSE=None, **kwargs):
    """ make it directly viewable when entering the objects URL """
    blob = self.get(instance, raw=True)  # TODO: why 'raw'?
    charset = instance.getCharset()
    add_download_record(instance)
    return blob.index_html(REQUEST=REQUEST,
                           RESPONSE=RESPONSE,
                           charset=charset,
                           **kwargs)
Esempio n. 34
0
from Products.ResourceRegistries import permissions
from zope.lifecycleevent import ObjectModifiedEvent
from zope.event import notify

security = ClassSecurityInfo()

def invalidateClientsCache(self, REQUEST=None):
    """ Invalidate client cache
    """
    notify(ObjectModifiedEvent(self))
    if REQUEST:
        portal_url = getToolByName(self, 'portal_url')()
        return REQUEST.RESPONSE.redirect(portal_url +
                '/@@invalidateClientsCache')

security.declareProtected(permissions.ManagePortal, 'manage_saveStylesheets')
def manage_saveStylesheets(self, REQUEST=None):
    """ Save stylesheets from the ZMI.
        Updates the whole sequence. For editing and reordering.
    """
    self._old_manage_saveStylesheets(REQUEST)
    invalidateClientsCache(self, REQUEST)

security.declareProtected(permissions.ManagePortal, 'manage_saveScripts')
def manage_saveScripts(self, REQUEST=None):
    """ Save scripts from the ZMI.
        Updates the whole sequence. For editing and reordering.
    """
    self._old_manage_saveScripts(REQUEST)
    invalidateClientsCache(self, REQUEST)
Esempio n. 35
0
                                  'but onDelete event failed.')
                if message:
                    # Abort deletion
                    if hasattr(self, 'REQUEST'):
                        doc.writeMessageOnPage(message, self.REQUEST, False)
                        self.REQUEST.RESPONSE.redirect(doc.absolute_url())
                    return None

            self.getIndex().unindexDocument(doc)
            if self.indexInPortal:
                self.portal_catalog.uncatalog_object(
                    "/".join(self.getPhysicalPath() + (doc.id, )))
            event.notify(ObjectRemovedEvent(doc, self.documents, doc.id))
            self.documents._delOb(doc.id)

    security.declareProtected(config.REMOVE_PERMISSION, 'deleteDocuments')

    def deleteDocuments(self, ids=None, massive=True):
        """ Batch delete documents from database.
        If ``massive`` is True, the ``onDelete`` formula and index
        updating are not performed (use ``refreshDB`` to update).
        """
        if ids is None:
            ids = [doc.id for doc in self.getAllDocuments()]

        if massive:
            ObjectManager.manage_delObjects(self.documents, ids)
        else:
            for id in ids:
                self.deleteDocument(self.getDocument(id))