def _potential_relations(obj):
    """Given an object return tuples of name, index, relation value.

    Returns both IRelationValue attributes as well as ITemporaryRelationValue
    attributes.

    If this is a IRelationList attribute, index will contain the index
    in the list. If it's a IRelation attribute, index will be None.
    """
    for field in obj.Schema().fields():
        if not interfaces.IZCRelationField.providedBy(obj):
            continue

        name = field.relationship
        value = field.getAccessor(obj)()

        if not (isinstance(value, (list, tuple))
                or IRelationValue.providedBy(value)):
            continue

        if not field.multiValued:
            yield name, None, value

        else:
            for i, relation in enumerate(value):
                yield name, i, relation
Beispiel #2
0
    def transform_list(self, fieldvalue, fieldname, original_obj):
        DEFAULT_VALUE = ''

        values = []
        for index, elem in enumerate(fieldvalue):
            if elem not in NOT_ALLOWED:
                if getattr(elem, 'portal_type', None) != None:
                    self.transform_object(elem, values, original_obj, index)
                elif IRelationValue.providedBy(elem):
                    to_object = elem.to_object
                    self.transform_object(to_object, values, original_obj, index)
                else:
                    values.append(elem)
        
        if fieldname in SEPARATORS:
            finalvalue = SEPARATORS[fieldname].join(values)
        else:
            finalvalue = ', '.join(values)
        
        if finalvalue not in NOT_ALLOWED:
            return finalvalue
        else:
            #Not valid
            return DEFAULT_VALUE

        return DEFAULT_VALUE
 def set(self, data, only_keys=None):
     if not only_keys:
         only_keys = data.keys()
     # relations are done later to avoid circular dependencies errors
     db = i.IDatabaseGetter(self.context).database()
     intids = getUtility(IIntIds)
     for it in [k for k in data if k in only_keys]:
         value = data[it]
         field = i.ILiberticEvent.get(it)
         if IRelationList.providedBy(field) and bool(value):
             newval = []
             for v in value:
                 if not IRelationValue.providedBy(v):
                     v = RelationValue(intids.getId(v))
                 newval.append(v)
             value = newval
         ctx = self.context
         if it in ['expires', 'effective']:
             ctx = IPublication(self.context)
         if (it in ['contained', 'related'] and value):
             nval = []
             for itm in value:
                 if not isinstance(itm, basestring):
                     itm = IUUID(itm)
                 nval.append(itm)
             value = tuple(nval)
         setattr(ctx, it, value)
     IExcludeFromNavigation(self.context).exclude_from_nav = False
     db.reindexObject()
    def copy_fields(self, translation):
        doomed = False

        target_language = queryAdapter(translation, ILanguage).get_language()
        relation_copier = lambda r, l=target_language, f=self.copy_relation: f(r, l)

        for schema in iterSchemata(self.context):
            for field_name in schema:
                if ILanguageIndependentField.providedBy(schema[field_name]):
                    value = getattr(schema(self.context), field_name, _marker)

                    if value == _marker:
                        continue
                    elif IRelationValue.providedBy(value):
                        value = self.copy_relation(value, target_language)
                    elif IRelationList.providedBy(schema[field_name]):
                        value = map(relation_copier, value or [])

                    doomed = True
                    setattr(schema(translation), field_name, value)

        # If at least one field has been copied over to the translation
        # we need to inform subscriber to trigger an ObjectModifiedEvent
        # on that translation.
        return doomed
def titleAuthorImprintCollation_titleAuthor_author(object, **kw):
    try:    
        if hasattr(object, 'titleAuthorImprintCollation_titleAuthor_author'):
            terms = []
            items = object.titleAuthorImprintCollation_titleAuthor_author
            for line in items:
                if 'authors' in line:
                    if line['authors']:
                        for author in line['authors']:
                            if IRelationValue.providedBy(author):
                                author_obj = author.to_object
                                title = getattr(author_obj, 'title', None)
                                if title:
                                    terms.append(title)
                            else:
                                title = getattr(author, 'title', None)
                                if title:
                                    terms.append(title)

                if 'roles' in line:
                    if line['roles']:
                        for term in line['roles']:
                            if term:
                                terms.append(term)

            return terms

        else:
            return []
    except:
        return []
 def copy_attributes(self, trans, attrs):
     res = []
     warnings = []
     for attr in attrs:
         field_name, behavior_name = attr.split('|')
         behavior_interface = None
         behavior_instance = queryUtility(IBehavior, name=behavior_name)
         if behavior_instance is not None:
             behavior_interface = behavior_instance.interface
         if behavior_interface is not None:
             value = getattr(
                 behavior_interface(self.context), field_name, _marker)
         else:
             value = getattr(self.context, field_name, _marker)
         if IRelationValue.providedBy(value):
             obj = value.to_object
             adapter = queryAdapter(trans, ILanguage)
             if ITranslatable.providedBy(obj):
                 trans_obj = ITranslationManager(obj)\
                     .get_translation(adapter.get_language())
                 if trans_obj:
                     intids = getUtility(IIntIds)
                     value = RelationValue(intids.getId(trans_obj))
         if not (value == _marker):
             # We check if not (value == _marker) because
             # z3c.relationfield has an __eq__
             if behavior_interface is not None:
                 setattr(behavior_interface(trans), field_name, value)
             else:
                 setattr(trans, field_name, value)
             res.append(
                 u"  > Transferred attribute '%s'" % field_name)
     return dict(res=res, warnings=warnings)
 def __init__(self, context, request):
     super(SQLDexterityPublishTraverse, self).__init__(context, request)
     annotations = IAnnotations(context)
     self.fti_id = annotations.get('collective.behavior.sql.sql_type')
     if self.fti_id:
         self.fti = getUtility(IDexterityFTI, name=self.fti_id)
         name = getattr(ISQLTypeSettings(self.fti), 'sql_folder_id', self.fti_id)
         if name and IRelationValue.providedBy(name):
             obj = name.to_object
             if obj:
                 name = obj.getId()
             else:
                 name = self.fti_id
             
         elif name and name.startswith('/'):
             portal = getToolByName(getSite(), 'portal_url').getPortalObject()
             obj = portal.restrictedTraverse(name)
             if obj:
                 name = obj.getId()
             else:
                 name = self.fti_id
         elif not name:
             name = self.fti_id
         self.name = name
         self.Title = self.fti.Title()
