'Update ownership fields in a record (DRY helper method for
s3_set_record_owner and set_realm_entity)
@param table: the table
@param record: the record or record ID
@param update: True to update realm_entity in all realm-components
@param fields: dict of {ownership_field:value}'

def s3_update_record_owner(self, table, record, update=False, **fields):

    OUSR = 'owned_by_user'
    OGRP = 'owned_by_group'
    REALM = 'realm_entity'
    ownership_fields = (OUSR, OGRP, REALM)
    pkey = table._id.name
    if (isinstance(record, (Row, dict)) and (pkey in record)):
        record_id = record[pkey]
    else:
        record_id = record
    data = Storage()
    for key in fields:
        if (key in ownership_fields):
            data[key] = fields[key]
    if data:
        s3db = current.s3db
        db = current.db
        q = (table._id == record_id)
        success = db(q).update(**data)
        if (success and update and (REALM in data)):
            rc = s3db.get_config(table, 'realm_components', ())
            resource = s3db.resource(table, components=rc)
            realm = {REALM: data[REALM]}
            for component in resource.components.values():
                ctable = component.table
                if (REALM not in ctable.fields):
                    continue
                query = (component.get_join() & q)
                rows = db(query).select(ctable._id)
                ids = list(set([row[ctable._id] for row in rows]))
                if ids:
                    if ctable._ot:
                        ctable = db[ctable._ot]
                    db(ctable._id.belongs(ids)).update(**realm)
        self.update_shared_fields(table, record, **data)
    else:
        return None
