/**
 * Get the mutual friend count of a current user.
 *
 * @params $friend_user_id int
 *
 * @return mixed|void
 */
function bp_mutual_friend_total_count($friend_user_id = 0)
{
    $current_user_friends = friends_get_friend_user_ids(get_current_user_id());
    if (empty($friend_user_id)) {
        $friend_user_id = bp_displayed_user_id();
    }
    $displayed_user_friends = friends_get_friend_user_ids($friend_user_id);
    $result = count(array_intersect($current_user_friends, $displayed_user_friends));
    return apply_filters('bp_mutual_friend_total_count', $result);
}
 static function refresh_friends_cache($user)
 {
     if (!class_exists('BuddyPress')) {
         return;
     }
     if (!bp_is_active('friends')) {
         return;
     }
     $friends = friends_get_friend_user_ids($user);
     wp_cache_set('rtmedia-user-friends-' . $user, $friends);
     return $friends;
 }
function social_articles_send_notification($id)
{
    global $bp, $socialArticles;
    $savedPost = get_post($id);
    $notification_already_sent = get_post_meta($id, 'notification_already_sent', true);
    if (empty($notification_already_sent) && function_exists("friends_get_friend_user_ids") && $savedPost->post_status == "publish" && $savedPost->post_type == "post" && !wp_is_post_revision($id) && $socialArticles->options['bp_notifications'] == "true") {
        $friends = friends_get_friend_user_ids($savedPost->post_author);
        foreach ($friends as $friend) {
            bp_core_add_notification($savedPost->ID, $friend, $bp->social_articles->id, 'new_article' . $savedPost->ID, $savedPost->post_author);
        }
        bp_core_add_notification($savedPost->ID, $savedPost->post_author, $bp->social_articles->id, 'new_article' . $savedPost->ID, -1);
        update_post_meta($id, 'notification_already_sent', true);
    }
}
Example #4
0
/**
 * Generate the reader selector interface.
 */
function cacsp_paper_reader_selector($paper_id)
{
    global $wpdb;
    // Get a list of readers, friends, and co-group-members to prime selectbox.
    // @todo Add AJAX support.
    $paper = new CACSP_Paper($paper_id);
    $paper_reader_ids = $paper->get_reader_ids();
    $groups_of_user = cacsp_get_groups_of_user(bp_loggedin_user_id());
    if (empty($groups_of_user)) {
        $groups_of_user = array(0);
    }
    // So dirty.
    $bp = buddypress();
    $group_member_ids = $wpdb->get_col($wpdb->prepare("SELECT user_id FROM {$bp->groups->table_name_members} WHERE group_id IN (" . implode(',', $groups_of_user) . ") AND user_id != %d AND is_banned = 0 AND is_confirmed = 1", bp_loggedin_user_id()));
    $group_member_ids = array_map('intval', $group_member_ids);
    $friend_member_ids = array();
    if (bp_is_active('friends')) {
        $friend_member_ids = friends_get_friend_user_ids(bp_loggedin_user_id());
    }
    $users = bp_core_get_users(array('include' => array_merge($paper_reader_ids, $group_member_ids, $friend_member_ids), 'type' => 'alphabetical'));
    $user_data = array();
    $selected = array();
    if (!empty($users['users'])) {
        foreach ($users['users'] as $user) {
            $user_id = (int) $user->ID;
            $user_data[] = array('id' => $user_id, 'text' => html_entity_decode($user->display_name, ENT_QUOTES, 'UTF-8'));
            // Collect data about the existing readers.
            if (in_array($user_id, $paper_reader_ids, true)) {
                $selected[] = array('id' => $user_id, 'text' => stripslashes($user->display_name));
            }
        }
    }
    $script = 'var CACSP_Potential_Readers = ' . wp_json_encode($user_data) . ';';
    echo "\n" . '<script type="text/javascript">' . $script . '</script>' . "\n";
    // Select2 only needs an <option> printed for the selected options.
    ?>
	<select name="cacsp-readers[]" multiple="multiple" style="width:100%;" id="cacsp-reader-selector">
		<?php 
    foreach ($selected as $_selected) {
        echo '<option value="' . esc_attr($_selected['id']) . '" selected="selected">' . esc_html($_selected['text']) . '</option>';
    }
    ?>
	</select>
	<?php 
    wp_nonce_field('cacsp-reader-selector', 'cacsp-reader-selector-nonce');
}
Example #5
0
    /** @see WP_Widget::widget -- do not rename this */
    function widget($args, $instance)
    {
        extract($args);
        //Our variables from the widget settings.
        $title = apply_filters('widget_title', $instance['title']);
        $num = $instance['number'];
        $friends = $instance['friends'];
        $width = $instance['width'];
        echo '<div class="' . $width . '"><div class="dash-widget activity">' . $before_widget;
        // Display the widget title
        if ($title) {
            echo $before_title . $title . $after_title;
        }
        if (isset($friends) && $friends) {
            $friends = friends_get_friend_user_ids(bp_loggedin_user_id());
            $friends[] = bp_loggedin_user_id();
            $friends_and_me = implode(',', (array) $friends);
        } else {
            $friends_and_me = bp_loggedin_user_id();
        }
        global $wpdb, $bp;
        $activities = apply_filters('wplms_dashboard_activity', $wpdb->get_results("\n\t\t\tSELECT *\n\t\t    FROM {$bp->activity->table_name} AS activity\n\t\t    WHERE \tactivity.user_id IN ({$friends_and_me})\n\t\t    AND     (activity.action != '' OR activity.action IS NOT NULL)\n\t\t    ORDER BY activity.date_recorded DESC\n\t\t    LIMIT 0,{$num}\n\t\t"));
        if (isset($activities) && is_array($activities)) {
            echo '<div class="student_activity"><a class="small button ' . ($title ? 'withtitle' : '') . '">' . __('VIEW ALL', 'wplms-dashboard') . '</a>
					<ul class="dash-activities">';
            foreach ($activities as $activity) {
                if (isset($activity->action) && $activity->action != '') {
                    $time = tofriendlytime(time() - strtotime($activity->date_recorded));
                    echo '<li class="' . $activity->component . ' ' . $activity->type . '">
						<div class="dash-activity">
							<span class="dash-activity-time">' . $time . ' ' . __('AGO', 'wplms-dashboard') . '</span>
								<strong>' . $activity->action . '</strong>
								<p>' . $activity->content . '</p>
						</div>
					  </li>';
                }
            }
            echo '</ul>
			</div></div>';
        }
        echo $after_widget . '</div>';
    }
Example #6
0
/**
 * Initialize the activity loop.
 *
 * Based on the $args passed, bp_has_activities() populates the
 * $activities_template global, enabling the use of BuddyPress templates and
 * template functions to display a list of activity items.
 *
 * @since BuddyPress (1.0)
 *
 * @global object $activities_template {@link BP_Activity_Template}
 * @global object $bp BuddyPress global settings.
 * @uses groups_is_user_member()
 * @uses bp_current_action()
 * @uses bp_is_current_action()
 * @uses bp_get_activity_slug()
 * @uses bp_action_variable()
 * @uses wp_parse_args()
 * @uses bp_is_active()
 * @uses friends_get_friend_user_ids()
 * @uses groups_get_user_groups()
 * @uses bp_activity_get_user_favorites()
 * @uses apply_filters() To call the 'bp_has_activities' hook.
 *
 * @param array $args {
 *     Arguments for limiting the contents of the activity loop. Most
 *     arguments are in the same format as {@link BP_Activity_Activity::get()}.
 *     However, because the format of the arguments accepted here differs in
 *     a number of ways, and because bp_has_activities() determines some
 *     default arguments in a dynamic fashion, we list all accepted arguments
 *     here as well.
 *
 *     Arguments can be passed as an associative array, or as a URL query
 *     string (eg, 'user_id=4&display_comments=threaded').
 *
 *     @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: 20.
 *     @type string $page_arg The string used as a query parameter in
 *           pagination links. Default: 'acpage'.
 *     @type int|bool $max Maximum number of results to return.
 *           Default: false (unlimited).
 *     @type string $sort 'ASC' or 'DESC'. Default: 'DESC'.
 *     @type array|bool $exclude Array of activity IDs to exclude. Default: false.
 *     @type array|bool $in Array of IDs to limit query by (IN). 'in' is
 *           intended to be used in conjunction with other filter parameters.
 *           Default: false.
 *     @type array|bool $include Array of exact activity IDs to query.
 *           Providing an 'include' array will override all other filters
 *           passed in the argument array. When viewing a the permalink page
 *           for a single activity item, this value defaults to the ID of that
 *           item. Otherwise the default is false.
 *     @type array $meta_query Limit by activitymeta by passing an array of
 *           meta_query conditions. See {@link WP_Meta_Query::queries} for a
 *           description of the syntax.
 *     @type string $search_terms Limit results by a search term. Default: false.
 *     @type string|bool $scope Use one of BuddyPress's pre-built filters. In
 *           each case, the term 'current user' refers to the displayed user
 *           when looking at a user profile, and otherwise to the logged-in user.
 *             - 'just-me' retrieves items belonging only to the logged-in user;
 *               this is equivalent to passing a 'user_id' argument
 *             - 'friends' retrieves items belonging to the friends of the
 *               current user
 *             - 'groups' retrieves items associated with the groups to which
 *               the current user belongs
 *             - 'favorites' retrieves the current user's favorited activity
 *               items
 *             - 'mentions' retrieves activity items where the current user has
 *               received an @-mention
 *           The default value of 'scope' is set to one of the above if that
 *           value appears in the appropriate place in the URL; eg, 'scope' will
 *           be 'groups' when visiting http://example.com/members/joe/activity/groups/.
 *           Otherwise defaults to false.
 *     @type int|array|bool $user_id The ID(s) of user(s) whose activity should
 *           be fetched. Pass a single ID or an array of IDs. When viewing a
 *           user profile page (but not that user's activity subpages, ie My
 *           Friends, My Groups, etc), 'user_id' defaults to the ID of the
 *           displayed user. Otherwise the default is false.
 *     @type string|array|bool $object Filters by the `component` column in the
 *           database, which is generally the component ID in the case of
 *           BuddyPress components, or the plugin slug in the case of plugins.
 *           For example, 'groups' will limit results to those that are
 *           associated with the BP Groups component. Accepts a single
 *           component string, or an array of multiple components. Defaults to
 *           'groups' when viewing the page of a single group, the My Groups
 *           activity filter, or the Activity > Groups filter of a user profile.
 *           Otherwise defaults to false.
 *     @type string|array|bool $action Filters by the `type` column in the
 *           database, which is a string categorizing the activity item (eg,
 *           'new_blog_post', 'created_group'). Accepts a single type string,
 *           or an array of multiple types. Defaults to false.
 *     @type int|array|bool $primary_id Filters by the `item_id` column in the
 *           database. The meaning of 'primary_id' differs between components/
 *           types; for example, in the case of 'created_group', 'primary_id'
 *           is the ID of the group. Accepts a single ID, or an array of
 *           multiple IDs. When viewing a single group, defaults to the current
 *           group ID. When viewing a user's Groups stream page, defaults to
 *           the IDs of the user's groups. Otherwise defaults to false.
 *     @type int|array|bool $secondary_id Filters by the `secondary_item_id`
 *           column in the database. The meaning of 'secondary_id' differs
 *           between components/types. Accepts a single ID, or an array of
 *           multiple IDs. Defaults to false.
 *     @type int $offset Return only activity items with an ID greater than or
 *           equal to this one. Note that providing an offset will disable
 *           pagination. Default: false.
 *     @type string|bool $display_comments How to handle activity comments.
 *           Possible values:
 *             - 'threaded' - comments appear in a threaded tree, under their
 *               parent items
 *             - 'stream' - the activity stream is presented in a flat manner,
 *               with comments sorted in chronological order alongside other
 *               activity items
 *             - false - don't fetch activity comments at all
 *           Default: 'threaded'.
 *     @type bool $show_hidden Whether to show items marked hide_sitewide.
 *           Defaults to false, except in the following cases:
 *             - User is viewing his own activity stream
 *             - User is viewing the activity stream of a non-public group of
 *               which he is a member
 *     @type bool $show_hidden Normally defaults to false, except when:
 *             - a user is viewing his own activity stream
 *             - a user is viewing the activity stream of a non-public group of
 *               which he is a member
 *     @type string|bool $spam Spam status. 'ham_only', 'spam_only', or false
 *           to show all activity regardless of spam status. Default: 'ham_only'.
 *     @type bool $populate_extras Whether to pre-fetch the activity metadata
 *           for the queried items. Default: true.
 * }
 * @return bool Returns true when activities are found, otherwise false.
 */