def registerPublisherForFTI(fti):
    # This registers a publisher that will allow to traverse to each sql item
    if not getattr(fti, 'sql_table', None):
        return
    name = getattr(fti, 'sql_folder_id', fti.id)
    has_folder = False
    if name and IRelationValue.providedBy(name):
        obj = name.to_object
        if obj:
            has_folder = True
            name = obj.getId()
        else:
            name = fti.context.getId()
    elif name and name.startswith('/'):
        portal = getToolByName(getSite(), "portal_url").getPortalObject()
        try:
            folder = portal.restrictedTraverse(name)
            has_folder = True
        except:
            pass
    elif not name:
        name = fti.context.getId()
    if not has_folder:
        view = queryMultiAdapter((None, ICollectiveBehaviorSQLLayer), IBrowserView, name='data-'+name, default=None)
        if view != None:
            return view
        publisher = SQLItemPublisher
        provideAdapter(
            factory=publisher,
            adapts=(None, ICollectiveBehaviorSQLLayer),
            provides=IBrowserView,
            name='data-'+name)

        LOG.info('Publisher registered for data-'+name)
def registerPublisherForFTI(fti):
    # This registers a publisher that will allow to traverse to each sql item
    if not getattr(fti, 'sql_table', None):
        return
    name = getattr(fti, 'sql_folder_id', fti.getId())
    has_folder = False
    if name and IRelationValue.providedBy(name):
        obj = name.to_object
        if obj:
            has_folder = True
            name = obj.getId()
        else:
            name = fti.getId()
    elif not name:
        name = fti.getId()
    if not has_folder:
        view = queryMultiAdapter((None, ICollectiveBehaviorSQLLayer), IBrowserView, name='data-'+name, default=None)
        if view != None:
            return view
        publisher = SQLItemPublisher
        provideAdapter(
            factory=publisher,
            adapts=(None, ICollectiveBehaviorSQLLayer),
            provides=IBrowserView,
            name='data-'+name)

        LOG.info('Publisher registered for data-'+name)
    def copy_fields(self, translation):
        fti = getUtility(IDexterityFTI, name=self.context.portal_type)
        schemas = []
        schemas.append(fti.lookupSchema())

        for behavior_schema in \
                utils.getAdditionalSchemata(self.context,
                                            self.context.portal_type):
            if behavior_schema is not None:
                schemas.append(behavior_schema)

        doomed = False
        for schema in schemas:
            for field_name in schema:
                if ILanguageIndependentField.providedBy(schema[field_name]):
                    doomed = True

                    value = getattr(schema(self.context), field_name, _marker)
                    if IRelationValue.providedBy(value):
                        obj = value.to_object
                        adapter = queryAdapter(translation, ILanguage)
                        trans_obj = ITranslationManager(obj)\
                            .get_translation(adapter.get_language())
                        if trans_obj:
                            intids = component.getUtility(IIntIds)
                            value = RelationValue(intids.getId(trans_obj))
                    if not (value == _marker):
                        # We check if not (value == _marker) because
                        # z3c.relationfield has an __eq__
                        setattr(schema(translation), field_name, value)

        # If at least one field has been copied over to the translation
        # we need to inform subscriber to trigger an ObjectModifiedEvent
        # on that translation.
        return doomed
    def set(self, value):
        """Sets the relationship target, creates a new instance of
        image/file object if upload is done
        """
        # No value to store
        if value is None:
            return super(ReferenceUploadDataManager, self).set(None)

        # Obtain current value
        current = None
        try:
            current = super(ReferenceUploadDataManager, self).get()
        except AttributeError:
            pass

        # Create/update object with uploaded file (based on chosen behaviour)
        if isinstance(value, FILE_UPLOAD):
            value = self.manage_upload(value)

        object_path = getUtility(IObjectPath)
        obj = object_path.resolve(value)
        intids = getUtility(IIntIds)
        to_id = intids.register(obj)

        if IRelationValue.providedBy(current):
            # If we already have a relation, just set the to_id
            current.to_id = to_id
        else:
            # otherwise create a relationship
            super(ReferenceUploadDataManager, self).set(obj)
    def copy_fields(self, translation):
        fti = getUtility(IDexterityFTI, name=self.context.portal_type)
        schemas = []
        schemas.append(fti.lookupSchema())

        for behavior_schema in \
                utils.getAdditionalSchemata(self.context, self.context.portal_type):
            if behavior_schema is not None:
                schemas.append(behavior_schema)

        for schema in schemas:
            for field_name in schema:
                if field_name in EXCLUDES:
                    continue
                if not ILanguageIndependentField.providedBy(schema[field_name]):
                    value = getattr(schema(self.context), field_name, _marker)
                    if IRelationValue.providedBy(value):
                        obj = value.to_object
                        adapter = queryAdapter(translation, ILanguage)
                        trans_obj = ITranslationManager(obj).get_translation(adapter.get_language())
                        if trans_obj:
                            intids = component.getUtility(IIntIds)
                            value = RelationValue(intids.getId(trans_obj))
                    if not (value == _marker):
                        # We check if not (value == _marker) because z3c.relationfield has an __eq__
                        setattr(schema(translation), field_name, value)
Beispiel #13
0
def _relations(obj):
    """Given an object, return tuples of name, relation value.

    Only real relations are returned, not temporary relations.
    """
    for name, index, relation in _potential_relations(obj):
        if IRelationValue.providedBy(relation):
            yield name, relation
