Esempio n. 1
0
def registerMetadataGhost(name):
    def ghoster(obj, portal, **kwargs):
        try:
            ghost=IIndexingGhost(obj)
        except TypeError:
            return
        return ghost.getValue(name)
    registerIndexableAttribute(name, ghoster)
    return ghoster
Esempio n. 2
0
def registerInterfaceIndexer(idx, iface, method=None, default=None):
    """
    dynamically register z3 interface based indexes

    @param idx: name of index

    @param iface: interface to adapt object for indexing

    @param method: optional method on adapter to index

    @param default: default value to return if no adapter found
    
    """
    def indexfx(obj, portal, **kw):
        adapter = iface(obj, _marker)
        if adapter is _marker:
            return default
        if method:
            return getattr(adapter, method)()
        return adapter
    registerIndexableAttribute(idx, indexfx)
Esempio n. 3
0
def initialize(context):
    registerIndexableAttribute('tree_categories', indexTree)
Esempio n. 4
0
 def addIndexerOld(self):
     def test_column(obj, portal, **kwargs):
         return obj.id
     registerIndexableAttribute("test_column", test_column)
# registerIndexableAttribute('user_rating_avg', z3_user_rating_avg)


# Storing the average and number as a tuple allows for quick sorting and easy
# access, while still allowing range searches on the average rating.
# This is probably the way to go if you care about both values.
def z3_user_rating_tuple(object, portal, **kwargs):
    try:
        rated = IUserRating(object)
        return (rated.averageRating, rated.numberOfRatings)
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError


registerIndexableAttribute('user_rating_tuple', z3_user_rating_tuple)


def z3_editorial_rating(object, portal, **kwargs):
    try:
        rated = IEditorialRating(object)
        return rated.rating
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError


registerIndexableAttribute('editorial_rating', z3_editorial_rating)

# Example code for adding a new index and metadata to your catalog, call this
# from your Extensions/Install.py, or use GenericSetup to add the desired
Esempio n. 6
0
                if getattr(props.pigeonhole, visible):
                    field_val = obj.Schema().get(field_name).getAccessor(obj)()
                    if field_val and len(field_val)>0:
                        # good enough -- we found a field that is active and 
                        # has data
                        return True
            return False
    return True

# make these methods available to the portal_catalog
if HAS_INDEXER:
    # Plone 3.3+
    # These indexers need to be registered for Interface instead of
    # IPigeonholeAware because otherwise non-pigeonhole aware types can acquire
    # the values from a pigeonhole-aware parent.
    ph_indexer = indexer(Interface)
    ph_field_1_indexer = ph_indexer(ph_field_1)
    ph_field_2_indexer = ph_indexer(ph_field_2)
    ph_field_3_indexer = ph_indexer(ph_field_3)
    ph_field_4_indexer = ph_indexer(ph_field_4)
    is_relatable_indexer = ph_indexer(is_relatable)
    is_ph_configured_indexer = ph_indexer(is_ph_configured)
else:
    # BBB Plone < 3.3
    registerIndexableAttribute("ph_field_1", ph_field_1)
    registerIndexableAttribute("ph_field_2", ph_field_2)
    registerIndexableAttribute("ph_field_3", ph_field_3)
    registerIndexableAttribute("ph_field_4", ph_field_4)
    registerIndexableAttribute("is_relatable", is_relatable)
    registerIndexableAttribute("is_ph_configured", is_ph_configured)
Esempio n. 7
0

def total_amount_of_products(object, portal, **kwargs):
    try:
        # This has to be done without the help of the catalog. Otherwise it
        # counts before all to counted objects are in the catalog. That is at
        # least the case for Advanced/Update Catalog.
        counter = 0
        # It has to be catalog independent
        if ICategory.providedBy(object):
            counter += len(object.getEasyshopproducts())
            counter = countCategories(object, counter)

        return counter

    except (ComponentLookupError, TypeError, ValueError):
        raise AttributeError


