Back to index

plone3  3.1.7
Classes | Functions | Variables
CMFCore.utils Namespace Reference

Classes

class  _ViewEmulator
class  ImmutableId
class  UniqueObject
class  SimpleItemWithProperties
class  ToolInit
class  ContentInit
class  SimpleRecord

Functions

def registerToolInterface
def getToolInterface
def getToolByName
def getToolByInterfaceName
def getUtilityByInterfaceName
def cookString
def tuplize
def _getAuthenticatedUser
def _checkPermission
def _limitGrantedRoles
def _mergedLocalRoles
def _ac_inherited_permissions
def _modifyPermissionMappings
def parse_etags
def _checkConditionalGET
def _setCacheHeaders
def manage_addToolForm
def manage_addTool
def manage_addContentForm
def manage_addContent
def initializeBasesPhase1
def initializeBasesPhase2
def registerIcon
def keywordsplitter
def contributorsplitter
def normalize
def expandpath
def minimalpath
def getContainingPackage
def getPackageLocation
def getPackageName
def _OldCacheHeaders
def _FSCacheHeaders

Variables

string SUBTEMPLATE = '__SUBTEMPLATE__'
tuple security = ModuleSecurityInfo( 'Products.CMFCore.utils' )
tuple _globals = globals()
tuple _dtmldir = os_path.join( package_home( globals() ), 'dtml' )
tuple _wwwdir = os_path.join( package_home( globals() ), 'www' )
list _marker = []
dictionary _tool_interface_registry = {}
tuple addInstanceForm = HTMLFile('dtml/addInstance', globals())
tuple KEYSPLITRE = re.compile(r'[,;]')
tuple CONTRIBSPLITRE = re.compile(r';')
list ProductsPath = [ abspath(ppath) for ppath in Products.__path__ ]
tuple Message = MessageFactory('cmf_default')

Function Documentation

def CMFCore.utils._ac_inherited_permissions (   ob,
  all = 0 
) [private]

Definition at line 242 of file utils.py.

00242 
00243 def _ac_inherited_permissions(ob, all=0):
00244     # Get all permissions not defined in ourself that are inherited
00245     # This will be a sequence of tuples with a name as the first item and
00246     # an empty tuple as the second.
00247     d = {}
00248     perms = getattr(ob, '__ac_permissions__', ())
00249     for p in perms: d[p[0]] = None
00250     r = gather_permissions(ob.__class__, [], d)
00251     if all:
00252        if hasattr(ob, '_subobject_permissions'):
00253            for p in ob._subobject_permissions():
00254                pname=p[0]
00255                if not d.has_key(pname):
00256                    d[pname]=1
00257                    r.append(p)
00258        r = list(perms) + r
00259     return r
00260 
security.declarePrivate('_modifyPermissionMappings')

Here is the caller graph for this function:

def CMFCore.utils._checkConditionalGET (   obj,
  extra_context 
) [private]
A conditional GET is done using one or both of the request
   headers:

   If-Modified-Since: Date
   If-None-Match: list ETags (comma delimited, sometimes quoted)

   If both conditions are present, both must be satisfied.

   This method checks the caching policy manager to see if
   a content object's Last-modified date and ETag satisfy
   the conditional GET headers.

   Returns the tuple (last_modified, etag) if the conditional
   GET requirements are met and None if not.

   It is possible for one of the tuple elements to be None.
   For example, if there is no If-None-Match header and
   the caching policy does not specify an ETag, we will
   just return (last_modified, None).

Definition at line 336 of file utils.py.