def getGlobalSectionItem(object):
    adapted = ISolgemaRichMenuAttributes(object, None)
    if getattr(adapted, 'section_menu_item', None):
        portal = getSite()
        context_state = getMultiAdapter((object, object.REQUEST), name=u'plone_context_state')
        folder = context_state.folder()
        folder_path = '/'.join(folder.getPhysicalPath())
        section_menu_item = adapted.section_menu_item
        if has_relation and IRelationValue.providedBy(section_menu_item):
            return section_menu_item.to_object.UID()
        return portal.restrictedTraverse(folder_path+adapted.section_menu_item).UID()
    return None
 def link(self, item, field):
     if field in ['id', 'sql_id', 'title']:
         sql_id = getattr(item, 'sql_id', '')
         results = self.catalog.searchResults(portal_type=self.fti_id, sql_id=sql_id)
         if results:
             return results[0].getURL()
         if IRelationValue.providedBy(self.sql_folder_id):
             return self.sql_folder_id.to_object.absolute_url()+'/'+str(item.id)
         return '{0}/{1}/{2}'.format(
             self.portal_url,
             urllib.quote('data-'+str(self.fti_id)),
             urllib.quote(str(item.id))
         )
 def getPhysicalPath(self):
     """this needs implementation if the object doesnt exists for real in portal"""
     if not self.sql_virtual:
         return super(SQLDexterityItem, self).getPhysicalPath()
     portal_url = getToolByName(getSite(), 'portal_url')()
     fti = ISQLTypeSettings(getUtility(IDexterityFTI, name=self.portal_type))
     folder = None
     parent_path = None
     if IRelationValue.providedBy(getattr(fti, 'sql_folder_id', None)):
         folder = fti.sql_folder_id.to_object
         if folder:
             parent_path = folder.getPhysicalPath()
     if not parent_path:
         parent_path = ('', getSite().id, 'data-'+self.portal_type,)
     return parent_path+(str(self.id),)
 def __init__(self, context, request):
     super(SQLDexterityPublishTraverse, self).__init__(context, request)
     annotations = IAnnotations(context)
     self.fti_id = annotations.get('collective.behavior.sql.sql_type')
     if self.fti_id:
         self.fti = getUtility(IDexterityFTI, name=self.fti_id)
         name = getattr(self.fti, 'sql_folder_id', self.fti_id)
         if name and IRelationValue.providedBy(name):
             obj = name.to_object
             if obj:
                 name = obj.getId()
             else:
                 name = self.fti_id
         elif not name:
             name = self.fti_id
         self.name = name
         self.Title = self.fti.Title()
    def set(self, value):
        """Sets the relationship target"""
        if value is None:
            return super(RelationDataManager, self).set(None)

        current = None
        try:
            current = super(RelationDataManager, self).get()
        except AttributeError:
            pass
        to_id = value
        if IRelationValue.providedBy(current):
            # If we already have a relation, just set the to_id
            current.to_id = to_id
        else:
            # otherwise create a relationship
            rel = RelationValue(to_id)
            super(RelationDataManager, self).set(rel)
    def set(self, value):
        """Sets the relationship target"""
        if value is None:
            return super(RelationDictDataManager, self).set(None)

        current = None
        try:
            current = super(RelationDictDataManager, self).get()
        except AttributeError:
            pass
        intids = getUtility(IIntIds)
        to_id = intids.getId(value)
        if IRelationValue.providedBy(current):
            # If we already have a relation, just set the to_id
            current.to_id = to_id
        else:
            # otherwise create a relationship
            rel = RelationValue(to_id)
            super(RelationDictDataManager, self).set(rel)
Beispiel #20
0
def type_cast(value):
    """Convert the value to something serializable.

    :param value: [required] value to be converted
    :type value: almost anything
    :returns: serializable value
    :rtype: str
    """
    if value is None:
        return ''

    elif isinstance(value, date):
        return value.isoformat()

    elif isinstance(value, datetime):
        return value.isoformat()

    elif isinstance(value, DateTime):
        return value.ISO()

    elif isinstance(value, NamedBlobImage):
        # XXX: we need to decide what to do with the images
        #      we can embed them or use an URL to point to
        return 'image'

    elif IRelationValue.providedBy(value):
        # return just the path to the related object for now
        return value.to_path

    elif isinstance(value, list):
        # XXX: we don't want to mess around the original list
        # object so we just create a copy of the value
        tmp = list(value)
        for i in tmp:
            # call function recursively on each value of the list
            if type(i) == dict:
                tmp[tmp.index(i)] = dict(
                    (v[0], type_cast(v[1])) for v in i.items())
            else:
                tmp[tmp.index(i)] = type_cast(i)
        return tmp

    return value
def registerPublisherForFTI(fti):
    # This registers a publisher that will allow to traverse to each sql item
    if not getattr(fti, 'sql_table', None):
        return
    sql_folder_id = getattr(fti, 'sql_folder_id', fti.id)
    has_folder = False
    if sql_folder_id:
        if IRelationValue.providedBy(sql_folder_id):
            obj = sql_folder_id.to_object
            if obj:
                has_folder = True
                name = obj.getId()
            else:
                name = fti.context.getId()
        elif sql_folder_id.startswith('/'):
            portal = getToolByName(getSite(), "portal_url").getPortalObject()
            try:
                folder = portal.restrictedTraverse(name)
                has_folder = True
            except:
                pass
        else:
            try:
                folder = uuidToObject(sql_folder_id)
                has_folder = True
            except:
                pass
    else:
        name = fti.context.getId()
    if not has_folder:
        view = queryMultiAdapter((None, ICollectiveBehaviorSQLLayer),
                                 IBrowserView,
                                 name='data-' + name,
                                 default=None)
        if not view:
            publisher = SQLItemPublisher
            provideAdapter(factory=publisher,
                           adapts=(None, ICollectiveBehaviorSQLLayer),
                           provides=IBrowserView,
                           name='data-' + name)

            LOG.info('Publisher registered for data-' + name)
 def getPhysicalPath(self):
     """this needs implementation if the object doesnt exists for real in portal"""
     if not self.sql_virtual:
         return super(SQLDexterityItem, self).getPhysicalPath()
     portal_url = getToolByName(getSite(), 'portal_url')()
     fti = ISQLTypeSettings(getUtility(IDexterityFTI,
                                       name=self.portal_type))
     folder = None
     parent_path = None
     if IRelationValue.providedBy(getattr(fti, 'sql_folder_id', None)):
         folder = fti.sql_folder_id.to_object
         if folder:
             parent_path = folder.getPhysicalPath()
     if not parent_path:
         parent_path = (
             '',
             getSite().id,
             'data-' + self.portal_type,
         )
     return parent_path + (str(self.id), )
