BP_Messages_Thread::get_threads_for_user( array $args = array() )

Get message threads.

Description

Parameters

$args

(Optional) Array of arguments

Default value: array()

Return

(array|bool) Array on success. Boolean false on failure.

Source

File: bp-messages/classes/class-bp-messages-thread.php

840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
public static function get_threads_for_user( $args = array() ) {
    global $wpdb;
 
    $bp            = buddypress();
    $function_args = func_get_args();
 
    // Backward compatibility with old method of passing arguments.
    if ( ! is_array( $args ) || count( $function_args ) > 1 ) {
        _deprecated_argument( __METHOD__, '2.2.0', sprintf( __( 'Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddyboss' ), __METHOD__, __FILE__ ) );
 
        $old_args_keys = array(
            0 => 'user_id',
            1 => 'box',
            2 => 'type',
            3 => 'limit',
            4 => 'page',
            5 => 'search_terms',
        );
 
        $args = bp_core_parse_args_array( $old_args_keys, $function_args );
    }
 
    $r = bp_parse_args(
        $args,
        array(
            'user_id'      => false,
            'box'          => 'inbox',
            'type'         => 'all',
            'limit'        => null,
            'page'         => null,
            'search_terms' => '',
            'include'      => false,
            'is_hidden'    => false,
            'meta_query'   => array(),
            'fields'       => 'all',
            'having_sql'   => false,
        )
    );
 
    $pag_sql        = $user_threads_query = $having_sql = '';
    $meta_query_sql = array(
        'join'  => '',
        'where' => '',
    );
 
    if ( $r['limit'] && $r['page'] ) {
        $pag_sql = $wpdb->prepare( ' LIMIT %d, %d', intval( ( $r['page'] - 1 ) * $r['limit'] ), intval( $r['limit'] ) );
    }
 
    $r['user_id'] = (int) $r['user_id'];
    $where_sql    = '1 = 1';
 
    if ( ! empty( $r['include'] ) ) {
        $user_threads_query = $r['include'];
    } elseif ( ! empty( $r['user_id'] ) ) {
        $user_threads_sql = "SELECT DISTINCT(thread_id) FROM {$bp->messages->table_name_recipients} WHERE user_id = %d AND is_deleted = 0";
        if ( false === $r['is_hidden'] && empty( $r['search_terms'] ) ) {
            $user_threads_sql .= " AND is_hidden = 0";
        }
        $user_threads_query = $wpdb->prepare( $user_threads_sql, $r['user_id'] );
    }
 
    $group_thread_in = array();
    if ( ! empty( $r['search_terms'] ) ) {
 
        // Search in xprofile field.
        $search_terms_like = '%' . bp_esc_like( $r['search_terms'] ) . '%';
        $where_sql         = $wpdb->prepare( 'm.message LIKE %s', $search_terms_like );
 
        $participants_sql           = array();
        $participants_sql['select'] = "SELECT DISTINCT(r.user_id), u.display_name";
        $participants_sql['from']   = "FROM {$bp->messages->table_name_recipients} r LEFT JOIN {$wpdb->users} u ON r.user_id = u.ID";
        $participants_sql['where']  = "WHERE 1=1";
        if ( ! empty( $user_threads_query ) ) {
            $participants_sql['where'] .= " AND r.thread_id IN ($user_threads_query)";
        }
        $participants_sql['where_like'] = "u.display_name LIKE %s OR u.user_login LIKE %s OR u.user_nicename LIKE %s";
 
        $participants_args = array(
            $search_terms_like,
            $search_terms_like,
            $search_terms_like
        );
 
        // Search in xprofile field
        if ( bp_is_active( 'xprofile' ) ) {
            // Explode the value if there is a space in search term.
            $split_name = explode( ' ', $r['search_terms'] );
 
            $participants_sql['from'] .= " LEFT JOIN {$bp->profile->table_name_data} spd ON r.user_id = spd.user_id";
 
            if ( isset( $split_name ) && isset( $split_name[0] ) && isset( $split_name[1] ) && ! empty( $split_name ) && ! empty( trim( $split_name[0] ) ) && ! empty( trim( $split_name[1] ) ) ) {
                $participants_sql['where_like'] .= ' OR spd.value LIKE %s OR spd.value LIKE %s';
                $participants_args[]            = $split_name[0];
                $participants_args[]            = $split_name[1];
            } else {
                $participants_sql['where_like'] .= ' OR spd.value LIKE %s';
                $participants_args[]            = $search_terms_like;
            }
        }
 
        $participants_sql['where'] .= " AND ( {$participants_sql['where_like']} )";
        $participants_sql          = "{$participants_sql['select']} {$participants_sql['from']} {$participants_sql['where']}";
        $current_user_participants = $wpdb->get_results( $wpdb->prepare( $participants_sql, $participants_args ) );
 
        $current_user_participants_ids = array_map( 'intval', wp_list_pluck( $current_user_participants, 'user_id' ) );
        $current_user_participants_ids = array_diff( $current_user_participants_ids, array( bp_loggedin_user_id() ) );
 
        // Search Group Thread via Group Name via search_terms
        $search_terms_like = '%' . bp_esc_like( $r['search_terms'] ) . '%';
        $groups            = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$bp->groups->table_name} g WHERE g.name LIKE %s", $search_terms_like ) );
        $group_creator_ids = array_map( 'intval', wp_list_pluck( $groups, 'creator_id' ) );
 
        // If Group Found
        if ( ! empty( $group_creator_ids ) ) {
            if ( is_array( $current_user_participants_ids ) ) {
                $current_user_participants_ids = array_merge( $current_user_participants_ids, $group_creator_ids );
            } else {
                $current_user_participants_ids = $group_creator_ids;
            }
        }
 
        // Search for deleted Group OR Deleted Users. Todo: Need refactor code
        $value = "(deleted)|(group)|(Deleted)|(group)|(user)|(User)|(del)|(Del)|(dele)|(Dele)|(dele)|(Dele)|(delet)|(Delet)|(use)|(Use)";
        if ( preg_match_all( '/\b' . $value . '\b/i', $r['search_terms'], $dest ) ) {
 
            // For deleted users.
            $current_user_participants_query = self::get(
                array(
                    'exclude_active_users' => true,
                    'per_page'             => - 1,
                )
            );
 
            $current_user_participants = ( ! empty( $current_user_participants_query['recipients'] ) ) ? array_unique( array_map( 'intval', wp_list_pluck( $current_user_participants_query['recipients'], 'user_id' ) ) ) : array();
 
            if ( ! empty( $current_user_participants ) ) {
                $deleted_user_ids = $current_user_participants;
                if ( is_array( $current_user_participants_ids ) ) {
                    $current_user_participants_ids = array_merge( $current_user_participants_ids, $deleted_user_ids );
                } else {
                    $current_user_participants_ids = $deleted_user_ids;
                }
            }
 
            // For deleted groups fetch all thread first.
            $threads    = self::get(
                array(
                    'per_page' => - 1,
                )
            );
            $thread_ids = ( ! empty( $threads['recipients'] ) ) ? array_map( 'intval', wp_list_pluck( $threads['recipients'], 'thread_id' ) ) : array();
 
            // If Group Found
            if ( ! empty( $thread_ids ) ) {
                foreach ( $thread_ids as $thread ) {
                    // Get the group id from the first message
                    $first_message    = BP_Messages_Thread::get_first_message( $thread );
                    $message_group_id = (int) bp_messages_get_meta( $first_message->id, 'group_id', true ); // group id
                    if ( $message_group_id ) {
                        if ( bp_is_active( 'groups' ) ) {
                            $group_name = bp_get_group_name( groups_get_group( $message_group_id ) );
                        } else {
                            $group_name = $wpdb->get_var( "SELECT name FROM {$groups_table} WHERE id = '{$message_group_id}';" ); // db call ok; no-cache ok;
                        }
                        if ( empty( $group_name ) ) {
                            $group_thread_in[] = $thread;
                        }
                    }
                }
            }
 
        }
 
        if ( $current_user_participants_ids ) {
            $user_ids  = implode( ',', array_unique( $current_user_participants_ids ) );
            $where_sql = '( ' . $wpdb->prepare( "m.message LIKE %s OR r.user_id IN ({$user_ids})", $search_terms_like );
            if ( ! empty( $group_thread_in ) ) {
                $thread_in = implode( ',', $group_thread_in );
                $where_sql .= " OR r.thread_id IN ({$thread_in})";
            }
            $where_sql .= ' )';
        }
    }
 
    if ( ! empty( $user_threads_query ) ) {
        $where_sql .= " AND r.thread_id IN ($user_threads_query)";
    }
 
    // Process meta query into SQL.
    $meta_query = self::get_meta_query_sql( $r['meta_query'] );
    if ( ! empty( $meta_query['join'] ) ) {
        $meta_query_sql['join'] = $meta_query['join'];
    }
    if ( ! empty( $meta_query['where'] ) ) {
        $meta_query_sql['where'] = $meta_query['where'];
    }
 
    if ( ! empty( $r['having_sql'] ) ) {
        $having_sql = $r['having_sql'];
    }
 
    // Set up SQL array.
    $sql           = array();
    $sql['select'] = 'SELECT m.thread_id, MAX(m.date_sent) AS date_sent, GROUP_CONCAT(DISTINCT r.user_id ORDER BY r.user_id separator \',\' ) as recipient_list';
    $sql['from']   = "FROM {$bp->messages->table_name_recipients} r INNER JOIN {$bp->messages->table_name_messages} m ON m.thread_id = r.thread_id {$meta_query_sql['join']}";
    $sql['where']  = "WHERE {$where_sql} {$meta_query_sql['where']}";
    $sql['misc']   = "GROUP BY m.thread_id {$having_sql} ORDER BY date_sent DESC {$pag_sql}";
 
    /**
     * Filters the Where SQL statement.
     *
     * @since BuddyBoss 1.5.4
     *
     * @param array $r                Array of parsed arguments for the get method.
     * @param array $where_conditions Where conditions SQL statement.
     */
    $sql['where'] = apply_filters( 'bp_messages_recipient_get_where_conditions', $sql['where'], $r );
 
    /**
     * Filters the From SQL statement.
     *
     * @since BuddyBoss 1.5.4
     *
     * @param array  $r   Array of parsed arguments for the get method.
     * @param string $sql From SQL statement.
     */
    $sql['from']  = apply_filters( 'bp_messages_recipient_get_join_sql', $sql['from'], $r );
 
    // Get thread IDs.
    $thread_ids = $wpdb->get_results( $qq = implode( ' ', $sql ) );
    // print_r($qq);die();
    if ( empty( $thread_ids ) ) {
        return false;
    }
 
    // Adjust $sql to work for thread total.
    $sql['select'] = 'SELECT COUNT( DISTINCT m.thread_id )';
    unset( $sql['misc'] );
    $total_threads = $wpdb->get_var( implode( ' ', $sql ) );
 
    // Sort threads by date_sent.
    foreach ( (array) $thread_ids as $thread ) {
        $sorted_threads[ $thread->thread_id ] = strtotime( $thread->date_sent );
    }
 
    arsort( $sorted_threads );
 
    $threads = array();
    if ( 'ids' === $r['fields'] ) {
        $threads = array_keys( $sorted_threads );
    } elseif ( 'select' === $r['fields'] ) {
        $threads = $thread_ids;
    } else {
        foreach ( (array) $sorted_threads as $thread_id => $date_sent ) {
            $threads[] = new BP_Messages_Thread(
                $thread_id,
                'ASC',
                array(
                    'update_meta_cache' => false,
                )
            );
        }
    }
 
    /**
     * Filters the results of the query for a user's message threads.
     *
     * @since BuddyPress 2.2.0
     *
     * @param array $value         {
     *
     * @type array  $threads       Array of threads. Passed by reference.
     * @type int    $total_threads Number of threads found by the query.
     * }
     */
    return apply_filters(
        'bp_messages_thread_current_threads',
        array(
            'threads' => &$threads,
            'total'   => (int) $total_threads,
        )
    );
}

Changelog

Changelog
Version Description
BuddyPress 1.0.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.