registerIndexableAttribute('total_amount_of_products',
                           total_amount_of_products)


def countCategories(category, counter):
    """
    """
    for category in category.objectValues("Category"):
        counter += len(category.getEasyshopproducts())
        counter = countCategories(category, counter)
    return counter
Esempio n. 8
0
        raise AttributeError

# registerIndexableAttribute('user_rating_avg', z3_user_rating_avg)

# Storing the average and number as a tuple allows for quick sorting and easy
# access, while still allowing range searches on the average rating.
# This is probably the way to go if you care about both values.
def z3_user_rating_tuple(object, portal, **kwargs):
    try:
        rated = IUserRating(object)
        return (rated.averageRating, rated.numberOfRatings)
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

registerIndexableAttribute('user_rating_tuple', z3_user_rating_tuple)

def z3_editorial_rating(object, portal, **kwargs):
    try:
        rated = IEditorialRating(object)
        return rated.rating
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

registerIndexableAttribute('editorial_rating', z3_editorial_rating)

# Example code for adding a new index and metadata to your catalog, call this
# from your Extensions/Install.py, or use GenericSetup to add the desired
# indexes/columns:
    rt = getToolByName(obj, 'portal_ratings')    
    return rt.getRatingStdDev(obj.UID())

def getRatingVariance(obj, portal, **kw):
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')    
    return rt.getRatingSumSquared(obj.UID())

def getEstimatedRating(obj, portal, **kw):
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')    
    return rt.getEstimatedRating(obj.UID())

def getCyninRating(obj, portal, **kw):
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')    
    return rt.getCyninRating(obj.UID())
#
#registerIndexableAttribute("getRatingMean", getRatingMean)
#registerIndexableAttribute("getRatingSumSquared", getRatingSumSquared)
#registerIndexableAttribute("getRatingSum", getRatingSum)
#registerIndexableAttribute("getHitCount", getHitCount)
#registerIndexableAttribute("getRatingCount", getRatingCount)
#registerIndexableAttribute("getRatingStdDev", getRatingStdDev)
#registerIndexableAttribute("getRatingVariance", getRatingVariance)
#registerIndexableAttribute("getEstimatedRating", getEstimatedRating)
registerIndexableAttribute("getCyninRating", getCyninRating)
    medias = behavior.contentMedias

    return medias


# Plone 3.3.x way
try:
    from plone.indexer.decorator import indexer

    @indexer(IConvergenceSupport)
    def getContentMedias(object, **kw):
        """ Provide indexing hook for portal_catalog for all converged content.

        Store multi channel medias for later nav tree generating.
        """
        return _getContentMedias(object, None, **kw)


except ImportError:
    # Plone 3.2.x code

    from Products.CMFPlone.CatalogTool import registerIndexableAttribute

    def getContentMedias(object, portal, **kw):
        """ Provide indexing hooksk for portal_catalog """
        return _getContentMedias(object, portal, **kw)


    registerIndexableAttribute('getContentMedias', getContentMedias)
"""Structured Document application package
"""
# Project globals
PACKAGE = "sd.app"

# We register the indexable attribute.
from sd.common.catalog.indexable_attributes import hasImageAndCaption
from Products.CMFPlone.CatalogTool import registerIndexableAttribute
registerIndexableAttribute('hasImageAndCaption', hasImageAndCaption)
def lastPreviewUpdate(object, portal, **kwargs):
    if not IPreviewAware.providedBy(object):
        return
    obj=IAnnotations(object)
    preview_annot = obj.get('htmlpreview', _marker)
    if preview_annot is _marker:
        return DateTime(0)
    last_preview_update = preview_annot.get('lastPreviewUpdate', _marker)
    if last_preview_update is _marker:
        return DateTime(0)
    return last_preview_update

def lastFileChange(object, portal, **kwargs):
    if not IPreviewAware.providedBy(object):
        return
    obj=IAnnotations(object)
    preview_annot = obj.get('htmlpreview', _marker)
    if preview_annot is _marker:
        return DateTime(0)
    last_file_change = preview_annot.get('lastFileChange', _marker)
    if last_file_change is _marker:
        return DateTime(0)
    return last_file_change