def titleAuthorImprintCollation_imprint_publishers(object, **kw):
    try:
        if hasattr(object, 'titleAuthorImprintCollation_imprint_publishers'):
            terms = []
            items = object.titleAuthorImprintCollation_imprint_publishers
            if items:
                for item in items:
                    if IRelationValue.providedBy(item):
                        to_obj = item.to_object
                        title = getattr(to_obj, 'title', None)
                        if title:
                            terms.append(title)
                    else:
                        title = getattr(item, 'title', None)
                        if title:
                            terms.append(title)

            return terms
        else:
            return []
    except:
        return []
def relation_set(self, value):
    """Sets the relationship target"""
    if value is None:
        return super(RelationDataManager, self).set(None)

    current = None
    try:
        current = super(RelationDataManager, self).get()
    except AttributeError:
        pass
    intids = getUtility(IIntIds)
    try:
        to_id = intids.getId(value)
    except KeyError:
        to_id = intids.register(value)
    if IRelationValue.providedBy(current):
        # If we already have a relation, just set the to_id
        current.to_id = to_id
    else:
        # otherwise create a relationship
        rel = RelationValue(to_id)
        super(RelationDataManager, self).set(rel)
def library_author(object, **kw):
    try:
        if hasattr(object, 'resourceDublinCore_creators'):
            list_authors = []
            items = object.resourceDublinCore_creators
            if items:
                for item in items:
                    author = item
                    if IRelationValue.providedBy(author):
                        author_obj = author.to_object
                        title = getattr(author_obj, 'title', None)
                        if title:
                            list_authors.append(title)
                    else:
                        title = getattr(author, 'title', None)
                        if title:
                            list_authors.append(title)

            return "_".join(list_authors)
        else:
            return ""
    except:
        return ""
Beispiel #26
0
def library_author(object, **kw):
    try:
        if hasattr(object, 'titleAuthorSource_titleAuthor_author'):
            list_authors = []
            items = object.titleAuthorSource_titleAuthor_author
            if items:
                for item in items:
                    if item['authors']:
                        author = item['authors'][0]
                        if IRelationValue.providedBy(author):
                            author_obj = author.to_object
                            title = getattr(author_obj, 'title', None)
                            if title:
                                list_authors.append(title)
                        else:
                            title = getattr(author, 'title', None)
                            if title:
                                list_authors.append(title)

            return "_".join(list_authors)
        else:
            return ""
    except:
        return ""
    def _aliasTarget(self, value):
        if '_aliasTarget' in self.__dict__:
            raise AttributeError("Cannot set _aliasTarget more than once")

        if not IRelationValue.providedBy(value):
            raise AttributeError("_aliasTarget must be an IRelationValue")

        counter = 0

        target = value.to_object
        while IAlias.providedBy(target) and counter < 1000: # avoid infinite loop
            target = aq_inner(target._target)
            counter += 1

        if counter > 0:
            intids = queryUtility(IIntIds)

            if intids is None:
                raise LookupError("Cannot find intid utility")

            to_id = intids.getId(target)
            value = RelationValue(to_id)

        self.__dict__['_aliasTarget'] = value
    def __getattribute__(self, name):
        if name.startswith('_') or name.startswith(
                'portal_') or name.startswith('@@'):
            return super(SQLDexterityItem, self).__getattribute__(name)
        if name == 'id' and not self.sql_virtual:
            return super(SQLDexterityItem, self).__getattribute__(name)
        connection = queryUtility(ISQLConnectionsUtility,
                                  name=self.portal_type,
                                  default=None)
        if connection == None and self.portal_type:
            fti = queryUtility(IDexterityFTI,
                               name=self.portal_type,
                               default=None)
            if not fti:
                return None
            updateConnectionsForFti(fti)
            connection = queryUtility(ISQLConnectionsUtility,
                                      name=self.portal_type,
                                      default=None)
        if not connection:
            return super(SQLDexterityItem, self).__getattribute__(name)
        if name == 'UID':
            return self.portal_type + '-' + connection.sql_table + '-' + str(
                self.sql_id)
        if name == 'id' and 'id' not in connection.fieldnames.keys():
            fti = ISQLTypeSettings(
                getUtility(IDexterityFTI, name=self.portal_type))
            nameFromTitle = INameFromTitle(self, None)
            if nameFromTitle is not None and nameFromTitle.title:
                sql_folder_id = getattr(fti, 'sql_folder_id',
                                        'data-' + self.portal_type)
                title = nameFromTitle.title
                if IRelationValue.providedBy(name):
                    folder = sql_folder_id.to_object
                    if folder:
                        return INameChooser(folder).chooseName(title, self)
                return INameChooser(getSite()).chooseName(title, self)
        if name in connection.fieldnames.keys():
            sql_column = connection.fieldnames[name]
            sql_item = self.getSQLItem()
            fieldname = 'name'
            if sql_item and sql_column:
                while '.' in sql_column:
                    sql_item = getattr(sql_item,
                                       sql_column.split('.')[0], None)
                    if sql_item and (
                        (isinstance(sql_item, list) and len(sql_item) > 1)
                            or hasattr(sql_item, '_sa_instance_state')):
                        value = sql_item
                        fieldname = sql_column.split('.')[-1]
                        break
                    sql_column = '.'.join(sql_column.split('.')[1:])
                else:
                    value = getattr(sql_item, sql_column, None)
                #this is a relation
                if value and (isinstance(value, list)
                              or hasattr(value, '_sa_instance_state')):
                    sqlftis = [
                        a for a in getAllUtilitiesRegisteredFor(IDexterityFTI)
                        if
                        'collective.behavior.sql.behavior.behaviors.ISQLContent'
                        in a.behaviors and getattr(a, 'sql_table', None)
                    ]
                    if name == 'subject':
                        return tuple(
                            [getattr(a, fieldname, '') for a in value])
                    tableftis = []
                    for iface in iterSchemataForType(self.portal_type):
                        if name in iface.names():
                            field = iface[name]
                            if IList.providedBy(field):
                                return [
                                    getattr(a, fieldname, '') for a in value
                                ]  # hope it has name!
                            elif ITuple.providedBy(field):
                                return tuple(
                                    [getattr(a, fieldname, '') for a in value])
                            if IRelationChoice.providedBy(
                                    field) or IRelationList.providedBy(field):
                                if IRelationChoice.providedBy(field):
                                    allowed_types = field.source.query.get(
                                        'portal_type', [])
                                else:
                                    allowed_types = field.value_type.source.query.get(
                                        'portal_type', [])
                                tableftis = []
                                for sqlfti in sqlftis:
                                    adapted = ISQLTypeSettings(sqlfti, None)
                                    if isinstance(value, list):
                                        classname = value[0].__class__.__name__
                                    else:
                                        classname = value.__class__.__name__
                                    if adapted and getattr(
                                            adapted, 'sql_table',
                                            None) == classname:
                                        if not allowed_types or sqlfti.id in allowed_types:
                                            tableftis.append(adapted)

                                catalog = getToolByName(
                                    getSite(), 'portal_catalog')
                                relations = []
                                for tablefti in tableftis:
                                    sql_id_column = getattr(
                                        tablefti, 'sql_id_column', 'id')
                                    valueids = []
                                    if isinstance(value, list):
                                        valueids = [
                                            getattr(a, sql_id_column, None)
                                            for a in value
                                            if getattr(a, sql_id_column, None)
                                        ]
                                    else:
                                        valueids = getattr(
                                            value, sql_id_column, None)
                                    brains = catalog.searchResults(
                                        portal_type=tablefti.id,
                                        sql_id=valueids)
                                    for brain in brains:
                                        relations.append(
                                            SQLRelationValue(
                                                brain.portal_type,
                                                brain.sql_id))
                                if IRelationChoice.providedBy(
                                        field) and relations:
                                    return relations[0]
                                elif IRelationList.providedBy(
                                        field) and relations:
                                    return relations
                for iface in iterSchemataForType(self.portal_type):
                    if name == 'subject':
                        try:
                            return tuple([
                                a.decode('utf-8') for a in literal_eval(value)
                            ])
                        except:
                            return tuple([a.strip() for a in value.split(',')])
                    if name in iface.names():
                        field = iface[name]
                        if IRichText.providedBy(field):
                            return RichTextValue(value)
                        if INamedBlobImage.providedBy(field):
                            return NamedBlobImage(
                                base64.b64decode(value),
                                filename=unicode(self.portal_type + self.id +
                                                 ".jpg"))
                        if IList.providedBy(field):
                            try:
                                return [
                                    a.decode('utf-8')
                                    for a in literal_eval(value)
                                ]
                            except:
                                return [a.strip() for a in value.split(',')]
                        if ITuple.providedBy(field):
                            try:
                                return tuple([
                                    a.decode('utf-8')
                                    for a in literal_eval(value)
                                ])
                            except:
                                return tuple(
                                    [a.strip() for a in value.split(',')])

                if isinstance(value, unicode) or name == 'id':
                    try:
                        return str(value)
                    except:
                        pass
                return value
        return super(SQLDexterityItem, self).__getattribute__(name)