function bp_has_activities($args = '')
{
    global $activities_template, $bp;
    /***
     * Set the defaults based on the current page. Any of these will be overridden
     * if arguments are directly passed into the loop. Custom plugins should always
     * pass their parameters directly to the loop.
     */
    $user_id = false;
    $include = false;
    $exclude = false;
    $in = false;
    $show_hidden = false;
    $object = false;
    $primary_id = false;
    // User filtering
    if (bp_displayed_user_id()) {
        $user_id = bp_displayed_user_id();
    }
    // Group filtering
    if (!empty($bp->groups->current_group)) {
        $object = $bp->groups->id;
        $primary_id = $bp->groups->current_group->id;
        if (groups_is_user_member(bp_loggedin_user_id(), $bp->groups->current_group->id) || bp_current_user_can('bp_moderate')) {
            $show_hidden = true;
        }
    }
    // The default scope should recognize custom slugs
    if (array_key_exists(bp_current_action(), (array) $bp->loaded_components)) {
        $scope = $bp->loaded_components[bp_current_action()];
    } else {
        $scope = bp_current_action();
    }
    // Support for permalinks on single item pages: /groups/my-group/activity/124/
    if (bp_is_current_action(bp_get_activity_slug())) {
        $include = bp_action_variable(0);
    }
    // Note: any params used for filtering can be a single value, or multiple values comma separated.
    $defaults = array('display_comments' => 'threaded', 'include' => $include, 'exclude' => $exclude, 'in' => $in, 'sort' => 'DESC', 'page' => 1, 'per_page' => 20, 'max' => false, 'show_hidden' => $show_hidden, 'spam' => 'ham_only', 'page_arg' => 'acpage', 'scope' => $scope, 'user_id' => $user_id, 'object' => $object, 'action' => false, 'primary_id' => $primary_id, 'secondary_id' => false, 'offset' => false, 'since' => false, 'meta_query' => false, 'date_query' => false, 'search_terms' => false, 'update_meta_cache' => true);
    $r = bp_parse_args($args, $defaults, 'has_activities');
    extract($r);
    // Translate various values for 'display_comments'
    // This allows disabling comments via ?display_comments=0
    // or =none or =false. Final true is a strict type check. See #5029
    if (in_array($display_comments, array(0, '0', 'none', 'false'), true)) {
        $display_comments = false;
    }
    // Ignore pagination if an offset is passed
    if (!empty($offset)) {
        $page = 0;
    }
    if (empty($search_terms) && !empty($_REQUEST['s'])) {
        $search_terms = $_REQUEST['s'];
    }
    // If you have passed a "scope" then this will override any filters you have passed.
    if ('just-me' == $scope || 'friends' == $scope || 'groups' == $scope || 'favorites' == $scope || 'mentions' == $scope) {
        if ('just-me' == $scope) {
            $display_comments = 'stream';
        }
        // determine which user_id applies
        if (empty($user_id)) {
            $user_id = bp_displayed_user_id() ? bp_displayed_user_id() : bp_loggedin_user_id();
        }
        // are we displaying user specific activity?
        if (is_numeric($user_id)) {
            $show_hidden = $user_id == bp_loggedin_user_id() && $scope != 'friends' ? 1 : 0;
            switch ($scope) {
                case 'friends':
                    if (bp_is_active('friends')) {
                        $friends = friends_get_friend_user_ids($user_id);
                    }
                    if (empty($friends)) {
                        return false;
                    }
                    $user_id = implode(',', (array) $friends);
                    break;
                case 'groups':
                    if (bp_is_active('groups')) {
                        $groups = groups_get_user_groups($user_id);
                        if (empty($groups['groups'])) {
                            return false;
                        }
                        $object = $bp->groups->id;
                        $primary_id = implode(',', (array) $groups['groups']);
                        $user_id = 0;
                    }
                    break;
                case 'favorites':
                    $favs = bp_activity_get_user_favorites($user_id);
                    if (empty($favs)) {
                        return false;
                    }
                    $in = implode(',', (array) $favs);
                    $display_comments = true;
                    $user_id = 0;
                    break;
                case 'mentions':
                    // Are mentions disabled?
                    if (!bp_activity_do_mentions()) {
                        return false;
                    }
                    // Start search at @ symbol and stop search at closing tag delimiter.
                    $search_terms = '@' . bp_activity_get_user_mentionname($user_id) . '<';
                    $display_comments = 'stream';
                    $user_id = 0;
                    break;
            }
        }
    }
    // Do not exceed the maximum per page
    if (!empty($max) && (int) $per_page > (int) $max) {
        $per_page = $max;
    }
    // Support for basic filters in earlier BP versions is disabled by default. To enable, put
    //   add_filter( 'bp_activity_enable_afilter_support', '__return_true' );
    // into bp-custom.php or your theme's functions.php
    if (isset($_GET['afilter']) && apply_filters('bp_activity_enable_afilter_support', false)) {
        $filter = array('object' => $_GET['afilter']);
    } else {
        if (!empty($user_id) || !empty($object) || !empty($action) || !empty($primary_id) || !empty($secondary_id) || !empty($offset) || !empty($since)) {
            $filter = array('user_id' => $user_id, 'object' => $object, 'action' => $action, 'primary_id' => $primary_id, 'secondary_id' => $secondary_id, 'offset' => $offset, 'since' => $since);
        } else {
            $filter = false;
        }
    }
    // If specific activity items have been requested, override the $hide_spam argument. This prevents backpat errors with AJAX.
    if (!empty($include) && 'ham_only' == $spam) {
        $spam = 'all';
    }
    $template_args = array('page' => $page, 'per_page' => $per_page, 'page_arg' => $page_arg, 'max' => $max, 'sort' => $sort, 'include' => $include, 'exclude' => $exclude, 'in' => $in, 'filter' => $filter, 'search_terms' => $search_terms, 'meta_query' => $meta_query, 'date_query' => $date_query, 'display_comments' => $display_comments, 'show_hidden' => $show_hidden, 'spam' => $spam, 'update_meta_cache' => $update_meta_cache);
    $activities_template = new BP_Activity_Template($template_args);
    return apply_filters('bp_has_activities', $activities_template->has_activities(), $activities_template, $template_args);
}
 /**
  * GET WALL ACTIVITES
  */
 function get_wall_activities($page = 0, $per_page = 20)
 {
     global $bp, $wpdb;
     $min = $page > 0 ? ($page - 1) * $per_page : 0;
     $max = ($page + 1) * $per_page;
     $per_page = bp_get_activity_per_page();
     buddy_boss_log(" per page {$per_page}");
     if (isset($bp->loggedin_user) && isset($bp->loggedin_user->id) && $bp->displayed_user->id == $bp->loggedin_user->id) {
         $myprofile = true;
     } else {
         $myprofile = false;
     }
     $wpdb->show_errors = BUDDY_BOSS_DEBUG;
     $user_id = $bp->displayed_user->id;
     buddy_boss_log("Looking at {$user_id}");
     $filter = addslashes($bp->displayed_user->fullname);
     $friend_ids = friends_get_friend_user_ids($user_id);
     $admin_ids = array();
     //buddyboss_users_by_role( 'administrator' );
     $friend_ids = array_merge($friend_ids, $admin_ids);
     // var_dump($friend_ids);
     buddy_boss_log($friend_ids);
     if (!empty($friend_ids)) {
         $friend_id_list = implode(",", $friend_ids);
     }
     buddy_boss_log($friend_id_list);
     $table = $wpdb->prefix . bp_activity;
     $table2 = $wpdb->prefix . bp_activity_meta;
     // Group Display code
     if (array_search("groups", $bp->active_components)) {
         $groups = BP_Groups_Member::get_group_ids($user_id);
     }
     //var_dump($groups);
     $valid_groups = array();
     if (!empty($groups)) {
         foreach ($groups['groups'] as $id) {
             $group = new BP_Groups_Group($id);
             //var_dump($group);
             if ("public" == $group->status) {
                 //echo $group->slug;
                 $valid_groups[] = $id;
             }
             $user_group[] = $group->slug;
         }
     }
     $group_modifier = "OR ( {$table}.user_id = {$user_id} AND {$table}.component = 'groups' ) ";
     $group_mentions = "OR ( {$table}.component = 'groups' AND ({$table}.content LIKE '%@{$filter}%'))";
     $friendships = "OR ( {$table}.user_id = {$user_id} AND {$table}.component = 'friends' )";
     $mentions_modifier = "OR ( {$table}.component = 'activity' AND {$table}.action LIKE '%@{$filter}%' ) ";
     //$mem_slugs = $bp->members->slug;
     $friends_modifier = "OR ( {$table2}.meta_value LIKE '%{$filter}%' AND {$table}.type!='activity_comment') ";
     $qry = "SELECT {$table}.id FROM {$table} LEFT JOIN {$table2} ON {$table}.id={$table2}.activity_id\r\n\t\t\tWHERE ( {$table}.user_id = {$user_id} AND {$table}.type!='activity_comment' AND {$table}.type!='friends' )\r\n\t\t\t{$friends_modifier}\r\n\t\t\t{$group_modifier}\r\n\t\t\t{$group_mentions}\r\n\t\t\t{$friendships}\r\n\t\t\t{$mentions_modifier}\r\n\t\t\tORDER BY date_recorded DESC LIMIT {$min}, 30";
     //echo $qry;
     $activities = $wpdb->get_results($qry, ARRAY_A);
     //var_dump($wpdb->print_error());
     buddy_boss_log($qry);
     buddy_boss_log($activities);
     if (empty($activities)) {
         return null;
     }
     $tmp = array();
     foreach ($activities as $a) {
         $tmp[] = $a["id"];
     }
     $activity_list = implode(",", $tmp);
     return $activity_list;
 }