00336 
00337 def _checkConditionalGET(obj, extra_context):
00338     """A conditional GET is done using one or both of the request
00339        headers:
00340 
00341        If-Modified-Since: Date
00342        If-None-Match: list ETags (comma delimited, sometimes quoted)
00343 
00344        If both conditions are present, both must be satisfied.
00345 
00346        This method checks the caching policy manager to see if
00347        a content object's Last-modified date and ETag satisfy
00348        the conditional GET headers.
00349 
00350        Returns the tuple (last_modified, etag) if the conditional
00351        GET requirements are met and None if not.
00352 
00353        It is possible for one of the tuple elements to be None.
00354        For example, if there is no If-None-Match header and
00355        the caching policy does not specify an ETag, we will
00356        just return (last_modified, None).
00357        """
00358 
00359     REQUEST = getattr(obj, 'REQUEST', None)
00360     if REQUEST is None:
00361         return False
00362 
00363     # check whether we need to suppress subtemplates
00364     call_count = getattr(REQUEST, SUBTEMPLATE, 0)
00365     setattr(REQUEST, SUBTEMPLATE, call_count+1)
00366     if call_count != 0:
00367         return False
00368 
00369     if_modified_since = REQUEST.get_header('If-Modified-Since', None)
00370     if_none_match = REQUEST.get_header('If-None-Match', None)
00371 
00372     if if_modified_since is None and if_none_match is None:
00373         # not a conditional GET
00374         return False
00375 
00376     manager = getToolByName(obj, 'caching_policy_manager', None)
00377     if manager is None:
00378         return False
00379 
00380     ret = manager.getModTimeAndETag(aq_parent(obj), obj.getId(), extra_context)
00381     if ret is None:
00382         # no appropriate policy or 304s not enabled
00383         return False
00384 
00385     (content_mod_time, content_etag, set_last_modified_header) = ret
00386     if content_mod_time:
00387         mod_time_secs = long(content_mod_time.timeTime())
00388     else:
00389         mod_time_secs = None
00390 
00391     if if_modified_since:
00392         # from CMFCore/FSFile.py:
00393         if_modified_since = if_modified_since.split(';')[0]
00394         # Some proxies seem to send invalid date strings for this
00395         # header. If the date string is not valid, we ignore it
00396         # rather than raise an error to be generally consistent
00397         # with common servers such as Apache (which can usually
00398         # understand the screwy date string as a lucky side effect
00399         # of the way they parse it).
00400         try:
00401             if_modified_since=long(DateTime(if_modified_since).timeTime())
00402         except:
00403             if_mod_since=None
00404 
00405     client_etags = None
00406     if if_none_match:
00407         client_etags = parse_etags(if_none_match)
00408 
00409     if not if_modified_since and not client_etags:
00410         # not a conditional GET, or headers are messed up
00411         return False
00412 
00413     if if_modified_since:
00414         if ( not content_mod_time or 
00415              mod_time_secs < 0 or 
00416              mod_time_secs > if_modified_since ):
00417             return False
00418 
00419     if client_etags:
00420         if ( not content_etag or 
00421              (content_etag not in client_etags and '*' not in client_etags) ):
00422             return False
00423     else:
00424         # If we generate an ETag, don't validate the conditional GET unless 
00425         # the client supplies an ETag
00426         # This may be more conservative than the spec requires, but we are 
00427         # already _way_ more conservative.
00428         if content_etag:
00429             return False
00430 
00431     response = REQUEST.RESPONSE
00432     if content_mod_time and set_last_modified_header:
00433         response.setHeader('Last-modified', str(content_mod_time))
00434     if content_etag:
00435         response.setHeader('ETag', content_etag, literal=1)
00436     response.setStatus(304)
00437     delattr(REQUEST, SUBTEMPLATE)
00438 
00439     return True
00440 
security.declarePrivate('_setCacheHeaders')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils._checkPermission (   permission,
  obj 
) [private]

Definition at line 192 of file utils.py.

00192 
00193 def _checkPermission(permission, obj):
00194     return getSecurityManager().checkPermission(permission, obj)
00195 
00196 # If Zope ever provides a call to getRolesInContext() through
00197 # the SecurityManager API, the method below needs to be updated.
security.declarePrivate('_limitGrantedRoles')

Here is the caller graph for this function:

def CMFCore.utils._FSCacheHeaders (   obj) [private]

Definition at line 898 of file utils.py.

00898 
00899 def _FSCacheHeaders(obj):
00900     # Old-style setting of modified headers for FS-based objects
00901 
00902     REQUEST = getattr(obj, 'REQUEST', None)
00903     if REQUEST is None:
00904         return False
00905 
00906     RESPONSE = REQUEST.RESPONSE
00907     header = REQUEST.get_header('If-Modified-Since', None)
00908     last_mod = obj._file_mod_time
00909 
00910     if header is not None:
00911         header = header.split(';')[0]
00912         # Some proxies seem to send invalid date strings for this
00913         # header. If the date string is not valid, we ignore it
00914         # rather than raise an error to be generally consistent
00915         # with common servers such as Apache (which can usually
00916         # understand the screwy date string as a lucky side effect
00917         # of the way they parse it).
00918         try:
00919             mod_since=DateTime(header)
00920             mod_since=long(mod_since.timeTime())
00921         except TypeError:
00922             mod_since=None
00923 
00924         if mod_since is not None:
00925             if last_mod > 0 and last_mod <= mod_since:
00926                 RESPONSE.setStatus(304)
00927                 return True
00928 
00929     #Last-Modified will get stomped on by a cache policy if there is
00930     #one set....
00931     RESPONSE.setHeader('Last-Modified', rfc1123_date(last_mod))
00932 