Beispiel #29
0
    def _as_relation_value(self, value):
        if IRelationValue.providedBy(value):
            return value

        intids = getUtility(IIntIds)
        return RelationValue(intids.getId(value))
Beispiel #30
0
    def __getattribute__(self, name):
        if name.startswith('_') or name.startswith(
                'portal_') or name.startswith('@@') or name == 'sql_id':
            return super(SQLDexterityItem, self).__getattribute__(name)
        connection = queryUtility(ISQLConnectionsUtility,
                                  name=self.portal_type,
                                  default=None)
        if connection == None and self.portal_type:
            fti = queryUtility(IDexterityFTI,
                               name=self.portal_type,
                               default=None)
            if not fti:
                return None
            updateConnectionsForFti(fti)
            connection = queryUtility(ISQLConnectionsUtility,
                                      name=self.portal_type,
                                      default=None)
        if name == 'view':
            #be sure session and sqlitem are up to date
            self._v_sql_item = None
            connection.session.close()
        if not connection:
            return super(SQLDexterityItem, self).__getattribute__(name)
        if name == 'UID' and self.sql_virtual:
            return self.portal_type + '-' + connection.sql_table + '-' + str(
                self.sql_id)
        if name == 'id' and 'id' not in connection.fieldnames.keys():
            if not self.sql_virtual:
                return super(SQLDexterityItem, self).__getattribute__(name)
            fti = ISQLTypeSettings(
                getUtility(IDexterityFTI, name=self.portal_type))
            nameFromTitle = INameFromTitle(self, None)
            if nameFromTitle is not None and nameFromTitle.title:
                sql_folder_id = getattr(fti, 'sql_folder_id',
                                        'data-' + self.portal_type)
                title = nameFromTitle.title
                folder = None
                if IRelationValue.providedBy(sql_folder_id):
                    folder = sql_folder_id.to_object
                elif sql_folder_id and sql_folder_id.startswith('/'):
                    portal = getToolByName(getSite(),
                                           'portal_url').getPortalObject()
                    folder = portal.restrictedTraverse(sql_folder_id)
                if folder:
                    name = INameChooser(folder).chooseName(title, self)
                    return name
