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


Generated: Tue Jul 16 01:01:43 2019 Cross-referenced by PHPXref 0.7.1