Here is the caller graph for this function:

def CMFCore.utils._getAuthenticatedUser (   self) [private]

Definition at line 188 of file utils.py.

00188 
00189 def _getAuthenticatedUser(self):
00190     return getSecurityManager().getUser()
00191 
security.declarePrivate('_checkPermission')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils._limitGrantedRoles (   roles,
  context,
  special_roles = () 
) [private]

Definition at line 198 of file utils.py.

00198 
00199 def _limitGrantedRoles(roles, context, special_roles=()):
00200     # Only allow a user to grant roles already possessed by that user,
00201     # with the exception that all special_roles can also be granted.
00202     user = _getAuthenticatedUser(context)
00203     if user is None:
00204         user_roles = ()
00205     else:
00206         user_roles = user.getRolesInContext(context)
00207     if 'Manager' in user_roles:
00208         # Assume all other roles are allowed.
00209         return
00210     for role in roles:
00211         if role not in special_roles and role not in user_roles:
00212             raise AccessControl_Unauthorized('Too many roles specified.')
00213 
security.declarePrivate('_mergedLocalRoles')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils._mergedLocalRoles (   object) [private]
Returns a merging of object and its ancestors'
__ac_local_roles__.

Definition at line 214 of file utils.py.

00214 
00215 def _mergedLocalRoles(object):
00216     """Returns a merging of object and its ancestors'
00217     __ac_local_roles__."""
00218     # Modified from AccessControl.User.getRolesInContext().
00219     merged = {}
00220     object = getattr(object, 'aq_inner', object)
00221     while 1:
00222         if hasattr(object, '__ac_local_roles__'):
00223             dict = object.__ac_local_roles__ or {}
00224             if callable(dict): dict = dict()
00225             for k, v in dict.items():
00226                 if merged.has_key(k):
00227                     merged[k] = merged[k] + v
00228                 else:
00229                     merged[k] = v
00230         if hasattr(object, 'aq_parent'):
00231             object=object.aq_parent
00232             object=getattr(object, 'aq_inner', object)
00233             continue
00234         if hasattr(object, 'im_self'):
00235             object=object.im_self
00236             object=getattr(object, 'aq_inner', object)
00237             continue
00238         break
00239 
00240     return deepcopy(merged)
00241 
security.declarePrivate('_ac_inherited_permissions')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils._modifyPermissionMappings (   ob,
  map 
) [private]
Modifies multiple role to permission mappings.

Definition at line 261 of file utils.py.

00261 
00262 def _modifyPermissionMappings(ob, map):
00263     """
00264     Modifies multiple role to permission mappings.
00265     """
00266     # This mimics what AccessControl/Role.py does.
00267     # Needless to say, it's crude. :-(
00268     something_changed = 0
00269     perm_info = _ac_inherited_permissions(ob, 1)
00270     for name, settings in map.items():
00271         cur_roles = rolesForPermissionOn(name, ob)
00272         if isinstance(cur_roles, basestring):
00273             cur_roles = [cur_roles]
00274         else:
00275             cur_roles = list(cur_roles)
00276         changed = 0
00277         for (role, allow) in settings.items():
00278             if not allow:
00279                 if role in cur_roles:
00280                     changed = 1
00281                     cur_roles.remove(role)
00282             else:
00283                 if role not in cur_roles:
00284                     changed = 1
00285                     cur_roles.append(role)
00286         if changed:
00287             data = ()  # The list of methods using this permission.
00288             for perm in perm_info:
00289                 n, d = perm[:2]
00290                 if n == name:
00291                     data = d
00292                     break
00293             p = Permission(name, data, ob)
00294             p.setRoles(tuple(cur_roles))
00295             something_changed = 1
00296     return something_changed
00297 
00298 
00299 # Parse a string of etags from an If-None-Match header
00300 # Code follows ZPublisher.HTTPRequest.parse_cookie
parse_etags_lock=allocate_lock()

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils._OldCacheHeaders (   obj) [private]