#                return INameChooser(getSite()).chooseName(title, self)
#                return getUtility(IURLNormalizer).normalize(title)
                return self.sql_id
        if name in connection.fieldnames.keys():
            sql_column = connection.fieldnames[name]
            sql_item = self.getSQLItem()
            try:
                sql_id = getattr(sql_item, connection.sql_id_column, None)
            except orm_exc.DetachedInstanceError:
                self._v_sql_item = None
                sql_item = self.getSQLItem()
                sql_id = getattr(sql_item, connection.sql_id_column, None)
            fieldname = 'name'
            if sql_item and sql_column:
                while '.' in sql_column:
                    sql_key = sql_column.split('.')[0]
                    sql_item = getattr(sql_item, sql_key, None)
                    if isinstance(sql_item, list):
                        value = sql_item
                        fieldname = sql_column.split('.')[-1]
                        break
                    sql_column = '.'.join(sql_column.split('.')[1:])
                else:
                    if not isinstance(sql_item, list):
                        value = getattr(sql_item, sql_column, None)
                if not value and (isinstance(value, list)
                                  or hasattr(value, '_sa_instance_state')):
                    value = ''
                elif (isinstance(value, list)
                      or hasattr(value, '_sa_instance_state')):
                    sqlftis = [
                        a for a in getAllUtilitiesRegisteredFor(IDexterityFTI)
                        if
                        'collective.behavior.sql.behavior.behaviors.ISQLContent'
                        in a.behaviors and getattr(a, 'sql_table', None)
                    ]
                    if name == 'subject':
                        return tuple(
                            [getattr(a, fieldname, '') for a in value])
                    tableftis = []
                    for iface in iterSchemataForType(self.portal_type):
                        if name in iface.names():
                            field = iface[name]
                            if IRelationChoice.providedBy(
                                    field) or IRelationList.providedBy(field):
                                if IRelationChoice.providedBy(field):
                                    allowed_types = field.source.query.get(
                                        'portal_type', [])
                                else:
                                    allowed_types = field.value_type.source.query.get(
                                        'portal_type', [])
                                tableftis = []
                                for sqlfti in sqlftis:
                                    adapted = ISQLTypeSettings(sqlfti, None)
                                    if isinstance(value, list):
                                        classname = value[0].__class__.__name__
                                    else:
                                        classname = value.__class__.__name__
                                    if adapted and getattr(
                                            adapted, 'sql_table',
                                            None) == classname:
                                        if not allowed_types or sqlfti.id in allowed_types:
                                            tableftis.append(adapted)
                                catalog = getToolByName(
                                    getSite(), 'portal_catalog')
                                relations = []
                                for tablefti in tableftis:
                                    sql_id_column = getattr(
                                        tablefti, 'sql_id_column', 'id')
                                    valueids = []
                                    if isinstance(value, list):
                                        valueids = [
                                            getattr(a, sql_id_column, None)
                                            for a in value
                                            if getattr(a, sql_id_column, None)
                                        ]
                                    else:
                                        valueids = getattr(
                                            value, sql_id_column, None)
                                    valueids = [str(a) for a in valueids]
                                    brains = catalog.unrestrictedSearchResults(
                                        portal_type=tablefti.id,
                                        sql_id=valueids)
                                    for brain in brains:
                                        relations.append(
                                            SQLRelationValue(
                                                brain.portal_type, brain.UID,
                                                self))
                                if IRelationChoice.providedBy(
                                        field) and relations:
                                    return relations[0]
                                elif IRelationList.providedBy(
                                        field) and relations:
                                    return relations
                            elif ITuple.providedBy(field):
                                return tuple(
                                    [getattr(a, fieldname, '') for a in value])
                            elif IList.providedBy(field):
                                return [
                                    getattr(a, fieldname, '') for a in value
                                ]
                            elif value and isinstance(value, list):
                                value = getattr(value[0], fieldname, '')
                for iface in iterSchemataForType(self.portal_type):
                    if name == 'subject':
                        try:
                            return tuple([
                                a.decode('utf-8') for a in literal_eval(value)
                            ])
                        except:
                            return tuple([a.strip() for a in value.split(',')])
                    if name in iface.names():
                        field = iface[name]
                        if IRichText.providedBy(field):
                            if not value:
                                return ''
                            if not '<p' in value or not '<br' in value:
                                value = '<p>' + '</p><p>'.join([
                                    a for a in value.split('\n') if a.strip()
                                ]) + '</p>'