/**
 * Get a comma-separated list of IDs of a user's friends.
 *
 * @param int $user_id Optional. Default: the displayed user's ID, or the
 *                     logged-in user's ID.
 * @return string|bool A comma-separated list of friend IDs if any are found,
 *                     otherwise false.
 */
function bp_get_friend_ids($user_id = 0)
{
    if (empty($user_id)) {
        $user_id = bp_displayed_user_id() ? bp_displayed_user_id() : bp_loggedin_user_id();
    }
    $friend_ids = friends_get_friend_user_ids($user_id);
    if (empty($friend_ids)) {
        return false;
    }
    return implode(',', friends_get_friend_user_ids($user_id));
}
function bp_show_friend_suggestions_list($limit = 5)
{
    $user_id = get_current_user_id();
    $my_friends = (array) friends_get_friend_user_ids($user_id);
    //get all friend ids
    $my_friend_req = (array) friend_suggest_get_friendship_requested_user_ids($user_id);
    //get all friend request by me
    $possible_friends = array();
    //we will store the possible friend ids here
    foreach ($my_friends as $friend_id) {
        $possible_friends = array_merge($possible_friends, (array) friends_get_friend_user_ids($friend_id));
    }
    //we have the list of friends of friends, we will just remove
    //now get only udifferent friend ids(unique)
    $possible_friends = array_unique($possible_friends);
    //intersect my friends with this array
    $my_friends[] = get_current_user_id();
    //include me to
    $excluded_users = get_user_meta($user_id, 'hidden_friend_suggestions', true);
    $excluded_users = array_merge($my_friends, (array) $excluded_users, (array) $my_friend_req);
    //we may check the preference of the user regarding , like not add
    $possible_friends = array_diff($possible_friends, $excluded_users);
    //get those user who are not my friend and also exclude me too
    if (!empty($possible_friends)) {
        shuffle($possible_friends);
        //randomize
        $possible_friends = array_slice($possible_friends, 0, $limit);
    }
    if (!empty($possible_friends)) {
        ?>
		<ul id="members-suggestion-list" class="item-list suggested-friend-item-list">
				<?php 
        foreach ($possible_friends as $possible_friend) {
            ?>
				<li>
				<?php 
            $member_link = bp_core_get_user_domain($possible_friend);
            $member_name = bp_core_get_user_displayname($possible_friend);
            ?>
					<div class="item-avatar">
						<a href="<?php 
            echo $member_link;
            ?>
"><?php 
            echo bp_core_fetch_avatar(array('type' => 'thumb', 'width' => 50, 'height' => 50, 'item_id' => $possible_friend));
            ?>
</a>
					</div>

					<div class="item">
						<div class="item-title">
							<a href="<?php 
            echo $member_link;
            ?>
"><?php 
            echo $member_name;
            ?>
</a>
						</div>
					</div>
					<div class="action">
					<?php 
            bp_friend_suggest_hide_link($possible_friend);
            ?>
					<?php 
            bp_add_friend_button($possible_friend);
            ?>
					</div>
					<div class="clear"></div>

				</li>

			<?php 
        }
        ?>
		</ul>
	<?php 
    } else {
        ?>
		<div id="message" class="info">
			<p><?php 
        _e("We don't have enough details to suggest a friend yet", 'bp-friends-suggest');
        ?>
</p>
		</div>

	<?php 
    }
    ?>

	<?php 
}
Example #10
0
 function get_friends()
 {
     $user_id = get_current_user_id();
     if (function_exists('friends_get_friend_user_ids')) {
         $friends = friends_get_friend_user_ids($user_id);
         foreach ($friends as $key => $friend) {
             $friends[$key] = array('id' => $friend, 'pic' => bp_core_fetch_avatar(array('item_id' => $friend, 'type' => 'thumb')), 'name' => bp_core_get_user_displayname($friend));
         }
         echo json_encode($friends);
     }
     die;
 }
/**
 * Set up activity arguments for use with the 'friends' scope.
 *
 * For details on the syntax, see {@link BP_Activity_Query}.
 *
 * @since 2.2.0
 *
 * @param array $retval Empty array by default.
 * @param array $filter Current activity arguments.
 * @return array
 */