Definition at line 864 of file utils.py.

00864 
00865 def _OldCacheHeaders(obj):
00866     # Old-style checking of modified headers
00867 
00868     REQUEST = getattr(obj, 'REQUEST', None)
00869     if REQUEST is None:
00870         return False
00871 
00872     RESPONSE = REQUEST.RESPONSE
00873     header = REQUEST.get_header('If-Modified-Since', None)
00874     last_mod = long(obj.modified().timeTime())
00875 
00876     if header is not None:
00877         header = header.split(';')[0]
00878         # Some proxies seem to send invalid date strings for this
00879         # header. If the date string is not valid, we ignore it
00880         # rather than raise an error to be generally consistent
00881         # with common servers such as Apache (which can usually
00882         # understand the screwy date string as a lucky side effect
00883         # of the way they parse it).
00884         try:
00885             mod_since=DateTime(header)
00886             mod_since=long(mod_since.timeTime())
00887         except TypeError:
00888             mod_since=None
00889 
00890         if mod_since is not None:
00891             if last_mod > 0 and last_mod <= mod_since:
00892                 RESPONSE.setStatus(304)
00893                 return True
00894 
00895     #Last-Modified will get stomped on by a cache policy if there is
00896     #one set....
00897     RESPONSE.setHeader('Last-Modified', rfc1123_date(last_mod))

Here is the caller graph for this function:

def CMFCore.utils._setCacheHeaders (   obj,
  extra_context 
) [private]
Set cache headers according to cache policy manager for the obj.

Definition at line 441 of file utils.py.

00441 
00442 def _setCacheHeaders(obj, extra_context):
00443     """Set cache headers according to cache policy manager for the obj."""
00444     REQUEST = getattr(obj, 'REQUEST', None)
00445 
00446     if REQUEST is not None:
00447         call_count = getattr(REQUEST, SUBTEMPLATE, 1) - 1
00448         setattr(REQUEST, SUBTEMPLATE, call_count)
00449         if call_count != 0:
00450            return
00451 
00452         # cleanup
00453         delattr(REQUEST, SUBTEMPLATE)
00454 
00455         content = aq_parent(obj)
00456         manager = getToolByName(obj, 'caching_policy_manager', None)
00457         if manager is None:
00458             return
00459 
00460         view_name = obj.getId()
00461         headers = manager.getHTTPCachingHeaders(
00462                           content, view_name, extra_context
00463                           )
00464         RESPONSE = REQUEST['RESPONSE']
00465         for key, value in headers:
00466             if key == 'ETag':
00467                 RESPONSE.setHeader(key, value, literal=1)
00468             else:
00469                 RESPONSE.setHeader(key, value)
00470         if headers:
00471             RESPONSE.setHeader('X-Cache-Headers-Set-By',
00472                                'CachingPolicyManager: %s' %
00473                                '/'.join(manager.getPhysicalPath()))

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils.contributorsplitter (   headers,
  names = ('Contributors',,
  splitter = CONTRIBSPLITRE.split 
)
Split contributors out of headers, keyed on names.  Returns list.

Definition at line 777 of file utils.py.

00777 
00778                        ):
00779     """ Split contributors out of headers, keyed on names.  Returns list.
00780     """
00781     return keywordsplitter( headers, names, splitter )
00782 
00783 #
00784 #   Directory-handling utilities
00785 #
security.declarePublic('normalize')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils.cookString (   text)
Make a Zope-friendly ID from 'text'.

o Remove any spaces

o Lowercase the ID.

Definition at line 157 of file utils.py.

00157 
00158 def cookString(text):
00159 
00160     """ Make a Zope-friendly ID from 'text'.
00161 
00162     o Remove any spaces
00163 
00164     o Lowercase the ID.
00165     """
00166     rgx = re.compile(r'(^_|[^a-zA-Z0-9-_~\,\.])')
00167     cooked = re.sub(rgx, "",text).lower()
00168     return cooked
00169 
security.declarePublic('tuplize')
Convert minimal filepath to (expanded) filepath.

The (expanded) filepath is the valid absolute path on the current platform
and setup.

Definition at line 795 of file utils.py.