#registerIndexableAttribute('SearchableText', previewIndexWrapper)

registerIndexableAttribute('lastPreviewUpdate', lastPreviewUpdate)
registerIndexableAttribute('lastFileChange', lastFileChange)
Esempio n. 13
0
from Products.CMFPlone.CatalogTool import registerIndexableAttribute
from Products.Ploneboard.interfaces import IConversation
from zope.interface import providedBy
try:
    from zope.component.interface import interfaceToName
except ImportError:
    # BBB for Zope < 2.9
    def interfaceToName(context, interface):
        return interface.__module__ + '.' + interface.__name__

# Use extensible object wrapper to always list the interfaces
def object_implements(object, portal, **kw):
    return [interfaceToName(portal, i) for i in providedBy(object).flattened()]

registerIndexableAttribute('object_implements', object_implements)

def num_comments(object, portal, **kw):
    conv = IConversation(object, None)
    if conv is None:
        return None
    else:
        return conv.getNumberOfComments()

registerIndexableAttribute('num_comments', num_comments)
Esempio n. 14
0
                    field_val = obj.Schema().get(field_name).getAccessor(obj)()
                    if field_val and len(field_val) > 0:
                        # good enough -- we found a field that is active and
                        # has data
                        return True
            return False
    return True


# make these methods available to the portal_catalog
if HAS_INDEXER:
    # Plone 3.3+
    # These indexers need to be registered for Interface instead of
    # IPigeonholeAware because otherwise non-pigeonhole aware types can acquire
    # the values from a pigeonhole-aware parent.
    ph_indexer = indexer(Interface)
    ph_field_1_indexer = ph_indexer(ph_field_1)
    ph_field_2_indexer = ph_indexer(ph_field_2)
    ph_field_3_indexer = ph_indexer(ph_field_3)
    ph_field_4_indexer = ph_indexer(ph_field_4)
    is_relatable_indexer = ph_indexer(is_relatable)
    is_ph_configured_indexer = ph_indexer(is_ph_configured)
else:
    # BBB Plone < 3.3
    registerIndexableAttribute("ph_field_1", ph_field_1)
    registerIndexableAttribute("ph_field_2", ph_field_2)
    registerIndexableAttribute("ph_field_3", ph_field_3)
    registerIndexableAttribute("ph_field_4", ph_field_4)
    registerIndexableAttribute("is_relatable", is_relatable)
    registerIndexableAttribute("is_ph_configured", is_ph_configured)
