[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-core/classes/ -> class-bp-core-user.php (source)

   1  <?php
   2  /**
   3   * Core component classes.
   4   *
   5   * @package BuddyPress
   6   * @subpackage Core
   7   * @since 1.0.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * Fetch data about a BuddyPress user.
  15   *
  16   * BP_Core_User class can be used by any component. It will fetch useful
  17   * details for any user when provided with a user_id.
  18   *
  19   * Example:
  20   *    $user = new BP_Core_User( $user_id );
  21   *    $user_avatar = $user->avatar;
  22   *    $user_email = $user->email;
  23   *    $user_status = $user->status;
  24   *    etc.
  25   */
  26  class BP_Core_User {
  27  
  28      /**
  29       * ID of the user which the object relates to.
  30       *
  31       * @var integer
  32       */
  33      public $id;
  34  
  35      /**
  36       * The URL to the full size of the avatar for the user.
  37       *
  38       * @var string
  39       */
  40      public $avatar;
  41  
  42      /**
  43       * The URL to the thumb size of the avatar for the user.
  44       *
  45       * @var string
  46       */
  47      public $avatar_thumb;
  48  
  49      /**
  50       * The URL to the mini size of the avatar for the user.
  51       *
  52       * @var string
  53       */
  54      public $avatar_mini;
  55  
  56      /**
  57       * The full name of the user.
  58       *
  59       * @var string
  60       */
  61      public $fullname;
  62  
  63      /**
  64       * The email for the user.
  65       *
  66       * @var string
  67       */
  68      public $email;
  69  
  70      /**
  71       * The absolute url for the user's profile.
  72       *
  73       * @var string
  74       */
  75      public $user_url;
  76  
  77      /**
  78       * The HTML for the user link, with the link text being the user's full name.
  79       *
  80       * @var string
  81       */
  82      public $user_link;
  83  
  84      /**
  85       * Contains a formatted string when the last time the user was active.
  86       *
  87       * Example: "active 2 hours and 50 minutes ago"
  88       *
  89       * @var string
  90       */
  91      public $last_active;
  92  
  93      /* Extras */
  94  
  95      /**
  96       * The total number of "Friends" the user has on site.
  97       *
  98       * @var integer
  99       */
 100      public $total_friends;
 101  
 102      /**
 103       * The total number of blog posts posted by the user.
 104       *
 105       * @var integer
 106       * @deprecated No longer used
 107       */
 108      public $total_blogs;
 109  
 110      /**
 111       * The total number of groups the user is a part of.
 112       *
 113       * Example: "1 group", "2 groups"
 114       *
 115       * @var string
 116       */
 117      public $total_groups;
 118  
 119      /**
 120       * Profile information for the specific user.
 121       *
 122       * @since 1.2.0
 123       * @var array
 124       */
 125      public $profile_data;
 126  
 127      /** Public Methods *******************************************************/
 128  
 129      /**
 130       * Class constructor.
 131       *
 132       * @param integer $user_id         The ID for the user being queried.
 133       * @param bool    $populate_extras Whether to fetch extra information such as
 134       *                                 group/friendship counts or not. Default: false.
 135       */
 136  	public function __construct( $user_id, $populate_extras = false ) {
 137          if ( !empty( $user_id ) ) {
 138              $this->id = $user_id;
 139              $this->populate();
 140  
 141              if ( !empty( $populate_extras ) ) {
 142                  $this->populate_extras();
 143              }
 144          }
 145      }
 146  
 147      /**
 148       * Populate the instantiated class with data based on the User ID provided.
 149       */
 150  	public function populate() {
 151  
 152          if ( bp_is_active( 'xprofile' ) )
 153              $this->profile_data = $this->get_profile_data();
 154  
 155          if ( !empty( $this->profile_data ) ) {
 156              $full_name_field_name = bp_xprofile_fullname_field_name();
 157  
 158              $this->user_url  = bp_core_get_user_domain( $this->id, $this->profile_data['user_nicename'], $this->profile_data['user_login'] );
 159              $this->fullname  = esc_attr( $this->profile_data[$full_name_field_name]['field_data'] );
 160              $this->user_link = "<a href='{$this->user_url}'>{$this->fullname}</a>";
 161              $this->email     = esc_attr( $this->profile_data['user_email'] );
 162          } else {
 163              $this->user_url  = bp_core_get_user_domain( $this->id );
 164              $this->user_link = bp_core_get_userlink( $this->id );
 165              $this->fullname  = esc_attr( bp_core_get_user_displayname( $this->id ) );
 166              $this->email     = esc_attr( bp_core_get_user_email( $this->id ) );
 167          }
 168  
 169          $this->avatar = bp_core_fetch_avatar(
 170              array(
 171                  'item_id' => $this->id,
 172                  'type'    => 'full',
 173                  'alt'     => sprintf(
 174                      /* translators: %s: member name */
 175                      __( 'Profile photo of %s', 'buddypress' ),
 176                      $this->fullname
 177                  )
 178              )
 179          );
 180  
 181          $this->avatar_thumb = bp_core_fetch_avatar(
 182              array(
 183                  'item_id' => $this->id,
 184                  'type'    => 'thumb',
 185                  'alt'     => sprintf(
 186                      /* translators: %s: member name */
 187                      __( 'Profile photo of %s', 'buddypress' ),
 188                      $this->fullname
 189                  )
 190              )
 191          );
 192  
 193          $this->avatar_mini = bp_core_fetch_avatar(
 194              array(
 195                  'item_id' => $this->id,
 196                  'type'    => 'thumb',
 197                  'alt'     => sprintf(
 198                      /* translators: %s: member name */
 199                      __( 'Profile photo of %s', 'buddypress' ),
 200                      $this->fullname
 201                  ),
 202                  'width'   => 30,
 203                  'height'  => 30
 204              )
 205          );
 206  
 207          /* translators: %s: human time diff of the last time the user was active on the site. */
 208          $this->last_active = bp_core_get_last_activity( bp_get_user_last_activity( $this->id ), _x( 'active %s', 'last time the user was active', 'buddypress' ) );
 209      }
 210  
 211      /**
 212       * Populates extra fields such as group and friendship counts.
 213       */
 214  	public function populate_extras() {
 215  
 216          if ( bp_is_active( 'friends' ) ) {
 217              $this->total_friends = BP_Friends_Friendship::total_friend_count( $this->id );
 218          }
 219  
 220          if ( bp_is_active( 'groups' ) ) {
 221              $this->total_groups = BP_Groups_Member::total_group_count( $this->id );
 222              $this->total_groups = sprintf(
 223                  /* translators: %s: total groups count */
 224                  _n( '%d group', '%d groups', $this->total_groups, 'buddypress' ),
 225                  $this->total_groups
 226              );
 227          }
 228      }
 229  
 230      /**
 231       * Fetch xprofile data for the current user.
 232       *
 233       * @see BP_XProfile_ProfileData::get_all_for_user() for description of
 234       *      return value.
 235       *
 236       * @return array See {@link BP_XProfile_Profile_Data::get_all_for_user()}.
 237       */
 238  	public function get_profile_data() {
 239          return BP_XProfile_ProfileData::get_all_for_user( $this->id );
 240      }
 241  
 242      /** Static Methods ********************************************************/
 243  
 244      /**
 245       * Get a list of users that match the query parameters.
 246       *
 247       * Since BuddyPress 1.7, use {@link BP_User_Query} instead.
 248       *
 249       * @deprecated 1.7.0 Use {@link BP_User_Query}.
 250       *
 251       * @see BP_User_Query for a description of parameters, most of which
 252       *      are used there in the same way.
 253       *
 254       * @param string      $type            See {@link BP_User_Query}.
 255       * @param int         $limit           See {@link BP_User_Query}. Default: 0.
 256       * @param int         $page            See {@link BP_User_Query}. Default: 1.
 257       * @param int         $user_id         See {@link BP_User_Query}. Default: 0.
 258       * @param mixed       $include         See {@link BP_User_Query}. Default: false.
 259       * @param string|bool $search_terms    See {@link BP_User_Query}.
 260       *                                     Default: false.
 261       * @param bool        $populate_extras See {@link BP_User_Query}.
 262       *                                     Default: true.
 263       * @param mixed       $exclude         See {@link BP_User_Query}. Default: false.
 264       * @param string|bool $meta_key        See {@link BP_User_Query}.
 265       *                                     Default: false.
 266       * @param string|bool $meta_value      See {@link BP_User_Query}.
 267       *                                     Default: false.
 268       * @return false|array {
 269       *     @type int   $total_users Total number of users matched by query
 270       *                              params.
 271       *     @type array $paged_users The current page of users matched by
 272       *                              query params.
 273       * }
 274       */
 275  	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 ) {
 276          global $wpdb;
 277  
 278          _deprecated_function( __METHOD__, '1.7', 'BP_User_Query' );
 279  
 280          $bp = buddypress();
 281  
 282          $sql = array();
 283  
 284          $sql['select_main'] = "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.display_name, u.user_email";
 285  
 286          if ( 'active' == $type || 'online' == $type || 'newest' == $type  ) {
 287              $sql['select_active'] = ", um.meta_value as last_activity";
 288          }
 289  
 290          if ( 'popular' == $type ) {
 291              $sql['select_popular'] = ", um.meta_value as total_friend_count";
 292          }
 293  
 294          if ( 'alphabetical' == $type ) {
 295              $sql['select_alpha'] = ", pd.value as fullname";
 296          }
 297  
 298          if ( $meta_key ) {
 299              $sql['select_meta'] = ", umm.meta_key";
 300  
 301              if ( $meta_value ) {
 302                  $sql['select_meta'] .= ", umm.meta_value";
 303              }
 304          }
 305  
 306          $sql['from'] = "FROM {$wpdb->users} u LEFT JOIN {$wpdb->usermeta} um ON um.user_id = u.ID";
 307  
 308          // We search against xprofile fields, so we must join the table.
 309          if ( $search_terms && bp_is_active( 'xprofile' ) ) {
 310              $sql['join_profiledata_search'] = "LEFT JOIN {$bp->profile->table_name_data} spd ON u.ID = spd.user_id";
 311          }
 312  
 313          // Alphabetical sorting is done by the xprofile Full Name field.
 314          if ( 'alphabetical' == $type ) {
 315              $sql['join_profiledata_alpha'] = "LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id";
 316          }
 317  
 318          if ( $meta_key ) {
 319              $sql['join_meta'] = "LEFT JOIN {$wpdb->usermeta} umm ON umm.user_id = u.ID";
 320          }
 321  
 322          $sql['where'] = 'WHERE ' . bp_core_get_status_sql( 'u.' );
 323  
 324          if ( 'active' == $type || 'online' == $type || 'newest' == $type ) {
 325              $sql['where_active'] = $wpdb->prepare( "AND um.meta_key = %s", bp_get_user_meta_key( 'last_activity' ) );
 326          }
 327  
 328          if ( 'popular' == $type ) {
 329              $sql['where_popular'] = $wpdb->prepare( "AND um.meta_key = %s", bp_get_user_meta_key( 'total_friend_count' ) );
 330          }
 331  
 332          if ( 'online' == $type ) {
 333              $sql['where_online'] = "AND DATE_ADD( um.meta_value, INTERVAL 5 MINUTE ) >= UTC_TIMESTAMP()";
 334          }
 335  
 336          if ( 'alphabetical' == $type ) {
 337              $sql['where_alpha'] = "AND pd.field_id = 1";
 338          }
 339  
 340          if ( !empty( $exclude ) ) {
 341              $exclude              = implode( ',', wp_parse_id_list( $exclude ) );
 342              $sql['where_exclude'] = "AND u.ID NOT IN ({$exclude})";
 343          }
 344  
 345          // Passing an $include value of 0 or '0' will necessarily result in an empty set
 346          // returned. The default value of false will hit the 'else' clause.
 347          if ( 0 === $include || '0' === $include ) {
 348              $sql['where_users'] = "AND 0 = 1";
 349          } else {
 350              if ( !empty( $include ) ) {
 351                  $include = implode( ',',  wp_parse_id_list( $include ) );
 352                  $sql['where_users'] = "AND u.ID IN ({$include})";
 353              } elseif ( !empty( $user_id ) && bp_is_active( 'friends' ) ) {
 354                  $friend_ids = friends_get_friend_user_ids( $user_id );
 355  
 356                  if ( !empty( $friend_ids ) ) {
 357                      $friend_ids = implode( ',', wp_parse_id_list( $friend_ids ) );
 358                      $sql['where_friends'] = "AND u.ID IN ({$friend_ids})";
 359  
 360                  // User has no friends, return false since there will be no users to fetch.
 361                  } else {
 362                      return false;
 363                  }
 364              }
 365          }
 366  
 367          if ( !empty( $search_terms ) && bp_is_active( 'xprofile' ) ) {
 368              $search_terms_like        = '%' . bp_esc_like( $search_terms ) . '%';
 369              $sql['where_searchterms'] = $wpdb->prepare( "AND spd.value LIKE %s", $search_terms_like );
 370          }
 371  
 372          if ( !empty( $meta_key ) ) {
 373              $sql['where_meta'] = $wpdb->prepare( " AND umm.meta_key = %s", $meta_key );
 374  
 375              // If a meta value is provided, match it.
 376              if ( $meta_value ) {
 377                  $sql['where_meta'] .= $wpdb->prepare( " AND umm.meta_value = %s", $meta_value );
 378              }
 379          }
 380  
 381          switch ( $type ) {
 382              case 'active': case 'online': default:
 383                  $sql[] = "ORDER BY um.meta_value DESC";
 384                  break;
 385              case 'newest':
 386                  $sql[] = "ORDER BY u.ID DESC";
 387                  break;
 388              case 'alphabetical':
 389                  $sql[] = "ORDER BY pd.value ASC";
 390                  break;
 391              case 'random':
 392                  $sql[] = "ORDER BY rand()";
 393                  break;
 394              case 'popular':
 395                  $sql[] = "ORDER BY CONVERT(um.meta_value, SIGNED) DESC";
 396                  break;
 397          }
 398  
 399          if ( !empty( $limit ) && !empty( $page ) ) {
 400              $sql['pagination'] = $wpdb->prepare( "LIMIT %d, %d", intval( ( $page - 1 ) * $limit), intval( $limit ) );
 401          }
 402  
 403          /**
 404           * Filters the SQL used to query for paged users.
 405           *
 406           * @since 1.2.6
 407           *
 408           * @param string $value Concatenated SQL statement for the query.
 409           * @param array  $sql   Array of SQL statement parts for the query.
 410           */
 411          $paged_users_sql = apply_filters( 'bp_core_get_paged_users_sql', join( ' ', (array) $sql ), $sql );
 412          $paged_users     = $wpdb->get_results( $paged_users_sql );
 413  
 414          // Re-jig the SQL so we can get the total user count.
 415          unset( $sql['select_main'] );
 416  
 417          if ( !empty( $sql['select_active'] ) ) {
 418              unset( $sql['select_active'] );
 419          }
 420  
 421          if ( !empty( $sql['select_popular'] ) ) {
 422              unset( $sql['select_popular'] );
 423          }
 424  
 425          if ( !empty( $sql['select_alpha'] ) ) {
 426              unset( $sql['select_alpha'] );
 427          }
 428  
 429          if ( !empty( $sql['pagination'] ) ) {
 430              unset( $sql['pagination'] );
 431          }
 432  
 433          array_unshift( $sql, "SELECT COUNT(u.ID)" );
 434  
 435          /**
 436           * Filters the SQL used to query for total users.
 437           *
 438           * @since 1.2.6
 439           *
 440           * @param string $value Concatenated SQL statement for the query.
 441           * @param array  $sql   Array of SQL statement parts for the query.
 442           */
 443          $total_users_sql = apply_filters( 'bp_core_get_total_users_sql', join( ' ', (array) $sql ), $sql );
 444          $total_users     = $wpdb->get_var( $total_users_sql );
 445  
 446          /**
 447           * Lets fetch some other useful data in a separate queries, this will be faster than querying the data for every user in a list.
 448           * 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).
 449           */
 450          if ( !empty( $populate_extras ) ) {
 451              $user_ids = array();
 452  
 453              foreach ( (array) $paged_users as $user ) {
 454                  $user_ids[] = $user->id;
 455              }
 456  
 457              // Add additional data to the returned results.
 458              $paged_users = BP_Core_User::get_user_extras( $paged_users, $user_ids, $type );
 459          }
 460  
 461          return array( 'users' => $paged_users, 'total' => $total_users );
 462      }
 463  
 464  
 465      /**
 466       * Fetch the details for all users whose usernames start with the given letter.
 467       *
 468       * @global wpdb $wpdb WordPress database object.
 469       *
 470       * @param string   $letter          The letter the users names are to start with.
 471       * @param int|null $limit           The number of users we wish to retrive.
 472       * @param int      $page            The page number we are currently on, used in conjunction
 473       *                                  with $limit to get the start position for the limit.
 474       * @param bool     $populate_extras If we should populate extra user fields.
 475       * @param string   $exclude         Comma-separated IDs of users whose results
 476       *                                  aren't to be fetched.
 477       * @return false|array False on error, otherwise associative array of results.
 478       */
 479  	public static function get_users_by_letter( $letter, $limit = null, $page = 1, $populate_extras = true, $exclude = '' ) {
 480          global $wpdb;
 481  
 482          $pag_sql = '';
 483          if ( $limit && $page ) {
 484              $pag_sql = $wpdb->prepare( " LIMIT %d, %d", intval( ( $page - 1 ) * $limit), intval( $limit ) );
 485          }
 486  
 487          // Multibyte compliance.
 488          if ( function_exists( 'mb_strlen' ) ) {
 489              if ( mb_strlen( $letter, 'UTF-8' ) > 1 || is_numeric( $letter ) || !$letter ) {
 490                  return false;
 491              }
 492          } else {
 493              if ( strlen( $letter ) > 1 || is_numeric( $letter ) || !$letter ) {
 494                  return false;
 495              }
 496          }
 497  
 498          $bp = buddypress();
 499  
 500          $letter_like = bp_esc_like( $letter ) . '%';
 501          $status_sql  = bp_core_get_status_sql( 'u.' );
 502  
 503          if ( !empty( $exclude ) ) {
 504              $exclude     = implode( ',', wp_parse_id_list( $exclude ) );
 505              $exclude_sql = " AND u.id NOT IN ({$exclude})";
 506          } else {
 507              $exclude_sql = '';
 508          }
 509  
 510          /**
 511           * Filters the SQL used to query for total user count by first letter.
 512           *
 513           * @since 1.0.0
 514           *
 515           * @param string $value SQL prepared statement for the user count query.
 516           */
 517          $total_users_sql = apply_filters( 'bp_core_users_by_letter_count_sql', $wpdb->prepare( "SELECT COUNT(DISTINCT u.ID) FROM {$wpdb->users} u LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id LEFT JOIN {$bp->profile->table_name_fields} pf ON pd.field_id = pf.id WHERE {$status_sql} AND pf.name = %s {$exclude_sql} AND pd.value LIKE %s ORDER BY pd.value ASC", bp_xprofile_fullname_field_name(), $letter_like ) );
 518  
 519          /**
 520           * Filters the SQL used to query for users by first letter.
 521           *
 522           * @since 1.0.0
 523           *
 524           * @param string $value SQL prepared statement for the user query.
 525           */
 526          $paged_users_sql = apply_filters( 'bp_core_users_by_letter_sql',       $wpdb->prepare( "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.user_email FROM {$wpdb->users} u LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id LEFT JOIN {$bp->profile->table_name_fields} pf ON pd.field_id = pf.id WHERE {$status_sql} AND pf.name = %s {$exclude_sql} AND pd.value LIKE %s ORDER BY pd.value ASC{$pag_sql}", bp_xprofile_fullname_field_name(), $letter_like ) );
 527  
 528          $total_users = $wpdb->get_var( $total_users_sql );
 529          $paged_users = $wpdb->get_results( $paged_users_sql );
 530  
 531          /**
 532           * Lets fetch some other useful data in a separate queries, this will be
 533           * faster than querying the data for every user in a list. We can't add
 534           * these to the main query above since only users who have this
 535           * information will be returned (since the much of the data is in
 536           * usermeta and won't support any type of directional join)
 537           */
 538          $user_ids = array();
 539          foreach ( (array) $paged_users as $user )
 540              $user_ids[] = (int) $user->id;
 541  
 542          // Add additional data to the returned results.
 543          if ( $populate_extras ) {
 544              $paged_users = BP_Core_User::get_user_extras( $paged_users, $user_ids );
 545          }
 546  
 547          return array( 'users' => $paged_users, 'total' => $total_users );
 548      }
 549  
 550      /**
 551       * Get details of specific users from the database.
 552       *
 553       * Use {@link BP_User_Query} with the 'user_ids' param instead.
 554       *
 555       * @global wpdb $wpdb WordPress database object.
 556       *
 557       * @param array    $user_ids        The user IDs of the users who we wish to
 558       *                                  fetch information on.
 559       * @param int|null $limit           The limit of results we want.
 560       * @param int      $page            The page we are on for pagination.
 561       * @param bool     $populate_extras If we should populate extra user fields.
 562       * @return array Associative array.
 563       */
 564  	public static function get_specific_users( $user_ids, $limit = null, $page = 1, $populate_extras = true ) {
 565          global $wpdb;
 566  
 567          $pag_sql = '';
 568          if ( $limit && $page )
 569              $pag_sql = $wpdb->prepare( " LIMIT %d, %d", intval( ( $page - 1 ) * $limit), intval( $limit ) );
 570  
 571          $user_ids   = implode( ',', wp_parse_id_list( $user_ids ) );
 572          $status_sql = bp_core_get_status_sql();
 573  
 574          /**
 575           * Filter the SQL string used for querying specific user count.
 576           *
 577           * This same filter name is used for the paged user SQL, and so should be avoided.
 578           * Use 'bp_core_user_get_specific_users_count_sql' instead.
 579           *
 580           * @deprecated 2.3.0
 581           *
 582           * @param string $sql SQL string.
 583           */
 584          $total_users_sql = apply_filters( 'bp_core_get_specific_users_count_sql', "SELECT COUNT(ID) FROM {$wpdb->users} WHERE {$status_sql} AND ID IN ({$user_ids})" );
 585  
 586          /**
 587           * Filter the SQL string used for querying specific user count results.
 588           *
 589           * Use this instead of the deprecated 'bp_core_get_specific_users_count_sql'.
 590           *
 591           * @since 2.3.0
 592           *
 593           * @param string   $sql             SQL string.
 594           * @param array    $user_ids        Array of IDs of specific users to fetch.
 595           * @param int|null $limit           Max number of records to return. Null for no limit.
 596           * @param int      $page            The page we're on for pagination.
 597           * @param bool     $populate_extras Whether to populate extra user fields.
 598           */
 599          $total_users_sql = apply_filters( 'bp_core_user_get_specific_users_count_sql', $total_users_sql, $user_ids, $limit, $page, $populate_extras );
 600  
 601          /**
 602           * Filter the SQL string used for querying specific user paged results.
 603           *
 604           * This same filter name is used for the user count SQL, and so should be avoided.
 605           * Use 'bp_core_user_get_specific_users_paged_sql' instead.
 606           *
 607           * @deprecated 2.3.0
 608           *
 609           * @param string $sql SQL string.
 610           */
 611          $paged_users_sql = apply_filters( 'bp_core_get_specific_users_count_sql', "SELECT ID as id, user_registered, user_nicename, user_login, user_email FROM {$wpdb->users} WHERE {$status_sql} AND ID IN ({$user_ids}) {$pag_sql}" );
 612  
 613          /**
 614           * Filter the SQL string used for querying specific user paged results.
 615           *
 616           * Use this instead of the deprecated 'bp_core_get_specific_users_count_sql'.
 617           *
 618           * @since 2.3.0
 619           *
 620           * @param string   $sql             SQL string.
 621           * @param array    $user_ids        Array of IDs of specific users to fetch.
 622           * @param int|null $limit           Max number of records to return. Null for no limit.
 623           * @param int      $page            The page we're on for pagination.
 624           * @param bool     $populate_extras Whether to populate extra user fields.
 625           */
 626          $paged_users_sql = apply_filters( 'bp_core_user_get_specific_users_paged_sql', $paged_users_sql, $user_ids, $limit, $page, $populate_extras );
 627  
 628          $total_users = $wpdb->get_var( $total_users_sql );
 629          $paged_users = $wpdb->get_results( $paged_users_sql );
 630  
 631          /**
 632           * Lets fetch some other useful data in a separate queries, this will be
 633           * faster than querying the data for every user in a list. We can't add
 634           * these to the main query above since only users who have this
 635           * information will be returned (since the much of the data is in
 636           * usermeta and won't support any type of directional join)
 637           */
 638  
 639          // Add additional data to the returned results.
 640          if ( !empty( $populate_extras ) ) {
 641              $paged_users = BP_Core_User::get_user_extras( $paged_users, $user_ids );
 642          }
 643  
 644          return array( 'users' => $paged_users, 'total' => $total_users );
 645      }
 646  
 647      /**
 648       * Find users who match on the value of an xprofile data.
 649       *
 650       * @global wpdb $wpdb WordPress database object.
 651       *
 652       * @param string   $search_terms    The terms to search the profile table
 653       *                                  value column for.
 654       * @param int|null $limit           The limit of results we want.
 655       * @param int      $page            The page we are on for pagination.
 656       * @param boolean  $populate_extras If we should populate extra user fields.
 657       * @return array Associative array.
 658       */
 659  	public static function search_users( $search_terms, $limit = null, $page = 1, $populate_extras = true ) {
 660          global $wpdb;
 661  
 662          $bp = buddypress();
 663  
 664          $user_ids = array();
 665          $pag_sql  = $limit && $page ? $wpdb->prepare( " LIMIT %d, %d", intval( ( $page - 1 ) * intval( $limit ) ), intval( $limit ) ) : '';
 666  
 667          $search_terms_like = '%' . bp_esc_like( $search_terms ) . '%';
 668          $status_sql        = bp_core_get_status_sql( 'u.' );
 669  
 670          /**
 671           * Filters the SQL used to query for searched users count.
 672           *
 673           * @since 1.0.0
 674           *
 675           * @param string $value SQL statement for the searched users count query.
 676           */
 677          $total_users_sql = apply_filters( 'bp_core_search_users_count_sql', $wpdb->prepare( "SELECT COUNT(DISTINCT u.ID) as id FROM {$wpdb->users} u LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id WHERE {$status_sql} AND pd.value LIKE %s ORDER BY pd.value ASC", $search_terms_like ), $search_terms );
 678  
 679          /**
 680           * Filters the SQL used to query for searched users.
 681           *
 682           * @since 1.0.0
 683           *
 684           * @param string $value SQL statement for the searched users query.
 685           */
 686          $paged_users_sql = apply_filters( 'bp_core_search_users_sql',       $wpdb->prepare( "SELECT DISTINCT u.ID as id, u.user_registered, u.user_nicename, u.user_login, u.user_email FROM {$wpdb->users} u LEFT JOIN {$bp->profile->table_name_data} pd ON u.ID = pd.user_id WHERE {$status_sql} AND pd.value LIKE %s ORDER BY pd.value ASC{$pag_sql}", $search_terms_like ), $search_terms, $pag_sql );
 687  
 688          $total_users = $wpdb->get_var( $total_users_sql );
 689          $paged_users = $wpdb->get_results( $paged_users_sql );
 690  
 691          /**
 692           * Lets fetch some other useful data in a separate queries, this will be faster than querying the data for every user in a list.
 693           * 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)
 694           */
 695          foreach ( (array) $paged_users as $user )
 696              $user_ids[] = $user->id;
 697  
 698          // Add additional data to the returned results.
 699          if ( $populate_extras )
 700              $paged_users = BP_Core_User::get_user_extras( $paged_users, $user_ids );
 701  
 702          return array( 'users' => $paged_users, 'total' => $total_users );
 703      }
 704  
 705      /**
 706       * Fetch extra user information, such as friend count and last profile update message.
 707       *
 708       * Accepts multiple user IDs to fetch data for.
 709       *
 710       * @global wpdb $wpdb WordPress database object.
 711       *
 712       * @param array       $paged_users An array of stdClass containing the users.
 713       * @param string      $user_ids    The user ids to select information about.
 714       * @param string|bool $type        The type of fields we wish to get.
 715       * @return mixed False on error, otherwise associative array of results.
 716       */
 717  	public static function get_user_extras( &$paged_users, &$user_ids, $type = false ) {
 718          global $wpdb;
 719  
 720          $bp = buddypress();
 721  
 722          if ( empty( $user_ids ) )
 723              return $paged_users;
 724  
 725          // Sanitize user IDs.
 726          $user_ids = implode( ',', wp_parse_id_list( $user_ids ) );
 727  
 728          // Fetch the user's full name.
 729          if ( bp_is_active( 'xprofile' ) && 'alphabetical' != $type ) {
 730              $names = $wpdb->get_results( $wpdb->prepare( "SELECT pd.user_id as id, pd.value as fullname FROM {$bp->profile->table_name_fields} pf, {$bp->profile->table_name_data} pd WHERE pf.id = pd.field_id AND pf.name = %s AND pd.user_id IN ( {$user_ids} )", bp_xprofile_fullname_field_name() ) );
 731              for ( $i = 0, $count = count( $paged_users ); $i < $count; ++$i ) {
 732                  foreach ( (array) $names as $name ) {
 733                      if ( $name->id == $paged_users[$i]->id )
 734                          $paged_users[$i]->fullname = $name->fullname;
 735                  }
 736              }
 737          }
 738  
 739          // Fetch the user's total friend count.
 740          if ( 'popular' != $type ) {
 741              $friend_count = $wpdb->get_results( $wpdb->prepare( "SELECT user_id as id, meta_value as total_friend_count FROM {$wpdb->usermeta} WHERE meta_key = %s AND user_id IN ( {$user_ids} )", bp_get_user_meta_key( 'total_friend_count' ) ) );
 742              for ( $i = 0, $count = count( $paged_users ); $i < $count; ++$i ) {
 743                  foreach ( (array) $friend_count as $fcount ) {
 744                      if ( $fcount->id == $paged_users[$i]->id )
 745                          $paged_users[$i]->total_friend_count = (int) $fcount->total_friend_count;
 746                  }
 747              }
 748          }
 749  
 750          // Fetch whether or not the user is a friend.
 751          if ( bp_is_active( 'friends' ) ) {
 752              $friend_status = $wpdb->get_results( $wpdb->prepare( "SELECT initiator_user_id, friend_user_id, is_confirmed FROM {$bp->friends->table_name} WHERE (initiator_user_id = %d AND friend_user_id IN ( {$user_ids} ) ) OR (initiator_user_id IN ( {$user_ids} ) AND friend_user_id = %d )", bp_loggedin_user_id(), bp_loggedin_user_id() ) );
 753              for ( $i = 0, $count = count( $paged_users ); $i < $count; ++$i ) {
 754                  foreach ( (array) $friend_status as $status ) {
 755                      if ( $status->initiator_user_id == $paged_users[$i]->id || $status->friend_user_id == $paged_users[$i]->id )
 756                          $paged_users[$i]->is_friend = $status->is_confirmed;
 757                  }
 758              }
 759          }
 760  
 761          // Fetch the user's last_activity.
 762          if ( 'active' != $type ) {
 763              $user_activity = $wpdb->get_results( $wpdb->prepare( "SELECT user_id as id, meta_value as last_activity FROM {$wpdb->usermeta} WHERE meta_key = %s AND user_id IN ( {$user_ids} )", bp_get_user_meta_key( 'last_activity' ) ) );
 764              for ( $i = 0, $count = count( $paged_users ); $i < $count; ++$i ) {
 765                  foreach ( (array) $user_activity as $activity ) {
 766                      if ( $activity->id == $paged_users[$i]->id )
 767                          $paged_users[$i]->last_activity = $activity->last_activity;
 768                  }
 769              }
 770          }
 771  
 772          // Fetch the user's latest update.
 773          $user_update = $wpdb->get_results( $wpdb->prepare( "SELECT user_id as id, meta_value as latest_update FROM {$wpdb->usermeta} WHERE meta_key = %s AND user_id IN ( {$user_ids} )", bp_get_user_meta_key( 'bp_latest_update' ) ) );
 774          for ( $i = 0, $count = count( $paged_users ); $i < $count; ++$i ) {
 775              foreach ( (array) $user_update as $update ) {
 776                  if ( $update->id == $paged_users[$i]->id )
 777                      $paged_users[$i]->latest_update = $update->latest_update;
 778              }
 779          }
 780  
 781          return $paged_users;
 782      }
 783  
 784      /**
 785       * Get WordPress user details for a specified user.
 786       *
 787       * @since 3.0.0 Results might be from cache
 788       *
 789       * @param int $user_id User ID.
 790       * @return false|object WP_User if successful, false on failure.
 791       */
 792  	public static function get_core_userdata( $user_id ) {
 793          return WP_User::get_data_by( 'id', $user_id );
 794      }
 795  
 796      /**
 797       * Get last activity data for a user or set of users.
 798       *
 799       * @param int|array $user_id User IDs or multiple user IDs.
 800       * @return false|array
 801       */
 802  	public static function get_last_activity( $user_id ) {
 803          global $wpdb;
 804  
 805          // Sanitize and remove empty values.
 806          $user_ids = array_filter( wp_parse_id_list( $user_id ) );
 807  
 808          if ( empty( $user_ids ) ) {
 809              return false;
 810          }
 811  
 812          $uncached_user_ids = bp_get_non_cached_ids( $user_ids, 'bp_last_activity' );
 813          if ( ! empty( $uncached_user_ids ) ) {
 814              $bp = buddypress();
 815  
 816              $user_ids_sql = implode( ',', $uncached_user_ids );
 817              $user_count   = count( $uncached_user_ids );
 818  
 819              $last_activities = $wpdb->get_results( $wpdb->prepare( "SELECT id, user_id, date_recorded FROM {$bp->members->table_name_last_activity} WHERE component = %s AND type = 'last_activity' AND user_id IN ({$user_ids_sql}) LIMIT {$user_count}", $bp->members->id ) );
 820  
 821              foreach ( $last_activities as $last_activity ) {
 822                  wp_cache_set( $last_activity->user_id, array(
 823                      'user_id'       => $last_activity->user_id,
 824                      'date_recorded' => $last_activity->date_recorded,
 825                      'activity_id'   => $last_activity->id,
 826                  ), 'bp_last_activity' );
 827              }
 828          }
 829  
 830          // Fetch all user data from the cache.
 831          $retval = array();
 832          foreach ( $user_ids as $user_id ) {
 833              $retval[ $user_id ] = wp_cache_get( $user_id, 'bp_last_activity' );
 834  
 835              if ( isset( $retval['user_id'] ) ) {
 836                  $retval[ $user_id ]['user_id']     = (int) $retval[ $user_id ]['user_id'];
 837              }
 838              if ( isset( $retval['activity_id'] ) ) {
 839                  $retval[ $user_id ]['activity_id'] = (int) $retval[ $user_id ]['activity_id'];
 840              }
 841          }
 842  
 843          return $retval;
 844      }
 845  
 846      /**
 847       * Set a user's last_activity value.
 848       *
 849       * Will create a new entry if it does not exist. Otherwise updates the
 850       * existing entry.
 851       *
 852       * @since 2.0.0
 853       *
 854       * @param int    $user_id ID of the user whose last_activity you are updating.
 855       * @param string $time    MySQL-formatted time string.
 856       * @return bool True on success, false on failure.
 857       */
 858  	public static function update_last_activity( $user_id, $time ) {
 859          global $wpdb;
 860  
 861          $table_name = buddypress()->members->table_name_last_activity;
 862  
 863          $activity = self::get_last_activity( $user_id );
 864  
 865          if ( ! empty( $activity[ $user_id ] ) ) {
 866              $updated = $wpdb->update(
 867                  $table_name,
 868  
 869                  // Data to update.
 870                  array(
 871                      'date_recorded' => $time,
 872                  ),
 873  
 874                  // WHERE.
 875                  array(
 876                      'id' => $activity[ $user_id ]['activity_id'],
 877                  ),
 878  
 879                  // Data sanitization format.
 880                  array(
 881                      '%s',
 882                  ),
 883  
 884                  // WHERE sanitization format.
 885                  array(
 886                      '%d',
 887                  )
 888              );
 889  
 890              // Add new date to existing activity entry for caching.
 891              $activity[ $user_id ]['date_recorded'] = $time;
 892  
 893          } else {
 894              $updated = $wpdb->insert(
 895                  $table_name,
 896  
 897                  // Data.
 898                  array(
 899                      'user_id'       => $user_id,
 900                      'component'     => buddypress()->members->id,
 901                      'type'          => 'last_activity',
 902                      'action'        => '',
 903                      'content'       => '',
 904                      'primary_link'  => '',
 905                      'item_id'       => 0,
 906                      'date_recorded' => $time,
 907                  ),
 908  
 909                  // Data sanitization format.
 910                  array(
 911                      '%d',
 912                      '%s',
 913                      '%s',
 914                      '%s',
 915                      '%s',
 916                      '%s',
 917                      '%d',
 918                      '%s',
 919                  )
 920              );
 921  
 922              // Set up activity array for caching.
 923              // View the foreach loop in the get_last_activity() method for format.
 924              $activity = array();
 925              $activity[ $user_id ] = array(
 926                  'user_id'       => $user_id,
 927                  'date_recorded' => $time,
 928                  'activity_id'   => $wpdb->insert_id,
 929              );
 930          }
 931  
 932          // Set cache.
 933          wp_cache_set( $user_id, $activity[ $user_id ], 'bp_last_activity' );
 934  
 935          /**
 936           * Fires when a user's last_activity value has been updated.
 937           *
 938           * @since 2.7.0
 939           *
 940           * @param int    $user_id ID of the user.
 941           * @param string $time    Last activity timestamp, in 'Y-m-d H:i:s' format.
 942           */
 943          do_action( 'bp_core_user_updated_last_activity', $user_id, $time );
 944  
 945          return $updated;
 946      }
 947  
 948      /**
 949       * Delete a user's last_activity value.
 950       *
 951       * @since 2.0.0
 952       *
 953       * @param int $user_id ID of the user whose activity should be deleted.
 954       * @return bool True on success, false on failure or if no last_activity
 955       *              is found for the user.
 956       */
 957  	public static function delete_last_activity( $user_id ) {
 958          global $wpdb;
 959  
 960          $existing = self::get_last_activity( $user_id );
 961  
 962          if ( empty( $existing ) || empty( $existing[ $user_id ]['activity_id'] ) ) {
 963              return false;
 964          }
 965  
 966          $deleted = $wpdb->delete(
 967              buddypress()->members->table_name_last_activity,
 968  
 969              // WHERE.
 970              array(
 971                  'id' => $existing[ $user_id ]['activity_id'],
 972              ),
 973  
 974              // WHERE sanitization format.
 975              array(
 976                  '%s',
 977              )
 978          );
 979  
 980          wp_cache_delete( $user_id, 'bp_last_activity' );
 981  
 982          return $deleted;
 983      }
 984  }


Generated: Tue Aug 11 01:01:35 2020 Cross-referenced by PHPXref 0.7.1