Ejemplo n.º 1
0
def initialize(context):
    ##Import Types here to register them
    import Products.Ploneboard.content

    # If we put this import line to the top of module then
    # utils will magically point to Ploneboard.utils
    from Products.CMFCore import utils
    utils.ToolInit('Ploneboard Tool',
                   tools=(PloneboardTool, ),
                   icon='tool.gif').initialize(context)

    content_types, constructors, ftis = process_types(listTypes(PROJECTNAME),
                                                      PROJECTNAME)

    # Assign an own permission to all content types
    # Heavily based on Bricolite's code from Ben Saller
    import permissions as perms

    allTypes = zip(content_types, constructors)
    for atype, constructor in allTypes:
        kind = "%s: %s" % (PROJECTNAME, atype.archetype_name)
        utils.ContentInit(
            kind,
            content_types=(atype, ),
            # Add permissions look like perms.Add{meta_type}
            permission=getattr(perms, 'Add%s' % atype.meta_type),
            extra_constructors=(constructor, ),
            fti=ftis,
        ).initialize(context)

    from AccessControl import allow_class
    from batch import Batch
    allow_class(Batch)
    this_module.Batch = Batch
Ejemplo n.º 2
0
def initialize(context):
    from Products.Extropy import content

    content_types, constructors, ftis = process_types(listTypes(config.PROJECTNAME), config.PROJECTNAME)

    ContentInit(
        config.PROJECTNAME + " Content",
        content_types=content_types,
        permission=config.ADD_CONTENT_PERMISSION,
        extra_constructors=constructors,
    ).initialize(context)

    TOOLS = (tools.ExtropyTimeTrackerTool.ExtropyTimeTrackerTool, tools.ExtropyTrackingTool.ExtropyTrackingTool)
    ToolInit(config.PROJECTNAME + " Tool", tools=TOOLS, icon="tool.gif").initialize(context)

    import patches

    allow_module("Products.Extropy.odict")
    from Products.Extropy.odict import OrderedDict

    allow_class(OrderedDict)

    from Products.CMFPlone import i18nl10n

    i18nl10n.setDefaultDateFormat(("en",), u"yyyy-MM-dd")
    i18nl10n.setDefaultTimeFormat(("en",), u"HH:mm:ss")
Ejemplo n.º 3
0
def registerAndAllowCommandSet(class_, name, provides, *arg, **kw):
    registerPlugin(CommandSet, ICommandSet, name, provides, *arg, **kw)
    try:
        import Products.Five
    except ImportError:
        pass
    else:
        # Allow TTW to use commandsets
        from AccessControl import allow_class
        allow_class(class_)
Ejemplo n.º 4
0
def whitelist_module(module, classes=[], definitions=[]):

    # For python scripts and zope
    allow_module(module)
    for klass in classes:
        allow_class(klass)
    if definitions:
        ModuleSecurityInfo(module).declarePublic(*definitions)

    # for zope.untrustedpython
    defineChecker(imodule, NamesChecker([meth for meth in dir(imodule) if meth[0] != "_"]))
Ejemplo n.º 5
0
def monkey_zope3_message_id():
    try:
        #BBB Zope 2.9 and earlier
        from zope.i18nmessageid.messageid import MessageID
        # open it up for Zope 2...
        allow_class(MessageID)
    except ImportError:
        # Zope since 2.10: we dont have to allow "Message", it seems
        from zope.i18nmessageid.message import Message
        # allow_class(Message)
        # instead we have to allow the module ...
        allow_module('zope.i18nmessageid.message')
Ejemplo n.º 6
0
def monkey_zope3_message_id():
    try:
        #BBB Zope 2.9 and earlier
        from zope.i18nmessageid.messageid import MessageID
        # open it up for Zope 2...
        allow_class(MessageID)
    except ImportError:
        # Zope since 2.10: we dont have to allow "Message", it seems
        from zope.i18nmessageid.message import Message
        # allow_class(Message)
        # instead we have to allow the module ...
        allow_module('zope.i18nmessageid.message')
Ejemplo n.º 7
0
def allow_modules():
    from AccessControl import ModuleSecurityInfo, ClassSecurityInfo
    from AccessControl import allow_module, allow_class, allow_type

    #copied from Products.PythonScript.module_access_examples.py
    ModuleSecurityInfo('re').declarePublic('compile', 'findall',
                                           'match', 'search', 'split', 'sub', 'subn', 'error',
                                           'I', 'L', 'M', 'S', 'X')
    import re
    allow_type(type(re.compile('')))
    allow_type(type(re.match('x','x')))

    import copy
    ModuleSecurityInfo('copy').declarePublic('deepcopy')


    """ Modulo Archetypes """
    ModuleSecurityInfo('wres').declarePublic('archetypes')
    ModuleSecurityInfo('wres.archetypes').declarePublic('content')

    ModuleSecurityInfo('wres.archetypes.content').declarePublic('patient')
    allow_module('wres.archetypes.content.patient')

    ModuleSecurityInfo('wres.archetypes.content').declarePublic('doctor')
    allow_module('wres.archetypes.content.doctor')

    ModuleSecurityInfo('wres.archetypes.content').declarePublic('documentfolder')
    allow_module('wres.archeytpes.content.documentfolder')

    ModuleSecurityInfo('wres.archetypes.content').declarePublic('secretarydesktop')
    allow_module('wres.archeytpes.content.secretarydesktop')
    from wres.archetypes.content.secretarydesktop import SecretaryDesktopData
    allow_class(SecretaryDesktopData)

    """ Modulo Policy """
    ModuleSecurityInfo('wres').declarePublic('policy')
    ModuleSecurityInfo('wres.policy').declarePublic('utils')
    ModuleSecurityInfo('wres.policy').declarePublic('cmedstat')
    ModuleSecurityInfo('wres.policy.utils').declarePublic('utils')

    allow_module('wres.policy.utils.utils')
    allow_module('wres.policy.cmedstat')

    """ Modulo Theme """
    ModuleSecurityInfo('wres').declarePublic('theme')
    ModuleSecurityInfo('wres.theme').declarePublic('skins')
    ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_custom_scripts')
    ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_custom_templates')
    ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_custom_images')
    ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_auxiliary')
    # ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_widgets')
    ModuleSecurityInfo('wres.theme.skins').declarePublic('wres_theme_custom_styles')
Ejemplo n.º 8
0
def initialize(context):
    ##Import Types here to register them
    from content import Ploneboard, PloneboardForum, PloneboardConversation, PloneboardComment

    # If we put this import line to the top of module then
    # utils will magically point to Ploneboard.utils
    from Products.CMFCore import utils
    utils.ToolInit('Ploneboard Tool', 
            tools=(PloneboardTool,), 
            icon='tool.gif'
            ).initialize(context)

    content_types, constructors, ftis = process_types(
        listTypes(PROJECTNAME),
        PROJECTNAME)

    # Assign an own permission to all content types
    # Heavily based on Bricolite's code from Ben Saller
    import permissions as perms

    allTypes = zip(content_types, constructors)
    for atype, constructor in allTypes:
        kind = "%s: %s" % (PROJECTNAME, atype.archetype_name)
        utils.ContentInit(
            kind,
            content_types      = (atype,),
            # Add permissions look like perms.Add{meta_type}
            permission         = getattr(perms, 'Add%s' % atype.meta_type),
            extra_constructors = (constructor,),
            fti                = ftis,
            ).initialize(context)

    if HAS_GENERICSETUP:
        profile_registry.registerProfile('Ploneboard',
                    'Ploneboard',
                    'Extension profile for default Ploneboard setup',
                    'profiles/default',
                    'Ploneboard',
                    EXTENSION,
                    for_=IPloneSiteRoot)
              
    from AccessControl import allow_module, allow_class      
    from batch import Batch
    allow_class(Batch)
    this_module.Batch = Batch