function bp_friends_filter_activity_scope($retval = array(), $filter = array())
{
    // Determine the user_id.
    if (!empty($filter['user_id'])) {
        $user_id = $filter['user_id'];
    } else {
        $user_id = bp_displayed_user_id() ? bp_displayed_user_id() : bp_loggedin_user_id();
    }
    // Determine friends of user.
    $friends = friends_get_friend_user_ids($user_id);
    if (empty($friends)) {
        $friends = array(0);
    }
    $retval = array('relation' => 'AND', array('column' => 'user_id', 'compare' => 'IN', 'value' => (array) $friends), array('column' => 'hide_sitewide', 'value' => 0), 'override' => array('filter' => array('user_id' => 0), 'show_hidden' => true));
    return $retval;
}
function bfox_bp_plans_schedule_loop_args()
{
    global $bp;
    $plan = bfox_bp_plan();
    wp_parse_str(bp_ajax_querystring('reading_schedules'), $args);
    if ($plan->id) {
        $args['plan_id'] = $plan->id;
        if ('my-schedules' == $bp->action_variables[0]) {
            $args['user_id'] = $bp->loggedin_user->id;
        } elseif ('friend-schedules' == $bp->action_variables[0]) {
            $args['user_id'] = (array) friends_get_friend_user_ids($bp->loggedin_user->id);
        }
    } else {
        $args = BfoxReadingSchedule::add_current_owner_to_args($args);
        $args['cache_latest_readings'] = true;
    }
    if (!$args['page']) {
        $args['page'] = 1;
    }
    if (!$args['per_page']) {
        $args['per_page'] = 20;
    }
    return $args;
}
Example #13
0
 /**
  * Get a list of users that match the query parameters.
  *
  * Since BuddyPress 1.7, use {@link BP_User_Query} instead.
  *
  * @deprecated 1.7.0 Use {@link BP_User_Query}.
  *
  * @see BP_User_Query for a description of parameters, most of which
  *      are used there in the same way.
  *
  * @param string $type See {@link BP_User_Query}.
  * @param int $limit See {@link BP_User_Query}. Default: 0.
  * @param int $page See {@link BP_User_Query}. Default: 1.
  * @param int $user_id See {@link BP_User_Query}. Default: 0.
  * @param mixed $include See {@link BP_User_Query}. Default: false.
  * @param string|bool $search_terms See {@link BP_User_Query}.
  *        Default: false.
  * @param bool $populate_extras See {@link BP_User_Query}.
  *        Default: true.
  * @param mixed $exclude See {@link BP_User_Query}. Default: false.
  * @param string|bool $meta_key See {@link BP_User_Query}.
  *        Default: false.
  * @param string|bool $meta_value See {@link BP_User_Query}.
  *        Default: false.
  * @return array {
  *     @type int $total_users Total number of users matched by query
  *           params.
  *     @type array $paged_users The current page of users matched by
  *           query params.
  * }
  */
 public static function get_users($type, $limit = 0, $page = 1, $user_id = 0, $include = false, $search_terms = false, $populate_extras = true, $exclude = false, $meta_key = false, $meta_value = false)
 {
     global $wpdb;
     _deprecated_function(__METHOD__, '1.7', 'BP_User_Query');
     $bp = buddypress();
     $sql = array();
     $sql['select_main'] = "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.display_name, u.user_email";
     if ('active' == $type || 'online' == $type || 'newest' == $type) {
         $sql['select_active'] = ", um.meta_value as last_activity";
     }
     if ('popular' == $type) {
         $sql['select_popular'] = ", um.meta_value as total_friend_count";
     }
     if ('alphabetical' == $type) {
         $sql['select_alpha'] = ", pd.value as fullname";
     }
     if ($meta_key) {
         $sql['select_meta'] = ", umm.meta_key";
         if ($meta_value) {
             $sql['select_meta'] .= ", umm.meta_value";
         }
     }
     $sql['from'] = "FROM {$wpdb->users} u LEFT JOIN {$wpdb->usermeta} um ON um.user_id = u.ID";
     // We search against xprofile fields, so we must join the table
     if ($search_terms && bp_is_active('xprofile')) {
         $sql['join_profiledata_search'] = "LEFT JOIN {$bp->profile->table_name_data} spd ON u.ID = spd.user_id";
     }
     // Alphabetical sorting is done by the xprofile Full Name field
     if ('alphabetical' == $type) {
         $sql['join_profiledata_alpha'] = "LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id";
     }
     if ($meta_key) {
         $sql['join_meta'] = "LEFT JOIN {$wpdb->usermeta} umm ON umm.user_id = u.ID";
     }
     $sql['where'] = 'WHERE ' . bp_core_get_status_sql('u.');
     if ('active' == $type || 'online' == $type || 'newest' == $type) {
         $sql['where_active'] = $wpdb->prepare("AND um.meta_key = %s", bp_get_user_meta_key('last_activity'));
     }
     if ('popular' == $type) {
         $sql['where_popular'] = $wpdb->prepare("AND um.meta_key = %s", bp_get_user_meta_key('total_friend_count'));
     }
     if ('online' == $type) {
         $sql['where_online'] = "AND DATE_ADD( um.meta_value, INTERVAL 5 MINUTE ) >= UTC_TIMESTAMP()";
     }
     if ('alphabetical' == $type) {
         $sql['where_alpha'] = "AND pd.field_id = 1";
     }
     if (!empty($exclude)) {
         $exclude = implode(',', wp_parse_id_list($exclude));
         $sql['where_exclude'] = "AND u.ID NOT IN ({$exclude})";
     }
     // Passing an $include value of 0 or '0' will necessarily result in an empty set
     // returned. The default value of false will hit the 'else' clause.
     if (0 === $include || '0' === $include) {
         $sql['where_users'] = "AND 0 = 1";
     } else {
         if (!empty($include)) {
             $include = implode(',', wp_parse_id_list($include));
             $sql['where_users'] = "AND u.ID IN ({$include})";
         } elseif (!empty($user_id) && bp_is_active('friends')) {
             $friend_ids = friends_get_friend_user_ids($user_id);
             if (!empty($friend_ids)) {
                 $friend_ids = implode(',', wp_parse_id_list($friend_ids));
                 $sql['where_friends'] = "AND u.ID IN ({$friend_ids})";
                 // User has no friends, return false since there will be no users to fetch.
             } else {
                 return false;
             }
         }
     }
     if (!empty($search_terms) && bp_is_active('xprofile')) {
         $search_terms_like = '%' . bp_esc_like($search_terms) . '%';
         $sql['where_searchterms'] = $wpdb->prepare("AND spd.value LIKE %s", $search_terms_like);
     }
     if (!empty($meta_key)) {
         $sql['where_meta'] = $wpdb->prepare(" AND umm.meta_key = %s", $meta_key);
         // If a meta value is provided, match it
         if ($meta_value) {
             $sql['where_meta'] .= $wpdb->prepare(" AND umm.meta_value = %s", $meta_value);
         }
     }
     switch ($type) {
         case 'active':
         case 'online':
         default:
             $sql[] = "ORDER BY um.meta_value DESC";
             break;
         case 'newest':
             $sql[] = "ORDER BY u.ID DESC";
             break;
         case 'alphabetical':
             $sql[] = "ORDER BY pd.value ASC";
             break;
         case 'random':
             $sql[] = "ORDER BY rand()";
             break;
         case 'popular':
             $sql[] = "ORDER BY CONVERT(um.meta_value, SIGNED) DESC";
             break;
     }
     if (!empty($limit) && !empty($page)) {
         $sql['pagination'] = $wpdb->prepare("LIMIT %d, %d", intval(($page - 1) * $limit), intval($limit));
     }
     /**
      * Filters the SQL used to query for paged users.
      *
      * @since BuddyPress (1.2.6)
      *
      * @param string $value Concatenated SQL statement for the query.
      * @param array  $sql   Array of SQL statement parts for the query.
      */
     $paged_users_sql = apply_filters('bp_core_get_paged_users_sql', join(' ', (array) $sql), $sql);
     $paged_users = $wpdb->get_results($paged_users_sql);
     // Re-jig the SQL so we can get the total user count
     unset($sql['select_main']);
     if (!empty($sql['select_active'])) {
         unset($sql['select_active']);
     }
     if (!empty($sql['select_popular'])) {
         unset($sql['select_popular']);
     }
     if (!empty($sql['select_alpha'])) {
         unset($sql['select_alpha']);
     }
     if (!empty($sql['pagination'])) {
         unset($sql['pagination']);
     }
     array_unshift($sql, "SELECT COUNT(u.ID)");
     /**
      * Filters the SQL used to query for total users.
      *
      * @since BuddyPress (1.2.6)
      *
      * @param string $value Concatenated SQL statement for the query.
      * @param array  $sql   Array of SQL statement parts for the query.
      */
     $total_users_sql = apply_filters('bp_core_get_total_users_sql', join(' ', (array) $sql), $sql);
     $total_users = $wpdb->get_var($total_users_sql);
     /***
      * Lets fetch some other useful data in a separate queries, this will be faster than querying the data for every user in a list.
      * We can't add these to the main query above since only users who have this information will be returned (since the much of the data is in usermeta and won't support any type of directional join)
      */
     if (!empty($populate_extras)) {
         $user_ids = array();
         foreach ((array) $paged_users as $user) {
             $user_ids[] = $user->id;
         }
         // Add additional data to the returned results
         $paged_users = BP_Core_User::get_user_extras($paged_users, $user_ids, $type);
     }
     return array('users' => $paged_users, 'total' => $total_users);
 }
 /**
  * AJAX receiver for the @mention autosuggest jQuery library. Performs a search on the string provided and returns matches.
  *
  * @global object $bp BuddyPress global settings
  * @return mixed Either HTML or JSON. If error, "-1" for missing parameters, "0" for no matches.
  * @see bp-labs/beakers/js/jquery.mentions.dev.js
  * @since 1.0
  */
 public function mention_autosuggest()
 {
     global $bp;
     if (empty($_POST['limit']) || empty($_POST['search'])) {
         exit('-1');
     }
     // Sanitise input
     $search_query = implode('', (array) preg_replace(array('|^https?://|i', '|\\*|', '|@|'), '', $_POST['search']));
     if (empty($search_query)) {
         exit('-1');
     }
     $args = array('count_total' => false, 'number' => (int) $_POST['limit'], 'search' => "{$search_query}*");
     if (!empty($bp->loggedin_user->id)) {
         $args['exclude'] = array($bp->loggedin_user->id);
     }
     if (bp_is_username_compatibility_mode()) {
         $args['fields'] = array('ID', 'user_login');
         $args['orderby'] = 'login';
     } else {
         $args['fields'] = array('ID', 'user_nicename');
         $args['orderby'] = 'nicename';
     }
     $args = apply_filters('bpl_mention_autosuggest_args', $args);
     // Search users
     $user_search_results = get_users($args);
     if (empty($user_search_results)) {
         // Return JSON
         if (!empty($_POST['format']) && 'json' == $_POST['format']) {
             exit(json_encode(false));
             // Return HTML
         } else {
             printf('<li class="section error"><p><span>%s</span> %s</p></li>', _x('No matches found.', 'no search results', 'bpl'), _x('Please check your spelling.', 'no search results', 'bpl'));
             exit;
         }
     }
     // If logged in, get user's friends
     $friend_ids = array();
     if (!empty($bp->loggedin_user->id) && bp_is_active('friends')) {
         $friend_ids = friends_get_friend_user_ids($bp->loggedin_user->id);
     }
     $search_results = array('friends' => array(), 'others' => array());
     // Build results
     foreach ((array) $user_search_results as $user) {
         $result = new stdClass();
         $result->avatar = bp_core_fetch_avatar(array('item_id' => $user->ID, 'width' => 30, 'height' => 30, 'type' => 'thumb', 'alt' => __('Profile picture of %s', 'bpl')));
         $result->name = bp_core_get_user_displayname($user->ID);
         if (bp_is_username_compatibility_mode()) {
             $result->id = $user->user_login;
         } else {
             $result->id = $user->user_nicename;
         }
         if (in_array($user->ID, (array) $friend_ids)) {
             $search_results['friends'][] = $result;
         } else {
             $search_results['others'][] = $result;
         }
     }
     apply_filters_ref_array('bpl_mention_autosuggest', array(&$search_results, $args));
     // Return JSON
     if (!empty($_POST['format']) && 'json' == $_POST['format']) {
         exit(json_encode($search_results));
         // Return HTML
     } else {
         $html = array();
         foreach ($search_results as $section => $items) {
             if (empty($items)) {
                 continue;
             }
             // Friends and other users
             if ('friends' == $section || 'others' == $section) {
                 if ('friends' == $section) {
                     $html[] = sprintf('<li class="section friends"><p>%s</p></li>', __('Your friends', 'bpl'));
                 } elseif ('others' == $section) {
                     if (!empty($search_results['friends'])) {
                         $html[] = sprintf('<li class="section other"><p>%s</p></li>', sprintf(__('Other people on %s', 'bpl'), get_bloginfo('name', 'display')));
                     } else {
                         $html[] = sprintf('<li class="section other"><p>%s</p></li>', sprintf(__('People on %s', 'bpl'), get_bloginfo('name', 'display')));
                     }
                 }
                 foreach ($items as $item) {
                     $html[] = sprintf('<li class=%s><p>%s</p></li>', esc_attr($item->id), $item->avatar . esc_html($item->name));
                 }
                 // For third-party extensions
             } else {
                 $custom_section = apply_filters('bpl_mention_autosuggest_custom_section', false, $section, $items);
                 if (!empty($custom_section)) {
                     $html = array_merge($html, (array) $custom_section);
                 }
             }
         }
         // Safety net
         if (empty($html)) {
             $html[] = sprintf('<li class="section error"><p><span>%s</span> %s</p></li>', _x('No matches found.', 'no search results', 'bpl'), _x('Please check your spelling.', 'no search results', 'bpl'));
         }
         exit(apply_filters('bpl_mention_autosuggest_html', implode(PHP_EOL, $html), $html));
     }
 }
Example #15
0
/**
 * Filter user activity stream if scope is "friends".
 *
 * @since 1.0.3
 *
 * @param array $r The activity arguments.
 * @return array
 */
function bp_mute_filter_user_activity_scope_friends($r)
{
    if (!bp_is_my_profile()) {
        return $r;
    }
    if ($r['scope'] !== "friends") {
        return $r;
    }
    $r['scope'] = '';
    $friend_ids = friends_get_friend_user_ids(bp_displayed_user_id());
    $muted_ids = Mute::get_muting(bp_displayed_user_id());
    $r['user_id'] = array_diff($friend_ids, $muted_ids);
    return $r;
}
    function widget($args, $instance)
    {
        if (!function_exists('bp_is_active')) {
            return false;
        }
        extract($args);
        $blog_url = get_bloginfo('url');
        $title = apply_filters('widget_title', empty($instance['title']) ? 'Atividades na rede' : $instance['title']);
        $maxActivities = empty($instance['maxActivities']) ? 9 : $instance['maxActivities'];
        $activityFilterBy = empty($instance['activityFilterBy']) ? '' : $instance['activityFilterBy'];
        // cria o filtro de actions, pega as chaves do array e cria uma string separando os valores por virgula
        $query_string = '&action=' . implode(",", array_keys($activityFilterBy));
        // máximo de atividades
        $query_string .= '&max=' . $maxActivities;
        $query_string .= '&per_page=' . $maxActivities;
        // $query_string .= '&display_comments=stream';
        // TODO: remover Mostrar essa widget apenas no perfil do usuário e na página inicial
        // se for a página do usuário
        if (bp_displayed_user_id()) {
            // pega os amigos do usuário da página atual
            $friends = friends_get_friend_user_ids(bp_displayed_user_id());
            if (!empty($friends)) {
                $friends_and_me = implode(',', (array) $friends);
                $friends_and_me = '&user_id=' . $friends_and_me;
                $query_string = $query_string . $friends_and_me;
            } else {
                return false;
            }
            // se não for a página inicial retorna falso.
        } else {
            if (!is_home()) {
                return false;
            }
        }
        print $before_widget;
        if (!empty($instance['title'])) {
            print $before_head;
            print $before_title . "<a href='{$blog_url}/activity' title='ver mais atividades'> " . $instance['title'] . "</a>" . $after_title;
            print $after_head;
        }
        print $before_body;
        ?>

			<?php 
        do_action('bp_before_directory_activity');
        ?>

			<div id="buddypress" >
				<div class="<?php 
        echo is_home() ? 'activity' : '';
        ?>
" role="main">

					<?php 
        do_action('template_notices');
        ?>

					<?php 
        do_action('bp_before_directory_activity_content');
        ?>

					<?php 
        if (is_user_logged_in() and is_home()) {
            ?>

						<?php 
            bp_get_template_part('activity/post-form');
            ?>

					<?php 
        }
        ?>

					
					<?php 
        do_action('bp_before_directory_activity_list');
        ?>

					<!-- loop -->

						<?php 
        do_action('bp_before_activity_loop');
        ?>

						<?php 
        //echo $query_string;
        ?>


						<?php 
        if (bp_has_activities(bp_ajax_querystring('activity') . $query_string)) {
            ?>

							<ul id="activity-stream" class="activity-list item-list">

								<?php 
            while (bp_activities()) {
                bp_the_activity();
                ?>

									<?php 
                bp_get_template_part('activity/entry');
                ?>

								<?php 
            }
            ?>

								<?php 
            if (bp_activity_has_more_items()) {
                ?>

									<li class="load-more">
										<a href="<?php 
                bp_activity_load_more_link();
                ?>
"><?php 
                _e('Load More', 'buddypress');
                ?>
</a>
									</li>

								<?php 
            }
            ?>

							</ul>

						<?php 
        } else {
            ?>

							<div id="message" class="info">
								<p><?php 
            _e('Sorry, there was no activity found. Please try a different filter.', 'buddypress');
            ?>
</p>
							</div>

						<?php 
        }
        ?>
		

						<?php 
        do_action('bp_after_activity_loop');
        ?>

					<!-- endloop -->

					<?php 
        do_action('bp_after_directory_activity_list');
        ?>

					<?php 
        do_action('bp_after_directory_activity_content');
        ?>
				</div>

			</div>	
		
			<?php 
        do_action('bp_after_directory_activity');
        ?>

		<?php 
        /*  aqui termina a parte do buddypress  */
        print $after_body;
        print $after_widget;
    }
 /**
  * Get friends/Following user ids
  * @param type $logged_user_id
  * @return type
  */
 public static function get_friend_user_ids($logged_user_id)
 {
     $friend_ids = array();
     if (function_exists('friends_get_friend_user_ids')) {
         $friend_ids = friends_get_friend_user_ids($logged_user_id);
     } elseif (function_exists('bp_follow_get_following')) {
         $friend_ids = bp_follow_get_following(array('user_id' => $logged_user_id));
     }
     return apply_filters('fblike_activity_get_friend_ids', $friend_ids, $logged_user_id);
 }
