'Lookup the realm entity for a record
@param table: the Table
@param record: the record (as Row or dict)
@param entity: the entity (pe_id)'

def get_realm_entity(self, table, record, entity=0):

    if ('realm_entity' not in table):
        return None
    s3db = current.s3db
    if isinstance(entity, tuple):
        realm_entity = s3db.pr_get_pe_id(entity)
    else:
        realm_entity = entity
    if (realm_entity == 0):
        handler = current.deployment_settings.get_auth_realm_entity()
        if callable(handler):
            realm_entity = handler(table, record)
    if (realm_entity == 0):
        handler = s3db.get_config(table, 'realm_entity')
        if callable(handler):
            realm_entity = handler(table, record)
    if (realm_entity == 0):
        tablename = original_tablename(table)
        if (('pe_id' in record) and (tablename not in ('pr_person', 'dvi_body'))):
            realm_entity = record['pe_id']
        elif ('organisation_id' in record):
            realm_entity = s3db.pr_get_pe_id('org_organisation', record['organisation_id'])
        elif ('site_id' in record):
            realm_entity = s3db.pr_get_pe_id('org_site', record['site_id'])
        elif ('group_id' in record):
            realm_entity = s3db.pr_get_pe_id('pr_group', record['group_id'])
        else:
            realm_entity = None
    return realm_entity