Ejemplo n.º 9
0
def initialize(context):
    """Initializer called when used as a Zope 2 product.

    This is referenced from configure.zcml. Regstrations as a "Zope 2 product"
    is necessary for GenericSetup profiles to work, for example.

    Here, we call the Archetypes machinery to register our content types
    with Zope and the CMF.
    """
    
    from AccessControl import allow_module, allow_class
    allow_module('tecnoteca.googlemap.content')
    
    from tecnoteca.googlemap.content.ttgooglemapcoordinates import TTGoogleMapCoordinates
    allow_class(TTGoogleMapCoordinates)
    
    from tecnoteca.googlemap.browser.logger import log
    allow_class(log)

    # Retrieve the content types that have been registered with Archetypes
    # This happens when the content type is imported and the registerType()
    # call in the content type's module is invoked. Actually, this happens
    # during ZCML processing, but we do it here again to be explicit. Of
    # course, even if we import the module several times, it is only run
    # once.

    content_types, constructors, ftis = atapi.process_types(
        atapi.listTypes(config.PROJECTNAME),
        config.PROJECTNAME)

    # Now initialize all these content types. The initialization process takes
    # care of registering low-level Zope 2 factories, including the relevant
    # add-permission. These are listed in config.py. We use different
    # permissions for each content type to allow maximum flexibility of who
    # can add which content types, where. The roles are set up in rolemap.xml
    # in the GenericSetup profile.

    for atype, constructor in zip(content_types, constructors):
        utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type),
            content_types=(atype, ),
            permission=config.ADD_PERMISSIONS[atype.portal_type],
            extra_constructors=(constructor,),
            ).initialize(context)
def initialize(context):
    ##Import Types here to register them
    import Products.Ploneboard.content

    # If we put this import line to the top of module then
    # utils will magically point to Ploneboard.utils
    from Products.CMFCore import utils
    utils.ToolInit('Ploneboard Tool', 
            tools=(PloneboardTool,), 
            icon='tool.gif'
            ).initialize(context)

    content_types, constructors, ftis = process_types(
        listTypes(PROJECTNAME),
        PROJECTNAME)

    # Assign an own permission to all content types
    # Heavily based on Bricolite's code from Ben Saller
    import permissions as perms

    allTypes = zip(content_types, constructors)
    for atype, constructor in allTypes:
        kind = "%s: %s" % (PROJECTNAME, atype.archetype_name)
        utils.ContentInit(
            kind,
            content_types      = (atype,),
            # Add permissions look like perms.Add{meta_type}
            permission         = getattr(perms, 'Add%s' % atype.meta_type),
            extra_constructors = (constructor,),
            fti                = ftis,
            ).initialize(context)

              
    from AccessControl import allow_class      
    from batch import Batch
    allow_class(Batch)
    this_module.Batch = Batch
Ejemplo n.º 11
0
        self._sintool = sintool
        self._template = template
        self._macro = macro

    def __repr__(self):
        return '<SinMacro at %s template: %s, macro: %s, maps: %s>' % \
               (id(self), self._template, self._macro, \
                ','.join(self._sintool.maps.keys()))

#
#     --> useless method ???
#
#     def __getattr__(self, key):
#         if key in self.__dict__.keys():
#             return getattr(self, key)
#         return getattr(self._sintool, key)

    def __getitem__(self, key):
        if key not in self._sintool.maps.keys():
            raise KeyError(key)
        skinstool = getToolByName(self._sintool, 'portal_skins')
        template = getattr(skinstool, self._template)
        macro = template.macros[self._macro]
        # this is a little bad, but here we dont have
        # request etc...
        self._sintool.setCurrentFeed(key)
        return macro


allow_class(SinMacro)
classImplements(Account, interfaces.IAccount, interfaces.IAccountFolder)

class entryproxy:
    __allow_access_to_unprotected_subobjects__=1
    def __init__(self, entry, balance):
        self.entry = entry
        self.balance = balance

    def __getattr__(self, name):
        if name == 'balance':
            return self.balance
        elif name == 'absolute_url':
            return getattr(self.entry.aq_parent, name)
        else:
            return getattr(self.entry, name)

from AccessControl import allow_class
allow_class(entryproxy)

from plone.indexer.decorator import indexer
@indexer(interfaces.IAccount)
def getBankStatementTextAsString(obj, **kwargs):
    """ Return BankStatementText lines field as text for indexing
    """
    return '\n'.join(obj.getBankStatementText())

##/code-section module-footer



Ejemplo n.º 13
0
import re
#allow_module('re')
ModuleSecurityInfo('re').declarePublic(
    'compile', 'findall', 'match', 'search', 'split', 'sub', 'subn', 'error',
    'I', 'L', 'M', 'S', 'X')
allow_type(type(re.compile('')))
allow_type(type(re.match('x', 'x')))


# Random
allow_module('random')
#z3
import random
#defineChecker(random, NamesChecker(['uniform','shuffle']))
defineChecker(random, NamesChecker([meth for meth in dir(random) if meth[0] != '_']))
allow_class(random.SystemRandom)


# UUID

#allow_module('uuid')
import uuid
allow_class(uuid.UUID)
ModuleSecurityInfo('uuid').declarePublic(
    'uuid1', 'uuid2', 'uuid3', 'uuid4', 'uuid5')



# Extension class so can't be supported
# import datetime
# defineChecker(datetime, NamesChecker([meth for meth in dir(datetime) if meth[0] != '_']))
Ejemplo n.º 14
0
# Do we have CMFPlone?
try:
    from Products import CMFPlone
    Plone = True
    from Products.FCKeditor.PloneFCKeditor import PloneFCKeditor
    from Products.FCKeditor import PloneFCKconnector
except ImportError:
    Plone = False



# Expose PloneFCKeditor to restricted Python.
# ===========================================

if Plone:
    allow_class(PloneFCKeditor)



# Initialize the Product.
# =======================

FCKglobals = globals()
def initialize(registrar):

    if CMFCore:
        registerDirectory('skins', FCKglobals)

    if Plone:
        PloneFCKconnector.initialize(registrar)
Ejemplo n.º 15
0
def initialize(context):

  perm='Add Documents, Images, and Files'
     
  context.registerClass(ZoomifyImage.ZoomifyImage, 
  permission=perm,
  constructors=(('imageAdd',ZoomifyImage.manage_addImageForm),
                 ZoomifyImage.manage_addImage),
  icon='images/Image_icon.gif',
  legacy=(ZoomifyImage.manage_addImage,),
  )
  
ModuleSecurityInfo('Products').declarePublic('ZoomifyImage')
ModuleSecurityInfo('Products.ZoomifyImage').declarePublic('ZoomifyBase')
ModuleSecurityInfo('Products.ZoomifyImage.ZoomifyBase').declarePublic('ZoomifyBase')
ModuleSecurityInfo('Products.ZoomifyImage').declarePublic('ZoomifyZopeProcessor')
ModuleSecurityInfo('Products.ZoomifyImage.ZoomifyZopeProcessor').declarePublic('ZoomifyZopeProcessor')
ModuleSecurityInfo('Products.ZoomifyImage').declarePublic('ZoomifyImage')
ModuleSecurityInfo('Products.ZoomifyImage').declarePublic('manage_addImage')
ModuleSecurityInfo('Products.ZoomifyImage').declarePublic('manage_addImageForm')
ModuleSecurityInfo('Products.ZoomifyImage.ZoomifyImage').declarePublic('manage_editForm')
ModuleSecurityInfo('Products.ZoomifyImage.ZoomifyImage').declarePublic('manage_edit')

allow_module('Products.ZoomifyImage')
allow_module('Products.ZoomifyImage.ZoomifyBase')
allow_class(ZoomifyBase)
allow_module('Products.ZoomifyImage.ZoomifyImage')
allow_module('Products.ZoomifyImage.ZoomifyZopeProcessor')
allow_class(ZoomifyZopeProcessor)

Ejemplo n.º 16
0
from Products.Archetypes import atapi
from Products.CMFCore import utils as cmfutils
from Products.CMFCore.permissions import setDefaultRoles

from AccessControl import allow_class

##code-section imports
from AccessControl import allow_module
##/code-section imports 

# Define a message factory for when this product is internationalised.
# This will be imported with the special name "_" in most modules. Strings
# like _(u"message") will then be extracted by i18n tools for translation.

DocpoolMessageFactory = MessageFactory('docpool.dbaccess')
allow_class(DocpoolMessageFactory)