#                            try:
#                                value = str(value)
#                            except:
#                                try:
#                                    value = value.decode('utf-8')
#                                except:
#                                    try:
#                                        value = value.encode('utf-8')
#                                    except:
#                                        pass
                            return RichTextValue(unidecode(value))
                        elif INamedBlobImage.providedBy(field):
                            return NamedBlobImage(
                                base64.b64decode(value),
                                filename=unicode(self.portal_type + self.id +
                                                 ".jpg"))
                        elif ITuple.providedBy(field):
                            if not value:
                                return tuple([])
                            try:
                                return tuple([
                                    a.decode('utf-8')
                                    for a in literal_eval(value)
                                ])
                            except:
                                return tuple(
                                    [a.strip() for a in value.split(',')])
                        elif IList.providedBy(field):
                            if not value:
                                return []
                            try:
                                return [
                                    a.decode('utf-8')
                                    for a in literal_eval(value)
                                ]
                            except:
                                return [a.strip() for a in value.split(',')]
                        elif IDatetime.providedBy(field) and hasattr(
                                value, 'day') and not hasattr(value, 'hour'):
                            value = datetime.datetime.combine(
                                value, datetime.datetime.min.time())
                if name in [
                        'expiration_date', 'effective_date', 'effective',
                        'expires'
                ] and hasattr(value, 'day') and not hasattr(value, 'hour'):
                    value = datetime.datetime.combine(
                        value, datetime.datetime.min.time())
                if isinstance(value, unicode) or name == 'id':
                    try:
                        value = str(value)
                    except:
                        pass
                return value
        return super(SQLDexterityItem, self).__getattribute__(name)
 def __getattribute__(self, name):
     if name.startswith('_') or name.startswith('portal_') or name.startswith('@@'):
         return super(SQLDexterityItem, self).__getattribute__(name)
     if name == 'id' and not self.sql_virtual:
         return super(SQLDexterityItem, self).__getattribute__(name)
     connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None)
     if connection == None and self.portal_type:
         fti = queryUtility(IDexterityFTI, name=self.portal_type, default=None)
         if not fti:
             return None
         updateConnectionsForFti(fti)
         connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None)
     if not connection:
         return super(SQLDexterityItem, self).__getattribute__(name)
     if name == 'UID':
         return self.portal_type+'-'+connection.sql_table+'-'+str(self.sql_id)
     if name == 'id' and 'id' not in connection.fieldnames.keys():
         fti = ISQLTypeSettings(getUtility(IDexterityFTI, name=self.portal_type))
         nameFromTitle = INameFromTitle(self, None)
         if nameFromTitle is not None and nameFromTitle.title:
             sql_folder_id = getattr(fti, 'sql_folder_id', 'data-'+self.portal_type)
             title = nameFromTitle.title
             if IRelationValue.providedBy(name):
                 folder = sql_folder_id.to_object
                 if folder:
                     return INameChooser(folder).chooseName(title, self)
             return INameChooser(getSite()).chooseName(title, self)
     if name in connection.fieldnames.keys():
         sql_column = connection.fieldnames[name]
         sql_item = self.getSQLItem()
         fieldname = 'name'
         if sql_item and sql_column:
             while '.' in sql_column:
                 sql_item = getattr(sql_item, sql_column.split('.')[0], None)
                 if sql_item and ((isinstance(sql_item, list) and len(sql_item)>1) or hasattr(sql_item, '_sa_instance_state')):
                     value = sql_item
                     fieldname = sql_column.split('.')[-1]
                     break
                 sql_column = '.'.join(sql_column.split('.')[1:])
             else:
                 value = getattr(sql_item, sql_column, None)
             #this is a relation
             if value and (isinstance(value, list) or hasattr(value, '_sa_instance_state')):
                 sqlftis = [a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None)]
                 if name == 'subject':
                     return tuple([getattr(a, fieldname, '') for a in value])
                 tableftis = []
                 for iface in iterSchemataForType(self.portal_type):
                     if name in iface.names():
                         field = iface[name]
                         if IList.providedBy(field):
                             return [getattr(a, fieldname, '') for a in value] # hope it has name!
                         elif ITuple.providedBy(field):
                             return tuple([getattr(a, fieldname, '') for a in value])
                         if IRelationChoice.providedBy(field) or IRelationList.providedBy(field):
                             if IRelationChoice.providedBy(field):
                                 allowed_types = field.source.query.get('portal_type', [])
                             else:
                                 allowed_types = field.value_type.source.query.get('portal_type', [])
                             tableftis = []
                             for sqlfti in sqlftis:
                                 adapted = ISQLTypeSettings(sqlfti, None)
                                 if isinstance(value, list):
                                     classname = value[0].__class__.__name__
                                 else:
                                     classname = value.__class__.__name__
                                 if adapted and getattr(adapted, 'sql_table', None) == classname:
                                     if not allowed_types or sqlfti.id in allowed_types:
                                         tableftis.append(adapted)
                     
                             catalog = getToolByName(getSite(), 'portal_catalog')
                             relations = []
                             for tablefti in tableftis:
                                 sql_id_column = getattr(tablefti, 'sql_id_column', 'id')
                                 valueids = []
                                 if isinstance(value, list):
                                     valueids = [getattr(a, sql_id_column, None) for a in value if getattr(a, sql_id_column, None)]
                                 else:
                                     valueids = getattr(value, sql_id_column, None)
                                 brains = catalog.searchResults(portal_type=tablefti.id, sql_id=valueids)
                                 for brain in brains:
                                     relations.append(SQLRelationValue(brain.portal_type, brain.sql_id))
                             if IRelationChoice.providedBy(field) and relations:
                                 return relations[0]
                             elif IRelationList.providedBy(field) and relations:
                                 return relations
             for iface in iterSchemataForType(self.portal_type):
                 if name == 'subject':
                     try:
                         return tuple([a.decode('utf-8') for a in literal_eval(value)])
                     except:
                         return tuple([a.strip() for a in value.split(',')])
                 if name in iface.names():
                     field = iface[name]
                     if IRichText.providedBy(field):
                         return RichTextValue(value)
                     if INamedBlobImage.providedBy(field):
                         return NamedBlobImage(base64.b64decode(value), filename=unicode(self.portal_type+self.id+".jpg"))
                     if IList.providedBy(field):
                         try:
                             return [a.decode('utf-8') for a in literal_eval(value)]
                         except:
                             return [a.strip() for a in value.split(',')]
                     if ITuple.providedBy(field):
                         try:
                             return tuple([a.decode('utf-8') for a in literal_eval(value)])
                         except:
                             return tuple([a.strip() for a in value.split(',')])
                         
             if isinstance(value, unicode) or name == 'id':
                 try:
                     return str(value)
                 except:
                     pass
             return value
     return super(SQLDexterityItem, self).__getattribute__(name)
    def __getattribute__(self, name):
        if name.startswith('_') or name.startswith('portal_') or name.startswith('@@') or name == 'sql_id':
            return super(SQLDexterityItem, self).__getattribute__(name)
        connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None)
        if connection == None and self.portal_type:
            fti = queryUtility(IDexterityFTI, name=self.portal_type, default=None)
            if not fti:
                return None
            updateConnectionsForFti(fti)
            connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None)
        if name == 'view':
            #be sure session and sqlitem are up to date
            self._v_sql_item = None
            connection.session.close()
        if not connection:
            return super(SQLDexterityItem, self).__getattribute__(name)
        if name == 'UID' and self.sql_virtual:
            return self.portal_type+'-'+connection.sql_table+'-'+str(self.sql_id)
        if name == 'id' and 'id' not in connection.fieldnames.keys():
            if not self.sql_virtual:
                return super(SQLDexterityItem, self).__getattribute__(name)
            fti = ISQLTypeSettings(getUtility(IDexterityFTI, name=self.portal_type))
            nameFromTitle = INameFromTitle(self, None)
            if nameFromTitle is not None and nameFromTitle.title:
                sql_folder_id = getattr(fti, 'sql_folder_id', 'data-'+self.portal_type)
                title = nameFromTitle.title
                folder = None
                if IRelationValue.providedBy(sql_folder_id):
                    folder = sql_folder_id.to_object
                elif sql_folder_id and sql_folder_id.startswith('/'):
                    portal = getToolByName(getSite(), 'portal_url').getPortalObject()
                    folder = portal.restrictedTraverse(sql_folder_id)
                if folder:
                    name = INameChooser(folder).chooseName(title, self)
                    return name