Example #18
0
	function get_users( $type, $limit = null, $page = 1, $user_id = false, $include = false, $search_terms = false, $populate_extras = true ) {
		global $wpdb, $bp;

		$sql = array();

		$sql['select_main'] = "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.display_name, u.user_email";

		if ( 'active' == $type || 'online' == $type )
			$sql['select_active'] = ", um.meta_value as last_activity";

		if ( 'popular' == $type )
			$sql['select_popular'] = ", um.meta_value as total_friend_count";

		if ( 'alphabetical' == $type )
			$sql['select_alpha'] = ", pd.value as fullname";

		$sql['from'] = "FROM " . CUSTOM_USER_TABLE . " u LEFT JOIN " . CUSTOM_USER_META_TABLE . " um ON um.user_id = u.ID";

		if ( $search_terms && function_exists( 'xprofile_install' ) || 'alphabetical' == $type )
			$sql['join_profiledata'] = "LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id";

		$sql['where'] = 'WHERE ' . bp_core_get_status_sql( 'u.' );

		if ( 'active' == $type || 'online' == $type )
			$sql['where_active'] = "AND um.meta_key = 'last_activity'";

		if ( 'popular' == $type )
			$sql['where_popular'] = "AND um.meta_key = 'total_friend_count'";

		if ( 'online' == $type )
			$sql['where_online'] = "AND DATE_ADD( um.meta_value, INTERVAL 5 MINUTE ) >= UTC_TIMESTAMP()";

		if ( 'alphabetical' == $type )
			$sql['where_alpha'] = "AND pd.field_id = 1";

		if ( $include ) {
			if ( is_array( $include ) )
				$uids = $wpdb->escape( implode( ',', (array)$include ) );
			else
				$uids = $wpdb->escape( $include );

			if ( !empty( $uids ) )
				$sql['where_users'] = "AND u.ID IN ({$uids})";
		}

		else if ( $user_id && function_exists( 'friends_install' ) ) {
			$friend_ids = friends_get_friend_user_ids( $user_id );
			$friend_ids = $wpdb->escape( implode( ',', (array)$friend_ids ) );

			if ( !empty( $friend_ids ) )
				$sql['where_friends'] = "AND u.ID IN ({$friend_ids})";
			else {
				/* User has no friends, return false since there will be no users to fetch. */
				return false;
			}
		}

		if ( $search_terms && function_exists( 'xprofile_install' ) ) {
			$search_terms = like_escape( $wpdb->escape( $search_terms ) );
			$sql['where_searchterms'] = "AND pd.value LIKE '%%$search_terms%%'";
		}

		switch ( $type ) {
			case 'active': case 'online': default:
				$sql[] = "ORDER BY um.meta_value DESC";
				break;
			case 'newest':
				$sql[] = "ORDER BY u.user_registered DESC";
				break;
			case 'alphabetical':
				$sql[] = "ORDER BY pd.value ASC";
				break;
			case 'random':
				$sql[] = "ORDER BY rand()";
				break;
			case 'popular':
				$sql[] = "ORDER BY CONVERT(um.meta_value, SIGNED) DESC";
				break;
		}

		if ( $limit && $page )
			$sql['pagination'] = $wpdb->prepare( "LIMIT %d, %d", intval( ( $page - 1 ) * $limit), intval( $limit ) );

		/* Get paginated results */
		$paged_users_sql = apply_filters( 'bp_core_get_paged_users_sql', join( ' ', (array)$sql ), $sql );
		$paged_users     = $wpdb->get_results( $paged_users_sql );

		/* Re-jig the SQL so we can get the total user count */
		unset( $sql['select_main'] );

		if ( !empty( $sql['select_active'] ) )
			unset( $sql['select_active'] );

		if ( !empty( $sql['select_popular'] ) )
			unset( $sql['select_popular'] );

		if ( !empty( $sql['select_alpha'] ) )
			unset( $sql['select_alpha'] );

		if ( !empty( $sql['pagination'] ) )
			unset( $sql['pagination'] );

		array_unshift( $sql, "SELECT COUNT(DISTINCT u.ID)" );

		/* Get total user results */
		$total_users_sql = apply_filters( 'bp_core_get_total_users_sql', join( ' ', (array)$sql ), $sql );
		$total_users     = $wpdb->get_var( $total_users_sql );

		/***
		 * Lets fetch some other useful data in a separate queries, this will be faster than querying the data for every user in a list.
		 * We can't add these to the main query above since only users who have this information will be returned (since the much of the data is in usermeta and won't support any type of directional join)
		 */
		if ( $populate_extras ) {
			foreach ( (array)$paged_users as $user )
				$user_ids[] = $user->id;

			$user_ids = $wpdb->escape( join( ',', (array)$user_ids ) );

			/* Add additional data to the returned results */
			$paged_users = BP_Core_User::get_user_extras( &$paged_users, $user_ids, $type );
		}

		return array( 'users' => $paged_users, 'total' => $total_users );
	}
/**
 * Initializes the activity loop.
 *
 * Based on the $args passed, bp_has_activities() populates the $activities_template global.
 *
 * @since 1.0.0
 *
 * @param array $args Arguments for limiting the contents of the activity loop. Can be passed as an associative array or as a URL argument string
 *
 * @global object $activities_template {@link BP_Activity_Template}
 * @global object $bp BuddyPress global settings
 * @uses groups_is_user_member()
 * @uses bp_current_action()
 * @uses bp_is_current_action()
 * @uses bp_get_activity_slug()
 * @uses bp_action_variable()
 * @uses nxt_parse_args()
 * @uses bp_is_active()
 * @uses friends_get_friend_user_ids()
 * @uses groups_get_user_groups()
 * @uses bp_activity_get_user_favorites()
 * @uses apply_filters() To call the 'bp_has_activities' hook
 *
 * @return bool Returns true when activities are found
 */