##code-section security
from docpool.dbaccess.content.errors import ObjectDuplicateException
allow_class(ObjectDuplicateException)
allow_module("docpool.dbaccess")
allow_module("docpool.dbaccess.utils")
##/code-section security 

def initialize(context):
    """Intializer called when used as a Zope 2 product.
    
    This is referenced from configure.zcml. Regstrations as a "Zope 2 product" 
    is necessary for GenericSetup profiles to work, for example.
    
    Here, we call the Archetypes machinery to register our content types 
Ejemplo n.º 17
0
xwfutils_security.declarePublic('users_can_join_group')
xwfutils_security.declarePublic('entity_exists')
xwfutils_security.declarePublic('add_marker_interfaces')
xwfutils_security.declarePublic('remove_marker_interfaces')
xwfutils_security.declarePublic('sort_by_name')
xwfutils_security.declarePublic('comma_comma_and')
xwfutils_security.declarePublic('timedelta_to_string')
xwfutils_security.declarePublic('deprecated')
xwfutils_security.declarePublic('format_exec')
xwfutils_security.declarePublic('object_values')

csv_security = ModuleSecurityInfo('Products.XWFCore.CSV')
csv_security.declarePublic('CSVFile')

from Products.XWFCore.CSV import CSVFile
allow_class(CSVFile)


def initialize(context):
    # Import lazily, and defer initialization to the module
    import XWFCatalog
    XWFCatalog.initialize(context)


validator_security = ModuleSecurityInfo('Products.XWFCore.validators')
validator_security.declarePublic('validate_email')
validator_security.declarePublic('ValidationError')

from odict import ODict  # lint:ok

from AccessControl import allow_module
Ejemplo n.º 18
0
import sys
this_module = sys.modules[ __name__ ]

product_globals = globals()

# Make the skins available as DirectoryViews
registerDirectory('skins', globals())

# Allow access to shlex for search parsing
from AccessControl import allow_module, allow_class
import shlex
allow_module('shlex')
allow_module('Products.RhaptosRepository.Extensions')
allow_module('Products.RhaptosRepository.Extensions.ObjectResult')
allow_class(ObjectResult)
allow_module('Products.RhaptosModuleStorage.Extensions')
allow_module('Products.RhaptosModuleStorage.Extensions.DBModule')
allow_class(DBModuleSearch)

contentConstructors = (Repository.manage_addRepository,)
contentClasses = (Repository.Repository,)

z_bases = utils.initializeBasesPhase1(contentClasses, this_module)

def initialize(context):

    utils.initializeBasesPhase2( z_bases, context )
    utils.ContentInit(Repository.Repository.meta_type,
                      content_types = contentClasses,
                      permission = CMFCorePermissions.AddPortalContent,
Ejemplo n.º 19
0
    'small',
    'medium',
    'large',
    'xlarge',
)
# default image qualitay (obsoleted use getPreferredImageQuality on a portal_preferences tool)
DEFAULT_IMAGE_QUALITY = 75.0

DEFAULT_CONTENT_TYPE = 'text/html'


class ConversionError(Exception):
    pass


allow_class(ConversionError)


class DocumentProxyError(Exception):
    pass


class NotConvertedError(Exception):
    pass


allow_class(NotConvertedError)

import base64
enc = base64.encodestring
dec = base64.decodestring
Ejemplo n.º 20
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from zope.i18nmessageid import MessageFactory
GSMessageFactory = MessageFactory('gs.profile.email.verify')

from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class
#lint:disable
from .emailverificationuser import EmailVerificationUser, \
    EmailVerificationUserFromUser, VerificationIdExists, \
    VerificationIdNotFound, VerificationIdUsed, NoUserForVerificationId
#lint:enable

allow_class(EmailVerificationUserFromUser)
moduleId = 'gs.profile.email.verify.emailverificationuser'
evu_security = ModuleSecurityInfo(moduleId)
evu_security.declarePublic('EmailVerificationUser')
Ejemplo n.º 21
0
# coding=utf-8
from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class

moduleSecurity = ModuleSecurityInfo('Products.GSSiteMenu.sitemenu')
moduleSecurity.declarePublic('SiteMenuItem')
moduleSecurity.declarePublic('SiteMenu')
from sitemenu import FolderMenuItem, SimpleMenuItem, SimpleBrowserMenuItem, SiteMenu

allow_class(FolderMenuItem)
allow_class(SimpleMenuItem)
allow_class(SimpleBrowserMenuItem)
allow_class(SiteMenu)
Ejemplo n.º 22
0
        del self._ann[index]

    def __len__(self):
        return len(self._ann)

    def clear(self):
        """Clear all storage data"""
        ann = IAnnotations(self.context)
        del ann[STORAGE_KEY]

    def add(self, data, index=-1):
        """Add data to the storage. Data must the a dict-like structure"""
        row = PersistentDict()
        row.update(data)
        if index > -1:
            self._ann.insert(index, row)
        else:
            self._ann.append(row)

    def update(self, index, data):
        self._ann[index].update(data)

    def nullify(self, index, key):
        try:
            del self._ann[index][key]
        except KeyError:
            pass


allow_class(DataStorage)
Ejemplo n.º 23
0
from Products.CMFCore.DirectoryView import registerDirectory
from Products.CMFCore import utils
from Products.CMFCore import CMFCorePermissions
import CMFDiffTool
import FieldDiff
import TextDiff
import ListDiff
import BinaryDiff
import XmlDiff
import ChangeSet

# Make MergeError available to TTW code
from AccessControl import ModuleSecurityInfo, allow_class
from BaseDiff import MergeError
ModuleSecurityInfo('Products.CMFDiffTool').declarePublic('MergeError')
allow_class(MergeError)

this_module = sys.modules[ __name__ ]
product_globals = globals()
tools = ( CMFDiffTool.CMFDiffTool,)

contentConstructors = (ChangeSet.manage_addChangeSet,)
contentClasses = (ChangeSet.ChangeSet,)
z_bases = utils.initializeBasesPhase1(contentClasses, this_module)

# Make the skins available as DirectoryViews
registerDirectory('skins', globals())
registerDirectory('skins/ChangeSet', globals())

CMFDiffTool.registerDiffType(BinaryDiff.BinaryDiff)
CMFDiffTool.registerDiffType(FieldDiff.FieldDiff)
Ejemplo n.º 24
0
                                                    id='',
                                                    notify_workflow=False)
            aggregate.__dict__.update(amount.aq_base.__dict__)
            aggregate._setQuantity(quantity)
            if isinstance(amount, RoundingProxy):
                aggregate = amount.getPortalObject(
                ).portal_roundings.getRoundingProxy(aggregate)
            else:
                del aggregate._base
            result_list.append(aggregate)
        return result_list

    def split(self):
        """Return a dictionary with all amounts grouped by base amount

    Return {amount: amount_list} where
      - amount is the Amount instance (e.g. movement, delivery)
        that generated amounts
      - amount_list is an instance of this class

    This is the opposite of aggregate(), which merges amounts that only differ
    by their base amounts.
    """
        result = defaultdict(self.__class__)
        for amount in self:
            result[amount._base].append(amount)
        return result


allow_class(GeneratedAmountList)
Ejemplo n.º 25
0
# This space intentionally left blank
import view
from AccessControl import ModuleSecurityInfo, allow_class, allow_module
from Products.GSContent.view import GSSiteInfo

siteInfo_security = ModuleSecurityInfo('Products.GSContent.view')
allow_class(GSSiteInfo)


# XXX: Dirty hack, purely to support legacy code. Remove as soon as possible
def GSGroupsInfoFactory():
    import logging
    logger = logging.getLogger("Products.GSContent")
    logger.warn("Deprecated: GSGroupsInfoFactory should be imported directly "
                "from gs.groups.groupsInfo")
    from gs.groups.groupsInfo import GSGroupsInfoFactory as GSGIFactory
    return GSGIFactory()


allow_module('Products.GSContent.GSGroupsInfoFactory')
        """
        # originally we weren't setting the ID correctly
        self.id = self.getId()


InitializeClass(CustomUser)


class ValidationError(Exception):
    """ Raised if an email address is invalid.

    """


