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

Get message threads.

Description

Parameters

$args

(array) (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

	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.