/**
  * BP_Groups_Invite_Template constructor.
  *
  * @since 1.5.0
  *
  * @param array $args
  */
 public function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '2.0.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'group_id');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = wp_parse_args($args, array('page' => 1, 'per_page' => 10, 'page_arg' => 'invitepage', 'user_id' => bp_loggedin_user_id(), 'group_id' => bp_get_current_group_id()));
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     $iquery = new BP_Group_Member_Query(array('group_id' => $r['group_id'], 'type' => 'first_joined', 'per_page' => $this->pag_num, 'page' => $this->pag_page, 'is_confirmed' => false, 'inviter_id' => $r['user_id']));
     $this->invite_data = $iquery->results;
     $this->total_invite_count = $iquery->total_users;
     $this->invites = array_values(wp_list_pluck($this->invite_data, 'ID'));
     $this->invite_count = count($this->invites);
     // If per_page is set to 0 (show all results), don't generate
     // pag_links.
     if (!empty($this->pag_num)) {
         $this->pag_links = paginate_links(array('base' => add_query_arg($this->pag_arg, '%#%'), 'format' => '', 'total' => ceil($this->total_invite_count / $this->pag_num), 'current' => $this->pag_page, 'prev_text' => '←', 'next_text' => '→', 'mid_size' => 1, 'add_args' => array()));
     } else {
         $this->pag_links = '';
     }
 }
 /**
  * Constructor method.
  *
  * @since 1.5.0
  *
  * @param array $args {
  *     @type int $group_id ID of the group whose membership requests
  *                         are being queried. Default: current group id.
  *     @type int $per_page Number of records to return per page of
  *                         results. Default: 10.
  *     @type int $page     Page of results to show. Default: 1.
  *     @type int $max      Max items to return. Default: false (show all)
  * }
  */
 public function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '2.0.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'group_id', 1 => 'per_page', 2 => 'max');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = wp_parse_args($args, array('page' => 1, 'per_page' => 10, 'page_arg' => 'mrpage', 'max' => false, 'type' => 'first_joined', 'group_id' => bp_get_current_group_id()));
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     $mquery = new BP_Group_Member_Query(array('group_id' => $r['group_id'], 'type' => $r['type'], 'per_page' => $this->pag_num, 'page' => $this->pag_page, 'is_confirmed' => false, 'inviter_id' => 0));
     $this->requests = array_values($mquery->results);
     $this->request_count = count($this->requests);
     // Compatibility with legacy format of request data objects.
     foreach ($this->requests as $rk => $rv) {
         // For legacy reasons, the 'id' property of each
         // request must match the membership id, not the ID of
         // the user (as it's returned by BP_Group_Member_Query).
         $this->requests[$rk]->user_id = $rv->ID;
         $this->requests[$rk]->id = $rv->membership_id;
         // Miscellaneous values.
         $this->requests[$rk]->group_id = $r['group_id'];
     }
     if (empty($r['max']) || $r['max'] >= (int) $mquery->total_users) {
         $this->total_request_count = (int) $mquery->total_users;
     } else {
         $this->total_request_count = (int) $r['max'];
     }
     if (empty($r['max']) || $r['max'] >= count($this->requests)) {
         $this->request_count = count($this->requests);
     } else {
         $this->request_count = (int) $r['max'];
     }
     $this->pag_links = paginate_links(array('base' => add_query_arg($this->pag_arg, '%#%'), 'format' => '', 'total' => ceil($this->total_request_count / $this->pag_num), 'current' => $this->pag_page, 'prev_text' => '←', 'next_text' => '→', 'mid_size' => 1, 'add_args' => array()));
 }
/**
 * Fetch the members of a group.
 *
 * Since BuddyPress 1.8, a procedural wrapper for BP_Group_Member_Query.
 * Previously called BP_Groups_Member::get_all_for_group().
 *
 * To use the legacy query, filter 'bp_use_legacy_group_member_query',
 * returning true.
 *
 * @param array $args {
 *     An array of optional arguments.
 *     @type int      $group_id     ID of the group whose members are being queried.
 *                                  Default: current group ID.
 *     @type int      $page         Page of results to be queried. Default: 1.
 *     @type int      $per_page     Number of items to return per page of results.
 *                                  Default: 20.
 *     @type int      $max          Optional. Max number of items to return.
 *     @type array    $exclude      Optional. Array of user IDs to exclude.
 *     @type bool|int $value        True (or 1) to exclude admins and mods from results.
 *                                  Default: 1.
 *     @type bool|int $value        True (or 1) to exclude banned users from results.
 *                                  Default: 1.
 *     @type array    $group_role   Optional. Array of group roles to include.
 *     @type string   $search_terms Optional. Filter results by a search string.
 *     @type string   $type         Optional. Sort the order of results. 'last_joined',
 *                                  'first_joined', or any of the $type params available
 *                                  in {@link BP_User_Query}. Default: 'last_joined'.
 * }
 * @return array Multi-d array of 'members' list and 'count'.
 */