allow_class(ValidationError)


def addCustomUser(self, name, password, roles, domains):
    """ Add a CustomUser to a folder.

    """
    ob = CustomUser(name, password, roles, domains)
    ob.id = ob.getId()  # make sure we have an actual ID
    self._setObject(name, ob)


def removedCustomUser(ob, event):
    """ A CustomUser was removed.

    """
Ejemplo n.º 27
0
Archivo: policy.py Proyecto: RBINS/mars
    'datetime',
    're',
    'time',
    'urllib',
    'urllib2',
    'StringIO',
    'cStringIO',
    'rbins_masschange',
    'rbins_masschange.utils',
    'plone.app.textfield.value',
]:
    exec 'import {0}'.format(i)
    allow_module(i)

ModuleSecurityInfo('datetime').declarePublic('datetime')
allow_class(csv.DictReader)
allow_class(csv.DictWriter)
allow_class(csv.Dialect)
allow_class(csv.excel)
allow_class(csv.excel_tab)
allow_class(csv.Sniffer)
allow_class(plone.app.textfield.value.RichTextValue)


allow_module('re')
ModuleSecurityInfo('re').declarePublic(
    'compile', 'findall', 'match', 'search', 'split', 'sub', 'subn', 'error',
    'I', 'L', 'M', 'S', 'X')
allow_type(type(re.compile('')))
allow_type(type(re.match('x', 'x')))
Ejemplo n.º 28
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
#lint:disable
from .notifyuser import NotifyUser
from .sender import MessageSender
#lint:enable

from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class
m_security = ModuleSecurityInfo('gs.profile.notify.notifyuser')
m_security.declarePublic('NotifyUser')
allow_class(NotifyUser)
Ejemplo n.º 29
0
def initialize(context):

    # Stuff has been moved from module level to this method for a
    # better separation of import and installation.
    # For the general user this change does not make a difference.
    # For test authors (and people who use parts of Plone only)
    # it does speed up import *significantly*.

    from AccessControl import ModuleSecurityInfo
    from AccessControl import allow_class
    from AccessControl import allow_module
    from AccessControl import allow_type

    # protect OFS.ObjectManager
    ModuleSecurityInfo('OFS.ObjectManager').setDefaultAccess(0)
    ModuleSecurityInfo('OFS.ObjectManager').declareObjectPrivate()
    ModuleSecurityInfo('OFS.ObjectManager').declarePublic(
        'BeforeDeleteException')

    # allow logging
    ModuleSecurityInfo('logging').declarePublic('getLogger')
    from logging import Logger
    allow_class(Logger)

    # various small utils functions
    # added for unescaping view names in urls when finding selected action
    ModuleSecurityInfo('urllib').declarePublic('unquote')

    allow_module('Products.CMFPlone.utils')

    # For content_status_modify
    from Products.CMFCore.WorkflowCore import ObjectDeleted
    from Products.CMFCore.WorkflowCore import ObjectMoved
    from Products.CMFCore.WorkflowCore import WorkflowException
    ModuleSecurityInfo(
        'Products.CMFCore.WorkflowCore').declarePublic('ObjectDeleted')
    ModuleSecurityInfo(
        'Products.CMFCore.WorkflowCore').declarePublic('ObjectMoved')
    ModuleSecurityInfo(
        'Products.CMFCore.WorkflowCore').declarePublic('WorkflowException')
    allow_class(ObjectDeleted)
    allow_class(ObjectMoved)
    allow_class(WorkflowException)

    from Products.CMFPlone.PloneBatch import Batch
    allow_class(Batch)

    # Make Batch available at module level
    this_module.Batch = Batch

    ModuleSecurityInfo('StringIO').declarePublic('StringIO')
    from six import StringIO
    allow_class(StringIO)

    # Make Unauthorized importable TTW
    ModuleSecurityInfo('AccessControl').declarePublic('Unauthorized')

    # Make Forbidden importable TTW
    ModuleSecurityInfo('zExceptions').declarePublic('Forbidden')

    # Make ConflictError importable TTW
    ModuleSecurityInfo('ZODB.POSException').declarePublic('ConflictError')

    # Make ZCTextIndex ParseError importable TTW
    ModuleSecurityInfo('Products.ZCTextIndex.ParseTree') \
        .declarePublic('ParseError')

    # Make DateTimeError importable TTW
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('SyntaxError')

    # BBB support for DateTime < 3
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('SyntaxError')

    # Make CopyError importable TTW
    ModuleSecurityInfo('OFS.CopySupport').declarePublic('CopyError')

    # Make AllowSendto importable TTW
    ModuleSecurityInfo('Products.CMFPlone.PloneTool') \
        .declarePublic('AllowSendto')

    # Make ZCatalog's mergeResults importable TTW
    ModuleSecurityInfo('Products.ZCatalog.Catalog') \
        .declarePublic('mergeResults')

    # Make the navtree constructs available TTW
    allow_module('Products.CMFPlone.browser.navtree')

    # Allow access to the exception in the folder_delete script
    from OFS.ObjectManager import BeforeDeleteException
    allow_module('OFS.ObjectManager')
    allow_class(BeforeDeleteException)

    # Make cgi.escape available TTW
    ModuleSecurityInfo('cgi').declarePublic('escape')

    # We want to allow all methods on string type except 'format'.
    # That one needs special handling to avoid access to attributes.
    from Products.CMFPlone.utils import _safe_format
    rules = dict([(m, True) for m in dir(str) if not m.startswith('_')])
    rules['format'] = _safe_format
    allow_type(str, rules)

    # Same for unicode instead of str.
    rules = dict([(m, True) for m in dir(unicode) if not m.startswith('_')])
    rules['format'] = _safe_format
    allow_type(unicode, rules)

    # Apply monkey patches
    from Products.CMFPlone import patches  # noqa

    # Register unicode splitter w/ ZCTextIndex
    # pipeline registry
    from Products.CMFPlone import UnicodeSplitter  # noqa

    # Plone content

    # Usage of PloneFolder is discouraged.
    from Products.CMFPlone import PloneFolder

    contentClasses = (PloneFolder.PloneFolder, )
    contentConstructors = (PloneFolder.addPloneFolder, )

    # CMFCore tools
    from Products.CMFCore import CachingPolicyManager

    # Plone tools
    from Products.CMFPlone import PloneTool
    from Products.CMFPlone import MigrationTool
    from Products.CMFPlone import PloneControlPanel
    from Products.CMFPlone import WorkflowTool
    from Products.CMFPlone import URLTool
    from Products.CMFPlone import RegistrationTool
    from Products.CMFPlone import PropertiesTool
    from Products.CMFPlone import ActionsTool
    from Products.CMFPlone import TypesTool
    from Products.CMFPlone import CatalogTool
    from Products.CMFPlone import SkinsTool
    from Products.CMFPlone import QuickInstallerTool
    from Products.CMFPlone import TranslationServiceTool

    tools = (
        PloneTool.PloneTool,
        WorkflowTool.WorkflowTool,
        CachingPolicyManager.CachingPolicyManager,
        PropertiesTool.PropertiesTool,
        MigrationTool.MigrationTool,
        PloneControlPanel.PloneControlPanel,
        RegistrationTool.RegistrationTool,
        URLTool.URLTool,
        ActionsTool.ActionsTool,
        TypesTool.TypesTool,
        CatalogTool.CatalogTool,
        SkinsTool.SkinsTool,
        QuickInstallerTool.QuickInstallerTool,
        TranslationServiceTool.TranslationServiceTool,
    )

    from Products.CMFCore.utils import ContentInit
    from Products.CMFPlone.utils import ToolInit

    # Register tools and content
    ToolInit(
        'Plone Tool',
        tools=tools,
        icon='tool.gif',
    ).initialize(context)

    ContentInit(
        'Plone Content',
        content_types=contentClasses,
        permission=ADD_CONTENT_PERMISSION,
        extra_constructors=contentConstructors,
    ).initialize(context)

    from AccessControl.Permissions import view_management_screens
    from Products.CMFPlone.Portal import PloneSite
    from Products.CMFPlone.factory import zmi_constructor
    context.registerClass(
        instance_class=PloneSite,
        permission=view_management_screens,
        constructors=(zmi_constructor, ),
    )

    from plone.app.folder import nogopip
    context.registerClass(
        nogopip.GopipIndex,
        permission='Add Pluggable Index',
        constructors=(nogopip.manage_addGopipForm,
                      nogopip.manage_addGopipIndex),
        icon='index.gif',
        visibility=None
    )