function bp_has_activities($args = '')
{
    global $activities_template, $bp;
    /***
     * Set the defaults based on the current page. Any of these will be overridden
     * if arguments are directly passed into the loop. Custom plugins should always
     * pass their parameters directly to the loop.
     */
    $user_id = false;
    $include = false;
    $exclude = false;
    $in = false;
    $show_hidden = false;
    $object = false;
    $primary_id = false;
    // User filtering
    if (!empty($bp->displayed_user->id)) {
        $user_id = $bp->displayed_user->id;
    }
    // Group filtering
    if (!empty($bp->groups->current_group)) {
        $object = $bp->groups->id;
        $primary_id = $bp->groups->current_group->id;
        if ('public' != $bp->groups->current_group->status && (groups_is_user_member($bp->loggedin_user->id, $bp->groups->current_group->id) || $bp->loggedin_user->is_super_admin)) {
            $show_hidden = true;
        }
    }
    // The default scope should recognize custom slugs
    if (array_key_exists($bp->current_action, (array) $bp->loaded_components)) {
        $scope = $bp->loaded_components[$bp->current_action];
    } else {
        $scope = bp_current_action();
    }
    // Support for permalinks on single item pages: /groups/my-group/activity/124/
    if (bp_is_current_action(bp_get_activity_slug())) {
        $include = bp_action_variable(0);
    }
    // Note: any params used for filtering can be a single value, or multiple values comma separated.
    $defaults = array('display_comments' => 'threaded', 'include' => $include, 'exclude' => $exclude, 'in' => $in, 'sort' => 'DESC', 'page' => 1, 'per_page' => 20, 'max' => false, 'show_hidden' => $show_hidden, 'scope' => $scope, 'user_id' => $user_id, 'object' => $object, 'action' => false, 'primary_id' => $primary_id, 'secondary_id' => false, 'search_terms' => false);
    $r = nxt_parse_args($args, $defaults);
    extract($r);
    // If you have passed a "scope" then this will override any filters you have passed.
    if ('just-me' == $scope || 'friends' == $scope || 'groups' == $scope || 'favorites' == $scope || 'mentions' == $scope) {
        if ('just-me' == $scope) {
            $display_comments = 'stream';
        }
        // determine which user_id applies
        if (empty($user_id)) {
            $user_id = !empty($bp->displayed_user->id) ? $bp->displayed_user->id : $bp->loggedin_user->id;
        }
        // are we displaying user specific activity?
        if (is_numeric($user_id)) {
            $show_hidden = $user_id == $bp->loggedin_user->id && $scope != 'friends' ? 1 : 0;
            switch ($scope) {
                case 'friends':
                    if (bp_is_active('friends')) {
                        $friends = friends_get_friend_user_ids($user_id);
                    }
                    if (empty($friends)) {
                        return false;
                    }
                    $user_id = implode(',', (array) $friends);
                    break;
                case 'groups':
                    if (bp_is_active('groups')) {
                        $groups = groups_get_user_groups($user_id);
                        if (empty($groups['groups'])) {
                            return false;
                        }
                        $object = $bp->groups->id;
                        $primary_id = implode(',', (array) $groups['groups']);
                        $user_id = 0;
                    }
                    break;
                case 'favorites':
                    $favs = bp_activity_get_user_favorites($user_id);
                    if (empty($favs)) {
                        return false;
                    }
                    $include = implode(',', (array) $favs);
                    $display_comments = true;
                    break;
                case 'mentions':
                    $user_nicename = !empty($bp->displayed_user->id) ? $bp->displayed_user->userdata->user_nicename : $bp->loggedin_user->userdata->user_nicename;
                    $user_login = !empty($bp->displayed_user->id) ? $bp->displayed_user->userdata->user_login : $bp->loggedin_user->userdata->user_login;
                    $search_terms = '@' . bp_core_get_username($user_id, $user_nicename, $user_login) . '<';
                    // Start search at @ symbol and stop search at closing tag delimiter.
                    $display_comments = 'stream';
                    $user_id = 0;
                    break;
            }
        }
    }
    // Do not exceed the maximum per page
    if (!empty($max) && (int) $per_page > (int) $max) {
        $per_page = $max;
    }
    // Support for basic filters in earlier BP versions.
    if (isset($_GET['afilter'])) {
        $filter = array('object' => $_GET['afilter']);
    } else {
        if (!empty($user_id) || !empty($object) || !empty($action) || !empty($primary_id) || !empty($secondary_id)) {
            $filter = array('user_id' => $user_id, 'object' => $object, 'action' => $action, 'primary_id' => $primary_id, 'secondary_id' => $secondary_id);
        } else {
            $filter = false;
        }
    }
    $activities_template = new BP_Activity_Template($page, $per_page, $max, $include, $sort, $filter, $search_terms, $display_comments, $show_hidden, $exclude, $in);
    return apply_filters('bp_has_activities', $activities_template->has_activities(), $activities_template);
}
Example #20
0
 /** Static Functions ******************************************************/
 function get_users($type, $limit = 0, $page = 1, $user_id = 0, $include = false, $search_terms = false, $populate_extras = true, $exclude = false, $meta_key = false, $meta_value = false)
 {
     global $nxtdb, $bp;
     $sql = array();
     $sql['select_main'] = "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.display_name, u.user_email";
     if ('active' == $type || 'online' == $type || 'newest' == $type) {
         $sql['select_active'] = ", um.meta_value as last_activity";
     }
     if ('popular' == $type) {
         $sql['select_popular'] = ", um.meta_value as total_friend_count";
     }
     if ('alphabetical' == $type) {
         $sql['select_alpha'] = ", pd.value as fullname";
     }
     if ($meta_key) {
         $sql['select_meta'] = ", umm.meta_key";
         if ($meta_value) {
             $sql['select_meta'] .= ", umm.meta_value";
         }
     }
     $sql['from'] = "FROM {$nxtdb->users} u LEFT JOIN {$nxtdb->usermeta} um ON um.user_id = u.ID";
     // We search against xprofile fields, so we must join the table
     if ($search_terms && bp_is_active('xprofile')) {
         $sql['join_profiledata_search'] = "LEFT JOIN {$bp->profile->table_name_data} spd ON u.ID = spd.user_id";
     }
     // Alphabetical sorting is done by the xprofile Full Name field
     if ('alphabetical' == $type) {
         $sql['join_profiledata_alpha'] = "LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id";
     }
     if ($meta_key) {
         $sql['join_meta'] = "LEFT JOIN {$nxtdb->usermeta} umm ON umm.user_id = u.ID";
     }
     $sql['where'] = 'WHERE ' . bp_core_get_status_sql('u.');
     if ('active' == $type || 'online' == $type || 'newest' == $type) {
         $sql['where_active'] = $nxtdb->prepare("AND um.meta_key = %s", bp_get_user_meta_key('last_activity'));
     }
     if ('popular' == $type) {
         $sql['where_popular'] = $nxtdb->prepare("AND um.meta_key = %s", bp_get_user_meta_key('total_friend_count'));
     }
     if ('online' == $type) {
         $sql['where_online'] = "AND DATE_ADD( um.meta_value, INTERVAL 5 MINUTE ) >= UTC_TIMESTAMP()";
     }
     if ('alphabetical' == $type) {
         $sql['where_alpha'] = "AND pd.field_id = 1";
     }
     if (!empty($exclude)) {
         $sql['where_exclude'] = "AND u.ID NOT IN ({$exclude})";
     }
     if ($include) {
         if (is_array($include)) {
             $uids = $nxtdb->escape(implode(',', (array) $include));
         } else {
             $uids = $nxtdb->escape($include);
         }
         if (!empty($uids)) {
             $sql['where_users'] = "AND u.ID IN ({$uids})";
         }
     } else {
         if ($user_id && bp_is_active('friends')) {
             $friend_ids = friends_get_friend_user_ids($user_id);
             $friend_ids = $nxtdb->escape(implode(',', (array) $friend_ids));
             if (!empty($friend_ids)) {
                 $sql['where_friends'] = "AND u.ID IN ({$friend_ids})";
             } else {
                 return false;
             }
         }
     }
     if ($search_terms && bp_is_active('xprofile')) {
         $search_terms = like_escape($nxtdb->escape($search_terms));
         $sql['where_searchterms'] = "AND spd.value LIKE '%%{$search_terms}%%'";
     }
     if ($meta_key) {
         $sql['where_meta'] = $nxtdb->prepare(" AND umm.meta_key = %s", $meta_key);
         // If a meta value is provided, match it
         if ($meta_value) {
             $sql['where_meta'] .= $nxtdb->prepare(" AND umm.meta_value = %s", $meta_value);
         }
     }
     switch ($type) {
         case 'active':
         case 'online':
         default:
             $sql[] = "ORDER BY um.meta_value DESC";
             break;
         case 'newest':
             $sql[] = "ORDER BY u.ID DESC";
             break;
         case 'alphabetical':
             $sql[] = "ORDER BY pd.value ASC";
             break;
         case 'random':
             $sql[] = "ORDER BY rand()";
             break;
         case 'popular':
             $sql[] = "ORDER BY CONVERT(um.meta_value, SIGNED) DESC";
             break;
     }
     if ($limit && $page) {
         $sql['pagination'] = $nxtdb->prepare("LIMIT %d, %d", intval(($page - 1) * $limit), intval($limit));
     }
     // Get paginated results
     $paged_users_sql = apply_filters('bp_core_get_paged_users_sql', join(' ', (array) $sql), $sql);
     $paged_users = $nxtdb->get_results($paged_users_sql);
     // Re-jig the SQL so we can get the total user count
     unset($sql['select_main']);
     if (!empty($sql['select_active'])) {
         unset($sql['select_active']);
     }
     if (!empty($sql['select_popular'])) {
         unset($sql['select_popular']);
     }
     if (!empty($sql['select_alpha'])) {
         unset($sql['select_alpha']);
     }
     if (!empty($sql['pagination'])) {
         unset($sql['pagination']);
     }
     array_unshift($sql, "SELECT COUNT(DISTINCT u.ID)");
     // Get total user results
     $total_users_sql = apply_filters('bp_core_get_total_users_sql', join(' ', (array) $sql), $sql);
     $total_users = $nxtdb->get_var($total_users_sql);
     /***
      * Lets fetch some other useful data in a separate queries, this will be faster than querying the data for every user in a list.
      * We can't add these to the main query above since only users who have this information will be returned (since the much of the data is in usermeta and won't support any type of directional join)
      */
     if (!empty($populate_extras)) {
         $user_ids = array();
         foreach ((array) $paged_users as $user) {
             $user_ids[] = $user->id;
         }
         $user_ids = $nxtdb->escape(join(',', (array) $user_ids));
         // Add additional data to the returned results
         $paged_users = BP_Core_User::get_user_extras($paged_users, $user_ids, $type);
     }
     return array('users' => $paged_users, 'total' => $total_users);
 }
/**
 * bp_like_get_likes()
 *
 * Outputs a list of users who have liked a given item.
 *
 */