#                return INameChooser(getSite()).chooseName(title, self)
#                return getUtility(IURLNormalizer).normalize(title)
                return self.sql_id
        if name in connection.fieldnames.keys():
            sql_column = connection.fieldnames[name]
            sql_item = self.getSQLItem()
            try:
                sql_id = getattr(sql_item, connection.sql_id_column, None)
            except orm_exc.DetachedInstanceError:
                self._v_sql_item = None
                sql_item = self.getSQLItem()
                sql_id = getattr(sql_item, connection.sql_id_column, None)
            fieldname = 'name'
            if sql_item and sql_column:
                while '.' in sql_column:
                    sql_key = sql_column.split('.')[0]
                    sql_item = getattr(sql_item, sql_key, None)
                    if isinstance(sql_item, list):
                        value = sql_item
                        fieldname = sql_column.split('.')[-1]
                        break
                    sql_column = '.'.join(sql_column.split('.')[1:])
                else:
                    if not isinstance(sql_item, list):
                        value = getattr(sql_item, sql_column, None)
                if not value and (isinstance(value, list) or hasattr(value, '_sa_instance_state')):
                    value = ''
                elif (isinstance(value, list) or hasattr(value, '_sa_instance_state')):
                    sqlftis = [a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None)]
                    if name == 'subject':
                        return tuple([getattr(a, fieldname, '') for a in value])
                    tableftis = []
                    for iface in iterSchemataForType(self.portal_type):
                        if name in iface.names():
                            field = iface[name]
                            if IRelationChoice.providedBy(field) or IRelationList.providedBy(field):
                                if IRelationChoice.providedBy(field):
                                    allowed_types = field.source.query.get('portal_type', [])
                                else:
                                    allowed_types = field.value_type.source.query.get('portal_type', [])
                                tableftis = []
                                for sqlfti in sqlftis:
                                    adapted = ISQLTypeSettings(sqlfti, None)
                                    if isinstance(value, list):
                                        classname = value[0].__class__.__name__
                                    else:
                                        classname = value.__class__.__name__
                                    if adapted and getattr(adapted, 'sql_table', None) == classname:
                                        if not allowed_types or sqlfti.id in allowed_types:
                                            tableftis.append(adapted)
                                catalog = getToolByName(getSite(), 'portal_catalog')
                                relations = []
                                for tablefti in tableftis:
                                    sql_id_column = getattr(tablefti, 'sql_id_column', 'id')
                                    valueids = []
                                    if isinstance(value, list):
                                        valueids = [getattr(a, sql_id_column, None) for a in value if getattr(a, sql_id_column, None)]
                                    else:
                                        valueids = getattr(value, sql_id_column, None)
                                    valueids = [str(a) for a in valueids]
                                    brains = catalog.unrestrictedSearchResults(portal_type=tablefti.id, sql_id=valueids)
                                    for brain in brains:
                                        relations.append(SQLRelationValue(brain.portal_type, brain.UID, self))
                                if IRelationChoice.providedBy(field) and relations:
                                    return relations[0]
                                elif IRelationList.providedBy(field) and relations:
                                    return relations
                            elif ITuple.providedBy(field):
                                return tuple([getattr(a, fieldname, '') for a in value])
                            elif IList.providedBy(field):
                                return [getattr(a, fieldname, '') for a in value]
                            elif value and isinstance(value, list):
                                value = getattr(value[0], fieldname, '')
                for iface in iterSchemataForType(self.portal_type):
                    if name == 'subject':
                        try:
                            return tuple([a.decode('utf-8') for a in literal_eval(value)])
                        except:
                            return tuple([a.strip() for a in value.split(',')])
                    if name in iface.names():
                        field = iface[name]
                        if IRichText.providedBy(field):
                            if not value:
                                return ''
                            if not '<p' in value or not '<br' in value:
                                value = '<p>'+'</p><p>'.join([a for a in value.split('\n') if a.strip()])+'</p>'
#                            try:
#                                value = str(value)
#                            except:
#                                try:
#                                    value = value.decode('utf-8')
#                                except:
#                                    try:
#                                        value = value.encode('utf-8')
#                                    except:
#                                        pass
                            return RichTextValue(unidecode(value))
                        elif INamedBlobImage.providedBy(field):
                            return NamedBlobImage(base64.b64decode(value), filename=unicode(self.portal_type+self.id+".jpg"))
                        elif ITuple.providedBy(field):
                            if not value:
                                return tuple([])
                            try:
                                return tuple([a.decode('utf-8') for a in literal_eval(value)])
                            except:
                                return tuple([a.strip() for a in value.split(',')])
                        elif IList.providedBy(field):
                            if not value:
                                return []
                            try:
                                return [a.decode('utf-8') for a in literal_eval(value)]
                            except:
                                return [a.strip() for a in value.split(',')]
                        elif IDatetime.providedBy(field) and hasattr(value, 'day') and not hasattr(value, 'hour'):
                            value = datetime.datetime.combine(value, datetime.datetime.min.time())
                if name in ['expiration_date','effective_date', 'effective', 'expires'] and hasattr(value, 'day') and not hasattr(value, 'hour'):
                    value = datetime.datetime.combine(value, datetime.datetime.min.time())
                if isinstance(value, unicode) or name == 'id':
                    try:
                        value = str(value)
                    except:
                        pass
                return value
        return super(SQLDexterityItem, self).__getattribute__(name)