Ejemplo n.º 30
0
from plone.batching.batch import Batch

from AccessControl import allow_class
from AccessControl import allow_module

allow_module('plone.batching')
allow_class(Batch)
Ejemplo n.º 31
0
# This space intentionally left blank
from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class

module_security = ModuleSecurityInfo('Products.GSGroup')
groupInfo_security = ModuleSecurityInfo('Products.GSGroup.groupInfo')
from groupInfo import GSGroupInfoFactory, GSGroupInfo
allow_class(GSGroupInfoFactory)
allow_class(GSGroupInfo)
Ejemplo n.º 32
0
    'getDefaultContentType')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declareProtected(
    permissions.ManagePortal, 'setForbiddenContentTypes')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declareProtected(
    permissions.ManagePortal, 'setDefaultContentType')

# Import "PloneMessageFactory as _" to create messages in plone domain
# duplicated here so we don't add a dependency on CMFPlone
from zope.i18nmessageid import MessageFactory

PloneMessageFactory = MessageFactory('plone')
ModuleSecurityInfo('Products.Archetypes').declarePublic('PloneMessageFactory')

# make DisplayList accessible from python scripts and others objects executed
# in a restricted environment
allow_class(DisplayList)

# Allow import of NotFound exception
ModuleSecurityInfo('zExceptions').declarePublic('NotFound')

###
# register tools and content types
###
from Products.Archetypes.ArchetypeTool import process_types, listTypes
from Products.Archetypes.ArchetypeTool import ArchetypeTool

ATToolModule = sys.modules[ArchetypeTool.__module__]  # mpf :|
from Products.Archetypes.ReferenceEngine import ReferenceCatalog as RefTool
from Products.Archetypes.UIDCatalog import UIDCatalog as UIDTool

tools = (ArchetypeTool, RefTool, UIDTool)
Ejemplo n.º 33
0
allow_type(type(np.c_))
allow_type(type(np.dtype('int16')))

allow_module('pandas')

allow_type(pd.Series)
allow_type(pd.Timestamp)
allow_type(pd.DatetimeIndex)
# XXX: pd.DataFrame has its own security thus disable until we can fully integrate it
#allow_type(pd.DataFrame)
allow_type(pd.MultiIndex)
allow_type(pd.indexes.range.RangeIndex)
allow_type(pd.indexes.numeric.Int64Index)
allow_type(pd.core.groupby.DataFrameGroupBy)
allow_type(pd.core.groupby.SeriesGroupBy)
allow_class(pd.DataFrame)


def restrictedMethod(s, name):
    def dummyMethod(*args, **kw):
        raise Unauthorized(name)

    return dummyMethod


# Note: These black_list methods are for pandas 0.19.2
series_black_list = [
    'to_csv', 'to_json', 'to_pickle', 'to_hdf', 'to_sql', 'to_msgpack'
]
series_black_list_dict = {m: restrictedMethod for m in series_black_list}
ContainerAssertions[pd.Series] = _check_access_wrapper(pd.Series,
Ejemplo n.º 34
0
                    return
        del self._ann[index]

    def __len__(self):
        return len(self._ann)

    def clear(self):
        """Clear all storage data"""
        ann = IAnnotations(self.context)
        del ann[STORAGE_KEY]

    def add(self, data, index=-1):
        """Add data to the storage. Data must the a dict-like structure"""
        row = PersistentDict()
        row.update(data)
        if index>-1:
            self._ann.insert(index, row)
        else:
            self._ann.append(row)

    def update(self, index, data):
        self._ann[index].update(data)

    def nullify(self, index, key):
        try:
            del self._ann[index][key]
        except KeyError:
            pass

allow_class(DataStorage)
Ejemplo n.º 35
0
""" Declare Exceptions used throughout the CMF.

$Id$
"""

from AccessControl import allow_class
from AccessControl import Unauthorized
from webdav.Lockable import ResourceLockedError


class CMFError(Exception):
    """ The root of all CMF evil.
    """


allow_class(CMFError)


class CMFNotImplementedError(NotImplementedError, CMFError):
    """ NotImplementedError in CMF.
    """


allow_class(CMFNotImplementedError)


class CMFResourceLockedError(ResourceLockedError, CMFError):
    """ ResourceLockedError in CMF.
    """

Ejemplo n.º 36
0
"""Exception Classes for Formulator"""

# These classes are placed here so that they can be imported into TTW Python
# scripts. To do so, add the following line to your Py script:
# from Products.Formulator.Errors import ValidationError, FormValidationError

from AccessControl import allow_class

class FormValidationError(Exception):

    def __init__(self, errors, result):
        Exception.__init__(self,"Form Validation Error")
        self.errors = errors
        self.result = result

allow_class(FormValidationError)

class ValidationError(Exception):

    def __init__(self, error_key, field):
        Exception.__init__(self, error_key, field.id)
        self.error_key = error_key
        self.field_id = field.id
        self.field = field
        self.error_text = field.get_error_message(error_key)

allow_class(ValidationError)

class FieldDisabledError(AttributeError):

    def __init__(self, error_key, field):
Ejemplo n.º 37
0
def initialize(context):

    # Stuff has been moved from module level to this method for a
    # better separation of import and installation.
    # For the general user this change does not make a difference.
    # For test authors (and people who use parts of Plone only)
    # it does speed up import *significantly*.

    from AccessControl import ModuleSecurityInfo
    from AccessControl import allow_module, allow_class

    # allow logging
    ModuleSecurityInfo('logging').declarePublic('getLogger')
    from logging import Logger
    allow_class(Logger)

    # Register kss extension to allow it used from fs skins
    from Products.CMFCore.DirectoryView import registerFileExtension
    from Products.CMFCore.FSFile import FSFile
    registerFileExtension('kss', FSFile)

    # various small utils functions
    # added for unescaping view names in urls when finding selected action
    ModuleSecurityInfo('urllib').declarePublic('unquote')

    allow_module('Products.CMFPlone.utils')

    # For content_status_modify
    from Products.CMFCore.WorkflowCore import ObjectMoved, ObjectDeleted, \
                                              WorkflowException
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore').declarePublic(
        'ObjectMoved')
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore').declarePublic(
        'ObjectDeleted')
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore').declarePublic(
        'WorkflowException')
    allow_class(ObjectMoved)
    allow_class(ObjectDeleted)
    allow_class(WorkflowException)

    from PloneBatch import Batch
    allow_class(Batch)

    # Make Batch available at module level
    this_module.Batch = Batch

    from StringIO import StringIO
    allow_class(StringIO)

    # Make Unauthorized importable TTW
    ModuleSecurityInfo('AccessControl').declarePublic('Unauthorized')

    # Make Forbidden importable TTW
    ModuleSecurityInfo('zExceptions').declarePublic('Forbidden')

    # Make ConflictError importable TTW
    ModuleSecurityInfo('ZODB.POSException').declarePublic('ConflictError')

    # Make ZCTextIndex ParseError importable TTW
    ModuleSecurityInfo('Products.ZCTextIndex.ParseTree').declarePublic(
        'ParseError')

    # Make DateTimeError importable TTW
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('SyntaxError')

    # BBB support for DateTime < 3
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('SyntaxError')

    # Make CopyError importable TTW
    ModuleSecurityInfo('OFS.CopySupport').declarePublic('CopyError')

    # Make DiscussionNotAllowed importable TTW
    ModuleSecurityInfo('Products.CMFDefault.DiscussionTool').declarePublic(
        'DiscussionNotAllowed')

    # Make AllowSendto importable TTW
    ModuleSecurityInfo('Products.CMFPlone.PloneTool').declarePublic(
        'AllowSendto')

    # Make ZCatalog's mergeResults importable TTW
    ModuleSecurityInfo('Products.ZCatalog.Catalog').declarePublic(
        'mergeResults')

    # Make the navtree constructs available TTW
    allow_module('Products.CMFPlone.browser.navtree')

    # Allow access to the exception in the folder_delete script
    from OFS.ObjectManager import BeforeDeleteException
    allow_module('OFS.ObjectManager')
    allow_class(BeforeDeleteException)

    # Make cgi.escape available TTW
    ModuleSecurityInfo('cgi').declarePublic('escape')

    # Apply monkey patches
    import patches

    # Register unicode splitter w/ ZCTextIndex
    # pipeline registry
    import UnicodeSplitter

    # Plone content

    # Usage of PloneFolder is discouraged.
    import PloneFolder

    contentClasses = (PloneFolder.PloneFolder, )
    contentConstructors = (PloneFolder.addPloneFolder, )

    # CMFCore and CMFDefault tools
    from Products.CMFCore import CachingPolicyManager

    # Plone tools
    import PloneTool
    import FactoryTool
    import InterfaceTool
    import MigrationTool
    import PloneControlPanel
    import WorkflowTool
    import URLTool
    import MetadataTool
    import RegistrationTool
    import SyndicationTool
    import PropertiesTool
    import ActionsTool
    import TypesTool
    import UndoTool
    import CatalogTool
    import SkinsTool
    import DiscussionTool
    import CalendarTool
    import ActionIconsTool
    import QuickInstallerTool
    import TranslationServiceTool

    tools = (
        PloneTool.PloneTool,
        WorkflowTool.WorkflowTool,
        CachingPolicyManager.CachingPolicyManager,
        FactoryTool.FactoryTool,
        PropertiesTool.PropertiesTool,
        MigrationTool.MigrationTool,
        InterfaceTool.InterfaceTool,
        PloneControlPanel.PloneControlPanel,
        RegistrationTool.RegistrationTool,
        URLTool.URLTool,
        MetadataTool.MetadataTool,
        ActionsTool.ActionsTool,
        TypesTool.TypesTool,
        UndoTool.UndoTool,
        SyndicationTool.SyndicationTool,
        CatalogTool.CatalogTool,
        SkinsTool.SkinsTool,
        DiscussionTool.DiscussionTool,
        ActionIconsTool.ActionIconsTool,
        CalendarTool.CalendarTool,
        QuickInstallerTool.QuickInstallerTool,
        TranslationServiceTool.TranslationServiceTool,
    )

    from Products.CMFCore.utils import ContentInit
    from Products.CMFPlone.utils import ToolInit

    # Register tools and content
    ToolInit(
        'Plone Tool',
        tools=tools,
        icon='tool.gif',
    ).initialize(context)

    ContentInit(
        'Plone Content',
        content_types=contentClasses,
        permission=ADD_CONTENT_PERMISSION,
        extra_constructors=contentConstructors,
    ).initialize(context)

    from Products.CMFPlone.Portal import PloneSite
    from Products.CMFPlone.factory import zmi_constructor
    from AccessControl.Permissions import view_management_screens
    context.registerClass(
        instance_class=PloneSite,
        permission=view_management_screens,
        constructors=(zmi_constructor, ),
    )

    from plone.app.folder import nogopip
    context.registerClass(nogopip.GopipIndex,
                          permission='Add Pluggable Index',
                          constructors=(nogopip.manage_addGopipForm,
                                        nogopip.manage_addGopipIndex),
                          icon='index.gif',
                          visibility=None)