00795 
00796 def expandpath(p):
00797     """ Convert minimal filepath to (expanded) filepath.
00798 
00799     The (expanded) filepath is the valid absolute path on the current platform
00800     and setup.
00801     """
00802     warn('expandpath() is deprecated and will be removed in CMF 2.3.',
00803          DeprecationWarning, stacklevel=2)
00804 
00805     p = os_path.normpath(p)
00806     if os_path.isabs(p):
00807         return p
00808 
00809     for ppath in ProductsPath:
00810         abs = os_path.join(ppath, p)
00811         if os_path.exists(abs):
00812             return abs
00813 
00814     # return the last one, errors will happen else where as as result
00815     # and be caught
00816     return abs
00817 
security.declarePublic('minimalpath')

Here is the call graph for this function:

Definition at line 838 of file utils.py.

00838 
00839 def getContainingPackage(module):
00840     parts = module.split('.')
00841     while parts:
00842         name = '.'.join(parts)
00843         mod = sys.modules[name]
00844         if '__init__' in mod.__file__:
00845             return name
00846         parts = parts[:-1]
00847 
00848     raise ValueError('Unable to find package for module %s' % module)
00849 
security.declarePrivate('getPackageLocation')

Here is the caller graph for this function:

Return the filesystem location of a module.

This is a simple wrapper around the global package_home method which
tricks it into working with just a module name.

Definition at line 850 of file utils.py.

00850 
00851 def getPackageLocation(module):
00852     """ Return the filesystem location of a module.
00853 
00854     This is a simple wrapper around the global package_home method which
00855     tricks it into working with just a module name.
00856     """
00857     package = getContainingPackage(module)
00858     return package_home({'__name__' : package})
00859 
security.declarePrivate('getPackageName')

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils.getPackageName (   globals_)

Definition at line 860 of file utils.py.

00860 
00861 def getPackageName(globals_):
00862     module = globals_['__name__']
00863     return getContainingPackage(module)

Here is the call graph for this function:

Here is the caller graph for this function:

def CMFCore.utils.getToolByInterfaceName (   dotted_name,
  default = _marker 
)

Definition at line 127 of file utils.py.

00127 
00128 def getToolByInterfaceName(dotted_name, default=_marker):
00129     warn('getToolByInterfaceName() is deprecated and will be removed in CMF '
00130          '2.3. Use getUtilityByInterfaceName instead.',
00131          DeprecationWarning, stacklevel=2)
00132 
00133     return getUtilityByInterfaceName(dotted_name, default)
00134 
00135 
security.declarePublic('getUtilityByInterfaceName')

Here is the call graph for this function:

def CMFCore.utils.getToolByName (   obj,
  name,
  default = _marker 
)
Get the tool, 'toolname', by acquiring it.

o Application code should use this method, rather than simply
  acquiring the tool by name, to ease forward migration (e.g.,
  to Zope3).

Definition at line 89 of file utils.py.

00089 
00090 def getToolByName(obj, name, default=_marker):
00091 
00092     """ Get the tool, 'toolname', by acquiring it.
00093 
00094     o Application code should use this method, rather than simply
00095       acquiring the tool by name, to ease forward migration (e.g.,
00096       to Zope3).
00097     """
00098     tool_interface = _tool_interface_registry.get(name)
00099 
00100     if tool_interface is not None:
00101         try:
00102             utility = getUtility(tool_interface)
00103             # Site managers, except for five.localsitemanager, return unwrapped
00104             # utilities. If the result is something which is acquisition-unaware
00105             # but unwrapped we wrap it on the context.
00106             if IAcquirer.providedBy(obj) and \
00107                     aq_parent(utility) is None and \
00108                     IAcquirer.providedBy(utility):
00109                 utilty = utility.__of__(obj)
00110             return utility
00111         except ComponentLookupError:
00112             # behave in backwards-compatible way
00113             # fall through to old implementation
00114             pass
00115     
00116     try:
00117         tool = aq_get(obj, name, default, 1)
00118     except AttributeError:
00119         if default is _marker:
00120             raise
00121         return default
00122     else:
00123         if tool is _marker:
00124             raise AttributeError, name
00125         return tool
00126 
security.declarePublic('getToolByInterfaceName')

Here is the caller graph for this function:

def CMFCore.utils.getToolInterface (   tool_id)
Get the interface registered for a tool ID

Definition at line 82 of file utils.py.

00082 
00083 def getToolInterface(tool_id):
00084     """ Get the interface registered for a tool ID
00085     """
00086     global  _tool_interface_registry
00087     return _tool_interface_registry.get(tool_id, None)
00088 
security.declarePublic('getToolByName')