Esempio n. 15
0
        """

        # get modification date
        child_mdate = dateTime(default_page)

        if folderish_date > child_mdate:
            last_date = folderish_date
        else:
            last_date = child_mdate

        child = getDefaultPage(default_page)
        if not child:
            return last_date

        return lastModificationDate(last_date,
                                    default_page[child])

    default_page = getDefaultPage(obj)
    # get modification date
    date = dateTime(obj)
    if default_page:
        date = lastModificationDate(date, getattr(obj, default_page))

    return date.HTML4()

#BBB: for compatibility with older plone versions
# (Plone 3.0, Plone 3.1, Plone3.2)
if not IS_NEW:
    from Products.CMFPlone.CatalogTool import registerIndexableAttribute
    registerIndexableAttribute('sitemap_date', sitemap_date)
        if data is None:
            self.setPreview(u"")
            return
        
        #get the html code
        html_converted = data.getData()
        #update internal links
        #remove bad character '\xef\x81\xac' from HTMLPreview
        html_converted = re.sub('\xef\x81\xac', "", html_converted)
        # patch image sources since html base is that of our parent
        subobjs = data.getSubObjects()
        if len(subobjs)>0:
            for id, data in subobjs.items():
                self.setSubObject(id, data)
            html_converted = self._re_imgsrc.sub(self._replacer(subobjs.keys(), self.context), html_converted)
        #store the html in the HTMLPreview field for preview
        self.setPreview(html_converted.decode('utf-8'))
	self.context.reindexObject()

def previewIndexWrapper(object, portal, **kwargs):
    data = object.SearchableText()
    try:
        obj = IPreviewable(object)
        preview = obj.getPreview(mimetype="text/plain")
        return " ".join([data, preview.encode('utf-8')])
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        return data

registerIndexableAttribute('SearchableText', previewIndexWrapper)
Esempio n. 17
0
from zope.component import queryAdapter
from zope.component.interfaces import ComponentLookupError

def audio_artist(object, portal, **kwargs):
    """Return the name of the artist in the audio file for use in
    searching the catalog.
    """

    try:
        audiofile = interfaces.IAudio(object)
        return audiofile.artist
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

registerIndexableAttribute('audio_artist', audio_artist)

def audio_genre_id(object, portal, **kwargs):
    """Return the genre id of the audio file for use in searching
    the catalog.
    """

    try:
        audiofile = interfaces.IAudio(object)
        return audiofile.genre
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

registerIndexableAttribute('audio_genre_id', audio_genre_id)
Esempio n. 18
0
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import aq_base
from Products.CMFPlone.utils import base_hasattr
from Products.CMFPlone.utils import safe_callable
from ubify.coretypes.interfaces import ITypesRestriction
from Products.CMFPlone.CatalogTool import registerIndexableAttribute

def disallowedtypes(obj,portal, **kw):
    if ITypesRestriction.providedBy(obj):
        return obj.disallowedtypes()
    else:
        return []
    
registerIndexableAttribute('disallowedtypes', disallowedtypes)
    
class CatalogTool(base.CatalogTool):

    security = AccessControl.ClassSecurityInfo()
    
    def reindexComments(self):
        pass
    
    def clearFindAndRebuild(self):
        """Empties catalog, then finds all contentish objects (i.e. objects
           with an indexObject method), and reindexes them.
           This may take a long time.
        """
        
        def indexObject(obj, path):	    
Esempio n. 19
0
            pass

        if not size:
            return None

        if isinstance(size, (int, long)):
            if size < SIZE_CONST[smaller]:
                return '1 %s' % smaller
            for c in SIZE_ORDER:
                if size / SIZE_CONST[c] > 0:
                    break
            return '%.1f %s' % (float(size / float(SIZE_CONST[c])), c)
        return size

    _eioRegistry.unregister('getObjSize')
    registerIndexableAttribute('getObjSize', getObjSize)

## Monkeypatch the breadcrumbs to show the name of the page you're on, even if its the defult page

from Products.CMFPlone.browser.navigation import PhysicalNavigationBreadcrumbs

if not hasattr(PhysicalNavigationBreadcrumbs, 'RhaptosSite_patch'):
    logger.info(
        "Patching CMFPlone.browser.navigation to include default page in breadcrumbs"
    )

    PhysicalNavigationBreadcrumbs.RhaptosSite_patch = 1

    from Products.CMFPlone.browser.navigation import *  # get all the original's imports and definitions

    def breadcrumbs(self):
Esempio n. 20
0
def initialize(context):
    """Initializer called when used as a Zope 2 product."""
    if registerIndexableAttribute is not None:
        registerIndexableAttribute('revisit_date', indexing.index_revisit)
Esempio n. 21
0
from zope.component import queryAdapter
from Products.CMFPlone.CatalogTool import registerIndexableAttribute

from interfaces import ICanonicalPath


def canonical_path(obj, portal, **kwargs):
    """Return canonical_path property for the object.
    """
    cpath = queryAdapter(obj, interface=ICanonicalPath)
    if cpath:
        return cpath.canonical_path()
    return None

registerIndexableAttribute('canonical_path', canonical_path)
Esempio n. 22
0
from Products.CMFPlone.CatalogTool import registerIndexableAttribute
from Products.Ploneboard.interfaces import IConversation

def num_comments(object, portal, **kw):
    conv = IConversation(object, None)
    if conv is None:
        return None
    else:
        return conv.getNumberOfComments()

registerIndexableAttribute('num_comments', num_comments)
Esempio n. 23
0
    #Move PloneBookmarklets document actions to bottom of the list
    dactions = portal.portal_actions.document_actions
    if 'bookmarklets' in dactions:
        dactions.moveObjectsToBottom(('bookmarklets',))


    
def copyrightClearedOnObj_value(object, portal, **kwargs):
    try:
        copyright = IAnnotations(object)
 	return copyright['eduCommons.clearcopyright']
    except (ComponentLookupError, TypeError, ValueError, KeyError):
 	# The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

registerIndexableAttribute('copyrightClearedOnObj', copyrightClearedOnObj_value)


def addCopyrightIndexToCatalog(portal,
                             indexes=('copyrightClearedOnObj',),
                             catalog='portal_catalog'):
    """Adds the specified indices as FieldIndexes to the catalog specified,
       which must inherit from CMFPlone.CatalogTool.CatalogTool, or otherwise
       use the Plone ExtensibleIndexableObjectWrapper."""
    cat = getToolByName(portal, catalog, None)
    reindex = []
    if cat is not None:
        for index in indexes:
            if index in cat.indexes():
                continue
            ProxyIndex.manage_addProxyIndex(portal.portal_catalog, 
from collective.contentleadimage.config import IMAGE_FIELD_NAME

# try:
#     from plone.indexer import indexer
#     from zope.component import provideAdapter
#     HAS_INDEXER = True
# except ImportError:
#     from Products.CMFPlone.CatalogTool import registerIndexableAttribute
#     HAS_INDEXER = False
# 
# if HAS_INDEXER:
#     @indexer(ILeadImageable)
#     def hasContentLeadImage(obj):
#         field = obj.getField(IMAGE_FIELD_NAME)
#         if field is not None:
#             value = field.get(obj)
#             return not not value
#     provideAdapter(hasContentLeadImage, name='hasContentLeadImage')
#     
# else:

from Products.CMFPlone.CatalogTool import registerIndexableAttribute
def hasContentLeadImage(obj, portal, **kw):
    if ILeadImageable.providedBy(obj):
        field = obj.getField(IMAGE_FIELD_NAME)
        if field is not None:
            value = field.get(obj)
            return not not value
    return False
registerIndexableAttribute('hasContentLeadImage', hasContentLeadImage)
Esempio n. 25
0
            pass

        if not size:
            return None

        if isinstance(size, (int, long)):
            if size < SIZE_CONST[smaller]:
                return '1 %s' % smaller
            for c in SIZE_ORDER:
                if size/SIZE_CONST[c] > 0:
                    break
            return '%.1f %s' % (float(size/float(SIZE_CONST[c])), c)
        return size

    _eioRegistry.unregister('getObjSize')
    registerIndexableAttribute('getObjSize', getObjSize)


## Monkeypatch the breadcrumbs to show the name of the page you're on, even if its the defult page
    
from Products.CMFPlone.browser.navigation import PhysicalNavigationBreadcrumbs

if not hasattr(PhysicalNavigationBreadcrumbs, 'RhaptosSite_patch'):
    logger.info("Patching CMFPlone.browser.navigation to include default page in breadcrumbs")

    PhysicalNavigationBreadcrumbs.RhaptosSite_patch = 1

    from Products.CMFPlone.browser.navigation import *     # get all the original's imports and definitions

    def breadcrumbs(self):
        context = utils.context(self)
Esempio n. 26
0
# CMFPlone imports
from Products.CMFPlone.CatalogTool import registerIndexableAttribute

def total_amount_of_products(object, portal, **kwargs):
    try:
        # This has to be done without the help of the catalog. Otherwise it
        # counts before all to counted objects are in the catalog. That is at
        # least the case for Advanced/Update Catalog.
        counter = 0
        # It has to be catalog independent
        if ICategory.providedBy(object):
            counter += len(object.getEasyshopproducts())
            counter = countCategories(object, counter)
                
        return counter
        
    except (ComponentLookupError, TypeError, ValueError):
        raise AttributeError

registerIndexableAttribute('total_amount_of_products',
                            total_amount_of_products)
                            
def countCategories(category, counter):
    """
    """
    for category in category.objectValues("Category"):
        counter += len(category.getEasyshopproducts())
        counter = countCategories(category, counter)
    return counter
    
Esempio n. 27
0
    try:
        # This has to be done without the help of the catalog. Otherwise it
        # counts before all to counted objects are in the catalog. That is at
        # least the case for Advanced/Update Catalog.

        counter = 0
        if ICategory.providedBy(object):
            counter += len(object.getProducts())
            counter = countCategories(object, counter)
                
        return counter
        
    except (ComponentLookupError, TypeError, ValueError):
        raise AttributeError

registerIndexableAttribute('total_amount_of_products', total_amount_of_products)

def amount_of_categories(object, portal, **kwargs):
    try:
        # This has to be done without the help of the catalog. Otherwise it
        # counts before all to counted objects are in the catalog. That is at
        # least the case for Advanced/Update Catalog.
        
        counter = 0
        if ICategory.providedBy(object):
            counter = len(object.objectValues("Category"))

        return counter
        
    except (ComponentLookupError, TypeError, ValueError):
        raise AttributeError
Esempio n. 28
0

def audio_artist(object, portal, **kwargs):
    """Return the name of the artist in the audio file for use in
    searching the catalog.
    """

    try:
        audiofile = interfaces.IAudio(object)
        return audiofile.artist
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError


registerIndexableAttribute('audio_artist', audio_artist)


def audio_genre_id(object, portal, **kwargs):
    """Return the genre id of the audio file for use in searching
    the catalog.
    """

    try:
        audiofile = interfaces.IAudio(object)
        return audiofile.genre
    except (ComponentLookupError, TypeError, ValueError):
        # The catalog expects AttributeErrors when a value can't be found
        raise AttributeError

Esempio n. 29
0
def geoLocation(obj, portal, **kw):
    """ return the location list """
    if hasattr(obj.aq_base, 'geoLocation'):
        return obj.geoLocation()
    adapter = IGEOLocated(obj, None)
    if adapter:
        lng = adapter.getLongitude()
        lat = adapter.getLatitude()
        if not (lat or lng):
            return None
        else:
            return (lat, lng)
    return default
"""
def Longitude(obj, portal, **kw):
    adapter = IGEOLocated(obj, None)
    if adapter:
        return adapter.getLongitude()
    return default