Ejemplo n.º 38
0
# coding=utf-8
from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class

moduleSecurity = ModuleSecurityInfo('Products.GSSiteMenu.sitemenu')
moduleSecurity.declarePublic('SiteMenuItem')
moduleSecurity.declarePublic('SiteMenu')
from sitemenu import FolderMenuItem, SimpleMenuItem, SimpleBrowserMenuItem, SiteMenu
allow_class(FolderMenuItem)
allow_class(SimpleMenuItem)
allow_class(SimpleBrowserMenuItem)
allow_class(SiteMenu)

Ejemplo n.º 39
0
            authors.append({
                "id": None,
                "first": None,
                "middle": None,
                "last": self.obj.getByline(),
                "email": None,
                "description": None,
            })

        if len(authors):
            return authors
        else:
            return None


allow_class(_Article)


class ArticleFactory(object):
    def __init__(self, lookupObj_func, request=None):
        self.getObject = lookupObj_func
        self.request = request

    def makeArticle(self, uid=None, obj=None, request=None):
        #if uid and object are both none, throw an exception.
        if uid is not None:
            obj = self.getObject(uid)
            obj = aq_inner(obj)
            if obj is None:
                return None
        elif obj is None:
Ejemplo n.º 40
0
        else:
            mt = MailTemplate(id, file, headers.get('content_type'))

        self._setObject(id, mt)
        ob = getattr(self, id)
        if mailhost:
            ob._setPropValue('mailhost', mailhost)

        if submit == " Add and Edit ":
            u = ob.absolute_url()
        else:
            u = ob.aq_parent.absolute_url()
        REQUEST.RESPONSE.redirect(u + '/manage_main')


# allow all the email module's public bits
import email
for name in email.__all__:
    path = 'email.' + name
    allow_module(path)
    try:
        mod = __import__(path)
    except ImportError:
        pass
    else:
        mod = getattr(mod, name)
        for mod_name in dir(mod):
            obj = getattr(mod, mod_name)
            if isinstance(obj, ClassType):
                allow_class(obj)
Ejemplo n.º 41
0
from Products.CMFCore.DirectoryView import registerDirectory
from config import GLOBALS

registerDirectory('skins', GLOBALS)


from AccessControl import allow_module, allow_class
from Acquisition import aq_inner, aq_parent
from Products.SIFATipp09.interfaces import ISubscriberInfo
from Products.SIFATipp09.interfaces import INewsletterInfo
allow_module('Products.SIFATipp09.interfaces')
allow_class(ISubscriberInfo)
allow_class(INewsletterInfo)
allow_module('Acquisition')

Ejemplo n.º 42
0
              *args, **kwd)
    return value

  def delete(self, *args, **kwd):
    """ Delete cache key. 
    accept same arguments as __call__ to clear
    the cache entry with the same cache_id
    """
    cache_factory = self.cache_factory
    scope = kwd.pop('scope', DEFAULT_CACHE_SCOPE)
    cache_id = self.generateCacheId(self.id, *args, **kwd)
    cache_factory = CachingMethod.factories[cache_factory]
    for cp in cache_factory.getCachePluginList():
      cp.delete(cache_id, scope)

allow_class(CachingMethod)

# TransactionCache is a cache per transaction. The purpose of this cache is
# to accelerate some heavy read-only operations. Note that this must not be
# enabled when a transaction may modify ZODB objects.
def getReadOnlyTransactionCache():
  """Get the transaction cache.
  """
  return getTransactionalVariable().get('read_only_transaction_cache')

@contextmanager
def readOnlyTransactionCache():
  tv = getTransactionalVariable()
  if 'read_only_transaction_cache' in tv:
    yield
  else:
Ejemplo n.º 43
0
            u"This URL must be properly configured in Velruse to call the remote "
            u"service"),
        missing_value="",
        required=False)
    service_icon = schema.ASCIILine(
        title=_(u"Icon"),
        description=_(
            "velruse_backend_icon_help",
            default=
            u"An URL (can also be a relative path) to an icon to be displayed in "
            u"the login form. Best format is 64x64px."),
        missing_value="",
        required=False)


class VelruseBackendConfig(object):
    implements(IVelruseBackendConfig)

    def __init__(self, service_name=u'', service_url='', service_icon=""):
        self.service_name = service_name
        self.service_url = service_url
        self.service_icon = service_icon


registerFactoryAdapter(IVelruseBackendConfig, VelruseBackendConfig)
allow_class(VelruseBackendConfig)


class PersistentObject(PersistentField, schema.Object):
    pass