function groups_get_group_members($args = array())
{
    // Backward compatibility with old method of passing arguments
    if (!is_array($args) || func_num_args() > 1) {
        _deprecated_argument(__METHOD__, '2.0.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
        $old_args_keys = array(0 => 'group_id', 1 => 'per_page', 2 => 'page', 3 => 'exclude_admins_mods', 4 => 'exclude_banned', 5 => 'exclude', 6 => 'group_role');
        $func_args = func_get_args();
        $args = bp_core_parse_args_array($old_args_keys, $func_args);
    }
    $r = wp_parse_args($args, array('group_id' => bp_get_current_group_id(), 'per_page' => false, 'page' => false, 'exclude_admins_mods' => true, 'exclude_banned' => true, 'exclude' => false, 'group_role' => array(), 'search_terms' => false, 'type' => 'last_joined'));
    // For legacy users. Use of BP_Groups_Member::get_all_for_group()
    // is deprecated. func_get_args() can't be passed to a function in PHP
    // 5.2.x, so we create a variable
    $func_args = func_get_args();
    if (apply_filters('bp_use_legacy_group_member_query', false, __FUNCTION__, $func_args)) {
        $retval = BP_Groups_Member::get_all_for_group($r['group_id'], $r['per_page'], $r['page'], $r['exclude_admins_mods'], $r['exclude_banned'], $r['exclude']);
    } else {
        // exclude_admins_mods and exclude_banned are legacy arguments.
        // Convert to group_role
        if (empty($r['group_role'])) {
            $r['group_role'] = array('member');
            if (!$r['exclude_admins_mods']) {
                $r['group_role'][] = 'mod';
                $r['group_role'][] = 'admin';
            }
            if (!$r['exclude_banned']) {
                $r['group_role'][] = 'banned';
            }
        }
        // Perform the group member query (extends BP_User_Query)
        $members = new BP_Group_Member_Query(array('group_id' => $r['group_id'], 'per_page' => $r['per_page'], 'page' => $r['page'], 'group_role' => $r['group_role'], 'exclude' => $r['exclude'], 'search_terms' => $r['search_terms'], 'type' => $r['type']));
        // Structure the return value as expected by the template functions
        $retval = array('members' => array_values($members->results), 'count' => $members->total_users);
    }
    return $retval;
}
 /**
  * Get current message threads for a user.
  *
  * @since 1.0.0
  *
  * @param array $args {
  *     Array of arguments.
  *     @type int    $user_id      The user ID.
  *     @type string $box          The type of mailbox to get. Either 'inbox' or 'sentbox'.
  *                                Defaults to 'inbox'.
  *     @type string $type         The type of messages to get. Either 'all' or 'unread'
  *                                or 'read'. Defaults to 'all'.
  *     @type int    $limit        The number of messages to get. Defaults to null.
  *     @type int    $page         The page number to get. Defaults to null.
  *     @type string $search_terms The search term to use. Defaults to ''.
  *     @type array  $meta_query   Meta query arguments. See WP_Meta_Query for more details.
  * }
  * @return array|bool Array on success. Boolean false on failure.
  */
 public static function get_current_threads_for_user($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_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.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'box', 2 => 'type', 3 => 'limit', 4 => 'page', 5 => 'search_terms');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = bp_parse_args($args, array('user_id' => false, 'box' => 'inbox', 'type' => 'all', 'limit' => null, 'page' => null, 'search_terms' => '', 'meta_query' => array()));
     $pag_sql = $type_sql = $search_sql = $user_id_sql = $sender_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']));
     }
     if ($r['type'] == 'unread') {
         $type_sql = " AND r.unread_count != 0 ";
     } elseif ($r['type'] == 'read') {
         $type_sql = " AND r.unread_count = 0 ";
     }
     if (!empty($r['search_terms'])) {
         $search_terms_like = '%' . bp_esc_like($r['search_terms']) . '%';
         $search_sql = $wpdb->prepare("AND ( subject LIKE %s OR message LIKE %s )", $search_terms_like, $search_terms_like);
     }
     $r['user_id'] = (int) $r['user_id'];
     // Default deleted SQL
     $deleted_sql = 'r.is_deleted = 0';
     switch ($r['box']) {
         case 'sentbox':
             $user_id_sql = 'AND ' . $wpdb->prepare('m.sender_id = %d', $r['user_id']);
             $sender_sql = 'AND m.sender_id = r.user_id';
             break;
         case 'inbox':
             $user_id_sql = 'AND ' . $wpdb->prepare('r.user_id = %d', $r['user_id']);
             $sender_sql = 'AND r.sender_only = 0';
             break;
         default:
             // Omit user-deleted threads from all other custom message boxes
             $deleted_sql = $wpdb->prepare('( r.user_id = %d AND r.is_deleted = 0 )', $r['user_id']);
             break;
     }
     // 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'];
     }
     $bp = buddypress();
     // set up SQL array
     $sql = array();
     $sql['select'] = 'SELECT m.thread_id, MAX(m.date_sent) AS date_sent';
     $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 {$deleted_sql} {$user_id_sql} {$sender_sql} {$type_sql} {$search_sql} {$meta_query_sql['where']}";
     $sql['misc'] = "GROUP BY m.thread_id ORDER BY date_sent DESC {$pag_sql}";
     // get thread IDs
     $thread_ids = $wpdb->get_results(implode(' ', $sql));
     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();
     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 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));
 }
 /**
  * Constructor method.
  *
  * The arguments passed to this class constructor are of the same
  * format as {@link BP_Activity_Activity::get()}.
  *
  * @since 1.5.0
  *
  * @see BP_Activity_Activity::get() for a description of the argument
  *      structure, as well as default values.
  *
  * @param array $args {
  *     Array of arguments. Supports all arguments from
  *     BP_Activity_Activity::get(), as well as 'page_arg' and
  *     'include'. Default values for 'per_page' and 'display_comments'
  *     differ from the originating function, and are described below.
  *     @type string      $page_arg         The string used as a query parameter in
  *                                         pagination links. Default: 'acpage'.
  *     @type array|bool  $include          Pass an array of activity IDs to
  *                                         retrieve only those items, or false to noop the 'include'
  *                                         parameter. 'include' differs from 'in' in that 'in' forms
  *                                         an IN clause that works in conjunction with other filters
  *                                         passed to the function, while 'include' is interpreted as
  *                                         an exact list of items to retrieve, which skips all other
  *                                         filter-related parameters. Default: false.
  *     @type int|bool    $per_page         Default: 20.
  *     @type string|bool $display_comments Default: 'threaded'.
  * }
  */
 public function __construct($args)
 {
     $bp = buddypress();
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'page', 1 => 'per_page', 2 => 'max', 3 => 'include', 4 => 'sort', 5 => 'filter', 6 => 'search_terms', 7 => 'display_comments', 8 => 'show_hidden', 9 => 'exclude', 10 => 'in', 11 => 'spam', 12 => 'page_arg');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 20, 'page_arg' => 'acpage', 'max' => false, 'fields' => 'all', 'count_total' => false, 'sort' => false, 'include' => false, 'exclude' => false, 'in' => false, 'filter' => false, 'scope' => false, 'search_terms' => false, 'meta_query' => false, 'date_query' => false, 'filter_query' => false, 'display_comments' => 'threaded', 'show_hidden' => false, 'spam' => 'ham_only', 'update_meta_cache' => true);
     $r = wp_parse_args($args, $defaults);
     extract($r);
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     // Check if blog/forum replies are disabled.
     $this->disable_blogforum_replies = (bool) bp_core_get_root_option('bp-disable-blogforum-comments');
     // Get an array of the logged in user's favorite activities.
     $this->my_favs = maybe_unserialize(bp_get_user_meta(bp_loggedin_user_id(), 'bp_favorite_activities', true));
     // Fetch specific activity items based on ID's.
     if (!empty($include)) {
         $this->activities = bp_activity_get_specific(array('activity_ids' => explode(',', $include), 'max' => $max, 'count_total' => $count_total, 'page' => $this->pag_page, 'per_page' => $this->pag_num, 'sort' => $sort, 'display_comments' => $display_comments, 'show_hidden' => $show_hidden, 'spam' => $spam, 'update_meta_cache' => $update_meta_cache));
         // Fetch all activity items.
     } else {
         $this->activities = bp_activity_get(array('display_comments' => $display_comments, 'max' => $max, 'count_total' => $count_total, 'per_page' => $this->pag_num, 'page' => $this->pag_page, 'sort' => $sort, 'search_terms' => $search_terms, 'meta_query' => $meta_query, 'date_query' => $date_query, 'filter_query' => $filter_query, 'filter' => $filter, 'scope' => $scope, 'show_hidden' => $show_hidden, 'exclude' => $exclude, 'in' => $in, 'spam' => $spam, 'update_meta_cache' => $update_meta_cache));
     }
     // The total_activity_count property will be set only if a
     // 'count_total' query has taken place.
     if (!is_null($this->activities['total'])) {
         if (!$max || $max >= (int) $this->activities['total']) {
             $this->total_activity_count = (int) $this->activities['total'];
         } else {
             $this->total_activity_count = (int) $max;
         }
     }
     $this->has_more_items = $this->activities['has_more_items'];
     $this->activities = $this->activities['activities'];
     if ($max) {
         if ($max >= count($this->activities)) {
             $this->activity_count = count($this->activities);
         } else {
             $this->activity_count = (int) $max;
         }
     } else {
         $this->activity_count = count($this->activities);
     }
     $this->full_name = bp_get_displayed_user_fullname();
     // Fetch parent content for activity comments so we do not have to query in the loop.
     foreach ((array) $this->activities as $activity) {
         if ('activity_comment' != $activity->type) {
             continue;
         }
         $parent_ids[] = $activity->item_id;
     }
     if (!empty($parent_ids)) {
         $activity_parents = bp_activity_get_specific(array('activity_ids' => $parent_ids));
     }
     if (!empty($activity_parents['activities'])) {
         foreach ($activity_parents['activities'] as $parent) {
             $this->activity_parents[$parent->id] = $parent;
         }
         unset($activity_parents);
     }
     if ((int) $this->total_activity_count && (int) $this->pag_num) {
         $this->pag_links = paginate_links(array('base' => add_query_arg($this->pag_arg, '%#%'), 'format' => '', 'total' => ceil((int) $this->total_activity_count / (int) $this->pag_num), 'current' => (int) $this->pag_page, 'prev_text' => _x('←', 'Activity pagination previous text', 'buddypress'), 'next_text' => _x('→', 'Activity pagination next text', 'buddypress'), 'mid_size' => 1, 'add_args' => array()));
     }
 }
 /**
  * Get activity items, as specified by parameters
  *
  * @param array $args See $defaults for explanation of arguments
  * @return array
  */
 function get($args = array())
 {
     global $wpdb, $bp;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 25, 'max' => false, 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'filter' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only');
     $r = wp_parse_args($args, $defaults);
     extract($r);
     // Select conditions
     $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
     $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
     $join_sql = '';
     // Where conditions
     $where_conditions = array();
     // Spam
     if ('ham_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching
     if ($search_terms) {
         $search_terms = esc_sql($search_terms);
         $where_conditions['search_sql'] = "a.content LIKE '%%" . esc_sql(like_escape($search_terms)) . "%%'";
     }
     // Filtering
     if ($filter && ($filter_sql = BP_Activity_Activity::get_filter_sql($filter))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Sorting
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$show_hidden) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items
     if (!empty($exclude)) {
         $exclude = implode(',', wp_parse_id_list($exclude));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query
     if (!empty($in)) {
         $in = implode(',', wp_parse_id_list($in));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL
     $meta_query_sql = self::get_meta_query_sql($meta_query);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $display_comments || 'threaded' === $display_comments) {
         $where_conditions[] = "a.type != 'activity_comment'";
     }
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     // Define the preferred order for indexes
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     if (!empty($per_page) && !empty($page)) {
         // Make sure page values are absolute integers
         $page = absint($page);
         $per_page = absint($per_page);
         $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
         $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
     } else {
         $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort));
     }
     $total_activities_sql = apply_filters('bp_activity_total_activities_sql', "SELECT count(DISTINCT a.id) FROM {$bp->activity->table_name} a {$index_hint_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $where_sql, $sort);
     $total_activities = $wpdb->get_var($total_activities_sql);
     // Get the fullnames of users so we don't have to query in the loop
     if (bp_is_active('xprofile') && !empty($activities)) {
         $activity_user_ids = wp_list_pluck($activities, 'user_id');
         $activity_user_ids = implode(',', wp_parse_id_list($activity_user_ids));
         if (!empty($activity_user_ids)) {
             if ($names = $wpdb->get_results("SELECT user_id, value AS user_fullname FROM {$bp->profile->table_name_data} WHERE field_id = 1 AND user_id IN ({$activity_user_ids})")) {
                 foreach ((array) $names as $name) {
                     $tmp_names[$name->user_id] = $name->user_fullname;
                 }
                 foreach ((array) $activities as $i => $activity) {
                     if (!empty($tmp_names[$activity->user_id])) {
                         $activities[$i]->user_fullname = $tmp_names[$activity->user_id];
                     }
                 }
                 unset($names);
                 unset($tmp_names);
             }
         }
     }
     // Get activity meta
     $activity_ids = array();
     foreach ((array) $activities as $activity) {
         $activity_ids[] = $activity->id;
     }
     if (!empty($activity_ids)) {
         bp_activity_update_meta_cache($activity_ids);
     }
     if ($activities && $display_comments) {
         $activities = BP_Activity_Activity::append_comments($activities, $spam);
     }
     // If $max is set, only return up to the max results
     if (!empty($max)) {
         if ((int) $total_activities > (int) $max) {
             $total_activities = $max;
         }
     }
     return array('activities' => $activities, 'total' => (int) $total_activities);
 }
 /**
  * Query for groups.
  *
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @param array $args {
  *     Array of parameters. All items are optional.
  *     @type string       $type              Optional. Shorthand for certain orderby/
  *                                           order combinations. 'newest', 'active', 'popular',
  *                                           'alphabetical', 'random'. When present, will override
  *                                           orderby and order params. Default: null.
  *     @type string       $orderby           Optional. Property to sort by.
  *                                           'date_created', 'last_activity', 'total_member_count',
  *                                           'name', 'random'. Default: 'date_created'.
  *     @type string       $order             Optional. Sort order. 'ASC' or 'DESC'.
  *                                           Default: 'DESC'.
  *     @type int          $per_page          Optional. Number of items to return per page
  *                                           of results. Default: null (no limit).
  *     @type int          $page              Optional. Page offset of results to return.
  *                                           Default: null (no limit).
  *     @type int          $user_id           Optional. If provided, results will be limited to groups
  *                                           of which the specified user is a member. Default: null.
  *     @type string       $search_terms      Optional. If provided, only groups whose names
  *                                           or descriptions match the search terms will be
  *                                           returned. Default: false.
  *     @type array        $meta_query        Optional. An array of meta_query conditions.
  *                                           See {@link WP_Meta_Query::queries} for description.
  *     @type array|string $value             Optional. Array or comma-separated list of group IDs.
  *                                           Results will be limited to groups within the
  *                                           list. Default: false.
  *     @type bool         $populate_extras   Whether to fetch additional information
  *                                           (such as member count) about groups. Default: true.
  *     @type array|string $exclude           Optional. Array or comma-separated list of group IDs.
  *                                           Results will exclude the listed groups. Default: false.
  *     @type bool         $update_meta_cache Whether to pre-fetch groupmeta for
  *                                           the returned groups. Default: true.
  *     @type bool         $show_hidden       Whether to include hidden groups in results. Default: false.
  * }
  * @return array {
  *     @type array $groups Array of group objects returned by the
  *                         paginated query.
  *     @type int   $total  Total count of all groups matching non-
  *                         paginated query params.
  * }
  */
 public static function get($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'type', 1 => 'per_page', 2 => 'page', 3 => 'user_id', 4 => 'search_terms', 5 => 'include', 6 => 'populate_extras', 7 => 'exclude', 8 => 'show_hidden');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('type' => null, 'orderby' => 'date_created', 'order' => 'DESC', 'per_page' => null, 'page' => null, 'user_id' => 0, 'search_terms' => false, 'meta_query' => false, 'include' => false, 'populate_extras' => true, 'update_meta_cache' => true, 'exclude' => false, 'show_hidden' => false);
     $r = wp_parse_args($args, $defaults);
     $bp = buddypress();
     $sql = array();
     $total_sql = array();
     $sql['select'] = "SELECT DISTINCT g.id, g.*, gm1.meta_value AS total_member_count, gm2.meta_value AS last_activity";
     $sql['from'] = " FROM {$bp->groups->table_name_groupmeta} gm1, {$bp->groups->table_name_groupmeta} gm2,";
     if (!empty($r['user_id'])) {
         $sql['members_from'] = " {$bp->groups->table_name_members} m,";
     }
     $sql['group_from'] = " {$bp->groups->table_name} g WHERE";
     if (!empty($r['user_id'])) {
         $sql['user_where'] = " g.id = m.group_id AND";
     }
     $sql['where'] = " g.id = gm1.group_id AND g.id = gm2.group_id AND gm2.meta_key = 'last_activity' AND gm1.meta_key = 'total_member_count'";
     if (empty($r['show_hidden'])) {
         $sql['hidden'] = " AND g.status != 'hidden'";
     }
     if (!empty($r['search_terms'])) {
         $search_terms_like = '%' . bp_esc_like($r['search_terms']) . '%';
         $sql['search'] = $wpdb->prepare(" AND ( g.name LIKE %s OR g.description LIKE %s )", $search_terms_like, $search_terms_like);
     }
     $meta_query_sql = self::get_meta_query_sql($r['meta_query']);
     if (!empty($meta_query_sql['join'])) {
         $sql['from'] .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $sql['meta'] = $meta_query_sql['where'];
     }
     if (!empty($r['user_id'])) {
         $sql['user'] = $wpdb->prepare(" AND m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id']);
     }
     if (!empty($r['include'])) {
         $include = implode(',', wp_parse_id_list($r['include']));
         $sql['include'] = " AND g.id IN ({$include})";
     }
     if (!empty($r['exclude'])) {
         $exclude = implode(',', wp_parse_id_list($r['exclude']));
         $sql['exclude'] = " AND g.id NOT IN ({$exclude})";
     }
     /* Order/orderby ********************************************/
     $order = $r['order'];
     $orderby = $r['orderby'];
     // If a 'type' parameter was passed, parse it and overwrite
     // 'order' and 'orderby' params passed to the function.
     if (!empty($r['type'])) {
         /**
          * Filters the 'type' parameter used to overwrite 'order' and 'orderby' values.
          *
          * @since 2.1.0
          *
          * @param array  $value Converted 'type' value for order and orderby.
          * @param string $value Parsed 'type' value for the get method.
          */
         $order_orderby = apply_filters('bp_groups_get_orderby', self::convert_type_to_order_orderby($r['type']), $r['type']);
         // If an invalid type is passed, $order_orderby will be
         // an array with empty values. In this case, we stick
         // with the default values of $order and $orderby.
         if (!empty($order_orderby['order'])) {
             $order = $order_orderby['order'];
         }
         if (!empty($order_orderby['orderby'])) {
             $orderby = $order_orderby['orderby'];
         }
     }
     // Sanitize 'order'.
     $order = bp_esc_sql_order($order);
     /**
      * Filters the converted 'orderby' term.
      *
      * @since 2.1.0
      *
      * @param string $value   Converted 'orderby' term.
      * @param string $orderby Original orderby value.
      * @param string $value   Parsed 'type' value for the get method.
      */
     $orderby = apply_filters('bp_groups_get_orderby_converted_by_term', self::convert_orderby_to_order_by_term($orderby), $orderby, $r['type']);
     // Random order is a special case.
     if ('rand()' === $orderby) {
         $sql[] = "ORDER BY rand()";
     } else {
         $sql[] = "ORDER BY {$orderby} {$order}";
     }
     if (!empty($r['per_page']) && !empty($r['page']) && $r['per_page'] != -1) {
         $sql['pagination'] = $wpdb->prepare("LIMIT %d, %d", intval(($r['page'] - 1) * $r['per_page']), intval($r['per_page']));
     }
     /**
      * Filters the pagination SQL statement.
      *
      * @since 1.5.0
      *
      * @param string $value Concatenated SQL statement.
      * @param array  $sql   Array of SQL parts before concatenation.
      * @param array  $r     Array of parsed arguments for the get method.
      */
     $paged_groups_sql = apply_filters('bp_groups_get_paged_groups_sql', join(' ', (array) $sql), $sql, $r);
     $paged_groups = $wpdb->get_results($paged_groups_sql);
     $total_sql['select'] = "SELECT COUNT(DISTINCT g.id) FROM {$bp->groups->table_name} g, {$bp->groups->table_name_groupmeta} gm";
     if (!empty($r['user_id'])) {
         $total_sql['select'] .= ", {$bp->groups->table_name_members} m";
     }
     if (!empty($sql['hidden'])) {
         $total_sql['where'][] = "g.status != 'hidden'";
     }
     if (!empty($sql['search'])) {
         $total_sql['where'][] = $wpdb->prepare("( g.name LIKE %s OR g.description LIKE %s )", $search_terms_like, $search_terms_like);
     }
     if (!empty($r['user_id'])) {
         $total_sql['where'][] = $wpdb->prepare("m.group_id = g.id AND m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id']);
     }
     // Temporary implementation of meta_query for total count
     // See #5099.
     if (!empty($meta_query_sql['where'])) {
         // Join the groupmeta table.
         $total_sql['select'] .= ", " . substr($meta_query_sql['join'], 0, -2);
         // Modify the meta_query clause from paged_sql for our syntax.
         $meta_query_clause = preg_replace('/^\\s*AND/', '', $meta_query_sql['where']);
         $total_sql['where'][] = $meta_query_clause;
     }
     // Already escaped in the paginated results block.
     if (!empty($include)) {
         $total_sql['where'][] = "g.id IN ({$include})";
     }
     // Already escaped in the paginated results block.
     if (!empty($exclude)) {
         $total_sql['where'][] = "g.id NOT IN ({$exclude})";
     }
     $total_sql['where'][] = "g.id = gm.group_id";
     $total_sql['where'][] = "gm.meta_key = 'last_activity'";
     $t_sql = $total_sql['select'];
     if (!empty($total_sql['where'])) {
         $t_sql .= " WHERE " . join(' AND ', (array) $total_sql['where']);
     }
     /**
      * Filters the SQL used to retrieve total group results.
      *
      * @since 1.5.0
      *
      * @param string $t_sql     Concatenated SQL statement used for retrieving total group results.
      * @param array  $total_sql Array of SQL parts for the query.
      * @param array  $r         Array of parsed arguments for the get method.
      */
     $total_groups_sql = apply_filters('bp_groups_get_total_groups_sql', $t_sql, $total_sql, $r);
     $total_groups = $wpdb->get_var($total_groups_sql);
     $group_ids = array();
     foreach ((array) $paged_groups as $group) {
         $group_ids[] = $group->id;
     }
     // Populate some extra information instead of querying each time in the loop.
     if (!empty($r['populate_extras'])) {
         $paged_groups = BP_Groups_Group::get_group_extras($paged_groups, $group_ids, $r['type']);
     }
     // Grab all groupmeta.
     if (!empty($r['update_meta_cache'])) {
         bp_groups_update_meta_cache($group_ids);
     }
     unset($sql, $total_sql);
     return array('groups' => $paged_groups, 'total' => $total_groups);
 }
 /**
  * Constructor method.
  *
  * @param array $args {
  *     Array of arguments. See bp_has_message_threads() for full description.
  * }
  */
 public function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_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.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'box', 2 => 'per_page', 3 => 'max', 4 => 'type', 5 => 'search_terms', 6 => 'page_arg');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = wp_parse_args($args, array('page' => 1, 'per_page' => 10, 'page_arg' => 'mpage', 'box' => 'inbox', 'type' => 'all', 'user_id' => bp_loggedin_user_id(), 'max' => false, 'search_terms' => '', 'meta_query' => array()));
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     $this->user_id = $r['user_id'];
     $this->box = $r['box'];
     $this->type = $r['type'];
     $this->search_terms = $r['search_terms'];
     if ('notices' === $this->box) {
         $this->threads = BP_Messages_Notice::get_notices(array('pag_num' => $this->pag_num, 'pag_page' => $this->pag_page));
     } else {
         $threads = BP_Messages_Thread::get_current_threads_for_user(array('user_id' => $this->user_id, 'box' => $this->box, 'type' => $this->type, 'limit' => $this->pag_num, 'page' => $this->pag_page, 'search_terms' => $this->search_terms, 'meta_query' => $r['meta_query']));
         $this->threads = $threads['threads'];
         $this->total_thread_count = $threads['total'];
     }
     if (!$this->threads) {
         $this->thread_count = 0;
         $this->total_thread_count = 0;
     } else {
         $total_notice_count = BP_Messages_Notice::get_total_notice_count();
         if (empty($r['max']) || (int) $r['max'] >= (int) $total_notice_count) {
             if ('notices' === $this->box) {
                 $this->total_thread_count = (int) $total_notice_count;
             }
         } else {
             $this->total_thread_count = (int) $r['max'];
         }
         if (!empty($r['max'])) {
             if ((int) $r['max'] >= count($this->threads)) {
                 $this->thread_count = count($this->threads);
             } else {
                 $this->thread_count = (int) $r['max'];
             }
         } else {
             $this->thread_count = count($this->threads);
         }
     }
     if ((int) $this->total_thread_count && (int) $this->pag_num) {
         $pag_args = array($r['page_arg'] => '%#%');
         if (defined('DOING_AJAX') && true === (bool) DOING_AJAX) {
             $base = remove_query_arg('s', wp_get_referer());
         } else {
             $base = '';
         }
         $add_args = array();
         if (!empty($this->search_terms)) {
             $add_args['s'] = $this->search_terms;
         }
         $this->pag_links = paginate_links(array('base' => add_query_arg($pag_args, $base), 'format' => '', 'total' => ceil((int) $this->total_thread_count / (int) $this->pag_num), 'current' => $this->pag_page, 'prev_text' => _x('←', 'Message pagination previous text', 'buddypress'), 'next_text' => _x('→', 'Message pagination next text', 'buddypress'), 'mid_size' => 1, 'add_args' => $add_args));
     }
 }
 /**
  * Get activity items, as specified by parameters.
  *
  * @since 1.0.0
  * @since 2.4.0 Introduced the `$fields` parameter.
  *
  * @see BP_Activity_Activity::get_filter_sql() for a description of the
  *      'filter' parameter.
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @param array $args {
  *     An array of arguments. All items are optional.
  *     @type int          $page              Which page of results to fetch. Using page=1 without per_page will result
  *                                           in no pagination. Default: 1.
  *     @type int|bool     $per_page          Number of results per page. Default: 25.
  *     @type int|bool     $max               Maximum number of results to return. Default: false (unlimited).
  *     @type string       $fields            Activity fields to return. Pass 'ids' to get only the activity IDs.
  *                                           'all' returns full activity objects.
  *     @type string       $sort              ASC or DESC. Default: 'DESC'.
  *     @type array        $exclude           Array of activity IDs to exclude. Default: false.
  *     @type array        $in                Array of ids to limit query by (IN). Default: false.
  *     @type array        $meta_query        Array of meta_query conditions. See WP_Meta_Query::queries.
  *     @type array        $date_query        Array of date_query conditions. See first parameter of
  *                                           WP_Date_Query::__construct().
  *     @type array        $filter_query      Array of advanced query conditions. See BP_Activity_Query::__construct().
  *     @type string|array $scope             Pre-determined set of activity arguments.
  *     @type array        $filter            See BP_Activity_Activity::get_filter_sql().
  *     @type string       $search_terms      Limit results by a search term. Default: false.
  *     @type bool         $display_comments  Whether to include activity comments. Default: false.
  *     @type bool         $show_hidden       Whether to show items marked hide_sitewide. Default: false.
  *     @type string       $spam              Spam status. Default: 'ham_only'.
  *     @type bool         $update_meta_cache Whether to pre-fetch metadata for queried activity items. Default: true.
  *     @type string|bool  $count_total       If true, an additional DB query is run to count the total activity items
  *                                           for the query. Default: false.
  * }
  * @return array The array returned has two keys:
  *               - 'total' is the count of located activities
  *               - 'activities' is an array of the located activities
  */
 public static function get($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $bp = buddypress();
     $r = wp_parse_args($args, array('page' => 1, 'per_page' => 25, 'max' => false, 'fields' => 'all', 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'date_query' => false, 'filter_query' => false, 'filter' => false, 'scope' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only', 'update_meta_cache' => true, 'count_total' => false));
     // Select conditions.
     $select_sql = "SELECT DISTINCT a.id";
     $from_sql = " FROM {$bp->activity->table_name} a";
     $join_sql = '';
     // Where conditions.
     $where_conditions = array();
     // Excluded types.
     $excluded_types = array();
     // Scope takes precedence.
     if (!empty($r['scope'])) {
         $scope_query = self::get_scope_query_sql($r['scope'], $r);
         // Add our SQL conditions if matches were found.
         if (!empty($scope_query['sql'])) {
             $where_conditions['scope_query_sql'] = $scope_query['sql'];
         }
         // Override some arguments if needed.
         if (!empty($scope_query['override'])) {
             $r = self::array_replace_recursive($r, $scope_query['override']);
         }
         // Advanced filtering.
     } elseif (!empty($r['filter_query'])) {
         $filter_query = new BP_Activity_Query($r['filter_query']);
         $sql = $filter_query->get_sql();
         if (!empty($sql)) {
             $where_conditions['filter_query_sql'] = $sql;
         }
     }
     // Regular filtering.
     if ($r['filter'] && ($filter_sql = BP_Activity_Activity::get_filter_sql($r['filter']))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Spam.
     if ('ham_only' == $r['spam']) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $r['spam']) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching.
     if ($r['search_terms']) {
         $search_terms_like = '%' . bp_esc_like($r['search_terms']) . '%';
         $where_conditions['search_sql'] = $wpdb->prepare('a.content LIKE %s', $search_terms_like);
     }
     // Sorting.
     $sort = $r['sort'];
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$r['show_hidden']) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items.
     if (!empty($r['exclude'])) {
         $exclude = implode(',', wp_parse_id_list($r['exclude']));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query.
     if (!empty($r['in'])) {
         $in = implode(',', wp_parse_id_list($r['in']));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL.
     $meta_query_sql = self::get_meta_query_sql($r['meta_query']);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Process date_query into SQL.
     $date_query_sql = self::get_date_query_sql($r['date_query']);
     if (!empty($date_query_sql)) {
         $where_conditions['date'] = $date_query_sql;
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $r['display_comments'] || 'threaded' === $r['display_comments']) {
         $excluded_types[] = 'activity_comment';
     }
     // Exclude 'last_activity' items unless the 'action' filter has
     // been explicitly set.
     if (empty($r['filter']['object'])) {
         $excluded_types[] = 'last_activity';
     }
     // Build the excluded type sql part.
     if (!empty($excluded_types)) {
         $not_in = "'" . implode("', '", esc_sql($excluded_types)) . "'";
         $where_conditions['excluded_types'] = "a.type NOT IN ({$not_in})";
     }
     /**
      * Filters the MySQL WHERE conditions for the Activity items get method.
      *
      * @since 1.9.0
      *
      * @param array  $where_conditions Current conditions for MySQL WHERE statement.
      * @param array  $r                Parsed arguments passed into method.
      * @param string $select_sql       Current SELECT MySQL statement at point of execution.
      * @param string $from_sql         Current FROM MySQL statement at point of execution.
      * @param string $join_sql         Current INNER JOIN MySQL statement at point of execution.
      */
     $where_conditions = apply_filters('bp_activity_get_where_conditions', $where_conditions, $r, $select_sql, $from_sql, $join_sql);
     // Join the where conditions together.
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     /**
      * Filters the preferred order of indexes for activity item.
      *
      * @since 1.6.0
      *
      * @param array $value Array of indexes in preferred order.
      */
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find.
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     // Sanitize page and per_page parameters.
     $page = absint($r['page']);
     $per_page = absint($r['per_page']);
     $retval = array('activities' => null, 'total' => null, 'has_more_items' => null);
     /**
      * Filters if BuddyPress should use legacy query structure over current structure for version 2.0+.
      *
      * It is not recommended to use the legacy structure, but allowed to if needed.
      *
      * @since 2.0.0
      *
      * @param bool                 $value Whether to use legacy structure or not.
      * @param BP_Activity_Activity $value Current method being called.
      * @param array                $r     Parsed arguments passed into method.
      */
     if (apply_filters('bp_use_legacy_activity_query', false, __METHOD__, $r)) {
         // Legacy queries joined against the user table.
         $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
         $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
         if (!empty($page) && !empty($per_page)) {
             $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
             /** This filter is documented in bp-activity/bp-activity-classes.php */
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         } else {
             $pag_sql = '';
             /**
              * Filters the legacy MySQL query statement so plugins can alter before results are fetched.
              *
              * @since 1.5.0
              *
              * @param string $value      Concatenated MySQL statement pieces to be query results with for legacy query.
              * @param string $select_sql Final SELECT MySQL statement portion for legacy query.
              * @param string $from_sql   Final FROM MySQL statement portion for legacy query.
              * @param string $where_sql  Final WHERE MySQL statement portion for legacy query.
              * @param string $sort       Final sort direction for legacy query.
              */
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         }
     } else {
         // Query first for activity IDs.
         $activity_ids_sql = "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}";
         if (!empty($per_page) && !empty($page)) {
             // We query for $per_page + 1 items in order to
             // populate the has_more_items flag.
             $activity_ids_sql .= $wpdb->prepare(" LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page + 1);
         }
         /**
          * Filters the paged activities MySQL statement.
          *
          * @since 2.0.0
          *
          * @param string $activity_ids_sql MySQL statement used to query for Activity IDs.
          * @param array  $r                Array of arguments passed into method.
          */
         $activity_ids_sql = apply_filters('bp_activity_paged_activities_sql', $activity_ids_sql, $r);
         $activity_ids = $wpdb->get_col($activity_ids_sql);
         $retval['has_more_items'] = !empty($per_page) && count($activity_ids) > $per_page;
         // If we've fetched more than the $per_page value, we
         // can discard the extra now.
         if (!empty($per_page) && count($activity_ids) === $per_page + 1) {
             array_pop($activity_ids);
         }
         if ('ids' === $r['fields']) {
             $activities = array_map('intval', $activity_ids);
         } else {
             $activities = self::get_activity_data($activity_ids);
         }
     }
     if ('ids' !== $r['fields']) {
         // Get the fullnames of users so we don't have to query in the loop.
         $activities = self::append_user_fullnames($activities);
         // Get activity meta.
         $activity_ids = array();
         foreach ((array) $activities as $activity) {
             $activity_ids[] = $activity->id;
         }
         if (!empty($activity_ids) && $r['update_meta_cache']) {
             bp_activity_update_meta_cache($activity_ids);
         }
         if ($activities && $r['display_comments']) {
             $activities = BP_Activity_Activity::append_comments($activities, $r['spam']);
         }
         // Pre-fetch data associated with activity users and other objects.
         BP_Activity_Activity::prefetch_object_data($activities);
         // Generate action strings.
         $activities = BP_Activity_Activity::generate_action_strings($activities);
     }
     $retval['activities'] = $activities;
     // If $max is set, only return up to the max results.
     if (!empty($r['count_total'])) {
         /**
          * Filters the total activities MySQL statement.
          *
          * @since 1.5.0
          *
          * @param string $value     MySQL statement used to query for total activities.
          * @param string $where_sql MySQL WHERE statement portion.
          * @param string $sort      Sort direction for query.
          */
         $total_activities_sql = apply_filters('bp_activity_total_activities_sql', "SELECT count(DISTINCT a.id) FROM {$bp->activity->table_name} a {$join_sql} {$where_sql}", $where_sql, $sort);
         $total_activities = $wpdb->get_var($total_activities_sql);
         if (!empty($r['max'])) {
             if ((int) $total_activities > (int) $r['max']) {
                 $total_activities = $r['max'];
             }
         }
         $retval['total'] = $total_activities;
     }
     return $retval;
 }
Exemple #10
0
 /**
  * Get activity items, as specified by parameters
  *
  * @see BP_Activity_Activity::get_filter_sql() for a description of the
  *      'filter' parameter.
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @param array $args {
  *     An array of arguments. All items are optional.
  *     @type int $page Which page of results to fetch. Using page=1
  *                     without per_page will result in no pagination.
  *                     Default: 1.
  *     @type int|bool $per_page Number of results per page. Default: 25.
  *     @type int|bool $max Maximum number of results to return.
  *                         Default: false (unlimited).
  *     @type string $sort ASC or DESC. Default: 'DESC'.
  *     @type array $exclude Array of activity IDs to exclude.
  *                          Default: false.
  *     @type array $in Array of ids to limit query by (IN).
  *                     Default: false.
  *     @type array $meta_query An array of meta_query conditions.
  *                             See WP_Meta_Query::queries for description.
  *     @type array $date_query An array of date_query conditions.
  *                             See first parameter of WP_Date_Query::__construct()
  *                             for description.
  *     @type array $filter See BP_Activity_Activity::get_filter_sql().
  *     @type string $search_terms Limit results by a search term.
  *                                Default: false.
  *     @type bool $display_comments Whether to include activity comments.
  *                                  Default: false.
  *     @type bool $show_hidden Whether to show items marked hide_sitewide.
  *                             Default: false.
  *     @type string $spam Spam status. Default: 'ham_only'.
  *     @type bool $update_meta_cache Whether to pre-fetch metadata for
  *           queried activity items. Default: true.
  *     @type string|bool $count_total If true, an additional DB query
  *           is run to count the total activity items for the query.
  *           Default: false.
  * }
  * @return array The array returned has two keys:
  *     - 'total' is the count of located activities
  *     - 'activities' is an array of the located activities
  */
 public static function get($args = array())
 {
     global $wpdb, $bp;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 25, 'max' => false, 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'date_query' => false, 'filter' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only', 'update_meta_cache' => true, 'count_total' => false);
     $r = wp_parse_args($args, $defaults);
     extract($r);
     // Select conditions
     $select_sql = "SELECT DISTINCT a.id";
     $from_sql = " FROM {$bp->activity->table_name} a";
     $join_sql = '';
     // Where conditions
     $where_conditions = array();
     // Excluded types
     $excluded_types = array();
     // Spam
     if ('ham_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching
     if ($search_terms) {
         $search_terms_like = '%' . bp_esc_like($search_terms) . '%';
         $where_conditions['search_sql'] = $wpdb->prepare('a.content LIKE %s', $search_terms_like);
     }
     // Filtering
     if ($filter && ($filter_sql = BP_Activity_Activity::get_filter_sql($filter))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Sorting
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$show_hidden) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items
     if (!empty($exclude)) {
         $exclude = implode(',', wp_parse_id_list($exclude));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query
     if (!empty($in)) {
         $in = implode(',', wp_parse_id_list($in));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL
     $meta_query_sql = self::get_meta_query_sql($meta_query);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Process date_query into SQL
     $date_query_sql = self::get_date_query_sql($date_query);
     if (!empty($date_query_sql)) {
         $where_conditions['date'] = $date_query_sql;
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $display_comments || 'threaded' === $display_comments) {
         $excluded_types[] = 'activity_comment';
     }
     // Exclude 'last_activity' items unless the 'action' filter has
     // been explicitly set
     if (empty($filter['object'])) {
         $excluded_types[] = 'last_activity';
     }
     // Exclude 'new_member' items if xprofile component is not active
     if (!bp_is_active('xprofile')) {
         $excluded_types[] = 'new_member';
     }
     // Build the excluded type sql part
     if (!empty($excluded_types)) {
         $not_in = "'" . implode("', '", esc_sql($excluded_types)) . "'";
         $where_conditions['excluded_types'] = "a.type NOT IN ({$not_in})";
     }
     // Filter the where conditions
     $where_conditions = apply_filters('bp_activity_get_where_conditions', $where_conditions, $r, $select_sql, $from_sql, $join_sql);
     // Join the where conditions together
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     // Define the preferred order for indexes
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     // Sanitize page and per_page parameters
     $page = absint($page);
     $per_page = absint($per_page);
     $retval = array('activities' => null, 'total' => null, 'has_more_items' => null);
     // Filter and return true to use the legacy query structure (not recommended)
     if (apply_filters('bp_use_legacy_activity_query', false, __METHOD__, $r)) {
         // Legacy queries joined against the user table
         $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
         $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
         if (!empty($page) && !empty($per_page)) {
             $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         } else {
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort));
         }
     } else {
         // Query first for activity IDs
         $activity_ids_sql = "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}";
         if (!empty($per_page) && !empty($page)) {
             // We query for $per_page + 1 items in order to
             // populate the has_more_items flag
             $activity_ids_sql .= $wpdb->prepare(" LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page + 1);
         }
         $activity_ids_sql = apply_filters('bp_activity_paged_activities_sql', $activity_ids_sql, $r);
         $activity_ids = $wpdb->get_col($activity_ids_sql);
         $retval['has_more_items'] = !empty($per_page) && count($activity_ids) > $per_page;
         // If we've fetched more than the $per_page value, we
         // can discard the extra now
         if (!empty($per_page) && count($activity_ids) === $per_page + 1) {
             array_pop($activity_ids);
         }
         $activities = self::get_activity_data($activity_ids);
     }
     // Get the fullnames of users so we don't have to query in the loop
     $activities = self::append_user_fullnames($activities);
     // Get activity meta
     $activity_ids = array();
     foreach ((array) $activities as $activity) {
         $activity_ids[] = $activity->id;
     }
     if (!empty($activity_ids) && $update_meta_cache) {
         bp_activity_update_meta_cache($activity_ids);
     }
     if ($activities && $display_comments) {
         $activities = BP_Activity_Activity::append_comments($activities, $spam);
     }
     // Pre-fetch data associated with activity users and other objects
     BP_Activity_Activity::prefetch_object_data($activities);
     // Generate action strings
     $activities = BP_Activity_Activity::generate_action_strings($activities);
     $retval['activities'] = $activities;
     // If $max is set, only return up to the max results
     if (!empty($r['count_total'])) {
         $total_activities_sql = apply_filters('bp_activity_total_activities_sql', "SELECT count(DISTINCT a.id) FROM {$bp->activity->table_name} a {$join_sql} {$where_sql}", $where_sql, $sort);
         $total_activities = $wpdb->get_var($total_activities_sql);
         if (!empty($max)) {
             if ((int) $total_activities > (int) $max) {
                 $total_activities = $max;
             }
         }
         $retval['total'] = $total_activities;
     }
     return $retval;
 }
 /**
  * Get activity items, as specified by parameters.
  *
  * @see BP_XProfile_Group::get() for more details about parameters.
  *
  * @since 1.5.0
  * @since 2.4.0 Introduced `$member_type` argument.
  *
  * @param array|string $args {
  *     An array of arguments. All items are optional.
  *
  *     @type int          $user_id                 Fetch field data for this user ID.
  *     @type string|array $member_type             Limit results to those matching member type(s).
  *     @type int          $profile_group_id        Field group to fetch fields & data for.
  *     @type int|bool     $hide_empty_groups       Should empty field groups be skipped.
  *     @type int|bool     $fetch_fields            Fetch fields for field group.
  *     @type int|bool     $fetch_field_data        Fetch field data for fields in group.
  *     @type array        $exclude_groups          Exclude these field groups.
  *     @type array        $exclude_fields          Exclude these fields.
  *     @type int|bool     $hide_empty_fields       Should empty fields be skipped.
  *     @type int|bool     $fetch_visibility_level  Fetch visibility levels.
  *     @type int|bool     $update_meta_cache       Should metadata cache be updated.
  * }
  */
 public function __construct($args = '')
 {
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '2.3.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'profile_group_id', 2 => 'hide_empty_groups', 3 => 'fetch_fields', 4 => 'fetch_field_data', 5 => 'exclude_groups', 6 => 'exclude_fields', 7 => 'hide_empty_fields', 8 => 'fetch_visibility_level', 9 => 'update_meta_cache');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = wp_parse_args($args, array('profile_group_id' => false, 'user_id' => false, 'member_type' => 'any', 'hide_empty_groups' => false, 'hide_empty_fields' => false, 'fetch_fields' => false, 'fetch_field_data' => false, 'fetch_visibility_level' => false, 'exclude_groups' => false, 'exclude_fields' => false, 'update_meta_cache' => true));
     $this->groups = bp_xprofile_get_groups($r);
     $this->group_count = count($this->groups);
     $this->user_id = $r['user_id'];
 }
 function get($args = array())
 {
     global $wpdb, $bp;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'type', 1 => 'per_page', 2 => 'page', 3 => 'user_id', 4 => 'search_terms', 5 => 'include', 6 => 'populate_extras', 7 => 'exclude', 8 => 'show_hidden');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('type' => null, 'orderby' => 'date_created', 'order' => 'DESC', 'per_page' => null, 'page' => null, 'user_id' => 0, 'search_terms' => false, 'meta_query' => false, 'include' => false, 'populate_extras' => true, 'exclude' => false, 'show_hidden' => false);
     $r = wp_parse_args($args, $defaults);
     $sql = array();
     $total_sql = array();
     $sql['select'] = "SELECT g.*, gm1.meta_value AS total_member_count, gm2.meta_value AS last_activity";
     $sql['from'] = " FROM {$bp->groups->table_name_groupmeta} gm1, {$bp->groups->table_name_groupmeta} gm2,";
     if (!empty($r['user_id'])) {
         $sql['members_from'] = " {$bp->groups->table_name_members} m,";
     }
     $sql['group_from'] = " {$bp->groups->table_name} g WHERE";
     if (!empty($r['user_id'])) {
         $sql['user_where'] = " g.id = m.group_id AND";
     }
     $sql['where'] = " g.id = gm1.group_id AND g.id = gm2.group_id AND gm2.meta_key = 'last_activity' AND gm1.meta_key = 'total_member_count'";
     if (empty($r['show_hidden'])) {
         $sql['hidden'] = " AND g.status != 'hidden'";
     }
     if (!empty($r['search_terms'])) {
         $search_terms = esc_sql(like_escape($r['search_terms']));
         $sql['search'] = " AND ( g.name LIKE '%%{$search_terms}%%' OR g.description LIKE '%%{$search_terms}%%' )";
     }
     $meta_query_sql = self::get_meta_query_sql($r['meta_query']);
     if (!empty($meta_query_sql['join'])) {
         $sql['from'] .= $meta_query_sql['join'];
         $total_sql['select'] .= $meta_query_sql['join_total'];
     }
     if (!empty($meta_query_sql['where'])) {
         $sql['meta'] = $meta_query_sql['where'];
     }
     if (!empty($r['user_id'])) {
         $sql['user'] = $wpdb->prepare(" AND m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id']);
     }
     if (!empty($r['include'])) {
         $include = wp_parse_id_list($r['include']);
         $include = $wpdb->escape(implode(',', $include));
         $sql['include'] = " AND g.id IN ({$include})";
     }
     if (!empty($r['exclude'])) {
         $exclude = wp_parse_id_list($r['exclude']);
         $exclude = $wpdb->escape(implode(',', $exclude));
         $sql['exclude'] = " AND g.id NOT IN ({$exclude})";
     }
     /** Order/orderby ********************************************/
     $order = $r['order'];
     $orderby = $r['orderby'];
     // If a 'type' parameter was passed, parse it and overwrite
     // 'order' and 'orderby' params passed to the function
     if (!empty($r['type'])) {
         $order_orderby = self::convert_type_to_order_orderby($r['type']);
         // If an invalid type is passed, $order_orderby will be
         // an array with empty values. In this case, we stick
         // with the default values of $order and $orderby
         if (!empty($order_orderby['order'])) {
             $order = $order_orderby['order'];
         }
         if (!empty($order_orderby['orderby'])) {
             $orderby = $order_orderby['orderby'];
         }
     }
     // Sanitize 'order'
     $order = bp_esc_sql_order($order);
     // Convert 'orderby' into the proper ORDER BY term
     $orderby = self::convert_orderby_to_order_by_term($orderby);
     // Random order is a special case
     if ('rand()' === $orderby) {
         $sql[] = "ORDER BY rand()";
     } else {
         $sql[] = "ORDER BY {$orderby} {$order}";
     }
     if (!empty($r['per_page']) && !empty($r['page'])) {
         $sql['pagination'] = $wpdb->prepare("LIMIT %d, %d", intval(($r['page'] - 1) * $r['per_page']), intval($r['per_page']));
     }
     // Get paginated results
     $paged_groups_sql = apply_filters('bp_groups_get_paged_groups_sql', join(' ', (array) $sql), $sql);
     $paged_groups = $wpdb->get_results($paged_groups_sql);
     $total_sql['select'] = "SELECT COUNT(DISTINCT g.id) FROM {$bp->groups->table_name} g, {$bp->groups->table_name_members} gm1, {$bp->groups->table_name_groupmeta} gm2";
     if (!empty($r['user_id'])) {
         $total_sql['select'] .= ", {$bp->groups->table_name_members} m";
     }
     if (!empty($sql['hidden'])) {
         $total_sql['where'][] = "g.status != 'hidden'";
     }
     if (!empty($sql['search'])) {
         $total_sql['where'][] = "( g.name LIKE '%%{$search_terms}%%' OR g.description LIKE '%%{$search_terms}%%' )";
     }
     if (!empty($r['user_id'])) {
         $total_sql['where'][] = $wpdb->prepare("m.group_id = g.id AND m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id']);
     }
     // Temporary implementation of meta_query for total count
     // See #5099
     if (!empty($meta_query_sql['where'])) {
         // Join the groupmeta table
         $total_sql['select'] .= ", {$bp->groups->table_name_groupmeta} gmmq";
         // Modify the meta_query clause from paged_sql for our syntax
         $meta_query_clause = preg_replace('/^\\s*AND/', '', $meta_query_sql['where']);
         $meta_query_clause = str_replace($bp->groups->table_name_groupmeta, 'gmmq', $meta_query_clause);
         $total_sql['where'][] = $meta_query_clause;
     }
     // Already escaped in the paginated results block
     if (!empty($include)) {
         $total_sql['where'][] = "g.id IN ({$include})";
     }
     // Already escaped in the paginated results block
     if (!empty($exclude)) {
         $total_sql['where'][] = "g.id NOT IN ({$exclude})";
     }
     $total_sql['where'][] = "g.id = gm1.group_id";
     $total_sql['where'][] = "g.id = gm2.group_id";
     $total_sql['where'][] = "gm2.meta_key = 'last_activity'";
     $t_sql = $total_sql['select'];
     if (!empty($total_sql['where'])) {
         $t_sql .= " WHERE " . join(' AND ', (array) $total_sql['where']);
     }
     // Get total group results
     $total_groups_sql = apply_filters('bp_groups_get_total_groups_sql', $t_sql, $total_sql);
     $total_groups = $wpdb->get_var($total_groups_sql);
     $group_ids = array();
     foreach ((array) $paged_groups as $group) {
         $group_ids[] = $group->id;
     }
     // Populate some extra information instead of querying each time in the loop
     if (!empty($r['populate_extras'])) {
         $group_ids = $wpdb->escape(join(',', (array) $group_ids));
         $paged_groups = BP_Groups_Group::get_group_extras($paged_groups, $group_ids, $r['type']);
     }
     // Grab all groupmeta
     bp_groups_update_meta_cache($group_ids);
     unset($sql, $total_sql);
     return array('groups' => $paged_groups, 'total' => $total_groups);
 }
 /**
  * Constructor.
  *
  * @since 1.5.0
  *
  * @param array $args {
  *     An array of optional arguments.
  *     @type int      $group_id           ID of the group whose members are being
  *                                        queried. Default: current group ID.
  *     @type int      $page               Page of results to be queried. Default: 1.
  *     @type int      $per_page           Number of items to return per page of
  *                                        results. Default: 20.
  *     @type int      $max                Optional. Max number of items to return.
  *     @type array    $exclude            Optional. Array of user IDs to exclude.
  *     @type bool|int $exclude_admin_mods True (or 1) to exclude admins and mods from
  *                                        results. Default: 1.
  *     @type bool|int $exclude_banned     True (or 1) to exclude banned users from results.
  *                                        Default: 1.
  *     @type array    $group_role         Optional. Array of group roles to include.
  *     @type string   $search_terms       Optional. Search terms to match.
  * }
  */
 public function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '2.0.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'group_id', 1 => 'per_page', 2 => 'max', 3 => 'exclude_admins_mods', 4 => 'exclude_banned', 5 => 'exclude', 6 => 'group_role');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $r = wp_parse_args($args, array('group_id' => bp_get_current_group_id(), 'page' => 1, 'per_page' => 20, 'page_arg' => 'mlpage', 'max' => false, 'exclude' => false, 'exclude_admins_mods' => 1, 'exclude_banned' => 1, 'group_role' => false, 'search_terms' => false, 'type' => 'last_joined'));
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     /**
      * Check the current group is the same as the supplied group ID.
      * It can differ when using {@link bp_group_has_members()} outside the Groups screens.
      */
     $current_group = groups_get_current_group();
     if (empty($current_group) || $current_group && $current_group->id !== bp_get_current_group_id()) {
         $current_group = groups_get_group(array('group_id' => $r['group_id']));
     }
     // Assemble the base URL for pagination.
     $base_url = trailingslashit(bp_get_group_permalink($current_group) . bp_current_action());
     if (bp_action_variable()) {
         $base_url = trailingslashit($base_url . bp_action_variable());
     }
     $members_args = $r;
     $members_args['page'] = $this->pag_page;
     $members_args['per_page'] = $this->pag_num;
     // Get group members for this loop.
     $this->members = groups_get_group_members($members_args);
     if (empty($r['max']) || $r['max'] >= (int) $this->members['count']) {
         $this->total_member_count = (int) $this->members['count'];
     } else {
         $this->total_member_count = (int) $r['max'];
     }
     // Reset members array for subsequent looping.
     $this->members = $this->members['members'];
     if (empty($r['max']) || $r['max'] >= count($this->members)) {
         $this->member_count = (int) count($this->members);
     } else {
         $this->member_count = (int) $r['max'];
     }
     $this->pag_links = paginate_links(array('base' => add_query_arg(array($this->pag_arg => '%#%'), $base_url), 'format' => '', 'total' => !empty($this->pag_num) ? ceil($this->total_member_count / $this->pag_num) : $this->total_member_count, 'current' => $this->pag_page, 'prev_text' => '←', 'next_text' => '→', 'mid_size' => 1, 'add_args' => array()));
 }
 /**
  * Constructor method.
  *
  * @see BP_Groups_Group::get() for an in-depth description of arguments.
  *
  * @param array $args {
  *     Array of arguments. Accepts all arguments accepted by
  *     {@link BP_Groups_Group::get()}. In cases where the default
  *     values of the params differ, they have been discussed below.
  *     @type int $per_page Default: 20.
  *     @type int $page Default: 1.
  * }
  */
 function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'type', 2 => 'page', 3 => 'per_page', 4 => 'max', 5 => 'slug', 6 => 'search_terms', 7 => 'populate_extras', 8 => 'include', 9 => 'exclude', 10 => 'show_hidden', 11 => 'page_arg');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 20, 'page_arg' => 'grpage', 'max' => false, 'type' => 'active', 'order' => 'DESC', 'orderby' => 'date_created', 'show_hidden' => false, 'user_id' => 0, 'slug' => false, 'include' => false, 'exclude' => false, 'parent_id' => null, 'search_terms' => '', 'group_type' => '', 'group_type__in' => '', 'group_type__not_in' => '', 'meta_query' => false, 'update_meta_cache' => true, 'update_admin_cache' => false);
     $r = wp_parse_args($args, $defaults);
     extract($r);
     $this->pag_arg = sanitize_key($r['page_arg']);
     $this->pag_page = bp_sanitize_pagination_arg($this->pag_arg, $r['page']);
     $this->pag_num = bp_sanitize_pagination_arg('num', $r['per_page']);
     if (bp_current_user_can('bp_moderate') || is_user_logged_in() && $user_id == bp_loggedin_user_id()) {
         $show_hidden = true;
     }
     if ('invites' == $type) {
         $this->groups = groups_get_invites_for_user($user_id, $this->pag_num, $this->pag_page, $exclude);
     } elseif ('single-group' == $type) {
         $this->single_group = true;
         if (groups_get_current_group()) {
             $group = groups_get_current_group();
         } else {
             $group = groups_get_group(BP_Groups_Group::get_id_from_slug($r['slug']));
         }
         // Backwards compatibility - the 'group_id' variable is not part of the
         // BP_Groups_Group object, but we add it here for devs doing checks against it
         //
         // @see https://buddypress.trac.wordpress.org/changeset/3540
         //
         // this is subject to removal in a future release; devs should check against
         // $group->id instead.
         $group->group_id = $group->id;
         $this->groups = array($group);
     } else {
         $this->groups = groups_get_groups(array('type' => $type, 'order' => $order, 'orderby' => $orderby, 'per_page' => $this->pag_num, 'page' => $this->pag_page, 'user_id' => $user_id, 'search_terms' => $search_terms, 'meta_query' => $meta_query, 'group_type' => $group_type, 'group_type__in' => $group_type__in, 'group_type__not_in' => $group_type__not_in, 'include' => $include, 'exclude' => $exclude, 'parent_id' => $parent_id, 'update_meta_cache' => $update_meta_cache, 'update_admin_cache' => $update_admin_cache, 'show_hidden' => $show_hidden));
     }
     if ('invites' == $type) {
         $this->total_group_count = (int) $this->groups['total'];
         $this->group_count = (int) $this->groups['total'];
         $this->groups = $this->groups['groups'];
     } elseif ('single-group' == $type) {
         if (empty($group->id)) {
             $this->total_group_count = 0;
             $this->group_count = 0;
         } else {
             $this->total_group_count = 1;
             $this->group_count = 1;
         }
     } else {
         if (empty($max) || $max >= (int) $this->groups['total']) {
             $this->total_group_count = (int) $this->groups['total'];
         } else {
             $this->total_group_count = (int) $max;
         }
         $this->groups = $this->groups['groups'];
         if (!empty($max)) {
             if ($max >= count($this->groups)) {
                 $this->group_count = count($this->groups);
             } else {
                 $this->group_count = (int) $max;
             }
         } else {
             $this->group_count = count($this->groups);
         }
     }
     // Build pagination links.
     if ((int) $this->total_group_count && (int) $this->pag_num) {
         $pag_args = array($this->pag_arg => '%#%');
         if (defined('DOING_AJAX') && true === (bool) DOING_AJAX) {
             $base = remove_query_arg('s', wp_get_referer());
         } else {
             $base = '';
         }
         $add_args = array('num' => $this->pag_num, 'sortby' => $this->sort_by, 'order' => $this->order);
         if (!empty($search_terms)) {
             $query_arg = bp_core_get_component_search_query_arg('groups');
             $add_args[$query_arg] = urlencode($search_terms);
         }
         $this->pag_links = paginate_links(array('base' => add_query_arg($pag_args, $base), 'format' => '', 'total' => ceil((int) $this->total_group_count / (int) $this->pag_num), 'current' => $this->pag_page, 'prev_text' => _x('←', 'Group pagination previous text', 'buddypress'), 'next_text' => _x('→', 'Group pagination next text', 'buddypress'), 'mid_size' => 1, 'add_args' => $add_args));
     }
 }
 function __construct($args = array())
 {
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'user_id', 1 => 'type', 2 => 'page', 3 => 'per_page', 4 => 'max', 5 => 'slug', 6 => 'search_terms', 7 => 'populate_extras', 8 => 'include', 9 => 'exclude', 10 => 'show_hidden', 11 => 'page_arg');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('type' => 'active', 'page' => 1, 'per_page' => 20, 'max' => false, 'show_hidden' => false, 'page_arg' => 'grpage', 'user_id' => 0, 'slug' => false, 'include' => false, 'exclude' => false, 'search_terms' => '', 'meta_query' => false, 'populate_extras' => true);
     $r = wp_parse_args($args, $defaults);
     extract($r);
     $this->pag_page = isset($_REQUEST[$page_arg]) ? intval($_REQUEST[$page_arg]) : $page;
     $this->pag_num = isset($_REQUEST['num']) ? intval($_REQUEST['num']) : $per_page;
     if (bp_current_user_can('bp_moderate') || is_user_logged_in() && $user_id == bp_loggedin_user_id()) {
         $show_hidden = true;
     }
     if ('invites' == $type) {
         $this->groups = groups_get_invites_for_user($user_id, $this->pag_num, $this->pag_page, $exclude);
     } else {
         if ('single-group' == $type) {
             $group = new stdClass();
             $group->group_id = BP_Groups_Group::get_id_from_slug($slug);
             $this->groups = array($group);
         } else {
             $this->groups = groups_get_groups(array('type' => $type, 'order' => $order, 'orderby' => $orderby, 'per_page' => $this->pag_num, 'page' => $this->pag_page, 'user_id' => $user_id, 'search_terms' => $search_terms, 'meta_query' => $meta_query, 'include' => $include, 'exclude' => $exclude, 'populate_extras' => $populate_extras, 'show_hidden' => $show_hidden));
         }
     }
     if ('invites' == $type) {
         $this->total_group_count = (int) $this->groups['total'];
         $this->group_count = (int) $this->groups['total'];
         $this->groups = $this->groups['groups'];
     } else {
         if ('single-group' == $type) {
             $this->single_group = true;
             $this->total_group_count = 1;
             $this->group_count = 1;
         } else {
             if (empty($max) || $max >= (int) $this->groups['total']) {
                 $this->total_group_count = (int) $this->groups['total'];
             } else {
                 $this->total_group_count = (int) $max;
             }
             $this->groups = $this->groups['groups'];
             if (!empty($max)) {
                 if ($max >= count($this->groups)) {
                     $this->group_count = count($this->groups);
                 } else {
                     $this->group_count = (int) $max;
                 }
             } else {
                 $this->group_count = count($this->groups);
             }
         }
     }
     // Build pagination links
     if ((int) $this->total_group_count && (int) $this->pag_num) {
         $this->pag_links = paginate_links(array('base' => add_query_arg(array($page_arg => '%#%', 'num' => $this->pag_num, 's' => $search_terms, 'sortby' => $this->sort_by, 'order' => $this->order)), 'format' => '', 'total' => ceil((int) $this->total_group_count / (int) $this->pag_num), 'current' => $this->pag_page, 'prev_text' => _x('←', 'Group pagination previous text', 'buddypress'), 'next_text' => _x('→', 'Group pagination next text', 'buddypress'), 'mid_size' => 1));
     }
 }
 /**
  * Query for groups.
  *
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @since 1.6.0
  * @since 2.6.0 Added `$group_type`, `$group_type__in`, and `$group_type__not_in` parameters.
  * @since 2.7.0 Added `$update_admin_cache` and `$parent_id` parameters.
  *
  * @param array $args {
  *     Array of parameters. All items are optional.
  *     @type string       $type               Optional. Shorthand for certain orderby/order combinations.
  *                                            'newest', 'active', 'popular', 'alphabetical', 'random'.
  *                                            When present, will override orderby and order params.
  *                                            Default: null.
  *     @type string       $orderby            Optional. Property to sort by. 'date_created', 'last_activity',
  *                                            'total_member_count', 'name', 'random'. Default: 'date_created'.
  *     @type string       $order              Optional. Sort order. 'ASC' or 'DESC'. Default: 'DESC'.
  *     @type int          $per_page           Optional. Number of items to return per page of results.
  *                                            Default: null (no limit).
  *     @type int          $page               Optional. Page offset of results to return.
  *                                            Default: null (no limit).
  *     @type int          $user_id            Optional. If provided, results will be limited to groups
  *                                            of which the specified user is a member. Default: null.
  *     @type string       $search_terms       Optional. If provided, only groups whose names or descriptions
  *                                            match the search terms will be returned. Default: false.
  *     @type array|string $group_type         Array or comma-separated list of group types to limit results to.
  *     @type array|string $group_type__in     Array or comma-separated list of group types to limit results to.
  *     @type array|string $group_type__not_in Array or comma-separated list of group types that will be
  *                                            excluded from results.
  *     @type array        $meta_query         Optional. An array of meta_query conditions.
  *                                            See {@link WP_Meta_Query::queries} for description.
  *     @type array|string $value              Optional. Array or comma-separated list of group IDs. Results
  *                                            will be limited to groups within the list. Default: false.
  *     @type array|string $parent_id          Optional. Array or comma-separated list of group IDs. Results
  *                                            will be limited to children of the specified groups. Default: null.
  *     @type array|string $exclude            Optional. Array or comma-separated list of group IDs.
  *                                            Results will exclude the listed groups. Default: false.
  *     @type bool         $update_meta_cache  Whether to pre-fetch groupmeta for the returned groups.
  *                                            Default: true.
  *     @type bool         $update_admin_cache Whether to pre-fetch administrator IDs for the returned
  *                                            groups. Default: false.
  *     @type bool         $show_hidden        Whether to include hidden groups in results. Default: false.
  * }
  * @return array {
  *     @type array $groups Array of group objects returned by the
  *                         paginated query.
  *     @type int   $total  Total count of all groups matching non-
  *                         paginated query params.
  * }
  */
 public static function get($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'type', 1 => 'per_page', 2 => 'page', 3 => 'user_id', 4 => 'search_terms', 5 => 'include', 6 => 'populate_extras', 7 => 'exclude', 8 => 'show_hidden');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('type' => null, 'orderby' => 'date_created', 'order' => 'DESC', 'per_page' => null, 'page' => null, 'user_id' => 0, 'search_terms' => false, 'group_type' => '', 'group_type__in' => '', 'group_type__not_in' => '', 'meta_query' => false, 'include' => false, 'parent_id' => null, 'update_meta_cache' => true, 'update_admin_cache' => false, 'exclude' => false, 'show_hidden' => false);
     $r = wp_parse_args($args, $defaults);
     $bp = buddypress();
     $sql = array('select' => "SELECT DISTINCT g.id", 'from' => "{$bp->groups->table_name} g", 'where' => '', 'orderby' => '', 'pagination' => '');
     if (!empty($r['user_id'])) {
         $sql['from'] .= " JOIN {$bp->groups->table_name_members} m ON ( g.id = m.group_id )";
     }
     $where_conditions = array();
     if (empty($r['show_hidden'])) {
         $where_conditions['hidden'] = "g.status != 'hidden'";
     }
     if (!empty($r['search_terms'])) {
         $search_terms_like = '%' . bp_esc_like($r['search_terms']) . '%';
         $where_conditions['search'] = $wpdb->prepare("( g.name LIKE %s OR g.description LIKE %s )", $search_terms_like, $search_terms_like);
     }
     $meta_query_sql = self::get_meta_query_sql($r['meta_query']);
     if (!empty($meta_query_sql['join'])) {
         $sql['from'] .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions['meta'] = $meta_query_sql['where'];
     }
     // Only use 'group_type__in', if 'group_type' is not set.
     if (empty($r['group_type']) && !empty($r['group_type__in'])) {
         $r['group_type'] = $r['group_type__in'];
     }
     // Group types to exclude. This has priority over inclusions.
     if (!empty($r['group_type__not_in'])) {
         $group_type_clause = self::get_sql_clause_for_group_types($r['group_type__not_in'], 'NOT IN');
         // Group types to include.
     } elseif (!empty($r['group_type'])) {
         $group_type_clause = self::get_sql_clause_for_group_types($r['group_type'], 'IN');
     }
     if (!empty($group_type_clause)) {
         $where_conditions['group_type'] = $group_type_clause;
     }
     if (!empty($r['user_id'])) {
         $where_conditions['user'] = $wpdb->prepare("m.user_id = %d AND m.is_confirmed = 1 AND m.is_banned = 0", $r['user_id']);
     }
     if (!empty($r['include'])) {
         $include = implode(',', wp_parse_id_list($r['include']));
         $where_conditions['include'] = "g.id IN ({$include})";
     }
     if (!is_null($r['parent_id'])) {
         // Note that `wp_parse_id_list()` converts `false` to 0.
         $parent_id = implode(',', wp_parse_id_list($r['parent_id']));
         $where_conditions['parent_id'] = "g.parent_id IN ({$parent_id})";
     }
     if (!empty($r['exclude'])) {
         $exclude = implode(',', wp_parse_id_list($r['exclude']));
         $where_conditions['exclude'] = "g.id NOT IN ({$exclude})";
     }
     /* Order/orderby ********************************************/
     $order = $r['order'];
     $orderby = $r['orderby'];
     // If a 'type' parameter was passed, parse it and overwrite
     // 'order' and 'orderby' params passed to the function.
     if (!empty($r['type'])) {
         /**
          * Filters the 'type' parameter used to overwrite 'order' and 'orderby' values.
          *
          * @since 2.1.0
          *
          * @param array  $value Converted 'type' value for order and orderby.
          * @param string $value Parsed 'type' value for the get method.
          */
         $order_orderby = apply_filters('bp_groups_get_orderby', self::convert_type_to_order_orderby($r['type']), $r['type']);
         // If an invalid type is passed, $order_orderby will be
         // an array with empty values. In this case, we stick
         // with the default values of $order and $orderby.
         if (!empty($order_orderby['order'])) {
             $order = $order_orderby['order'];
         }
         if (!empty($order_orderby['orderby'])) {
             $orderby = $order_orderby['orderby'];
         }
     }
     // 'total_member_count' and 'last_activity' sorts require additional table joins.
     if ('total_member_count' === $orderby) {
         $sql['from'] .= " JOIN {$bp->groups->table_name_groupmeta} gm_total_member_count ON ( g.id = gm_total_member_count.group_id )";
         $where_conditions['total_member_count'] = "gm_total_member_count.meta_key = 'total_member_count'";
     } elseif ('last_activity' === $orderby) {
         $sql['from'] .= " JOIN {$bp->groups->table_name_groupmeta} gm_last_activity on ( g.id = gm_last_activity.group_id )";
         $where_conditions['last_activity'] = "gm_last_activity.meta_key = 'last_activity'";
     }
     // Sanitize 'order'.
     $order = bp_esc_sql_order($order);
     /**
      * Filters the converted 'orderby' term.
      *
      * @since 2.1.0
      *
      * @param string $value   Converted 'orderby' term.
      * @param string $orderby Original orderby value.
      * @param string $value   Parsed 'type' value for the get method.
      */
     $orderby = apply_filters('bp_groups_get_orderby_converted_by_term', self::convert_orderby_to_order_by_term($orderby), $orderby, $r['type']);
     // Random order is a special case.
     if ('rand()' === $orderby) {
         $sql['orderby'] = "ORDER BY rand()";
     } else {
         $sql['orderby'] = "ORDER BY {$orderby} {$order}";
     }
     if (!empty($r['per_page']) && !empty($r['page']) && $r['per_page'] != -1) {
         $sql['pagination'] = $wpdb->prepare("LIMIT %d, %d", intval(($r['page'] - 1) * $r['per_page']), intval($r['per_page']));
     }
     $where = '';
     if (!empty($where_conditions)) {
         $sql['where'] = implode(' AND ', $where_conditions);
         $where = "WHERE {$sql['where']}";
     }
     $paged_groups_sql = "{$sql['select']} FROM {$sql['from']} {$where} {$sql['orderby']} {$sql['pagination']}";
     /**
      * Filters the pagination SQL statement.
      *
      * @since 1.5.0
      *
      * @param string $value Concatenated SQL statement.
      * @param array  $sql   Array of SQL parts before concatenation.
      * @param array  $r     Array of parsed arguments for the get method.
      */
     $paged_groups_sql = apply_filters('bp_groups_get_paged_groups_sql', $paged_groups_sql, $sql, $r);
     $cached = bp_core_get_incremented_cache($paged_groups_sql, 'bp_groups');
     if (false === $cached) {
         $paged_group_ids = $wpdb->get_col($paged_groups_sql);
         bp_core_set_incremented_cache($paged_groups_sql, 'bp_groups', $paged_group_ids);
     } else {
         $paged_group_ids = $cached;
     }
     $uncached_group_ids = bp_get_non_cached_ids($paged_group_ids, 'bp_groups');
     if ($uncached_group_ids) {
         $group_ids_sql = implode(',', array_map('intval', $uncached_group_ids));
         $group_data_objects = $wpdb->get_results("SELECT g.* FROM {$bp->groups->table_name} g WHERE g.id IN ({$group_ids_sql})");
         foreach ($group_data_objects as $group_data_object) {
             wp_cache_set($group_data_object->id, $group_data_object, 'bp_groups');
         }
     }
     $paged_groups = array();
     foreach ($paged_group_ids as $paged_group_id) {
         $paged_groups[] = new BP_Groups_Group($paged_group_id);
     }
     $total_groups_sql = "SELECT COUNT(DISTINCT g.id) FROM {$sql['from']} {$where}";
     /**
      * Filters the SQL used to retrieve total group results.
      *
      * @since 1.5.0
      *
      * @param string $t_sql     Concatenated SQL statement used for retrieving total group results.
      * @param array  $total_sql Array of SQL parts for the query.
      * @param array  $r         Array of parsed arguments for the get method.
      */
     $total_groups_sql = apply_filters('bp_groups_get_total_groups_sql', $total_groups_sql, $sql, $r);
     $cached = bp_core_get_incremented_cache($total_groups_sql, 'bp_groups');
     if (false === $cached) {
         $total_groups = (int) $wpdb->get_var($total_groups_sql);
         bp_core_set_incremented_cache($total_groups_sql, 'bp_groups', $total_groups);
     } else {
         $total_groups = (int) $cached;
     }
     $group_ids = array();
     foreach ((array) $paged_groups as $group) {
         $group_ids[] = $group->id;
     }
     // Grab all groupmeta.
     if (!empty($r['update_meta_cache'])) {
         bp_groups_update_meta_cache($group_ids);
     }
     // Prefetch all administrator IDs, if requested.
     if ($r['update_admin_cache']) {
         BP_Groups_Member::prime_group_admins_mods_cache($group_ids);
     }
     // Set up integer properties needing casting.
     $int_props = array('id', 'creator_id', 'enable_forum');
     // Integer casting.
     foreach ($paged_groups as $key => $g) {
         foreach ($int_props as $int_prop) {
             $paged_groups[$key]->{$int_prop} = (int) $paged_groups[$key]->{$int_prop};
         }
     }
     unset($sql, $total_sql);
     return array('groups' => $paged_groups, 'total' => $total_groups);
 }