def Latitude(obj, portal, **kw):
    adapter = IGEOLocated(obj, None)
    if adapter:
        return adapter.getLatitude()
    return default
"""
registerIndexableAttribute('geoLocation', geoLocation)
#registerIndexableAttribute('Longitude', Longitude)
#registerIndexableAttribute('Latitude', Latitude)
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')
    return rt.getRatingSumSquared(obj.UID())


def getEstimatedRating(obj, portal, **kw):
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')
    return rt.getEstimatedRating(obj.UID())


def getCyninRating(obj, portal, **kw):
    if not IReferenceable.providedBy(obj):
        return None
    rt = getToolByName(obj, 'portal_ratings')
    return rt.getCyninRating(obj.UID())


#
#registerIndexableAttribute("getRatingMean", getRatingMean)
#registerIndexableAttribute("getRatingSumSquared", getRatingSumSquared)
#registerIndexableAttribute("getRatingSum", getRatingSum)
#registerIndexableAttribute("getHitCount", getHitCount)
#registerIndexableAttribute("getRatingCount", getRatingCount)
#registerIndexableAttribute("getRatingStdDev", getRatingStdDev)
#registerIndexableAttribute("getRatingVariance", getRatingVariance)
#registerIndexableAttribute("getEstimatedRating", getEstimatedRating)
registerIndexableAttribute("getCyninRating", getCyninRating)