Ejemplo n.º 44
0
def initialize(context):
    """Initializer called when used as a Zope 2 product."""

    tipos = """
        voidType
        stringType
        untypedType
        IDType
        NCNameType
        NameType
        ENTITYType
        IDREFType
        languageType
        NMTOKENType
        QNameType
        tokenType
        normalizedStringType
        CDATAType
        booleanType
        decimalType
        floatType
        doubleType
        durationType
        timeDurationType
        dateTimeType
        recurringInstantType
        timeInstantType
        timePeriodType
        timeType
        dateType
        gYearMonthType
        gYearType
        centuryType
        yearType
        gMonthDayType
        recurringDateType
        gMonthType
        monthType
        gDayType
        recurringDayType
        hexBinaryType
        base64BinaryType
        base64Type
        binaryType
        anyURIType
        uriType
        uriReferenceType
        NOTATIONType
        ENTITIESType
        IDREFSType
        NMTOKENSType
        integerType
        nonPositiveIntegerType
        non_Positive_IntegerType
        negativeIntegerType
        negative_IntegerType
        longType
        intType
        shortType
        byteType
        nonNegativeIntegerType
        non_Negative_IntegerType
        unsignedLongType
        unsignedIntType
        unsignedShortType
        unsignedByteType
        positiveIntegerType
        positive_IntegerType
        compoundType
        structType
        headerType
        bodyType
        arrayType
        typedArrayType
    """

    tipos = [t.strip() for t in tipos.split('\n') if t.strip()]
    
    product_globals = globals()
    
    for t in tipos:
        dotted_name = 'SOAPpy.Types.' + t
        parts = dotted_name.split('.')
        m_name = '.'.join(parts[:-1])
        k_name = parts[-1]
        ModuleSecurityInfo(m_name).declarePublic(t)
        module = __import__(m_name, product_globals, locals(), [k_name])
        klass = getattr(module, k_name)
        allow_class(klass)
    
    allow_module('xml.parsers.expat')
    
    ModuleSecurityInfo('App.Common').declarePublic('rfc1123_date')
    def upgrade(self):
        """ Upgrade existing objects.

        """
        # originally we weren't setting the ID correctly
        self.id = self.getId()

InitializeClass(CustomUser)


class ValidationError(Exception):
    """ Raised if an email address is invalid.

    """

allow_class(ValidationError)


def addCustomUser(self, name, password, roles, domains):
    """ Add a CustomUser to a folder.

    """
    ob = CustomUser(name, password, roles, domains)
    ob.id = ob.getId()  # make sure we have an actual ID
    self._setObject(name, ob)


def removedCustomUser(ob, event):
    """ A CustomUser was removed.

    """
Ejemplo n.º 46
0
from Products.Archetypes.utils import capitalize
from Products.CMFCore import DirectoryView
from Products.CMFCore import permissions as cmfpermissions
from Products.CMFCore import utils as cmfutils
from Products.CMFPlone.utils import ToolInit
from config import *

DirectoryView.registerDirectory('skins', product_globals)


##code-section custom-init-head #fill in your manual code here
##/code-section custom-init-head

allow_module("Products.PleiadesEntity.content.interfaces")
from Products.PleiadesEntity.content.interfaces import *
allow_class(IPlace)

def initialize(context):
    """initialize product (called by zope)"""
    ##code-section custom-init-top #fill in your manual code here
    ##/code-section custom-init-top

    # imports packages and types for registration
    import content


    # Initialize portal content
    all_content_types, all_constructors, all_ftis = process_types(
        listTypes(PROJECTNAME),
        PROJECTNAME)
#
# You MUST follow the rules in README_STYLE before checking in code
# to the head. Code which does not follow the rules will be rejected.
#
from __future__ import absolute_import, unicode_literals
from . import XWFMailingListManager
from . import XWFMailingList
from . import XWFVirtualMailingListArchive2

from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class, allow_type

from .queries import MessageQuery

q_security = ModuleSecurityInfo(b'Products.XWFMailingListManager.queries')
q_security.declarePublic(b'MessageQuery')
allow_class(MessageQuery)

from datetime import datetime
allow_type(datetime)

import time
allow_class(time)


def initialize(context):
    # import lazily and defer initialization to the module
    XWFMailingListManager.initialize(context)
    XWFMailingList.initialize(context)
    XWFVirtualMailingListArchive2.initialize(context)
Ejemplo n.º 48
0
def initialize(context):

    # Stuff has been moved from module level to this method for a
    # better separation of import and installation.
    # For the general user this change does not make a difference.
    # For test authors (and people who use parts of Plone only)
    # it does speed up import *significantly*.

    from AccessControl import ModuleSecurityInfo
    from AccessControl import allow_module, allow_class

    # protect OFS.ObjectManager
    ModuleSecurityInfo('OFS.ObjectManager').setDefaultAccess(0)
    ModuleSecurityInfo('OFS.ObjectManager').declareObjectPrivate()
    ModuleSecurityInfo('OFS.ObjectManager').declarePublic('BeforeDeleteException')

    # allow logging
    ModuleSecurityInfo('logging').declarePublic('getLogger')
    from logging import Logger
    allow_class(Logger)

    # various small utils functions
    # added for unescaping view names in urls when finding selected action
    ModuleSecurityInfo('urllib').declarePublic('unquote')

    allow_module('Products.CMFPlone.utils')

    # For content_status_modify
    from Products.CMFCore.WorkflowCore import ObjectMoved, ObjectDeleted, \
                                              WorkflowException
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore') \
        .declarePublic('ObjectMoved')
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore') \
        .declarePublic('ObjectDeleted')
    ModuleSecurityInfo('Products.CMFCore.WorkflowCore') \
        .declarePublic('WorkflowException')
    allow_class(ObjectMoved)
    allow_class(ObjectDeleted)
    allow_class(WorkflowException)

    from PloneBatch import Batch
    allow_class(Batch)

    # Make Batch available at module level
    this_module.Batch = Batch

    ModuleSecurityInfo('StringIO').declarePublic('StringIO')
    from StringIO import StringIO
    allow_class(StringIO)

    # Make Unauthorized importable TTW
    ModuleSecurityInfo('AccessControl').declarePublic('Unauthorized')

    # Make Forbidden importable TTW
    ModuleSecurityInfo('zExceptions').declarePublic('Forbidden')

    # Make ConflictError importable TTW
    ModuleSecurityInfo('ZODB.POSException').declarePublic('ConflictError')

    # Make ZCTextIndex ParseError importable TTW
    ModuleSecurityInfo('Products.ZCTextIndex.ParseTree') \
        .declarePublic('ParseError')

    # Make DateTimeError importable TTW
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.interfaces').declarePublic('SyntaxError')

    # BBB support for DateTime < 3
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('DateTimeError')
    ModuleSecurityInfo('DateTime.DateTime').declarePublic('SyntaxError')

    # Make CopyError importable TTW
    ModuleSecurityInfo('OFS.CopySupport').declarePublic('CopyError')

    # Make AllowSendto importable TTW
    ModuleSecurityInfo('Products.CMFPlone.PloneTool') \
        .declarePublic('AllowSendto')

    # Make ZCatalog's mergeResults importable TTW
    ModuleSecurityInfo('Products.ZCatalog.Catalog') \
        .declarePublic('mergeResults')

    # Make the navtree constructs available TTW
    allow_module('Products.CMFPlone.browser.navtree')

    # Allow access to the exception in the folder_delete script
    from OFS.ObjectManager import BeforeDeleteException
    allow_module('OFS.ObjectManager')
    allow_class(BeforeDeleteException)

    # Make cgi.escape available TTW
    ModuleSecurityInfo('cgi').declarePublic('escape')

    # Apply monkey patches
    import patches

    # Register unicode splitter w/ ZCTextIndex
    # pipeline registry
    import UnicodeSplitter

    # Plone content

    # Usage of PloneFolder is discouraged.
    import PloneFolder

    contentClasses = (PloneFolder.PloneFolder, )
    contentConstructors = (PloneFolder.addPloneFolder, )

    # CMFCore and CMFDefault tools
    from Products.CMFCore import CachingPolicyManager

    # Plone tools
    import PloneTool
    import FactoryTool
    import MigrationTool
    import PloneControlPanel
    import WorkflowTool
    import URLTool
    import MetadataTool
    import RegistrationTool
    import PropertiesTool
    import ActionsTool
    import TypesTool
    import CatalogTool
    import SkinsTool
    import CalendarTool
    import QuickInstallerTool
    import TranslationServiceTool

    tools = (PloneTool.PloneTool,
             WorkflowTool.WorkflowTool,
             CachingPolicyManager.CachingPolicyManager,
             FactoryTool.FactoryTool,
             PropertiesTool.PropertiesTool,
             MigrationTool.MigrationTool,
             PloneControlPanel.PloneControlPanel,
             RegistrationTool.RegistrationTool,
             URLTool.URLTool,
             MetadataTool.MetadataTool,
             ActionsTool.ActionsTool,
             TypesTool.TypesTool,
             CatalogTool.CatalogTool,
             SkinsTool.SkinsTool,
             CalendarTool.CalendarTool,
             QuickInstallerTool.QuickInstallerTool,
             TranslationServiceTool.TranslationServiceTool,
            )

    from Products.CMFCore.utils import ContentInit
    from Products.CMFPlone.utils import ToolInit

    # Register tools and content
    ToolInit('Plone Tool',
             tools=tools,
             icon='tool.gif',
             ).initialize(context)

    ContentInit('Plone Content',
                content_types=contentClasses,
                permission=ADD_CONTENT_PERMISSION,
                extra_constructors=contentConstructors,
                ).initialize(context)

    from Products.CMFPlone.Portal import PloneSite
    from Products.CMFPlone.factory import zmi_constructor
    from AccessControl.Permissions import view_management_screens
    context.registerClass(
        instance_class=PloneSite,
        permission=view_management_screens,
        constructors=(zmi_constructor, ),
    )

    from plone.app.folder import nogopip
    context.registerClass(nogopip.GopipIndex,
        permission='Add Pluggable Index',
        constructors=(nogopip.manage_addGopipForm,
                      nogopip.manage_addGopipIndex),
        icon='index.gif',
        visibility=None)