function bp_like_get_likes($item_id = '', $type = '', $user_id = '')
{
    global $bp;
    if (!$type || !$item_id) {
        return false;
    }
    if (!$user_id) {
        $user_id = $bp->loggedin_user->id;
    }
    if ($type == 'activity') {
        /* Grab some core data we will need later on, specific to activities */
        $users_who_like = array_keys(bp_activity_get_meta($item_id, 'liked_count'));
        $liked_count = count(bp_activity_get_meta($item_id, 'liked_count'));
        $output = '';
        /* Intercept any messages if nobody likes it, just incase the button was clicked when it shouldn't be */
        if ($liked_count == 0) {
            $output .= bp_like_get_text('get_likes_no_likes');
        } elseif (bp_like_get_settings('likers_visibility') == 'show_all') {
            /* Settings say we should show their name. */
            if (bp_like_get_settings('name_or_avatar') == 'name') {
                /* Current user likes it too, remove them from the liked count and output appropriate message */
                if (bp_like_is_liked($item_id, 'activity', $user_id)) {
                    // remove current user from liked count.
                    $liked_count = $liked_count - 1;
                    if ($liked_count == 1) {
                        //only current user and 1 other person likes this.
                        $output .= bp_like_get_text('get_likes_you_and_singular');
                        $other = $users_who_like[count($users_who_like)];
                        $output .= 'You and ' . bp_core_get_userlink($other) . ' liked this.';
                    } elseif ($liked_count == 0) {
                        //current user is the only person to like this.
                        $output .= bp_like_get_text('get_likes_only_liker');
                    } else {
                        $output .= bp_like_get_text('get_likes_you_and_plural');
                    }
                } else {
                    if ($liked_count == 1) {
                        $output .= bp_like_get_text('get_likes_count_people_singular');
                    } else {
                        $output .= bp_like_get_text('get_likes_count_people_plural');
                    }
                }
                /* Now output the name of each person who has liked it (except the current user obviously) */
                foreach ($users_who_like as $id) {
                    if ($id != $user_id) {
                        $output .= ' &middot <a href="' . bp_core_get_user_domain($id) . '" title="' . bp_core_get_user_displayname($id) . '">' . bp_core_get_user_displayname($id) . '</a>';
                    }
                }
            } elseif (bp_like_get_settings('name_or_avatar') == 'avatar') {
                /* Output the avatar of each person who has liked it. */
                foreach ($users_who_like as $id) {
                    $output .= '<a href="' . bp_core_get_user_domain($id) . '" title="' . bp_core_get_user_displayname($id) . '">' . bp_core_fetch_avatar(array('item_id' => $id, 'object' => 'user', 'type' => 'thumb', 'width' => 30, 'height' => 30)) . '</a> ';
                }
            }
        } elseif (bp_like_get_settings('likers_visibility') == 'friends_names_others_numbers' && bp_is_active('friends')) {
            /* Grab some information about their friends. */
            $users_friends = friends_get_friend_user_ids($user_id);
            if (!empty($users_friends)) {
                $friends_who_like = array_intersect($users_who_like, $users_friends);
            }
            /* Current user likes it, so reduce the liked count by 1, to get the number of other people who like it. */
            if (bp_like_is_liked($item_id, 'activity', $user_id)) {
                $liked_count = $liked_count - 1;
            }
            /* Settings say we should show their names. */
            if (bp_like_get_settings('name_or_avatar') == 'name') {
                /* Current user likes it too, tell them. */
                if (bp_like_is_liked($item_id, 'activity', $user_id)) {
                    $output .= 'You ';
                }
                /* Output the name of each friend who has liked it. */
                foreach ($users_who_like as $id) {
                    if (in_array($id, $friends_who_like)) {
                        //$output .= ' &middot <a href="' . bp_core_get_user_domain( $id ) . '" title="' . bp_core_get_user_displayname( $id ) . '">' . bp_core_get_user_displayname( $id ) . '</a> ';
                        $output .= bp_core_get_userlink($id);
                        $liked_count = $liked_count - 1;
                    }
                }
                /* If non-friends like it, say so. */
                if ($liked_count == 1) {
                    $output .= bp_like_get_text('get_likes_and_people_singular');
                } elseif ($liked_count > 1) {
                    $output .= bp_like_get_text('get_likes_and_people_plural');
                } else {
                    $output .= bp_like_get_text('get_likes_like_this');
                }
            } elseif (bp_like_get_settings('name_or_avatar') == 'avatar') {
                /* Output the avatar of each friend who has liked it, as well as the current users' if they have. */
                if (!empty($friends_who_like)) {
                    foreach ($users_who_like as $id) {
                        if ($id == $user_id || in_array($id, $friends_who_like)) {
                            $user_info = get_userdata($id);
                            $output .= '<a href="' . bp_core_get_user_domain($id) . '" title="' . bp_core_get_user_displayname($id) . '">' . get_avatar($user_info->user_email, 30) . '</a> ';
                        }
                    }
                }
            } elseif (bp_like_get_settings('likers_visibility') == 'friends_names_others_numbers' && !bp_is_active('friends') || bp_like_get_settings('likers_visibility') == 'just_numbers') {
                /* Current user likes it too, remove them from the liked count and output appropriate message */
                if (bp_like_is_liked($item_id, 'activity', $user_id)) {
                    $liked_count = $liked_count - 1;
                    if ($liked_count == 1) {
                        $output .= bp_like_get_text('get_likes_you_and_singular');
                    } elseif ($liked_count == 0) {
                        $output .= bp_like_get_text('get_likes_only_liker');
                    } else {
                        $output .= bp_like_get_text('get_likes_you_and_plural');
                    }
                } else {
                    if ($liked_count == 1) {
                        $output .= bp_like_get_text('get_likes_count_people_singular');
                    } else {
                        $output .= bp_like_get_text('get_likes_count_people_plural');
                    }
                }
            }
        }
    }
    /* Filter out the placeholder. */
    $output = str_replace('%count%', $liked_count, $output);
    echo $output;
}
 function get_activity_for_friends($user_id, $max_items, $since, $max_items_per_friend, $limit, $page)
 {
     global $wpdb, $bp;
     // TODO: Max items per friend not yet implemented.
     if (!function_exists('friends_get_friend_user_ids')) {
         return false;
     }
     if ($limit && $page) {
         $pag_sql = $wpdb->prepare("LIMIT %d, %d", intval(($page - 1) * $limit), intval($limit));
     }
     if ($max) {
         $max_sql = $wpdb->prepare("LIMIT %d", $max);
     }
     $since = strtotime($since);
     $friend_ids = friends_get_friend_user_ids($user_id);
     if (!$friend_ids) {
         return false;
     }
     $friend_ids = implode(',', $friend_ids);
     if ($limit && $page && $max) {
         $activities = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT user_id, content, primary_link, date_recorded, component_name, component_action FROM {$bp->activity->table_name_sitewide} WHERE user_id IN ({$friend_ids}) AND date_recorded >= FROM_UNIXTIME(%d) ORDER BY date_recorded DESC {$pag_sql}", $since));
     } else {
         $activities = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT user_id, content, primary_link, date_recorded, component_name, component_action FROM {$bp->activity->table_name_sitewide} WHERE user_id IN ({$friend_ids}) AND date_recorded >= FROM_UNIXTIME(%d) ORDER BY date_recorded DESC {$pag_sql} {$max_sql}", $since));
     }
     $total_activities = $wpdb->get_var($wpdb->prepare("SELECT DISTINCT count(user_id) FROM {$bp->activity->table_name_sitewide} WHERE user_id IN ({$friend_ids}) AND date_recorded >= FROM_UNIXTIME(%d) ORDER BY date_recorded DESC {$max_sql}", $since));
     return array('activities' => $activities, 'total' => (int) $total_activities);
 }
/**
 * filters bp_get_message_get_recipient_usernames if needed
 *
 * @param  string $recipients the message recipients
 * @uses   friends_get_friend_user_ids() to get the friends list
 * @uses   bp_loggedin_user_id() to get the current logged in user
 * @uses   bp_core_get_username() to get the usernames of the friends.
 * @return string list of the usernames of the friends of the loggedin users
 */
function buddydrive_add_friend_to_recipients($recipients)
{
    if (empty($_REQUEST['buddyitem'])) {
        return $recipients;
    }
    $ids = friends_get_friend_user_ids(bp_loggedin_user_id());
    $usernames = false;
    foreach ($ids as $id) {
        $usernames[] = bp_core_get_username($id);
    }
    if (is_array($usernames)) {
        return implode(' ', $usernames);
    } else {
        return $recipients;
    }
}
Example #24
0
/**
 * @since 1.1.0
 * 
 * @internal Used for generating the query args to fetch online users
 * @param type $limit
 * @param type $page
 * @return type
 */
function bpchat_get_online_user_query_args($limit = null, $page = 1)
{
    $user_query_args = array('page' => $page, 'per_page' => $limit, 'count_total' => false);
    $meta_query = array(array('key' => 'bpchat_state', 'value' => array('online', 'idle', 'busy', 'away'), 'compare' => 'IN'));
    $user_query_args['meta_query'] = $meta_query;
    $user_id = get_current_user_id();
    if ($user_id) {
        $user_query_args['exclude'] = (array) $user_id;
    }
    $chat_buddy_prefernce = bpchat_get_user_chat_preference($user_id);
    // Only return matches of friends of this user.
    if ($chat_buddy_prefernce == 'friends' && $user_id) {
        //we need to work on it as wp will include all frinds which is not what we want
        $user_query_args['include'] = friends_get_friend_user_ids($user_id);
    }
    $user_query_args = apply_filters('bp_chat_online_users_query_args', $user_query_args);
    return $user_query_args;
}
Example #25
0
 function set_friends_object()
 {
     if (is_user_logged_in()) {
         $user = get_current_user_id();
         $friends = friends_get_friend_user_ids($user);
     } else {
         $user = 0;
     }
 }