Here is the caller graph for this function:

def CMFCore.utils.getUtilityByInterfaceName (   dotted_name,
  default = _marker 
)
Get a tool by its fully-qualified dotted interface path

This method replaces getToolByName for use in untrusted code.
Trusted code should use zope.component.getUtility instead.

Definition at line 136 of file utils.py.

00136 
00137 def getUtilityByInterfaceName(dotted_name, default=_marker):
00138     """ Get a tool by its fully-qualified dotted interface path
00139 
00140     This method replaces getToolByName for use in untrusted code.
00141     Trusted code should use zope.component.getUtility instead.
00142     """
00143     try:
00144         iface = resolve_dotted_name(dotted_name)
00145     except ImportError:
00146         if default is _marker:
00147             raise ComponentLookupError, dotted_name
00148         return default
00149 
00150     try:
00151         return getUtility(iface)
00152     except ComponentLookupError:
00153         if default is _marker:
00154             raise
00155         return default
00156 
security.declarePublic('cookString')

Here is the caller graph for this function:

def CMFCore.utils.initializeBasesPhase1 (   base_classes,
  module 
)
Execute the first part of initialization of ZClass base classes.

Stuffs a _ZClass_for_x class in the module for each base.

Definition at line 694 of file utils.py.

00694 
00695 def initializeBasesPhase1(base_classes, module):
00696     """ Execute the first part of initialization of ZClass base classes.
00697 
00698     Stuffs a _ZClass_for_x class in the module for each base.
00699     """
00700     warn('initializeBasesPhase1() is deprecated and will be removed in CMF '
00701          '2.3. There is no replacement because ZClasses are also deprecated.',
00702          DeprecationWarning, stacklevel=2)
00703 
00704     rval = []
00705     for base_class in base_classes:
00706         d={}
00707         zclass_name = '_ZClass_for_%s' % base_class.__name__
00708         exec 'class %s: pass' % zclass_name in d
00709         Z = d[ zclass_name ]
00710         Z.propertysheets = PropertySheets()
00711         Z._zclass_ = base_class
00712         Z.manage_options = ()
00713         Z.__module__ = module.__name__
00714         setattr( module, zclass_name, Z )
00715         rval.append(Z)
00716     return rval

Here is the call graph for this function:

def CMFCore.utils.initializeBasesPhase2 (   zclasses,
  context 
)
Finishes ZClass base initialization.

o 'zclasses' is the list returned by initializeBasesPhase1().

o 'context' is a ProductContext object.

Definition at line 717 of file utils.py.

00717 
00718 def initializeBasesPhase2(zclasses, context):
00719     """ Finishes ZClass base initialization.
00720 
00721     o 'zclasses' is the list returned by initializeBasesPhase1().
00722 
00723     o 'context' is a ProductContext object.
00724     """
00725     warn('initializeBasesPhase2() is deprecated and will be removed in CMF '
00726          '2.3. There is no replacement because ZClasses are also deprecated.',
00727          DeprecationWarning, stacklevel=2)
00728 
00729     for zclass in zclasses:
00730         context.registerZClass(zclass)

Here is the call graph for this function:

def CMFCore.utils.keywordsplitter (   headers,
  names = ('Subject', 'Keywords',
  splitter = KEYSPLITRE.split 
)
Split keywords out of headers, keyed on names.  Returns list.

Definition at line 758 of file utils.py.

00758 
00759                    ):
00760     """ Split keywords out of headers, keyed on names.  Returns list.
00761     """
00762     out = []
00763     for head in names:
00764         keylist = splitter(headers.get(head, ''))
00765         keylist = map(lambda x: x.strip(), keylist)
00766         out.extend( [key for key in keylist if key] )
00767     return out
00768 
00769 #
00770 #   Metadata Contributors splitter utilities
#

Here is the caller graph for this function:

def CMFCore.utils.manage_addContent (   self,
  id,
  type,
  REQUEST = None 
)
Add the content type specified by name.

Definition at line 676 of file utils.py.

00676 
00677 def manage_addContent( self, id, type, REQUEST=None ):
00678 
00679     """ Add the content type specified by name.
00680     """
00681     # self is a FactoryDispatcher.
00682     contentinit = self.contentinit
00683     obj = None
00684     for content_type in contentinit.content_types:
00685         if content_type.meta_type == type:
00686             obj = content_type( id )
00687             break
00688     if obj is None:
00689         raise NotFound(type)
00690     self._setObject( id, obj )
00691     if REQUEST is not None:
00692         return self.manage_main(self, REQUEST)
00693 