Ejemplo n.º 49
0
from Products.Formulator import Widget, Validator
from Products.Formulator.Field import ZMIField
from Products.Formulator.DummyField import fields
from Products.Formulator.Errors import ValidationError
from Products.Formulator.TALESField import TALESMethod
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from Products.ERP5Type.ObjectMessage import ObjectMessage
from Products.ERP5Type.Globals import DTMLFile


class BrokenProxyField(Exception):
    pass


allow_class(BrokenProxyField)


class WidgetDelegatedMethod(Method):
    """Method delegated to the proxied field's widget.
  """
    func_code = None

    def __init__(self, method_id, default=''):
        self._method_id = method_id
        self._default = default

    def __call__(self, instance, *args, **kw):
        field = instance
        proxied_field = field.getRecursiveTemplateField()
        if proxied_field:
Ejemplo n.º 50
0
Archivo: Cache.py Proyecto: ra2003/erp5
        return value

    def delete(self, *args, **kwd):
        """ Delete cache key.
    accept same arguments as __call__ to clear
    the cache entry with the same cache_id
    """
        cache_factory = self.cache_factory
        scope = kwd.pop('scope', DEFAULT_CACHE_SCOPE)
        cache_id = self.generateCacheId(self.id, *args, **kwd)
        cache_factory = CachingMethod.factories[cache_factory]
        for cp in cache_factory.getCachePluginList():
            cp.delete(cache_id, scope)


allow_class(CachingMethod)


# TransactionCache is a cache per transaction. The purpose of this cache is
# to accelerate some heavy read-only operations. Note that this must not be
# enabled when a transaction may modify ZODB objects.
def getReadOnlyTransactionCache():
    """Get the transaction cache.
  """
    return getTransactionalVariable().get('read_only_transaction_cache')


@contextmanager
def readOnlyTransactionCache():
    tv = getTransactionalVariable()
    if 'read_only_transaction_cache' in tv:
Ejemplo n.º 51
0
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declarePublic('getAllowableContentTypes')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declarePublic('getAllowedContentTypes')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declarePublic('getForbiddenContentTypes')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declarePublic('getDefaultContentType')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declareProtected(permissions.ManagePortal, 'setForbiddenContentTypes')
ModuleSecurityInfo('Products.Archetypes.mimetype_utils').declareProtected(permissions.ManagePortal, 'setDefaultContentType')

# Import "PloneMessageFactory as _" to create messages in plone domain
# duplicated here so we don't add a dependency on CMFPlone
from zope.i18nmessageid import MessageFactory
PloneMessageFactory = MessageFactory('plone')
ModuleSecurityInfo('Products.Archetypes').declarePublic('PloneMessageFactory')

# make DisplayList accessible from python scripts and others objects executed
# in a restricted environment
allow_class(DisplayList)

# Allow import of NotFound exception
ModuleSecurityInfo('zExceptions').declarePublic('NotFound')

###
# register tools and content types
###
from Products.Archetypes.ArchetypeTool import process_types, listTypes
from Products.Archetypes.ArchetypeTool import ArchetypeTool
ATToolModule = sys.modules[ArchetypeTool.__module__]  # mpf :|
from Products.Archetypes.ArchTTWTool import ArchTTWTool
from Products.Archetypes.ReferenceEngine import ReferenceCatalog as RefTool
from Products.Archetypes.UIDCatalog import UIDCatalog as UIDTool

Ejemplo n.º 52
0
        missing_value="",
        required=False,
    )
    service_icon = schema.ASCIILine(
        title=_(u"Icon"),
        description=_(
            "velruse_backend_icon_help",
            default=u"An URL (can also be a relative path) to an icon to be displayed in "
            u"the login form. Best format is 64x64px.",
        ),
        missing_value="",
        required=False,
    )


class VelruseBackendConfig(object):
    implements(IVelruseBackendConfig)

    def __init__(self, service_name=u"", service_url="", service_icon=""):
        self.service_name = service_name
        self.service_url = service_url
        self.service_icon = service_icon


registerFactoryAdapter(IVelruseBackendConfig, VelruseBackendConfig)
allow_class(VelruseBackendConfig)


class PersistentObject(PersistentField, schema.Object):
    pass
Ejemplo n.º 53
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from AccessControl import ModuleSecurityInfo
from AccessControl import allow_class

eu_security = ModuleSecurityInfo('gs.profile.email.base.emailuser')
eu_security.declarePublic('EmailUser')

#lint:disable
from .emailuser import EmailUserFromUser, EmailUser
from .emailaddress import NewEmailAddress, EmailAddressExists
from .err import AddressError, AddressMissingError, AddressExistsError
from .utils import sanitise_address
#lint:enable
allow_class(EmailUserFromUser)
Ejemplo n.º 54
0
from Products.Archetypes import atapi
from Products.CMFCore import utils as cmfutils
from Products.CMFCore.permissions import setDefaultRoles

from AccessControl import allow_class

##code-section imports
##/code-section imports 

# Define a message factory for when this product is internationalised.
# This will be imported with the special name "_" in most modules. Strings
# like _(u"message") will then be extracted by i18n tools for translation.

DocpoolMessageFactory = MessageFactory('elan.irix')
allow_class(DocpoolMessageFactory)

##code-section security
##/code-section security 

def initialize(context):
    """Intializer called when used as a Zope 2 product.
    
    This is referenced from configure.zcml. Regstrations as a "Zope 2 product" 
    is necessary for GenericSetup profiles to work, for example.
    
    Here, we call the Archetypes machinery to register our content types 
    with Zope and the CMF.
    
    """
    ##code-section init
Ejemplo n.º 55
0
# These classes are placed here so that they can be imported into TTW Python
# scripts. To do so, add the following line to your Py script:
# from Products.Formulator.Errors import ValidationError, FormValidationError

from AccessControl import allow_class


class FormValidationError(Exception):
    def __init__(self, errors, result):
        Exception.__init__(self, "Form Validation Error")
        self.errors = errors
        self.result = result


allow_class(FormValidationError)


class ValidationError(Exception):
    def __init__(self, error_key, field):
        Exception.__init__(self, error_key, field.id)
        self.error_key = error_key
        self.field_id = field.id
        self.field = field
        self.error_text = field.get_error_message(error_key)


allow_class(ValidationError)


class FieldDisabledError(AttributeError):