Example #26
0
function bp_get_friend_ids( $user_id = false ) {
	global $bp;

	if ( !$user_id )
		$user_id = ( $bp->displayed_user->id ) ? $bp->displayed_user->id : $bp->loggedin_user->id;

	$friend_ids = friends_get_friend_user_ids( $user_id );

	if ( empty( $friend_ids ) )
		return false;

	return implode( ',', friends_get_friend_user_ids( $user_id ) );
}
 /**
  * Prepare the query for user_ids.
  *
  * @since 1.7.0
  */
 public function prepare_user_ids_query()
 {
     global $wpdb;
     $bp = buddypress();
     // Default query variables used here.
     $type = '';
     $per_page = 0;
     $page = 1;
     $user_id = 0;
     $include = false;
     $search_terms = false;
     $exclude = false;
     $meta_key = false;
     $meta_value = false;
     extract($this->query_vars);
     // Setup the main SQL query container.
     $sql = array('select' => '', 'where' => array(), 'orderby' => '', 'order' => '', 'limit' => '');
     /* TYPE **************************************************************/
     // Determines the sort order, which means it also determines where the
     // user IDs are drawn from (the SELECT and WHERE statements).
     switch ($type) {
         // 'online' query happens against the last_activity usermeta key
         // Filter 'bp_user_query_online_interval' to modify the
         // number of minutes used as an interval.
         case 'online':
             $this->uid_name = 'user_id';
             $this->uid_table = $bp->members->table_name_last_activity;
             $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
             $sql['where'][] = $wpdb->prepare("u.component = %s AND u.type = 'last_activity'", buddypress()->members->id);
             /**
              * Filters the threshold for activity timestamp minutes since to indicate online status.
              *
              * @since 1.8.0
              *
              * @param int $value Amount of minutes for threshold. Default 15.
              */
             $sql['where'][] = $wpdb->prepare("u.date_recorded >= DATE_SUB( UTC_TIMESTAMP(), INTERVAL %d MINUTE )", apply_filters('bp_user_query_online_interval', 15));
             $sql['orderby'] = "ORDER BY u.date_recorded";
             $sql['order'] = "DESC";
             break;
             // 'active', 'newest', and 'random' queries
             // all happen against the last_activity usermeta key.
         // 'active', 'newest', and 'random' queries
         // all happen against the last_activity usermeta key.
         case 'active':
         case 'newest':
         case 'random':
             $this->uid_name = 'user_id';
             $this->uid_table = $bp->members->table_name_last_activity;
             $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
             $sql['where'][] = $wpdb->prepare("u.component = %s AND u.type = 'last_activity'", buddypress()->members->id);
             if ('newest' == $type) {
                 $sql['orderby'] = "ORDER BY u.user_id";
                 $sql['order'] = "DESC";
             } elseif ('random' == $type) {
                 $sql['orderby'] = "ORDER BY rand()";
             } else {
                 $sql['orderby'] = "ORDER BY u.date_recorded";
                 $sql['order'] = "DESC";
             }
             break;
             // 'popular' sorts by the 'total_friend_count' usermeta.
         // 'popular' sorts by the 'total_friend_count' usermeta.
         case 'popular':
             $this->uid_name = 'user_id';
             $this->uid_table = $wpdb->usermeta;
             $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
             $sql['where'][] = $wpdb->prepare("u.meta_key = %s", bp_get_user_meta_key('total_friend_count'));
             $sql['orderby'] = "ORDER BY CONVERT(u.meta_value, SIGNED)";
             $sql['order'] = "DESC";
             break;
             // 'alphabetical' sorts depend on the xprofile setup.
         // 'alphabetical' sorts depend on the xprofile setup.
         case 'alphabetical':
             // We prefer to do alphabetical sorts against the display_name field
             // of wp_users, because the table is smaller and better indexed. We
             // can do so if xprofile sync is enabled, or if xprofile is inactive.
             //
             // @todo remove need for bp_is_active() check.
             if (!bp_disable_profile_sync() || !bp_is_active('xprofile')) {
                 $this->uid_name = 'ID';
                 $this->uid_table = $wpdb->users;
                 $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
                 $sql['orderby'] = "ORDER BY u.display_name";
                 $sql['order'] = "ASC";
                 // When profile sync is disabled, alphabetical sorts must happen against
                 // the xprofile table.
             } else {
                 $this->uid_name = 'user_id';
                 $this->uid_table = $bp->profile->table_name_data;
                 $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
                 $sql['where'][] = $wpdb->prepare("u.field_id = %d", bp_xprofile_fullname_field_id());
                 $sql['orderby'] = "ORDER BY u.value";
                 $sql['order'] = "ASC";
             }
             // Alphabetical queries ignore last_activity, while BP uses last_activity
             // to infer spam/deleted/non-activated users. To ensure that these users
             // are filtered out, we add an appropriate sub-query.
             $sql['where'][] = "u.{$this->uid_name} IN ( SELECT ID FROM {$wpdb->users} WHERE " . bp_core_get_status_sql('') . " )";
             break;
             // Any other 'type' falls through.
         // Any other 'type' falls through.
         default:
             $this->uid_name = 'ID';
             $this->uid_table = $wpdb->users;
             $sql['select'] = "SELECT u.{$this->uid_name} as id FROM {$this->uid_table} u";
             // In this case, we assume that a plugin is
             // handling order, so we leave those clauses
             // blank.
             break;
     }
     /* WHERE *************************************************************/
     // 'include' - User ids to include in the results.
     $include = false !== $include ? wp_parse_id_list($include) : array();
     $include_ids = $this->get_include_ids($include);
     if (!empty($include_ids)) {
         $include_ids = implode(',', wp_parse_id_list($include_ids));
         $sql['where'][] = "u.{$this->uid_name} IN ({$include_ids})";
     }
     // 'exclude' - User ids to exclude from the results.
     if (false !== $exclude) {
         $exclude_ids = implode(',', wp_parse_id_list($exclude));
         $sql['where'][] = "u.{$this->uid_name} NOT IN ({$exclude_ids})";
     }
     // 'user_id' - When a user id is passed, limit to the friends of the user
     // @todo remove need for bp_is_active() check.
     if (!empty($user_id) && bp_is_active('friends')) {
         $friend_ids = friends_get_friend_user_ids($user_id);
         $friend_ids = implode(',', wp_parse_id_list($friend_ids));
         if (!empty($friend_ids)) {
             $sql['where'][] = "u.{$this->uid_name} IN ({$friend_ids})";
             // If the user has no friends, the query should always
             // return no users.
         } else {
             $sql['where'][] = $this->no_results['where'];
         }
     }
     /* Search Terms ******************************************************/
     // 'search_terms' searches user_login and user_nicename
     // xprofile field matches happen in bp_xprofile_bp_user_query_search().
     if (false !== $search_terms) {
         $search_terms = bp_esc_like(wp_kses_normalize_entities($search_terms));
         if ($search_wildcard === 'left') {
             $search_terms_nospace = '%' . $search_terms;
             $search_terms_space = '%' . $search_terms . ' %';
         } elseif ($search_wildcard === 'right') {
             $search_terms_nospace = $search_terms . '%';
             $search_terms_space = '% ' . $search_terms . '%';
         } else {
             $search_terms_nospace = '%' . $search_terms . '%';
             $search_terms_space = '%' . $search_terms . '%';
         }
         $sql['where']['search'] = $wpdb->prepare("u.{$this->uid_name} IN ( SELECT ID FROM {$wpdb->users} WHERE ( user_login LIKE %s OR user_login LIKE %s OR user_nicename LIKE %s OR user_nicename LIKE %s ) )", $search_terms_nospace, $search_terms_space, $search_terms_nospace, $search_terms_space);
     }
     // Only use $member_type__in if $member_type is not set.
     if (empty($member_type) && !empty($member_type__in)) {
         $member_type = $member_type__in;
     }
     // Member types to exclude. Note that this takes precedence over inclusions.
     if (!empty($member_type__not_in)) {
         $member_type_clause = $this->get_sql_clause_for_member_types($member_type__not_in, 'NOT IN');
         // Member types to include.
     } elseif (!empty($member_type)) {
         $member_type_clause = $this->get_sql_clause_for_member_types($member_type, 'IN');
     }
     if (!empty($member_type_clause)) {
         $sql['where']['member_type'] = $member_type_clause;
     }
     // 'meta_key', 'meta_value' allow usermeta search
     // To avoid global joins, do a separate query.
     if (false !== $meta_key) {
         $meta_sql = $wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s", $meta_key);
         if (false !== $meta_value) {
             $meta_sql .= $wpdb->prepare(" AND meta_value = %s", $meta_value);
         }
         $found_user_ids = $wpdb->get_col($meta_sql);
         if (!empty($found_user_ids)) {
             $sql['where'][] = "u.{$this->uid_name} IN (" . implode(',', wp_parse_id_list($found_user_ids)) . ")";
         } else {
             $sql['where'][] = '1 = 0';
         }
     }
     // 'per_page', 'page' - handles LIMIT.
     if (!empty($per_page) && !empty($page)) {
         $sql['limit'] = $wpdb->prepare("LIMIT %d, %d", intval(($page - 1) * $per_page), intval($per_page));
     } else {
         $sql['limit'] = '';
     }
     /**
      * Filters the clauses for the user query.
      *
      * @since 2.0.0
      *
      * @param array         $sql  Array of SQL clauses to be used in the query.
      * @param BP_User_Query $this Current BP_User_Query instance.
      */
     $sql = apply_filters_ref_array('bp_user_query_uid_clauses', array($sql, &$this));
     // Assemble the query chunks.
     $this->uid_clauses['select'] = $sql['select'];
     $this->uid_clauses['where'] = !empty($sql['where']) ? 'WHERE ' . implode(' AND ', $sql['where']) : '';
     $this->uid_clauses['orderby'] = $sql['orderby'];
     $this->uid_clauses['order'] = $sql['order'];
     $this->uid_clauses['limit'] = $sql['limit'];
     /**
      * Fires before the BP_User_Query query is made.
      *
      * @since 1.7.0
      *
      * @param BP_User_Query $this Current BP_User_Query instance. Passed by reference.
      */
     do_action_ref_array('bp_pre_user_query', array(&$this));
 }
Example #28
0
function friends_get_newest($user_id, $pag_num = false, $pag_page = false, $filter = false)
{
    if ($filter) {
        $friend_ids = friends_search_friends($filter, $user_id, false);
    } else {
        $friend_ids = friends_get_friend_user_ids($user_id);
    }
    if (!$friend_ids) {
        return false;
    }
    if ($filter) {
        $friend_ids = $friend_ids['friends'];
    }
    $total_friends = count($friend_ids);
    if ($pag_num && $pag_page) {
        return array('friends' => array_slice($friend_ids, intval(($pag_page - 1) * $pag_num), intval($pag_num)), 'total' => $total_friends);
    } else {
        return array('friends' => $friend_ids, 'total' => $total_friends);
    }
}
Example #29
0
function bp_get_friend_ids($user_id = 0)
{
    global $bp;
    if (!$user_id) {
        $user_id = $bp->displayed_user->id ? $bp->displayed_user->id : $bp->loggedin_user->id;
    }
    $friend_ids = friends_get_friend_user_ids($user_id);
    if (empty($friend_ids)) {
        return false;
    }
    return implode(',', friends_get_friend_user_ids($user_id));
}
 /**
  * GET FEED ACTIVITES
  */
 function get_feed_activities($page = 0, $per_page = 20)
 {
     global $bp, $wpdb, $buddyboss_ajax_qs;
     $min = $page > 0 ? ($page - 1) * $per_page : 0;
     $max = ($page + 1) * $per_page;
     $per_page = bp_get_activity_per_page();
     buddyboss_log("per page: {$per_page}");
     if (isset($bp->loggedin_user) && isset($bp->loggedin_user->id) && $bp->displayed_user->id == $bp->loggedin_user->id) {
         $myprofile = true;
     } else {
         $myprofile = false;
     }
     $wpdb->show_errors = BUDDYBOSS_DEBUG;
     $user_id = $bp->displayed_user->id;
     $user_name = $bp->displayed_user->userdata->user_login;
     $filter = $bp->displayed_user->domain;
     buddyboss_log("Looking at {$user_id}");
     // Get friend's user IDs
     $user_ids = friends_get_friend_user_ids($user_id, false, false);
     // Add logged in user to news feed results
     // $user_ids[] = $user_id;
     $user_list = implode(',', $user_ids);
     // buddyboss_log( $friend_id_list );
     $table = bp_core_get_table_prefix() . 'bp_activity';
     $table2 = bp_core_get_table_prefix() . 'bp_activity_meta';
     // Default WHERE
     $where = "WHERE ( {$table}.user_id IN ({$user_list}) AND {$table}.type != 'activity_comment' )";
     // Add when user joined a group
     $group_modifier = "OR ( {$table}.user_id = {$user_id} AND {$table}.component = 'groups' ) ";
     // If we have a filter enabled, let's handle that
     $ajax_qs = !empty($buddyboss_ajax_qs) ? wp_parse_args($buddyboss_ajax_qs) : false;
     if (is_array($ajax_qs) && isset($ajax_qs['action'])) {
         // Clear group modifier
         $group_modifier = '';
         $filter_qs = $ajax_qs['action'];
         // Check for commas and adjust
         if (strpos($filter_qs, ',')) {
             $filters = explode(',', $filter_qs);
         } else {
             $filters = (array) $filter_qs;
         }
         // Clean each filter
         $filters_clean = array();
         foreach ($filters as $filter) {
             $filters_clean[] = $wpdb->escape($filter);
         }
         $filter_sql = "AND ( {$table}.type='" . implode("' OR {$table}.type='", $filters_clean) . "' )";
         $where = "WHERE ( {$table}.user_id IN ({$user_list}) {$filter_sql} )";
     }
     // Filter where SQL
     $where_filtered = apply_filters('buddyboss_wall_query_feed_activity_ids_where', $where);
     // Filter modifier SQL
     $group_filtered = apply_filters('buddyboss_wall_query_feed_activity_ids_groups', $group_modifier);
     // Build Query
     $query_sql = "SELECT DISTINCT {$table}.id FROM {$table} LEFT JOIN {$table2} ON {$table}.id = {$table2}.activity_id\n\t\t\t{$where_filtered}\n\t\t\t{$group_filtered}\n\t\t\tORDER BY date_recorded DESC LIMIT {$min}, 40";
     // Filter full query SQL
     $query_filtered = apply_filters('buddyboss_wall_query_feed_activity_ids_full', $query_sql);
     // Run query
     $activities = $wpdb->get_results($query_filtered, ARRAY_A);
     buddyboss_log($query_filtered);
     buddyboss_log($activities);
     if (empty($activities)) {
         return null;
     }
     $tmp = array();
     foreach ($activities as $a) {
         $tmp[] = $a["id"];
     }
     $activity_list = implode(",", $tmp);
     return $activity_list;
 }