def CMFCore.utils.manage_addContentForm (   self,
  REQUEST 
)
Show the add content type form.

Definition at line 660 of file utils.py.

00660 
00661 def manage_addContentForm(self, REQUEST):
00662 
00663     """ Show the add content type form.
00664     """
00665     # self is a FactoryDispatcher.
00666     ci = self.contentinit
00667     tl = []
00668     for t in ci.content_types:
00669         tl.append(t.meta_type)
00670     return addInstanceForm(addInstanceForm, self, REQUEST,
00671                            factory_action='manage_addContent',
00672                            factory_meta_type=ci.meta_type,
00673                            factory_icon=None,
00674                            factory_types_list=tl,
00675                            factory_need_id=1)

def CMFCore.utils.manage_addTool (   self,
  type,
  REQUEST = None 
)
Add the tool specified by name.

Definition at line 599 of file utils.py.

00599 
00600 def manage_addTool(self, type, REQUEST=None):
00601 
00602     """ Add the tool specified by name.
00603     """
00604     # self is a FactoryDispatcher.
00605     toolinit = self.toolinit
00606     obj = None
00607     for tool in toolinit.tools:
00608         if tool.meta_type == type:
00609             obj = tool()
00610             break
00611     if obj is None:
00612         raise NotFound(type)
00613     self._setObject(obj.getId(), obj)
00614     if REQUEST is not None:
00615         return self.manage_main(self, REQUEST)
00616 
00617 
00618 #
00619 #   Now, do the same for creating content factories.
#
def CMFCore.utils.manage_addToolForm (   self,
  REQUEST 
)
Show the add tool form.

Definition at line 582 of file utils.py.

00582 
00583 def manage_addToolForm(self, REQUEST):
00584 
00585     """ Show the add tool form.
00586     """
00587     # self is a FactoryDispatcher.
00588     toolinit = self.toolinit
00589     tl = []
00590     for tool in toolinit.tools:
00591         tl.append(tool.meta_type)
00592     return addInstanceForm(addInstanceForm, self, REQUEST,
00593                            factory_action='manage_addTool',
00594                            factory_meta_type=toolinit.meta_type,
00595                            factory_product_name=toolinit.product_name,
00596                            factory_icon=toolinit.icon,
00597                            factory_types_list=tl,
00598                            factory_need_id=0)

Convert (expanded) filepath to minimal filepath.

The minimal filepath is the cross-platform / cross-setup path stored in
persistent objects and used as key in the directory registry.

Returns a slash-separated path relative to the Products path. If it can't
be found, a normalized path is returned.

Definition at line 818 of file utils.py.

00818 
00819 def minimalpath(p):
00820     """ Convert (expanded) filepath to minimal filepath.
00821 
00822     The minimal filepath is the cross-platform / cross-setup path stored in
00823     persistent objects and used as key in the directory registry.
00824 
00825     Returns a slash-separated path relative to the Products path. If it can't
00826     be found, a normalized path is returned.
00827     """
00828     warn('minimalpath() is deprecated and will be removed in CMF 2.3.',
00829          DeprecationWarning, stacklevel=2)
00830 
00831     p = abspath(p)
00832     for ppath in ProductsPath:
00833         if p.startswith(ppath):
00834             p = p[len(ppath)+1:]
00835             break
00836     return p.replace('\\','/')
00837 
security.declarePrivate('getContainingPackage')

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 786 of file utils.py.

00786 
00787 def normalize(p):
00788     # the first .replace is needed to help normpath when dealing with Windows
00789     # paths under *nix, the second to normalize to '/'
00790     return os_path.normpath(p.replace('\\','/')).replace('\\','/')

Here is the caller graph for this function:

def CMFCore.utils.parse_etags (   text,
  result = None                 # quoted etags (assumed separated by whitespace + a comma),
  etagre_quote = re.compile('(\s*\"([^\"]*)\"\s*,{0,1},
  etagre_noquote = re.compile('(\s*([^,]*)\s*,{0,
  acquire = parse_etags_lock.acquire,
  release = parse_etags_lock.release 
)

Definition at line 309 of file utils.py.

00309 
00310                ):
00311 
00312     if result is None: result=[]
00313     if not len(text):
00314         return result
00315 
00316     acquire()
00317     try:
00318         m = etagre_quote.match(text)
00319         if m:
00320             # Match quoted etag (spec-observing client)
00321             l     = len(m.group(1))
00322             value = m.group(2)
00323         else:
00324             # Match non-quoted etag (lazy client)
00325             m = etagre_noquote.match(text)
00326             if m:
00327                 l     = len(m.group(1))
00328                 value = m.group(2)
00329             else:
00330                 return result
00331     finally: release()
00332 
00333     if value:
00334         result.append(value)
00335     return apply(parse_etags,(text[l:],result))

Here is the caller graph for this function:

def CMFCore.utils.registerIcon (   klass,
  iconspec,
  _prefix = None 
)
Make an icon available for a given class.

o 'klass' is the class being decorated.

o 'iconspec' is the path within the product where the icon lives.

Definition at line 731 of file utils.py.

00731 
00732 def registerIcon(klass, iconspec, _prefix=None):
00733 
00734     """ Make an icon available for a given class.
00735 
00736     o 'klass' is the class being decorated.
00737 
00738     o 'iconspec' is the path within the product where the icon lives.
00739     """
00740     modname = klass.__module__
00741     pid = modname.split('.')[1]
00742     name = os_path.split(iconspec)[1]
00743     klass.icon = 'misc_/%s/%s' % (pid, name)
00744     icon = ImageFile(iconspec, _prefix)
00745     icon.__roles__=None
00746     if not hasattr(misc_images, pid):
00747         setattr(misc_images, pid, MiscImage(pid, {}))
00748     getattr(misc_images, pid)[name]=icon
00749 
00750 #
00751 #   Metadata Keyword splitter utilities
#

Here is the caller graph for this function:

def CMFCore.utils.registerToolInterface (   tool_id,
  tool_interface 
)
Register a tool ID for an interface

Definition at line 75 of file utils.py.

00075 
00076 def registerToolInterface(tool_id, tool_interface):
00077     """ Register a tool ID for an interface
00078     """
00079     global  _tool_interface_registry
00080     _tool_interface_registry[tool_id] = tool_interface
00081 
security.declarePrivate('getToolInterface')

Here is the caller graph for this function:

def CMFCore.utils.tuplize (   valueName,
  value 
)
Make a tuple from 'value'.

o Use 'valueName' to generate appropriate error messages.

Definition at line 170 of file utils.py.

00170 
00171 def tuplize( valueName, value ):
00172 
00173     """ Make a tuple from 'value'.
00174 
00175     o Use 'valueName' to generate appropriate error messages.
00176     """
00177     if isinstance(value, tuple):
00178         return value
00179     if isinstance(value, list):
00180         return tuple( value )
00181     if isinstance(value, basestring):
00182         return tuple( value.split() )
00183     raise ValueError, "%s of unsupported type" % valueName
00184 
00185 #
00186 #   Security utilities, callable only from unrestricted code.
00187 #
security.declarePrivate('_getAuthenticatedUser')

Here is the caller graph for this function:


Variable Documentation

tuple CMFCore.utils._dtmldir = os_path.join( package_home( globals() ), 'dtml' )

Definition at line 64 of file utils.py.

tuple CMFCore.utils._globals = globals()

Definition at line 63 of file utils.py.

Definition at line 70 of file utils.py.

Definition at line 72 of file utils.py.

tuple CMFCore.utils._wwwdir = os_path.join( package_home( globals() ), 'www' )

Definition at line 65 of file utils.py.

tuple CMFCore.utils.addInstanceForm = HTMLFile('dtml/addInstance', globals())

Definition at line 580 of file utils.py.

tuple CMFCore.utils.CONTRIBSPLITRE = re.compile(r';')

Definition at line 771 of file utils.py.

tuple CMFCore.utils.KEYSPLITRE = re.compile(r'[,;]')

Definition at line 752 of file utils.py.

tuple CMFCore.utils.Message = MessageFactory('cmf_default')

Definition at line 941 of file utils.py.

list CMFCore.utils.ProductsPath = [ abspath(ppath) for ppath in Products.__path__ ]

Definition at line 792 of file utils.py.

tuple CMFCore.utils.security = ModuleSecurityInfo( 'Products.CMFCore.utils' )

Definition at line 61 of file utils.py.

string CMFCore.utils.SUBTEMPLATE = '__SUBTEMPLATE__'

Definition at line 59 of file utils.py.