[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-members/ -> bp-members-functions.php (source)

   1  <?php
   2  /**
   3   * BuddyPress Member Functions.
   4   *
   5   * Functions specific to the members component.
   6   *
   7   * @package BuddyPress
   8   * @subpackage MembersFunctions
   9   * @since 1.5.0
  10   */
  11  
  12  // Exit if accessed directly.
  13  defined( 'ABSPATH' ) || exit;
  14  
  15  /**
  16   * Check for the existence of a Members directory page.
  17   *
  18   * @since 1.5.0
  19   *
  20   * @return bool True if found, otherwise false.
  21   */
  22  function bp_members_has_directory() {
  23      $bp = buddypress();
  24  
  25      return (bool) !empty( $bp->pages->members->id );
  26  }
  27  
  28  /**
  29   * Define the slug constants for the Members component.
  30   *
  31   * Handles the three slug constants used in the Members component -
  32   * BP_MEMBERS_SLUG, BP_REGISTER_SLUG, and BP_ACTIVATION_SLUG. If these
  33   * constants are not overridden in wp-config.php or bp-custom.php, they are
  34   * defined here to match the slug of the corresponding WP pages.
  35   *
  36   * In general, fallback values are only used during initial BP page creation,
  37   * when no slugs have been explicitly defined.
  38   *
  39   * @since 1.5.0
  40   */
  41  function bp_core_define_slugs() {
  42      $bp = buddypress();
  43  
  44      // No custom members slug.
  45      if ( !defined( 'BP_MEMBERS_SLUG' ) ) {
  46          if ( !empty( $bp->pages->members ) ) {
  47              define( 'BP_MEMBERS_SLUG', $bp->pages->members->slug );
  48          } else {
  49              define( 'BP_MEMBERS_SLUG', 'members' );
  50          }
  51      }
  52  
  53      // No custom registration slug.
  54      if ( !defined( 'BP_REGISTER_SLUG' ) ) {
  55          if ( !empty( $bp->pages->register ) ) {
  56              define( 'BP_REGISTER_SLUG', $bp->pages->register->slug );
  57          } else {
  58              define( 'BP_REGISTER_SLUG', 'register' );
  59          }
  60      }
  61  
  62      // No custom activation slug.
  63      if ( !defined( 'BP_ACTIVATION_SLUG' ) ) {
  64          if ( !empty( $bp->pages->activate ) ) {
  65              define( 'BP_ACTIVATION_SLUG', $bp->pages->activate->slug );
  66          } else {
  67              define( 'BP_ACTIVATION_SLUG', 'activate' );
  68          }
  69      }
  70  }
  71  add_action( 'bp_setup_globals', 'bp_core_define_slugs', 11 );
  72  
  73  /**
  74   * Fetch an array of users based on the parameters passed.
  75   *
  76   * Since BuddyPress 1.7, bp_core_get_users() uses BP_User_Query. If you
  77   * need backward compatibility with BP_Core_User::get_users(), filter the
  78   * bp_use_legacy_user_query value, returning true.
  79   *
  80   * @since 1.2.0
  81   *
  82   * @param array|string $args {
  83   *     Array of arguments. All are optional. See {@link BP_User_Query} for
  84   *     a more complete description of arguments.
  85   *     @type string       $type                Sort order. Default: 'active'.
  86   *     @type int          $user_id             Limit results to friends of a user. Default: false.
  87   *     @type mixed        $exclude             IDs to exclude from results. Default: false.
  88   *     @type string       $search_terms        Limit to users matching search terms. Default: false.
  89   *     @type string       $meta_key            Limit to users with a meta_key. Default: false.
  90   *     @type string       $meta_value          Limit to users with a meta_value (with meta_key). Default: false.
  91   *     @type array|string $member_type         Array or comma-separated string of member types.
  92   *     @type array|string $member_type__in     Array or comma-separated string of member types.
  93   *                                             `$member_type` takes precedence over this parameter.
  94   *     @type array|string $member_type__not_in Array or comma-separated string of member types to be excluded.
  95   *     @type mixed        $include             Limit results by user IDs. Default: false.
  96   *     @type int          $per_page            Results per page. Default: 20.
  97   *     @type int          $page                Page of results. Default: 1.
  98   *     @type bool         $populate_extras     Fetch optional extras. Default: true.
  99   *     @type string|bool  $count_total         How to do total user count. Default: 'count_query'.
 100   * }
 101   * @return array
 102   */
 103  function bp_core_get_users( $args = '' ) {
 104  
 105      // Parse the user query arguments.
 106      $r = bp_parse_args( $args, array(
 107          'type'                => 'active',     // Active, newest, alphabetical, random or popular.
 108          'user_id'             => false,        // Pass a user_id to limit to only friend connections for this user.
 109          'exclude'             => false,        // Users to exclude from results.
 110          'search_terms'        => false,        // Limit to users that match these search terms.
 111          'meta_key'            => false,        // Limit to users who have this piece of usermeta.
 112          'meta_value'          => false,        // With meta_key, limit to users where usermeta matches this value.
 113          'member_type'         => '',
 114          'member_type__in'     => '',
 115          'member_type__not_in' => '',
 116          'include'             => false,        // Pass comma separated list of user_ids to limit to only these users.
 117          'per_page'            => 20,           // The number of results to return per page.
 118          'page'                => 1,            // The page to return if limiting per page.
 119          'populate_extras'     => true,         // Fetch the last active, where the user is a friend, total friend count, latest update.
 120          'count_total'         => 'count_query' // What kind of total user count to do, if any. 'count_query', 'sql_calc_found_rows', or false.
 121      ), 'core_get_users' );
 122  
 123      // For legacy users. Use of BP_Core_User::get_users() is deprecated.
 124      if ( apply_filters( 'bp_use_legacy_user_query', false, __FUNCTION__, $r ) ) {
 125          $retval = BP_Core_User::get_users(
 126              $r['type'],
 127              $r['per_page'],
 128              $r['page'],
 129              $r['user_id'],
 130              $r['include'],
 131              $r['search_terms'],
 132              $r['populate_extras'],
 133              $r['exclude'],
 134              $r['meta_key'],
 135              $r['meta_value']
 136          );
 137  
 138      // Default behavior as of BuddyPress 1.7.0.
 139      } else {
 140  
 141          // Get users like we were asked to do...
 142          $users = new BP_User_Query( $r );
 143  
 144          // ...but reformat the results to match bp_core_get_users() behavior.
 145          $retval = array(
 146              'users' => array_values( $users->results ),
 147              'total' => $users->total_users
 148          );
 149      }
 150  
 151      /**
 152       * Filters the results of the user query.
 153       *
 154       * @since 1.2.0
 155       *
 156       * @param array $retval Array of users for the current query.
 157       * @param array $r      Array of parsed query arguments.
 158       */
 159      return apply_filters( 'bp_core_get_users', $retval, $r );
 160  }
 161  
 162  /**
 163   * Return the domain for the passed user: e.g. http://example.com/members/andy/.
 164   *
 165   * @since 1.0.0
 166   *
 167   * @param int         $user_id       The ID of the user.
 168   * @param string|bool $user_nicename Optional. user_nicename of the user.
 169   * @param string|bool $user_login    Optional. user_login of the user.
 170   * @return string
 171   */
 172  function bp_core_get_user_domain( $user_id = 0, $user_nicename = false, $user_login = false ) {
 173  
 174      if ( empty( $user_id ) ) {
 175          return;
 176      }
 177  
 178      $username = bp_core_get_username( $user_id, $user_nicename, $user_login );
 179  
 180      if ( bp_is_username_compatibility_mode() ) {
 181          $username = rawurlencode( $username );
 182      }
 183  
 184      $after_domain = bp_core_enable_root_profiles() ? $username : bp_get_members_root_slug() . '/' . $username;
 185      $domain       = trailingslashit( bp_get_root_domain() . '/' . $after_domain );
 186  
 187      // Don't use this filter.  Subject to removal in a future release.
 188      // Use the 'bp_core_get_user_domain' filter instead.
 189      $domain       = apply_filters( 'bp_core_get_user_domain_pre_cache', $domain, $user_id, $user_nicename, $user_login );
 190  
 191      /**
 192       * Filters the domain for the passed user.
 193       *
 194       * @since 1.0.1
 195       *
 196       * @param string $domain        Domain for the passed user.
 197       * @param int    $user_id       ID of the passed user.
 198       * @param string $user_nicename User nicename of the passed user.
 199       * @param string $user_login    User login of the passed user.
 200       */
 201      return apply_filters( 'bp_core_get_user_domain', $domain, $user_id, $user_nicename, $user_login );
 202  }
 203  
 204  /**
 205   * Fetch everything in the wp_users table for a user, without any usermeta.
 206   *
 207   * @since 1.2.0
 208   *
 209   * @param  int $user_id The ID of the user.
 210   * @return array|bool Array of data on success, boolean false on failure.
 211   */
 212  function bp_core_get_core_userdata( $user_id = 0 ) {
 213      if ( empty( $user_id ) ) {
 214          return false;
 215      }
 216  
 217      // Get core user data
 218      $userdata = BP_Core_User::get_core_userdata( $user_id );
 219  
 220      /**
 221       * Filters the userdata for a passed user.
 222       *
 223       * @since 1.2.0
 224       *
 225       * @param array|bool $userdata Array of user data for a passed user on success, boolean false on failure.
 226       */
 227      return apply_filters( 'bp_core_get_core_userdata', $userdata );
 228  }
 229  
 230  /**
 231   * Return the ID of a user, based on user_login.
 232   *
 233   * No longer used.
 234   *
 235   * @todo Deprecate.
 236   *
 237   * @param string $user_login user_login of the user being queried.
 238   * @return int
 239   */
 240  function bp_core_get_displayed_userid( $user_login ) {
 241      return apply_filters( 'bp_core_get_displayed_userid', bp_core_get_userid( $user_login ) );
 242  }
 243  
 244  /**
 245   * Return the user ID based on a user's user_login.
 246   *
 247   * @since 1.0.0
 248   *
 249   * @param string $username user_login to check.
 250   * @return int|null The ID of the matched user on success, null on failure.
 251   */
 252  function bp_core_get_userid( $username = '' ) {
 253      if ( empty( $username ) ) {
 254          return false;
 255      }
 256  
 257      $user = get_user_by( 'login', $username );
 258  
 259      /**
 260       * Filters the ID of a user, based on user_login.
 261       *
 262       * @since 1.0.1
 263       *
 264       * @param int|null $value    ID of the user or null.
 265       * @param string   $username User login to check.
 266       */
 267      return apply_filters( 'bp_core_get_userid', ! empty( $user->ID ) ? $user->ID : NULL, $username );
 268  }
 269  
 270  /**
 271   * Return the user ID based on a user's user_nicename.
 272   *
 273   * @since 1.2.3
 274   *
 275   * @param string $user_nicename user_nicename to check.
 276   * @return int|null The ID of the matched user on success, null on failure.
 277   */
 278  function bp_core_get_userid_from_nicename( $user_nicename = '' ) {
 279      if ( empty( $user_nicename ) ) {
 280          return false;
 281      }
 282  
 283      $user = get_user_by( 'slug', $user_nicename );
 284  
 285      /**
 286       * Filters the user ID based on user_nicename.
 287       *
 288       * @since 1.2.3
 289       *
 290       * @param int|null $value         ID of the user or null.
 291       * @param string   $user_nicename User nicename to check.
 292       */
 293      return apply_filters( 'bp_core_get_userid_from_nicename', ! empty( $user->ID ) ? $user->ID : NULL, $user_nicename );
 294  }
 295  
 296  /**
 297   * Return the username for a user based on their user id.
 298   *
 299   * This function is sensitive to the BP_ENABLE_USERNAME_COMPATIBILITY_MODE,
 300   * so it will return the user_login or user_nicename as appropriate.
 301   *
 302   * @since 1.0.0
 303   *
 304   * @param int         $user_id       User ID to check.
 305   * @param string|bool $user_nicename Optional. user_nicename of user being checked.
 306   * @param string|bool $user_login    Optional. user_login of user being checked.
 307   * @return string The username of the matched user or an empty string if no user is found.
 308   */
 309  function bp_core_get_username( $user_id = 0, $user_nicename = false, $user_login = false ) {
 310  
 311      if ( ! $user_nicename && ! $user_login ) {
 312          // Pull an audible and maybe use the login over the nicename.
 313          if ( bp_is_username_compatibility_mode() ) {
 314              $username = get_the_author_meta( 'login', $user_id );
 315          } else {
 316              $username = get_the_author_meta( 'nicename', $user_id );
 317          }
 318      } else {
 319          $username = bp_is_username_compatibility_mode() ? $user_login : $user_nicename;
 320      }
 321  
 322      /**
 323       * Filters the username based on originally provided user ID.
 324       *
 325       * @since 1.0.1
 326       *
 327       * @param string $username Username determined by user ID.
 328       */
 329      return apply_filters( 'bp_core_get_username', $username );
 330  }
 331  
 332  /**
 333   * Return the user_nicename for a user based on their user_id.
 334   *
 335   * This should be used for linking to user profiles and anywhere else a
 336   * sanitized and unique slug to a user is needed.
 337   *
 338   * @since 1.5.0
 339   *
 340   * @param int $user_id User ID to check.
 341   * @return string The username of the matched user or an empty string if no user is found.
 342   */
 343  function bp_members_get_user_nicename( $user_id ) {
 344      /**
 345       * Filters the user_nicename based on originally provided user ID.
 346       *
 347       * @since 1.5.0
 348       *
 349       * @param string $username User nice name determined by user ID.
 350       */
 351      return apply_filters( 'bp_members_get_user_nicename', get_the_author_meta( 'nicename', $user_id ) );
 352  }
 353  
 354  /**
 355   * Return the email address for the user based on user ID.
 356   *
 357   * @since 1.0.0
 358   *
 359   * @param int $uid User ID to check.
 360   * @return string The email for the matched user. Empty string if no user
 361   *                matches the $user_id.
 362   */
 363  function bp_core_get_user_email( $user_id ) {
 364      /**
 365       * Filters the user email for user based on user ID.
 366       *
 367       * @since 1.0.1
 368       *
 369       * @param string $email Email determined for the user.
 370       */
 371      return apply_filters( 'bp_core_get_user_email', get_the_author_meta( 'email', $user_id ) );
 372  }
 373  
 374  /**
 375   * Return a HTML formatted link for a user with the user's full name as the link text.
 376   *
 377   * Eg: <a href="http://andy.example.com/">Andy Peatling</a>
 378   *
 379   * Optional parameters will return just the name or just the URL.
 380   *
 381   * @since 1.0.0
 382   *
 383   * @param int  $user_id   User ID to check.
 384   * @param bool $no_anchor Disable URL and HTML and just return full name.
 385   *                        Default: false.
 386   * @param bool $just_link Disable full name and HTML and just return the URL
 387   *                        text. Default false.
 388   * @return string|bool The link text based on passed parameters, or false on
 389   *                     no match.
 390   */
 391  function bp_core_get_userlink( $user_id, $no_anchor = false, $just_link = false ) {
 392      $display_name = bp_core_get_user_displayname( $user_id );
 393  
 394      if ( empty( $display_name ) ) {
 395          return false;
 396      }
 397  
 398      if ( ! empty( $no_anchor ) ) {
 399          return $display_name;
 400      }
 401  
 402      if ( !$url = bp_core_get_user_domain( $user_id ) ) {
 403          return false;
 404      }
 405  
 406      if ( ! empty( $just_link ) ) {
 407          return $url;
 408      }
 409  
 410      /**
 411       * Filters the link text for the passed in user.
 412       *
 413       * @since 1.2.0
 414       *
 415       * @param string $value   Link text based on passed parameters.
 416       * @param int    $user_id ID of the user to check.
 417       */
 418      return apply_filters( 'bp_core_get_userlink', '<a href="' . esc_url( $url ) . '">' . $display_name . '</a>', $user_id );
 419  }
 420  
 421  /**
 422   * Fetch the display name for a group of users.
 423   *
 424   * Uses the 'Name' field in xprofile if available. Falls back on WP
 425   * display_name, and then user_nicename.
 426   *
 427   * @since 2.0.0
 428   *
 429   * @param array $user_ids Array of user IDs to get display names for.
 430   * @return array Associative array of the format "id" => "displayname".
 431   */
 432  function bp_core_get_user_displaynames( $user_ids ) {
 433  
 434      // Sanitize.
 435      $user_ids = wp_parse_id_list( $user_ids );
 436  
 437      // Remove dupes and empties.
 438      $user_ids = array_unique( array_filter( $user_ids ) );
 439  
 440      if ( empty( $user_ids ) ) {
 441          return array();
 442      }
 443  
 444      // Warm the WP users cache with a targeted bulk update.
 445      cache_users( $user_ids );
 446  
 447      $retval = array();
 448      foreach ( $user_ids as $user_id ) {
 449          $retval[ $user_id ] = bp_core_get_user_displayname( $user_id );
 450      }
 451  
 452      return $retval;
 453  }
 454  
 455  /**
 456   * Fetch the display name for a user.
 457   *
 458   * @since 1.0.1
 459   *
 460   * @param int|string|bool $user_id_or_username User ID or username.
 461   * @return string|bool The display name for the user in question, or false if
 462   *                     user not found.
 463   */
 464  function bp_core_get_user_displayname( $user_id_or_username ) {
 465      if ( empty( $user_id_or_username ) ) {
 466          return false;
 467      }
 468  
 469      if ( ! is_numeric( $user_id_or_username ) ) {
 470          $user_id = bp_core_get_userid( $user_id_or_username );
 471      } else {
 472          $user_id = $user_id_or_username;
 473      }
 474  
 475      if ( empty( $user_id ) ) {
 476          return false;
 477      }
 478  
 479      /**
 480       * Filters the display name for the passed in user.
 481       *
 482       * @since 1.0.1
 483       *
 484       * @param string $fullname Display name for the user.
 485       * @param int    $user_id  ID of the user to check.
 486       */
 487      return apply_filters( 'bp_core_get_user_displayname', get_the_author_meta( 'display_name', $user_id ), $user_id );
 488  }
 489  add_filter( 'bp_core_get_user_displayname', 'strip_tags', 1 );
 490  add_filter( 'bp_core_get_user_displayname', 'trim'          );
 491  add_filter( 'bp_core_get_user_displayname', 'stripslashes'  );
 492  add_filter( 'bp_core_get_user_displayname', 'esc_html'      );
 493  
 494  /**
 495   * Return the user link for the user based on user email address.
 496   *
 497   * @since 1.0.0
 498   *
 499   * @param string $email The email address for the user.
 500   * @return string The link to the users home base. False on no match.
 501   */
 502  function bp_core_get_userlink_by_email( $email ) {
 503      $user = get_user_by( 'email', $email );
 504  
 505      /**
 506       * Filters the user link for the user based on user email address.
 507       *
 508       * @since 1.0.1
 509       *
 510       * @param string|bool $value URL for the user if found, otherwise false.
 511       */
 512      return apply_filters( 'bp_core_get_userlink_by_email', bp_core_get_userlink( $user->ID, false, false, true ) );
 513  }
 514  
 515  /**
 516   * Return the user link for the user based on the supplied identifier.
 517   *
 518   * @since 1.0.0
 519   *
 520   * @param string $username If BP_ENABLE_USERNAME_COMPATIBILITY_MODE is set,
 521   *                         this should be user_login, otherwise it should
 522   *                         be user_nicename.
 523   * @return string|bool The link to the user's domain, false on no match.
 524   */
 525  function bp_core_get_userlink_by_username( $username ) {
 526      if ( bp_is_username_compatibility_mode() ) {
 527          $user_id = bp_core_get_userid( $username );
 528      } else {
 529          $user_id = bp_core_get_userid_from_nicename( $username );
 530      }
 531  
 532      /**
 533       * Filters the user link for the user based on username.
 534       *
 535       * @since 1.0.1
 536       *
 537       * @param string|bool $value URL for the user if found, otherwise false.
 538       */
 539      return apply_filters( 'bp_core_get_userlink_by_username', bp_core_get_userlink( $user_id, false, false, true ) );
 540  }
 541  
 542  /**
 543   * Return the total number of members for the installation.
 544   *
 545   * Note that this is a raw count of non-spam, activated users. It does not
 546   * account for users who have logged activity (last_active). See
 547   * {@link bp_core_get_active_member_count()}.
 548   *
 549   * @since 1.2.0
 550   *
 551   * @return int The total number of members.
 552   */
 553  function bp_core_get_total_member_count() {
 554      global $wpdb;
 555  
 556      $count = wp_cache_get( 'bp_total_member_count', 'bp' );
 557  
 558      if ( false === $count ) {
 559          $status_sql = bp_core_get_status_sql();
 560          $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->users} WHERE {$status_sql}" );
 561          wp_cache_set( 'bp_total_member_count', $count, 'bp' );
 562      }
 563  
 564      /**
 565       * Filters the total number of members for the installation.
 566       *
 567       * @since 1.2.0
 568       *
 569       * @param int $count Total number of members.
 570       */
 571      return apply_filters( 'bp_core_get_total_member_count', $count );
 572  }
 573  
 574  /**
 575   * Return the total number of members, limited to those members with last_activity.
 576   *
 577   * @since 1.6.0
 578   *
 579   * @return int The number of active members.
 580   */
 581  function bp_core_get_active_member_count() {
 582      global $wpdb;
 583  
 584      $count = get_transient( 'bp_active_member_count' );
 585      if ( false === $count ) {
 586          $bp = buddypress();
 587  
 588          // Avoid a costly join by splitting the lookup.
 589          if ( is_multisite() ) {
 590              $sql = "SELECT ID FROM {$wpdb->users} WHERE (user_status != 0 OR deleted != 0 OR user_status != 0)";
 591          } else {
 592              $sql = "SELECT ID FROM {$wpdb->users} WHERE user_status != 0";
 593          }
 594  
 595          $exclude_users     = $wpdb->get_col( $sql );
 596          $exclude_users_sql = !empty( $exclude_users ) ? "AND user_id NOT IN (" . implode( ',', wp_parse_id_list( $exclude_users ) ) . ")" : '';
 597          $count             = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(user_id) FROM {$bp->members->table_name_last_activity} WHERE component = %s AND type = 'last_activity' {$exclude_users_sql}", $bp->members->id ) );
 598  
 599          set_transient( 'bp_active_member_count', $count );
 600      }
 601  
 602      /**
 603       * Filters the total number of members for the installation limited to those with last_activity.
 604       *
 605       * @since 1.6.0
 606       *
 607       * @param int $count Total number of active members.
 608       */
 609      return apply_filters( 'bp_core_get_active_member_count', $count );
 610  }
 611  
 612  /**
 613   * Update the spam status of the member on multisite configs.
 614   *
 615   * @since 5.0.0
 616   *
 617   * @param int   $user_id The user ID to spam or ham.
 618   * @param int   $value   0 to mark the user as `ham`, 1 to mark as `spam`.
 619   * @return bool          True if the spam status of the member changed.
 620   *                       False otherwise.
 621   */
 622  function bp_core_update_member_status( $user_id = 0, $value = 0 ) {
 623      if ( ! is_multisite() || ! $user_id ) {
 624          return false;
 625      }
 626  
 627      /**
 628       * The `update_user_status()` function is deprecated since WordPress 5.3.0.
 629       * Continue to use it if WordPress current major version is lower than 5.3.
 630       */
 631      if ( bp_get_major_wp_version() < 5.3 ) {
 632          return update_user_status( $user_id, 'spam', $value );
 633      }
 634  
 635      // Otherwise use the replacement function.
 636      $user = wp_update_user( array(
 637          'ID'   => $user_id,
 638          'spam' => $value,
 639      ) );
 640  
 641      if ( is_wp_error( $user ) ) {
 642          return false;
 643      }
 644  
 645      return true;
 646  }
 647  
 648  /**
 649   * Process a spammed or unspammed user.
 650   *
 651   * This function is called from three places:
 652   *
 653   * - in bp_settings_action_capabilities() (from the front-end)
 654   * - by bp_core_mark_user_spam_admin()    (from wp-admin)
 655   * - bp_core_mark_user_ham_admin()        (from wp-admin)
 656   *
 657   * @since 1.6.0
 658   *
 659   * @param int    $user_id       The ID of the user being spammed/hammed.
 660   * @param string $status        'spam' if being marked as spam, 'ham' otherwise.
 661   * @param bool   $do_wp_cleanup True to force the cleanup of WordPress content
 662   *                              and status, otherwise false. Generally, this should
 663   *                              only be false if WordPress is expected to have
 664   *                              performed this cleanup independently, as when hooked
 665   *                              to 'make_spam_user'.
 666   * @return bool True on success, false on failure.
 667   */
 668  function bp_core_process_spammer_status( $user_id, $status, $do_wp_cleanup = true ) {
 669      global $wpdb;
 670  
 671      // Bail if no user ID.
 672      if ( empty( $user_id ) ) {
 673          return;
 674      }
 675  
 676      // Bail if user ID is super admin.
 677      if ( is_super_admin( $user_id ) ) {
 678          return;
 679      }
 680  
 681      // Get the functions file.
 682      if ( is_multisite() ) {
 683          require_once( ABSPATH . 'wp-admin/includes/ms.php' );
 684      }
 685  
 686      $is_spam = ( 'spam' == $status );
 687  
 688      // Only you can prevent infinite loops.
 689      remove_action( 'make_spam_user', 'bp_core_mark_user_spam_admin' );
 690      remove_action( 'make_ham_user',  'bp_core_mark_user_ham_admin'  );
 691  
 692      // Force the cleanup of WordPress content and status for multisite configs.
 693      if ( $do_wp_cleanup ) {
 694  
 695          // Get the blogs for the user.
 696          $blogs = get_blogs_of_user( $user_id, true );
 697  
 698          foreach ( (array) array_values( $blogs ) as $details ) {
 699  
 700              // Do not mark the main or current root blog as spam.
 701              if ( 1 == $details->userblog_id || bp_get_root_blog_id() == $details->userblog_id ) {
 702                  continue;
 703              }
 704  
 705              // Update the blog status.
 706              update_blog_status( $details->userblog_id, 'spam', $is_spam );
 707          }
 708  
 709          // Finally, mark this user as a spammer.
 710          bp_core_update_member_status( $user_id, $is_spam );
 711      }
 712  
 713      // Update the user status.
 714      $wpdb->update( $wpdb->users, array( 'user_status' => $is_spam ), array( 'ID' => $user_id ) );
 715  
 716      // Clean user cache.
 717      clean_user_cache( $user_id );
 718  
 719      if ( ! is_multisite() ) {
 720          // Call multisite actions in single site mode for good measure.
 721          if ( true === $is_spam ) {
 722  
 723              /**
 724               * Fires at end of processing spammer in Dashboard if not multisite and user is spam.
 725               *
 726               * @since 1.5.0
 727               *
 728               * @param int $value user ID.
 729               */
 730              do_action( 'make_spam_user', $user_id );
 731          } else {
 732  
 733              /**
 734               * Fires at end of processing spammer in Dashboard if not multisite and user is not spam.
 735               *
 736               * @since 1.5.0
 737               *
 738               * @param int $value user ID.
 739               */
 740              do_action( 'make_ham_user', $user_id );
 741          }
 742      }
 743  
 744      // Hide this user's activity.
 745      if ( ( true === $is_spam ) && bp_is_active( 'activity' ) ) {
 746          bp_activity_hide_user_activity( $user_id );
 747      }
 748  
 749      // We need a special hook for is_spam so that components can delete data at spam time.
 750      if ( true === $is_spam ) {
 751  
 752          /**
 753           * Fires at the end of the process spammer process if the user is spam.
 754           *
 755           * @since 1.5.0
 756           *
 757           * @param int $value Displayed user ID.
 758           */
 759          do_action( 'bp_make_spam_user', $user_id );
 760      } else {
 761  
 762          /**
 763           * Fires at the end of the process spammer process if the user is not spam.
 764           *
 765           * @since 1.5.0
 766           *
 767           * @param int $value Displayed user ID.
 768           */
 769          do_action( 'bp_make_ham_user', $user_id );
 770      }
 771  
 772      /**
 773       * Fires at the end of the process for hanlding spammer status.
 774       *
 775       * @since 1.5.5
 776       *
 777       * @param int  $user_id ID of the processed user.
 778       * @param bool $is_spam The determined spam status of processed user.
 779       */
 780      do_action( 'bp_core_process_spammer_status', $user_id, $is_spam );
 781  
 782      // Put things back how we found them.
 783      add_action( 'make_spam_user', 'bp_core_mark_user_spam_admin' );
 784      add_action( 'make_ham_user',  'bp_core_mark_user_ham_admin'  );
 785  
 786      return true;
 787  }
 788  /**
 789   * Hook to WP's make_spam_user and run our custom BP spam functions.
 790   *
 791   * @since 1.6.0
 792   *
 793   * @param int $user_id The user ID passed from the make_spam_user hook.
 794   */
 795  function bp_core_mark_user_spam_admin( $user_id ) {
 796      bp_core_process_spammer_status( $user_id, 'spam', false );
 797  }
 798  add_action( 'make_spam_user', 'bp_core_mark_user_spam_admin' );
 799  
 800  /**
 801   * Hook to WP's make_ham_user and run our custom BP spam functions.
 802   *
 803   * @since 1.6.0
 804   *
 805   * @param int $user_id The user ID passed from the make_ham_user hook.
 806   */
 807  function bp_core_mark_user_ham_admin( $user_id ) {
 808      bp_core_process_spammer_status( $user_id, 'ham', false );
 809  }
 810  add_action( 'make_ham_user', 'bp_core_mark_user_ham_admin' );
 811  
 812  /**
 813   * Check whether a user has been marked as a spammer.
 814   *
 815   * @since 1.6.0
 816   *
 817   * @param int $user_id The ID for the user.
 818   * @return bool True if spammer, otherwise false.
 819   */
 820  function bp_is_user_spammer( $user_id = 0 ) {
 821  
 822      // No user to check.
 823      if ( empty( $user_id ) ) {
 824          return false;
 825      }
 826  
 827      $bp = buddypress();
 828  
 829      // Assume user is not spam.
 830      $is_spammer = false;
 831  
 832      // Setup our user.
 833      $user = false;
 834  
 835      // Get locally-cached data if available.
 836      switch ( $user_id ) {
 837          case bp_loggedin_user_id() :
 838              $user = ! empty( $bp->loggedin_user->userdata ) ? $bp->loggedin_user->userdata : false;
 839              break;
 840  
 841          case bp_displayed_user_id() :
 842              $user = ! empty( $bp->displayed_user->userdata ) ? $bp->displayed_user->userdata : false;
 843              break;
 844  
 845          case bp_get_member_user_id() :
 846              global $members_template;
 847              $user = isset( $members_template ) && isset( $members_template->member ) ? $members_template->member :  false;
 848              break;
 849      }
 850  
 851      // Manually get userdata if still empty.
 852      if ( empty( $user ) ) {
 853          $user = get_userdata( $user_id );
 854      }
 855  
 856      // No user found.
 857      if ( empty( $user ) ) {
 858          $is_spammer = false;
 859  
 860      // User found.
 861      } else {
 862  
 863          // Check if spam.
 864          if ( !empty( $user->spam ) ) {
 865              $is_spammer = true;
 866          }
 867  
 868          if ( 1 == $user->user_status ) {
 869              $is_spammer = true;
 870          }
 871      }
 872  
 873      /**
 874       * Filters whether a user is marked as a spammer.
 875       *
 876       * @since 1.6.0
 877       *
 878       * @param bool $is_spammer Whether or not user is marked as spammer.
 879       */
 880      return apply_filters( 'bp_is_user_spammer', (bool) $is_spammer );
 881  }
 882  
 883  /**
 884   * Check whether a user has been marked as deleted.
 885   *
 886   * @since 1.6.0
 887   *
 888   * @param int $user_id The ID for the user.
 889   * @return bool True if deleted, otherwise false.
 890   */
 891  function bp_is_user_deleted( $user_id = 0 ) {
 892  
 893      // No user to check.
 894      if ( empty( $user_id ) ) {
 895          return false;
 896      }
 897  
 898      $bp = buddypress();
 899  
 900      // Assume user is not deleted.
 901      $is_deleted = false;
 902  
 903      // Setup our user.
 904      $user = false;
 905  
 906      // Get locally-cached data if available.
 907      switch ( $user_id ) {
 908          case bp_loggedin_user_id() :
 909              $user = ! empty( $bp->loggedin_user->userdata ) ? $bp->loggedin_user->userdata : false;
 910              break;
 911  
 912          case bp_displayed_user_id() :
 913              $user = ! empty( $bp->displayed_user->userdata ) ? $bp->displayed_user->userdata : false;
 914              break;
 915      }
 916  
 917      // Manually get userdata if still empty.
 918      if ( empty( $user ) ) {
 919          $user = get_userdata( $user_id );
 920      }
 921  
 922      // No user found.
 923      if ( empty( $user ) ) {
 924          $is_deleted = true;
 925  
 926      // User found.
 927      } else {
 928  
 929          // Check if deleted.
 930          if ( !empty( $user->deleted ) ) {
 931              $is_deleted = true;
 932          }
 933  
 934          if ( 2 == $user->user_status ) {
 935              $is_deleted = true;
 936          }
 937      }
 938  
 939      /**
 940       * Filters whether a user is marked as deleted.
 941       *
 942       * @since 1.6.0
 943       *
 944       * @param bool $is_deleted Whether or not user is marked as deleted.
 945       */
 946      return apply_filters( 'bp_is_user_deleted', (bool) $is_deleted );
 947  }
 948  
 949  /**
 950   * Check whether a user is "active", ie neither deleted nor spammer.
 951   *
 952   * @since 1.6.0
 953   *
 954   * @param int $user_id The user ID to check.
 955   * @return bool True if active, otherwise false.
 956   */
 957  function bp_is_user_active( $user_id = 0 ) {
 958  
 959      // Default to current user.
 960      if ( empty( $user_id ) && is_user_logged_in() ) {
 961          $user_id = bp_loggedin_user_id();
 962      }
 963  
 964      // No user to check.
 965      if ( empty( $user_id ) ) {
 966          return false;
 967      }
 968  
 969      // Check spam.
 970      if ( bp_is_user_spammer( $user_id ) ) {
 971          return false;
 972      }
 973  
 974      // Check deleted.
 975      if ( bp_is_user_deleted( $user_id ) ) {
 976          return false;
 977      }
 978  
 979      // Assume true if not spam or deleted.
 980      return true;
 981  }
 982  
 983  /**
 984   * Check whether user is not active.
 985   *
 986   * @since 1.6.0
 987   *
 988   * @todo No need for the user fallback checks, since they're done in
 989   *       bp_is_user_active().
 990   *
 991   * @param int $user_id The user ID to check.
 992   * @return bool True if inactive, otherwise false.
 993   */
 994  function bp_is_user_inactive( $user_id = 0 ) {
 995  
 996      // Default to current user.
 997      if ( empty( $user_id ) && is_user_logged_in() ) {
 998          $user_id = bp_loggedin_user_id();
 999      }
1000  
1001      // No user to check.
1002      if ( empty( $user_id ) ) {
1003          return false;
1004      }
1005  
1006      // Return the inverse of active.
1007      return !bp_is_user_active( $user_id );
1008  }
1009  
1010  /**
1011   * Update a user's last activity.
1012   *
1013   * @since 1.9.0
1014   *
1015   * @param int    $user_id ID of the user being updated.
1016   * @param string $time    Time of last activity, in 'Y-m-d H:i:s' format.
1017   * @return bool True on success, false on failure.
1018   */
1019  function bp_update_user_last_activity( $user_id = 0, $time = '' ) {
1020  
1021      // Fall back on current user.
1022      if ( empty( $user_id ) ) {
1023          $user_id = bp_loggedin_user_id();
1024      }
1025  
1026      // Bail if the user id is 0, as there's nothing to update.
1027      if ( empty( $user_id ) ) {
1028          return false;
1029      }
1030  
1031      // Fall back on current time.
1032      if ( empty( $time ) ) {
1033          $time = bp_core_current_time();
1034      }
1035  
1036      // As of BuddyPress 2.0, last_activity is no longer stored in usermeta.
1037      // However, we mirror it there for backward compatibility. Do not use!
1038      // Remove our warning and re-add.
1039      remove_filter( 'update_user_metadata', '_bp_update_user_meta_last_activity_warning', 10 );
1040      remove_filter( 'get_user_metadata', '_bp_get_user_meta_last_activity_warning', 10 );
1041      bp_update_user_meta( $user_id, 'last_activity', $time );
1042      add_filter( 'update_user_metadata', '_bp_update_user_meta_last_activity_warning', 10, 4 );
1043      add_filter( 'get_user_metadata', '_bp_get_user_meta_last_activity_warning', 10, 4 );
1044  
1045      return BP_Core_User::update_last_activity( $user_id, $time );
1046  }
1047  
1048  /**
1049   * Backward compatibility for 'last_activity' usermeta fetching.
1050   *
1051   * In BuddyPress 2.0, user last_activity data was moved out of usermeta. For
1052   * backward compatibility, we continue to mirror the data there. This function
1053   * serves two purposes: it warns plugin authors of the change, and it returns
1054   * the data from the proper location.
1055   *
1056   * @since 2.0.0
1057   * @since 2.9.3 Added the `$single` parameter.
1058   *
1059   * @access private For internal use only.
1060   *
1061   * @param null   $retval Null retval value.
1062   * @param int    $object_id ID of the user.
1063   * @param string $meta_key  Meta key being fetched.
1064   * @param bool   $single    Whether a single key is being fetched (vs an array).
1065   * @return string|null
1066   */
1067  function _bp_get_user_meta_last_activity_warning( $retval, $object_id, $meta_key, $single ) {
1068      static $warned = false;
1069  
1070      if ( 'last_activity' === $meta_key ) {
1071          // Don't send the warning more than once per pageload.
1072          if ( false === $warned ) {
1073              _doing_it_wrong( 'get_user_meta( $user_id, \'last_activity\' )', __( 'User last_activity data is no longer stored in usermeta. Use bp_get_user_last_activity() instead.', 'buddypress' ), '2.0.0' );
1074              $warned = true;
1075          }
1076  
1077          $user_last_activity = bp_get_user_last_activity( $object_id );
1078          if ( $single ) {
1079              return $user_last_activity;
1080          } else {
1081              return array( $user_last_activity );
1082          }
1083      }
1084  
1085      return $retval;
1086  }
1087  add_filter( 'get_user_metadata', '_bp_get_user_meta_last_activity_warning', 10, 4 );
1088  
1089  /**
1090   * Backward compatibility for 'last_activity' usermeta setting.
1091   *
1092   * In BuddyPress 2.0, user last_activity data was moved out of usermeta. For
1093   * backward compatibility, we continue to mirror the data there. This function
1094   * serves two purposes: it warns plugin authors of the change, and it updates
1095   * the data in the proper location.
1096   *
1097   * @since 2.0.0
1098   *
1099   * @access private For internal use only.
1100   *
1101   * @param int    $meta_id    ID of the just-set usermeta row.
1102   * @param int    $object_id  ID of the user.
1103   * @param string $meta_key   Meta key being fetched.
1104   * @param string $meta_value Active time.
1105   */
1106  function _bp_update_user_meta_last_activity_warning( $meta_id, $object_id, $meta_key, $meta_value ) {
1107      if ( 'last_activity' === $meta_key ) {
1108          _doing_it_wrong( 'update_user_meta( $user_id, \'last_activity\' )', __( 'User last_activity data is no longer stored in usermeta. Use bp_update_user_last_activity() instead.', 'buddypress' ), '2.0.0' );
1109          bp_update_user_last_activity( $object_id, $meta_value );
1110      }
1111  }
1112  add_filter( 'update_user_metadata', '_bp_update_user_meta_last_activity_warning', 10, 4 );
1113  
1114  /**
1115   * Get the last activity for a given user.
1116   *
1117   * @since 1.9.0
1118   *
1119   * @param int $user_id The ID of the user.
1120   * @return string Time of last activity, in 'Y-m-d H:i:s' format, or an empty
1121   *                string if none is found.
1122   */
1123  function bp_get_user_last_activity( $user_id = 0 ) {
1124      $activity = '';
1125  
1126      $last_activity = BP_Core_User::get_last_activity( $user_id );
1127      if ( ! empty( $last_activity[ $user_id ] ) ) {
1128          $activity = $last_activity[ $user_id ]['date_recorded'];
1129      }
1130  
1131      /**
1132       * Filters the last activity for a given user.
1133       *
1134       * @since 1.9.0
1135       *
1136       * @param string $activity Time of last activity, in 'Y-m-d H:i:s' format or
1137       *                         an empty string if none found.
1138       * @param int    $user_id  ID of the user being checked.
1139       */
1140      return apply_filters( 'bp_get_user_last_activity', $activity, $user_id );
1141  }
1142  
1143  /**
1144   * Migrate last_activity data from the usermeta table to the activity table.
1145   *
1146   * Generally, this function is only run when BP is upgraded to 2.0. It can also
1147   * be called directly from the BuddyPress Tools panel.
1148   *
1149   * @since 2.0.0
1150   *
1151   * @return bool
1152   */
1153  function bp_last_activity_migrate() {
1154      global $wpdb;
1155  
1156      $bp = buddypress();
1157  
1158      // Wipe out existing last_activity data in the activity table -
1159      // this helps to prevent duplicates when pulling from the usermeta
1160      // table.
1161      $wpdb->query( $wpdb->prepare( "DELETE FROM {$bp->members->table_name_last_activity} WHERE component = %s AND type = 'last_activity'", $bp->members->id ) );
1162  
1163      $sql = "INSERT INTO {$bp->members->table_name_last_activity} (`user_id`, `component`, `type`, `action`, `content`, `primary_link`, `item_id`, `date_recorded` ) (
1164            SELECT user_id, '{$bp->members->id}' as component, 'last_activity' as type, '' as action, '' as content, '' as primary_link, 0 as item_id, meta_value AS date_recorded
1165            FROM {$wpdb->usermeta}
1166            WHERE
1167              meta_key = 'last_activity'
1168      );";
1169  
1170      return $wpdb->query( $sql );
1171  }
1172  
1173  /**
1174   * Fetch every post that is authored by the given user for the current blog.
1175   *
1176   * No longer used in BuddyPress.
1177   *
1178   * @todo Deprecate.
1179   *
1180   * @param int $user_id ID of the user being queried.
1181   * @return array Post IDs.
1182   */
1183  function bp_core_get_all_posts_for_user( $user_id = 0 ) {
1184      global $wpdb;
1185  
1186      if ( empty( $user_id ) ) {
1187          $user_id = bp_displayed_user_id();
1188      }
1189  
1190      return apply_filters( 'bp_core_get_all_posts_for_user', $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_author = %d AND post_status = 'publish' AND post_type = 'post'", $user_id ) ) );
1191  }
1192  
1193  /**
1194   * Process account deletion requests.
1195   *
1196   * Primarily used for self-deletions, as requested through Settings.
1197   *
1198   * @since 1.0.0
1199   *
1200   * @param int $user_id Optional. ID of the user to be deleted. Default: the
1201   *                     logged-in user.
1202   * @return bool True on success, false on failure.
1203   */
1204  function bp_core_delete_account( $user_id = 0 ) {
1205  
1206      // Use logged in user ID if none is passed.
1207      if ( empty( $user_id ) ) {
1208          $user_id = bp_loggedin_user_id();
1209      }
1210  
1211      // Site admins cannot be deleted.
1212      if ( is_super_admin( $user_id ) ) {
1213          return false;
1214      }
1215  
1216      // Extra checks if user is not deleting themselves.
1217      if ( bp_loggedin_user_id() !== absint( $user_id ) ) {
1218  
1219          // Bail if current user cannot delete any users.
1220          if ( ! bp_current_user_can( 'delete_users' ) ) {
1221              return false;
1222          }
1223  
1224          // Bail if current user cannot delete this user.
1225          if ( ! current_user_can_for_blog( bp_get_root_blog_id(), 'delete_user', $user_id ) ) {
1226              return false;
1227          }
1228      }
1229  
1230      /**
1231       * Fires before the processing of an account deletion.
1232       *
1233       * @since 1.6.0
1234       *
1235       * @param int $user_id ID of the user account being deleted.
1236       */
1237      do_action( 'bp_core_pre_delete_account', $user_id );
1238  
1239      // Specifically handle multi-site environment.
1240      if ( is_multisite() ) {
1241          require_once( ABSPATH . '/wp-admin/includes/ms.php'   );
1242          require_once( ABSPATH . '/wp-admin/includes/user.php' );
1243  
1244          $retval = wpmu_delete_user( $user_id );
1245  
1246      // Single site user deletion.
1247      } else {
1248          require_once( ABSPATH . '/wp-admin/includes/user.php' );
1249          $retval = wp_delete_user( $user_id );
1250      }
1251  
1252      /**
1253       * Fires after the deletion of an account.
1254       *
1255       * @since 1.6.0
1256       *
1257       * @param int $user_id ID of the user account that was deleted.
1258       */
1259      do_action( 'bp_core_deleted_account', $user_id );
1260  
1261      return $retval;
1262  }
1263  
1264  /**
1265   * Determines whether user data should be removed on the 'delete_user' hook.
1266   *
1267   * WordPress's 'delete_user' hook is ambiguous: on a standard installation, it means that a user
1268   * account is being removed from the system, while on Multisite it simply means the user is
1269   * being removed from a specific site (ie its roles are being revoked). As a rule, this means
1270   * that BuddyPress should remove user data on the delete_user hook only on non-Multisite
1271   * installations - only when the user account is being removed altogether. However, this behavior
1272   * can be filtered in a global, per-user, or per-component fashion.
1273   *
1274   * @since 6.0.0
1275   *
1276   * @param string $data_type Type of data to be removed.
1277   * @param int    $user_id   ID of the user, as passed to 'delete_user'.
1278   * @return bool
1279   */
1280  function bp_remove_user_data_on_delete_user_hook( $component, $user_id ) {
1281      $remove = ! is_multisite();
1282  
1283      /**
1284       * Filters whether to remove user data on the 'delete_user' hook.
1285       *
1286       * @param bool   $remove    Whether data should be removed.
1287       * @param string $data_type Type of data to be removed.
1288       * @param int    $user_id   ID of the user, as passed to 'delete_user'.
1289       */
1290      return apply_filters( 'bp_remove_user_data_on_delete_user_hook', $remove, $component, $user_id );
1291  }
1292  
1293  /**
1294   * Delete a user's avatar when the user is deleted.
1295   *
1296   * @since 1.9.0
1297   *
1298   * @param int $user_id ID of the user who is about to be deleted.
1299   * @return bool True on success, false on failure.
1300   */
1301  function bp_core_delete_avatar_on_user_delete( $user_id ) {
1302      return bp_core_delete_existing_avatar( array(
1303          'item_id' => $user_id,
1304          'object'  => 'user',
1305      ) );
1306  }
1307  add_action( 'wpmu_delete_user', 'bp_core_delete_avatar_on_user_delete' );
1308  
1309  /**
1310   * Deletes last_activity data on the 'delete_user' hook.
1311   *
1312   * @since 6.0.0
1313   *
1314   * @param int $user_id The ID of the deleted user.
1315   */
1316  function bp_core_delete_avatar_on_delete_user( $user_id ) {
1317      if ( ! bp_remove_user_data_on_delete_user_hook( 'avatar', $user_id ) ) {
1318          return;
1319      }
1320  
1321      bp_core_delete_avatar_on_user_delete( $user_id );
1322  }
1323  add_action( 'delete_user', 'bp_core_delete_avatar_on_delete_user' );
1324  
1325  /**
1326   * Multibyte-safe ucfirst() support.
1327   *
1328   * Uses multibyte functions when available on the PHP build.
1329   *
1330   * @since 1.0.0
1331   *
1332   * @param string $str String to be upper-cased.
1333   * @return string
1334   */
1335  function bp_core_ucfirst( $str ) {
1336      if ( function_exists( 'mb_strtoupper' ) && function_exists( 'mb_substr' ) ) {
1337          $fc = mb_strtoupper( mb_substr( $str, 0, 1 ) );
1338          return $fc.mb_substr( $str, 1 );
1339      } else {
1340          return ucfirst( $str );
1341      }
1342  }
1343  
1344  /**
1345   * Prevent spammers from logging in.
1346   *
1347   * When a user logs in, check if they have been marked as a spammer. If yes
1348   * then simply redirect them to the home page and stop them from logging in.
1349   *
1350   * @since 1.1.2
1351   *
1352   * @param WP_User|WP_Error $user Either the WP_User object or the WP_Error
1353   *                               object, as passed to the 'authenticate' filter.
1354   * @return WP_User|WP_Error If the user is not a spammer, return the WP_User
1355   *                          object. Otherwise a new WP_Error object.
1356   */
1357  function bp_core_boot_spammer( $user ) {
1358  
1359      // Check to see if the $user has already failed logging in, if so return $user as-is.
1360      if ( is_wp_error( $user ) || empty( $user ) ) {
1361          return $user;
1362      }
1363  
1364      // The user exists; now do a check to see if the user is a spammer
1365      // if the user is a spammer, stop them in their tracks!
1366      if ( is_a( $user, 'WP_User' ) && ( ( is_multisite() && (int) $user->spam ) || 1 == $user->user_status ) ) {
1367          return new WP_Error( 'invalid_username', __( '<strong>Error</strong>: Your account has been marked as a spammer.', 'buddypress' ) );
1368      }
1369  
1370      // User is good to go!
1371      return $user;
1372  }
1373  add_filter( 'authenticate', 'bp_core_boot_spammer', 30 );
1374  
1375  /**
1376   * Delete last_activity data for the user when the user is deleted.
1377   *
1378   * @since 1.0.0
1379   *
1380   * @param int $user_id The user ID for the user to delete usermeta for.
1381   */
1382  function bp_core_remove_data( $user_id ) {
1383  
1384      // Remove last_activity data.
1385      BP_Core_User::delete_last_activity( $user_id );
1386  
1387      // Flush the cache to remove the user from all cached objects.
1388      wp_cache_flush();
1389  }
1390  add_action( 'wpmu_delete_user',  'bp_core_remove_data' );
1391  add_action( 'bp_make_spam_user', 'bp_core_remove_data' );
1392  
1393  /**
1394   * Deletes last_activity data on the 'delete_user' hook.
1395   *
1396   * @since 6.0.0
1397   *
1398   * @param int $user_id The ID of the deleted user.
1399   */
1400  function bp_core_remove_data_on_delete_user( $user_id ) {
1401      if ( ! bp_remove_user_data_on_delete_user_hook( 'last_activity', $user_id ) ) {
1402          return;
1403      }
1404  
1405      bp_core_remove_data( $user_id );
1406  }
1407  add_action( 'delete_user', 'bp_core_remove_data_on_delete_user' );
1408  
1409  /**
1410   * Check whether the logged-in user can edit settings for the displayed user.
1411   *
1412   * @since 1.5.0
1413   *
1414   * @return bool True if editing is allowed, otherwise false.
1415   */
1416  function bp_core_can_edit_settings() {
1417      $status = false;
1418  
1419      if ( bp_is_my_profile() ) {
1420          $status = true;
1421      } elseif ( is_super_admin( bp_displayed_user_id() ) && ! is_super_admin() ) {
1422          $status = false;
1423      } elseif ( bp_current_user_can( 'bp_moderate' ) || current_user_can( 'edit_users' ) ) {
1424          $status = true;
1425      }
1426  
1427      /**
1428       * Filters the status of whether the logged-in user can edit settings for the displayed user or not.
1429       *
1430       * @since 2.8.0
1431       *
1432       * @param bool True if editing is allowed, otherwise false.
1433       */
1434      return apply_filters( 'bp_core_can_edit_settings', $status );
1435  }
1436  
1437  /** Sign-up *******************************************************************/
1438  
1439  /**
1440   * Flush illegal names by getting and setting 'illegal_names' site option.
1441   *
1442   * @since 1.2.5
1443   */
1444  function bp_core_flush_illegal_names() {
1445      $illegal_names = get_site_option( 'illegal_names' );
1446      update_site_option( 'illegal_names', $illegal_names );
1447  }
1448  
1449  /**
1450   * Add BuddyPress-specific items to the illegal_names array.
1451   *
1452   * @since 1.2.7
1453   *
1454   * @param array|string $value    Illegal names as being saved defined in
1455   *                               Multisite settings.
1456   * @param array|string $oldvalue The old value of the option.
1457   * @return array Merged and unique array of illegal names.
1458   */
1459  function bp_core_get_illegal_names( $value = '', $oldvalue = '' ) {
1460  
1461      // Make sure $value is array.
1462      if ( empty( $value ) ) {
1463          $db_illegal_names = array();
1464      }
1465  
1466      if ( is_array( $value ) ) {
1467          $db_illegal_names = $value;
1468      } elseif ( is_string( $value ) ) {
1469          $db_illegal_names = explode( ' ', $value );
1470      }
1471  
1472      // Add the core components' slugs to the banned list even if their components aren't active.
1473      $bp_component_slugs = array(
1474          'groups',
1475          'members',
1476          'forums',
1477          'blogs',
1478          'activity',
1479          'profile',
1480          'friends',
1481          'search',
1482          'settings',
1483          'notifications',
1484          'register',
1485          'activate'
1486      );
1487  
1488      // Core constants.
1489      $slug_constants = array(
1490          'BP_GROUPS_SLUG',
1491          'BP_MEMBERS_SLUG',
1492          'BP_FORUMS_SLUG',
1493          'BP_BLOGS_SLUG',
1494          'BP_ACTIVITY_SLUG',
1495          'BP_XPROFILE_SLUG',
1496          'BP_FRIENDS_SLUG',
1497          'BP_SEARCH_SLUG',
1498          'BP_SETTINGS_SLUG',
1499          'BP_NOTIFICATIONS_SLUG',
1500          'BP_REGISTER_SLUG',
1501          'BP_ACTIVATION_SLUG',
1502      );
1503      foreach( $slug_constants as $constant ) {
1504          if ( defined( $constant ) ) {
1505              $bp_component_slugs[] = constant( $constant );
1506          }
1507      }
1508  
1509      /**
1510       * Filters the array of default illegal usernames.
1511       *
1512       * @since 1.2.2
1513       *
1514       * @param array $value Merged and unique array of illegal usernames.
1515       */
1516      $filtered_illegal_names = apply_filters( 'bp_core_illegal_usernames', array_merge( array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' ), $bp_component_slugs ) );
1517  
1518      /**
1519       * Filters the list of illegal usernames from WordPress.
1520       *
1521       * @since 3.0
1522       *
1523       * @param array Array of illegal usernames.
1524       */
1525      $wp_filtered_illegal_names = apply_filters( 'illegal_user_logins', array() );
1526  
1527      // First merge BuddyPress illegal names.
1528      $bp_merged_names           = array_merge( (array) $filtered_illegal_names, (array) $db_illegal_names );
1529  
1530      // Then merge WordPress and BuddyPress illegal names.
1531      $merged_names              = array_merge( (array) $wp_filtered_illegal_names, (array) $bp_merged_names );
1532  
1533      // Remove duplicates.
1534      $illegal_names             = array_unique( (array) $merged_names );
1535  
1536      /**
1537       * Filters the array of default illegal names.
1538       *
1539       * @since 1.2.5
1540       *
1541       * @param array $value Merged and unique array of illegal names.
1542       */
1543      return apply_filters( 'bp_core_illegal_names', $illegal_names );
1544  }
1545  add_filter( 'pre_update_site_option_illegal_names', 'bp_core_get_illegal_names', 10, 2 );
1546  
1547  /**
1548   * Check that an email address is valid for use.
1549   *
1550   * Performs the following checks:
1551   *   - Is the email address well-formed?
1552   *   - Is the email address already used?
1553   *   - If there's an email domain blacklist, is the current domain on it?
1554   *   - If there's an email domain whitelest, is the current domain on it?
1555   *
1556   * @since 1.6.2
1557   *
1558   * @param string $user_email The email being checked.
1559   * @return bool|array True if the address passes all checks; otherwise an array
1560   *                    of error codes.
1561   */
1562  function bp_core_validate_email_address( $user_email ) {
1563      $errors = array();
1564  
1565      $user_email = sanitize_email( $user_email );
1566  
1567      // Is the email well-formed?
1568      if ( ! is_email( $user_email ) ) {
1569          $errors['invalid'] = 1;
1570      }
1571  
1572      // Is the email on the Banned Email Domains list?
1573      // Note: This check only works on Multisite.
1574      if ( function_exists( 'is_email_address_unsafe' ) && is_email_address_unsafe( $user_email ) ) {
1575          $errors['domain_banned'] = 1;
1576      }
1577  
1578      // Is the email on the Limited Email Domains list?
1579      // Note: This check only works on Multisite.
1580      $limited_email_domains = get_site_option( 'limited_email_domains' );
1581      if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
1582          $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
1583          if ( ! in_array( $emaildomain, $limited_email_domains ) ) {
1584              $errors['domain_not_allowed'] = 1;
1585          }
1586      }
1587  
1588      // Is the email alreday in use?
1589      if ( email_exists( $user_email ) ) {
1590          $errors['in_use'] = 1;
1591      }
1592  
1593      $retval = ! empty( $errors ) ? $errors : true;
1594  
1595      return $retval;
1596  }
1597  
1598  /**
1599   * Add the appropriate errors to a WP_Error object, given results of a validation test.
1600   *
1601   * Functions like bp_core_validate_email_address() return a structured array
1602   * of error codes. bp_core_add_validation_error_messages() takes this array and
1603   * parses, adding the appropriate error messages to the WP_Error object.
1604   *
1605   * @since 1.7.0
1606   *
1607   * @see bp_core_validate_email_address()
1608   *
1609   * @param WP_Error $errors             WP_Error object.
1610   * @param array    $validation_results The return value of a validation function
1611   *                                     like bp_core_validate_email_address().
1612   */
1613  function bp_core_add_validation_error_messages( WP_Error $errors, $validation_results ) {
1614      if ( ! empty( $validation_results['invalid'] ) ) {
1615          $errors->add( 'user_email', __( 'Please check your email address.', 'buddypress' ) );
1616      }
1617  
1618      if ( ! empty( $validation_results['domain_banned'] ) ) {
1619          $errors->add( 'user_email',  __( 'Sorry, that email address is not allowed!', 'buddypress' ) );
1620      }
1621  
1622      if ( ! empty( $validation_results['domain_not_allowed'] ) ) {
1623          $errors->add( 'user_email', __( 'Sorry, that email address is not allowed!', 'buddypress' ) );
1624      }
1625  
1626      if ( ! empty( $validation_results['in_use'] ) ) {
1627          $errors->add( 'user_email', __( 'Sorry, that email address is already used!', 'buddypress' ) );
1628      }
1629  }
1630  
1631  /**
1632   * Validate a user name and email address when creating a new user.
1633   *
1634   * @since 1.2.2
1635   *
1636   * @param string $user_name  Username to validate.
1637   * @param string $user_email Email address to validate.
1638   * @return array Results of user validation including errors, if any.
1639   */
1640  function bp_core_validate_user_signup( $user_name, $user_email ) {
1641  
1642      // Make sure illegal names include BuddyPress slugs and values.
1643      bp_core_flush_illegal_names();
1644  
1645      // WordPress Multisite has its own validation. Use it, so that we
1646      // properly mirror restrictions on username, etc.
1647      if ( function_exists( 'wpmu_validate_user_signup' ) ) {
1648          $result = wpmu_validate_user_signup( $user_name, $user_email );
1649  
1650      // When not running Multisite, we perform our own validation. What
1651      // follows reproduces much of the logic of wpmu_validate_user_signup(),
1652      // minus the multisite-specific restrictions on user_login.
1653      } else {
1654          $errors = new WP_Error();
1655  
1656          /**
1657           * Filters the username before being validated.
1658           *
1659           * @since 1.5.5
1660           *
1661           * @param string $user_name Username to validate.
1662           */
1663          $user_name = apply_filters( 'pre_user_login', $user_name );
1664  
1665          // User name can't be empty.
1666          if ( empty( $user_name ) ) {
1667              $errors->add( 'user_name', __( 'Please enter a username', 'buddypress' ) );
1668          }
1669  
1670          // User name can't be on the blacklist.
1671          $illegal_names = get_site_option( 'illegal_names' );
1672          if ( in_array( $user_name, (array) $illegal_names ) ) {
1673              $errors->add( 'user_name', __( 'That username is not allowed', 'buddypress' ) );
1674          }
1675  
1676          // User name must pass WP's validity check.
1677          if ( ! validate_username( $user_name ) ) {
1678              $errors->add( 'user_name', __( 'Usernames can contain only letters, numbers, ., -, and @', 'buddypress' ) );
1679          }
1680  
1681          // Minimum of 4 characters.
1682          if ( strlen( $user_name ) < 4 ) {
1683              $errors->add( 'user_name',  __( 'Username must be at least 4 characters', 'buddypress' ) );
1684          }
1685  
1686          // No underscores. @todo Why not?
1687          if ( false !== strpos( ' ' . $user_name, '_' ) ) {
1688              $errors->add( 'user_name', __( 'Sorry, usernames may not contain the character "_"!', 'buddypress' ) );
1689          }
1690  
1691          // No usernames that are all numeric. @todo Why?
1692          $match = array();
1693          preg_match( '/[0-9]*/', $user_name, $match );
1694          if ( $match[0] == $user_name ) {
1695              $errors->add( 'user_name', __( 'Sorry, usernames must have letters too!', 'buddypress' ) );
1696          }
1697  
1698          // Check into signups.
1699          $signups = BP_Signup::get( array(
1700              'user_login' => $user_name,
1701          ) );
1702  
1703          $signup = isset( $signups['signups'] ) && ! empty( $signups['signups'][0] ) ? $signups['signups'][0] : false;
1704  
1705          // Check if the username has been used already.
1706          if ( username_exists( $user_name ) || ! empty( $signup ) ) {
1707              $errors->add( 'user_name', __( 'Sorry, that username already exists!', 'buddypress' ) );
1708          }
1709  
1710          // Validate the email address and process the validation results into
1711          // error messages.
1712          $validate_email = bp_core_validate_email_address( $user_email );
1713          bp_core_add_validation_error_messages( $errors, $validate_email );
1714  
1715          // Assemble the return array.
1716          $result = array(
1717              'user_name'  => $user_name,
1718              'user_email' => $user_email,
1719              'errors'     => $errors,
1720          );
1721  
1722          // Apply WPMU legacy filter.
1723          $result = apply_filters( 'wpmu_validate_user_signup', $result );
1724      }
1725  
1726      /**
1727       * Filters the result of the user signup validation.
1728       *
1729       * @since 1.2.2
1730       *
1731       * @param array $result Results of user validation including errors, if any.
1732       */
1733      return apply_filters( 'bp_core_validate_user_signup', $result );
1734  }
1735  
1736  /**
1737   * Validate blog URL and title provided at signup.
1738   *
1739   * @since 1.2.2
1740   *
1741   * @todo Why do we have this wrapper?
1742   *
1743   * @param string $blog_url   Blog URL requested during registration.
1744   * @param string $blog_title Blog title requested during registration.
1745   * @return array
1746   */
1747  function bp_core_validate_blog_signup( $blog_url, $blog_title ) {
1748      if ( ! is_multisite() || ! function_exists( 'wpmu_validate_blog_signup' ) ) {
1749          return false;
1750      }
1751  
1752      /**
1753       * Filters the validated blog url and title provided at signup.
1754       *
1755       * @since 1.2.2
1756       *
1757       * @param array $value Array with the new site data and error messages.
1758       */
1759      return apply_filters( 'bp_core_validate_blog_signup', wpmu_validate_blog_signup( $blog_url, $blog_title ) );
1760  }
1761  
1762  /**
1763   * Process data submitted at user registration and convert to a signup object.
1764   *
1765   * @since 1.2.0
1766   *
1767   * @todo There appears to be a bug in the return value on success.
1768   *
1769   * @param string $user_login    Login name requested by the user.
1770   * @param string $user_password Password requested by the user.
1771   * @param string $user_email    Email address entered by the user.
1772   * @param array  $usermeta      Miscellaneous metadata about the user (blog-specific
1773   *                              signup data, xprofile data, etc).
1774   * @return int|false True on success, WP_Error on failure.
1775   */
1776  function bp_core_signup_user( $user_login, $user_password, $user_email, $usermeta ) {
1777      $bp = buddypress();
1778  
1779      // We need to cast $user_id to pass to the filters.
1780      $user_id = false;
1781  
1782      // Multisite installs have their own install procedure.
1783      if ( is_multisite() ) {
1784          wpmu_signup_user( $user_login, $user_email, $usermeta );
1785  
1786      } else {
1787          // Format data.
1788          $user_login     = preg_replace( '/\s+/', '', sanitize_user( $user_login, true ) );
1789          $user_email     = sanitize_email( $user_email );
1790          $activation_key = wp_generate_password( 32, false );
1791  
1792          /**
1793           * WordPress's default behavior is to create user accounts
1794           * immediately at registration time. BuddyPress uses a system
1795           * borrowed from WordPress Multisite, where signups are stored
1796           * separately and accounts are only created at the time of
1797           * activation. For backward compatibility with plugins that may
1798           * be anticipating WP's default behavior, BP silently creates
1799           * accounts for registrations (though it does not use them). If
1800           * you know that you are not running any plugins dependent on
1801           * these pending accounts, you may want to save a little DB
1802           * clutter by defining setting the BP_SIGNUPS_SKIP_USER_CREATION
1803           * to true in your wp-config.php file.
1804           */
1805          if ( ! defined( 'BP_SIGNUPS_SKIP_USER_CREATION' ) || ! BP_SIGNUPS_SKIP_USER_CREATION ) {
1806              $user_id = BP_Signup::add_backcompat( $user_login, $user_password, $user_email, $usermeta );
1807  
1808              if ( is_wp_error( $user_id ) ) {
1809                  return $user_id;
1810              }
1811  
1812              bp_update_user_meta( $user_id, 'activation_key', $activation_key );
1813          }
1814  
1815          $args = array(
1816              'user_login'     => $user_login,
1817              'user_email'     => $user_email,
1818              'activation_key' => $activation_key,
1819              'meta'           => $usermeta,
1820          );
1821  
1822          BP_Signup::add( $args );
1823  
1824          /**
1825           * Filters if BuddyPress should send an activation key for a new signup.
1826           *
1827           * @since 1.2.3
1828           *
1829           * @param bool   $value          Whether or not to send the activation key.
1830           * @param int    $user_id        User ID to send activation key to.
1831           * @param string $user_email     User email to send activation key to.
1832           * @param string $activation_key Activation key to be sent.
1833           * @param array  $usermeta       Miscellaneous metadata about the user (blog-specific
1834           *                               signup data, xprofile data, etc).
1835           */
1836          if ( apply_filters( 'bp_core_signup_send_activation_key', true, $user_id, $user_email, $activation_key, $usermeta ) ) {
1837              $salutation = $user_login;
1838              if ( bp_is_active( 'xprofile' ) && isset( $usermeta[ 'field_' . bp_xprofile_fullname_field_id() ] ) ) {
1839                  $salutation = $usermeta[ 'field_' . bp_xprofile_fullname_field_id() ];
1840              }
1841  
1842              bp_core_signup_send_validation_email( $user_id, $user_email, $activation_key, $salutation );
1843          }
1844      }
1845  
1846      $bp->signup->username = $user_login;
1847  
1848      /**
1849       * Fires at the end of the process to sign up a user.
1850       *
1851       * @since 1.2.2
1852       *
1853       * @param bool|WP_Error   $user_id       True on success, WP_Error on failure.
1854       * @param string          $user_login    Login name requested by the user.
1855       * @param string          $user_password Password requested by the user.
1856       * @param string          $user_email    Email address requested by the user.
1857       * @param array           $usermeta      Miscellaneous metadata about the user (blog-specific
1858       *                                       signup data, xprofile data, etc).
1859       */
1860      do_action( 'bp_core_signup_user', $user_id, $user_login, $user_password, $user_email, $usermeta );
1861  
1862      return $user_id;
1863  }
1864  
1865  /**
1866   * Create a blog and user based on data supplied at user registration.
1867   *
1868   * @since 1.2.2
1869   *
1870   * @param string $blog_domain Domain requested by user.
1871   * @param string $blog_path   Path requested by user.
1872   * @param string $blog_title  Title as entered by user.
1873   * @param string $user_name   user_login of requesting user.
1874   * @param string $user_email  Email address of requesting user.
1875   * @param string $usermeta    Miscellaneous metadata for the user.
1876   * @return bool
1877   */
1878  function bp_core_signup_blog( $blog_domain, $blog_path, $blog_title, $user_name, $user_email, $usermeta ) {
1879      if ( ! is_multisite() || ! function_exists( 'wpmu_signup_blog' ) ) {
1880          return false;
1881      }
1882  
1883      /**
1884       * Filters the result of wpmu_signup_blog().
1885       *
1886       * This filter provides no value and is retained for
1887       * backwards compatibility.
1888       *
1889       * @since 1.2.2
1890       *
1891       * @param void $value
1892       */
1893      return apply_filters( 'bp_core_signup_blog', wpmu_signup_blog( $blog_domain, $blog_path, $blog_title, $user_name, $user_email, $usermeta ) );
1894  }
1895  
1896  /**
1897   * Activate a signup, as identified by an activation key.
1898   *
1899   * @since 1.2.2
1900   *
1901   * @param string $key Activation key.
1902   * @return int|bool User ID on success, false on failure.
1903   */
1904  function bp_core_activate_signup( $key ) {
1905      global $wpdb;
1906  
1907      $user = false;
1908  
1909      // Multisite installs have their own activation routine.
1910      if ( is_multisite() ) {
1911          $user = wpmu_activate_signup( $key );
1912  
1913          // If there were errors, add a message and redirect.
1914          if ( ! empty( $user->errors ) ) {
1915              return $user;
1916          }
1917  
1918          $user_id = $user['user_id'];
1919  
1920      } else {
1921          $signups = BP_Signup::get( array(
1922              'activation_key' => $key,
1923          ) );
1924  
1925          if ( empty( $signups['signups'] ) ) {
1926              return new WP_Error( 'invalid_key', __( 'Invalid activation key.', 'buddypress' ) );
1927          }
1928  
1929          $signup = $signups['signups'][0];
1930  
1931          if ( $signup->active ) {
1932              if ( empty( $signup->domain ) ) {
1933                  return new WP_Error( 'already_active', __( 'The user is already active.', 'buddypress' ), $signup );
1934              } else {
1935                  return new WP_Error( 'already_active', __( 'The site is already active.', 'buddypress' ), $signup );
1936              }
1937          }
1938  
1939          // Password is hashed again in wp_insert_user.
1940          $password = wp_generate_password( 12, false );
1941  
1942          $user_id = username_exists( $signup->user_login );
1943  
1944          // Create the user. This should only be necessary if BP_SIGNUPS_SKIP_USER_CREATION is true.
1945          if ( ! $user_id ) {
1946              $user_id = wp_create_user( $signup->user_login, $password, $signup->user_email );
1947  
1948          // Otherwise, update the existing user's status.
1949          } elseif ( $key === bp_get_user_meta( $user_id, 'activation_key', true ) || $key === wp_hash( $user_id ) ) {
1950  
1951              // Change the user's status so they become active.
1952              if ( ! $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->users} SET user_status = 0 WHERE ID = %d", $user_id ) ) ) {
1953                  return new WP_Error( 'invalid_key', __( 'Invalid activation key.', 'buddypress' ) );
1954              }
1955  
1956              bp_delete_user_meta( $user_id, 'activation_key' );
1957  
1958              $user_already_created = true;
1959  
1960          } else {
1961              $user_already_exists = true;
1962          }
1963  
1964          if ( ! $user_id ) {
1965              return new WP_Error( 'create_user', __( 'Could not create user', 'buddypress' ), $signup );
1966          }
1967  
1968          // Fetch the signup so we have the data later on.
1969          $signups = BP_Signup::get( array(
1970              'activation_key' => $key,
1971          ) );
1972  
1973          $signup = isset( $signups['signups'] ) && ! empty( $signups['signups'][0] ) ? $signups['signups'][0] : false;
1974  
1975          // Activate the signup.
1976          BP_Signup::validate( $key );
1977  
1978          if ( isset( $user_already_exists ) ) {
1979              return new WP_Error( 'user_already_exists', __( 'That username is already activated.', 'buddypress' ), $signup );
1980          }
1981  
1982          // Set up data to pass to the legacy filter.
1983          $user = array(
1984              'user_id'  => $user_id,
1985              'password' => isset( $signup->meta['password'] ) ? $signup->meta['password'] : '',
1986              'meta'     => $signup->meta,
1987          );
1988  
1989          /**
1990           * Maybe notify the site admin of a new user registration.
1991           *
1992           * @since 1.2.2
1993           *
1994           * @param bool $notification Whether to send the notification or not.
1995           */
1996          if ( apply_filters( 'bp_core_send_user_registration_admin_notification', true ) ) {
1997              wp_new_user_notification( $user_id );
1998          }
1999  
2000          if ( isset( $user_already_created ) ) {
2001  
2002              /**
2003               * Fires if the user has already been created.
2004               *
2005               * @since 1.2.2
2006               *
2007               * @param int    $user_id ID of the user being checked.
2008               * @param string $key     Activation key.
2009               * @param array  $user    Array of user data.
2010               */
2011              do_action( 'bp_core_activated_user', $user_id, $key, $user );
2012              return $user_id;
2013          }
2014      }
2015  
2016      // Set any profile data.
2017      if ( bp_is_active( 'xprofile' ) ) {
2018          if ( ! empty( $user['meta']['profile_field_ids'] ) ) {
2019              $profile_field_ids = explode( ',', $user['meta']['profile_field_ids'] );
2020  
2021              foreach( (array) $profile_field_ids as $field_id ) {
2022                  $current_field = isset( $user['meta']["field_{$field_id}"] ) ? $user['meta']["field_{$field_id}"] : false;
2023  
2024                  if ( !empty( $current_field ) ) {
2025                      xprofile_set_field_data( $field_id, $user_id, $current_field );
2026                  }
2027  
2028                  /*
2029                   * Save the visibility level.
2030                   *
2031                   * Use the field's default visibility if not present, and 'public' if a
2032                   * default visibility is not defined.
2033                   */
2034                  $key = "field_{$field_id}_visibility";
2035                  if ( isset( $user['meta'][ $key ] ) ) {
2036                      $visibility_level = $user['meta'][ $key ];
2037                  } else {
2038                      $vfield           = xprofile_get_field( $field_id );
2039                      $visibility_level = isset( $vfield->default_visibility ) ? $vfield->default_visibility : 'public';
2040                  }
2041                  xprofile_set_field_visibility_level( $field_id, $user_id, $visibility_level );
2042              }
2043          }
2044      }
2045  
2046      // Replace the password automatically generated by WordPress by the one the user chose.
2047      if ( ! empty( $user['meta']['password'] ) ) {
2048          $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->users} SET user_pass = %s WHERE ID = %d", $user['meta']['password'], $user_id ) );
2049  
2050          /**
2051           * Make sure to clean the user's cache as we've
2052           * directly edited the password without using
2053           * wp_update_user().
2054           *
2055           * If we can't use wp_update_user() that's because
2056           * we already hashed the password at the signup step.
2057           */
2058          $uc = wp_cache_get( $user_id, 'users' );
2059  
2060          if ( ! empty( $uc->ID ) ) {
2061              clean_user_cache( $uc->ID );
2062          }
2063      }
2064  
2065      /**
2066       * Fires at the end of the user activation process.
2067       *
2068       * @since 1.2.2
2069       *
2070       * @param int    $user_id ID of the user being checked.
2071       * @param string $key     Activation key.
2072       * @param array  $user    Array of user data.
2073       */
2074      do_action( 'bp_core_activated_user', $user_id, $key, $user );
2075  
2076      return $user_id;
2077  }
2078  
2079  /**
2080   * Add default WordPress role for new signups on the BP root blog.
2081   *
2082   * @since 3.0.0
2083   *
2084   * @param int $user_id The user ID to add the default role for.
2085   */
2086  function bp_members_add_role_after_activation( $user_id ) {
2087      // Get default role to add.
2088      $role = bp_get_option( 'default_role' );
2089  
2090      // Multisite.
2091      if ( is_multisite() && ! is_user_member_of_blog( $user_id, bp_get_root_blog_id() ) ) {
2092          add_user_to_blog( bp_get_root_blog_id(), $user_id, $role );
2093  
2094      // Single-site.
2095      } elseif ( ! is_multisite() ) {
2096          $member = get_userdata( $user_id );
2097          $member->set_role( $role );
2098      }
2099  }
2100  add_action( 'bp_core_activated_user', 'bp_members_add_role_after_activation', 1 );
2101  
2102  /**
2103   * Migrate signups from pre-2.0 configuration to wp_signups.
2104   *
2105   * @since 2.0.1
2106   */
2107  function bp_members_migrate_signups() {
2108      global $wpdb;
2109  
2110      $status_2_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->users} WHERE user_status = '2'" );
2111  
2112      if ( ! empty( $status_2_ids ) ) {
2113          $signups = get_users( array(
2114              'fields'  => array(
2115                  'ID',
2116                  'user_login',
2117                  'user_pass',
2118                  'user_registered',
2119                  'user_email',
2120                  'display_name',
2121              ),
2122              'include' => $status_2_ids,
2123          ) );
2124  
2125          // Fetch activation keys separately, to avoid the all_with_meta
2126          // overhead.
2127          $status_2_ids_sql = implode( ',', $status_2_ids );
2128          $ak_data = $wpdb->get_results( "SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'activation_key' AND user_id IN ({$status_2_ids_sql})" );
2129  
2130          // Rekey.
2131          $activation_keys = array();
2132          foreach ( $ak_data as $ak_datum ) {
2133              $activation_keys[ intval( $ak_datum->user_id ) ] = $ak_datum->meta_value;
2134          }
2135  
2136          unset( $status_2_ids_sql, $status_2_ids, $ak_data );
2137  
2138          // Merge.
2139          foreach ( $signups as &$signup ) {
2140              if ( isset( $activation_keys[ $signup->ID ] ) ) {
2141                  $signup->activation_key = $activation_keys[ $signup->ID ];
2142              }
2143          }
2144  
2145          // Reset the signup var as we're using it to process the migration.
2146          unset( $signup );
2147  
2148      } else {
2149          return;
2150      }
2151  
2152      foreach ( $signups as $signup ) {
2153          $meta = array();
2154  
2155          // Rebuild the activation key, if missing.
2156          if ( empty( $signup->activation_key ) ) {
2157              $signup->activation_key = wp_generate_password( 32, false );
2158          }
2159  
2160          if ( bp_is_active( 'xprofile' ) ) {
2161              $meta['field_1'] = $signup->display_name;
2162          }
2163  
2164          $meta['password'] = $signup->user_pass;
2165  
2166          $user_login = preg_replace( '/\s+/', '', sanitize_user( $signup->user_login, true ) );
2167          $user_email = sanitize_email( $signup->user_email );
2168  
2169          BP_Signup::add( array(
2170              'user_login'     => $user_login,
2171              'user_email'     => $user_email,
2172              'registered'     => $signup->user_registered,
2173              'activation_key' => $signup->activation_key,
2174              'meta'           => $meta
2175          ) );
2176  
2177          // Deleting these options will remove signups from users count.
2178          delete_user_option( $signup->ID, 'capabilities' );
2179          delete_user_option( $signup->ID, 'user_level'   );
2180      }
2181  }
2182  
2183  /**
2184   * Map a user's WP display name to the XProfile fullname field, if necessary.
2185   *
2186   * This only happens when a user is registered in wp-admin by an administrator;
2187   * during normal registration, XProfile data is provided directly by the user.
2188   *
2189   * @since 1.2.0
2190   *
2191   * @param int $user_id ID of the user.
2192   * @return bool
2193   */
2194  function bp_core_map_user_registration( $user_id ) {
2195  
2196      // Only map data when the site admin is adding users, not on registration.
2197      if ( ! is_admin() ) {
2198          return false;
2199      }
2200  
2201      // Add the user's fullname to Xprofile.
2202      if ( bp_is_active( 'xprofile' ) ) {
2203          $firstname = bp_get_user_meta( $user_id, 'first_name', true );
2204          $lastname = ' ' . bp_get_user_meta( $user_id, 'last_name', true );
2205          $name = $firstname . $lastname;
2206  
2207          if ( empty( $name ) || ' ' == $name ) {
2208              $name = bp_get_user_meta( $user_id, 'nickname', true );
2209          }
2210  
2211          xprofile_set_field_data( 1, $user_id, $name );
2212      }
2213  }
2214  add_action( 'user_register', 'bp_core_map_user_registration' );
2215  
2216  /**
2217   * Get the avatar storage directory for use during registration.
2218   *
2219   * @since 1.1.0
2220   *
2221   * @return string|bool Directory path on success, false on failure.
2222   */
2223  function bp_core_signup_avatar_upload_dir() {
2224      $bp = buddypress();
2225  
2226      if ( empty( $bp->signup->avatar_dir ) ) {
2227          return false;
2228      }
2229  
2230      $directory = 'avatars/signups';
2231      $path      = bp_core_avatar_upload_path() . '/' . $directory . '/' . $bp->signup->avatar_dir;
2232      $newbdir   = $path;
2233      $newurl    = bp_core_avatar_url() . '/' . $directory . '/' . $bp->signup->avatar_dir;
2234      $newburl   = $newurl;
2235      $newsubdir = '/' . $directory . '/' . $bp->signup->avatar_dir;
2236  
2237      /**
2238       * Filters the avatar storage directory for use during registration.
2239       *
2240       * @since 1.1.1
2241       *
2242       * @param array $value Array of path and URL values for created storage directory.
2243       */
2244      return apply_filters( 'bp_core_signup_avatar_upload_dir', array(
2245          'path'    => $path,
2246          'url'     => $newurl,
2247          'subdir'  => $newsubdir,
2248          'basedir' => $newbdir,
2249          'baseurl' => $newburl,
2250          'error'   => false
2251      ) );
2252  }
2253  
2254  /**
2255   * Send activation email to a newly registered user.
2256   *
2257   * @since 1.2.2
2258   * @since 2.5.0 Add the $user_login parameter.
2259   * @since 5.0.0 Change $user_login parameter to more general $salutation.
2260   *
2261   * @param int|bool $user_id    ID of the new user, false if BP_SIGNUPS_SKIP_USER_CREATION is true.
2262   * @param string   $user_email   Email address of the new user.
2263   * @param string   $key          Activation key.
2264   * @param string   $salutation   Optional. The name to be used as a salutation in the email.
2265   */
2266  function bp_core_signup_send_validation_email( $user_id, $user_email, $key, $salutation = '' ) {
2267      $args = array(
2268          'tokens' => array(
2269              'activate.url' => esc_url( trailingslashit( bp_get_activation_page() ) . "{$key}/" ),
2270              'key'          => $key,
2271              'user.email'   => $user_email,
2272              'user.id'      => $user_id,
2273          ),
2274      );
2275  
2276      $to = array( array( $user_email => $salutation ) );
2277  
2278      bp_send_email( 'core-user-registration', $to, $args );
2279  }
2280  
2281  /**
2282   * Display a "resend email" link when an unregistered user attempts to log in.
2283   *
2284   * @since 1.2.2
2285   *
2286   * @param WP_User|WP_Error|null $user     Either the WP_User or the WP_Error object.
2287   * @param string                $username The inputted, attempted username.
2288   * @param string                $password The inputted, attempted password.
2289   * @return WP_User|WP_Error
2290   */
2291  function bp_core_signup_disable_inactive( $user = null, $username = '', $password ='' ) {
2292      // Login form not used.
2293      if ( empty( $username ) && empty( $password ) ) {
2294          return $user;
2295      }
2296  
2297      // An existing WP_User with a user_status of 2 is either a legacy
2298      // signup, or is a user created for backward compatibility. See
2299      // {@link bp_core_signup_user()} for more details.
2300      if ( is_a( $user, 'WP_User' ) && 2 == $user->user_status ) {
2301          $user_login = $user->user_login;
2302  
2303      // If no WP_User is found corresponding to the username, this
2304      // is a potential signup.
2305      } elseif ( is_wp_error( $user ) && 'invalid_username' == $user->get_error_code() ) {
2306          $user_login = $username;
2307  
2308      // This is an activated user, so bail.
2309      } else {
2310          return $user;
2311      }
2312  
2313      // Look for the unactivated signup corresponding to the login name.
2314      $signup = BP_Signup::get( array( 'user_login' => sanitize_user( $user_login ) ) );
2315  
2316      // No signup or more than one, something is wrong. Let's bail.
2317      if ( empty( $signup['signups'][0] ) || $signup['total'] > 1 ) {
2318          return $user;
2319      }
2320  
2321      // Unactivated user account found!
2322      // Set up the feedback message.
2323      $signup_id = $signup['signups'][0]->signup_id;
2324  
2325      $resend_url_params = array(
2326          'action' => 'bp-resend-activation',
2327          'id'     => $signup_id,
2328      );
2329  
2330      $resend_url = wp_nonce_url(
2331          add_query_arg( $resend_url_params, wp_login_url() ),
2332          'bp-resend-activation'
2333      );
2334  
2335      $resend_string = '<br /><br />';
2336  
2337      /* translators: %s: the activation url */
2338      $resend_string .= sprintf( __( 'If you have not received an email yet, <a href="%s">click here to resend it</a>.', 'buddypress' ), esc_url( $resend_url ) );
2339  
2340      return new WP_Error( 'bp_account_not_activated', __( '<strong>Error</strong>: Your account has not been activated. Check your email for the activation link.', 'buddypress' ) . $resend_string );
2341  }
2342  add_filter( 'authenticate', 'bp_core_signup_disable_inactive', 30, 3 );
2343  
2344  /**
2345   * On the login screen, resends the activation email for a user.
2346   *
2347   * @since 2.0.0
2348   *
2349   * @see bp_core_signup_disable_inactive()
2350   */
2351  function bp_members_login_resend_activation_email() {
2352      global $error;
2353  
2354      if ( empty( $_GET['id'] ) || empty( $_GET['_wpnonce'] ) ) {
2355          return;
2356      }
2357  
2358      // Verify nonce.
2359      if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'bp-resend-activation' ) ) {
2360          die( 'Security check' );
2361      }
2362  
2363      $signup_id = (int) $_GET['id'];
2364  
2365      // Resend the activation email.
2366      // also updates the 'last sent' and '# of emails sent' values.
2367      $resend = BP_Signup::resend( array( $signup_id ) );
2368  
2369      // Add feedback message.
2370      if ( ! empty( $resend['errors'] ) ) {
2371          $error = __( '<strong>Error</strong>: Your account has already been activated.', 'buddypress' );
2372      } else {
2373          $error = __( 'Activation email resent! Please check your inbox or spam folder.', 'buddypress' );
2374      }
2375  }
2376  add_action( 'login_form_bp-resend-activation', 'bp_members_login_resend_activation_email' );
2377  
2378  /**
2379   * Redirect away from wp-signup.php if BP registration templates are present.
2380   *
2381   * @since 1.1.0
2382   */
2383  function bp_core_wpsignup_redirect() {
2384  
2385      // Bail in admin or if custom signup page is broken.
2386      if ( is_admin() || ! bp_has_custom_signup_page() ) {
2387          return;
2388      }
2389  
2390      $is_wp_signup = false;
2391      if ( ! empty( $_SERVER['SCRIPT_NAME'] ) ) {
2392          $script_name_path = wp_parse_url( $_SERVER['SCRIPT_NAME'], PHP_URL_PATH );
2393  
2394          if ( 'wp-signup.php' === basename( $script_name_path ) || ( 'wp-login.php' === basename( $script_name_path ) && ! empty( $_GET['action'] ) && 'register' === $_GET['action'] ) ) {
2395              $is_wp_signup = true;
2396          }
2397      }
2398  
2399      // If this is not wp-signup.php, there's nothing to do here.
2400      if ( ! $is_wp_signup ) {
2401          return;
2402      }
2403  
2404      /*
2405       * We redirect wp-signup.php to the registration page except when it's a site signup.
2406       * In that case, redirect to the BP site creation page if available, otherwise allow
2407       * access to wp-signup.php.
2408       */
2409      $redirect_to = bp_get_signup_page();
2410  
2411      $is_site_creation = false;
2412  
2413      $referer = wp_get_referer();
2414  
2415      // A new site is being added.
2416      if ( isset( $_POST['stage'] ) && $_POST['stage'] === 'gimmeanotherblog' ) {
2417          $is_site_creation = true;
2418  
2419      // We've arrived at wp-signup.php from my-sites.php.
2420      } elseif ( $referer ) {
2421          $referer_path     = wp_parse_url( $referer, PHP_URL_PATH );
2422          $is_site_creation = false !== strpos( $referer_path, 'wp-admin/my-sites.php' );
2423      }
2424  
2425      if ( $is_site_creation ) {
2426          if ( bp_is_active( 'blogs' ) ) {
2427              $redirect_to = trailingslashit( bp_get_blogs_directory_permalink() . 'create' );
2428          } else {
2429              // Perform no redirect in this case.
2430              $redirect_to = '';
2431          }
2432      }
2433  
2434      if ( ! $redirect_to ) {
2435          return;
2436      }
2437  
2438      bp_core_redirect( $redirect_to );
2439  }
2440  add_action( 'bp_init', 'bp_core_wpsignup_redirect' );
2441  
2442  /**
2443   * Stop a logged-in user who is marked as a spammer.
2444   *
2445   * When an admin marks a live user as a spammer, that user can still surf
2446   * around and cause havoc on the site until that person is logged out.
2447   *
2448   * This code checks to see if a logged-in user is marked as a spammer.  If so,
2449   * we redirect the user back to wp-login.php with the 'reauth' parameter.
2450   *
2451   * This clears the logged-in spammer's cookies and will ask the spammer to
2452   * reauthenticate.
2453   *
2454   * Note: A spammer cannot log back in - {@see bp_core_boot_spammer()}.
2455   *
2456   * Runs on 'bp_init' at priority 5 so the members component globals are setup
2457   * before we do our spammer checks.
2458   *
2459   * This is important as the $bp->loggedin_user object is setup at priority 4.
2460   *
2461   * @since 1.8.0
2462   */
2463  function bp_stop_live_spammer() {
2464      // If we're on the login page, stop now to prevent redirect loop.
2465      $is_login = false;
2466      if ( isset( $GLOBALS['pagenow'] ) && ( false !== strpos( $GLOBALS['pagenow'], 'wp-login.php' ) ) ) {
2467          $is_login = true;
2468      } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) && false !== strpos( $_SERVER['SCRIPT_NAME'], 'wp-login.php' ) ) {
2469          $is_login = true;
2470      }
2471  
2472      if ( $is_login ) {
2473          return;
2474      }
2475  
2476      // User isn't logged in, so stop!
2477      if ( ! is_user_logged_in() ) {
2478          return;
2479      }
2480  
2481      // If spammer, redirect to wp-login.php and reauthorize.
2482      if ( bp_is_user_spammer( bp_loggedin_user_id() ) ) {
2483          // Setup login args.
2484          $args = array(
2485              // Custom action used to throw an error message.
2486              'action' => 'bp-spam',
2487  
2488              // Reauthorize user to login.
2489              'reauth' => 1
2490          );
2491  
2492          /**
2493           * Filters the url used for redirection for a logged in user marked as spam.
2494           *
2495           * @since 1.8.0
2496           *
2497           * @param string $value URL to redirect user to.
2498           */
2499          $login_url = apply_filters( 'bp_live_spammer_redirect', add_query_arg( $args, wp_login_url() ) );
2500  
2501          // Redirect user to login page.
2502          wp_redirect( $login_url );
2503          die();
2504      }
2505  }
2506  add_action( 'bp_init', 'bp_stop_live_spammer', 5 );
2507  
2508  /**
2509   * Show a custom error message when a logged-in user is marked as a spammer.
2510   *
2511   * @since 1.8.0
2512   */
2513  function bp_live_spammer_login_error() {
2514      global $error;
2515  
2516      $error = __( '<strong>Error</strong>: Your account has been marked as a spammer.', 'buddypress' );
2517  
2518      // Shake shake shake!
2519      add_action( 'login_head', 'wp_shake_js', 12 );
2520  }
2521  add_action( 'login_form_bp-spam', 'bp_live_spammer_login_error' );
2522  
2523  /**
2524   * Get the displayed user Object
2525   *
2526   * @since 2.6.0
2527   *
2528   * @return object The displayed user object, null otherwise.
2529   */
2530  function bp_get_displayed_user() {
2531      $bp = buddypress();
2532  
2533      $displayed_user = null;
2534      if ( ! empty( $bp->displayed_user->id ) ) {
2535          $displayed_user = $bp->displayed_user;
2536      }
2537  
2538      /**
2539       * Filters the displayed_user object corresponding to the displayed member.
2540       *
2541       * @since 2.6.0
2542       *
2543       * @param object $displayed_user The displayed_user object.
2544       */
2545      return apply_filters( 'bp_get_displayed_user', $displayed_user );
2546  }
2547  
2548  /** Member Types *************************************************************/
2549  
2550  /**
2551   * Output the slug of the member type taxonomy.
2552   *
2553   * @since 2.7.0
2554   */
2555  function bp_member_type_tax_name() {
2556      echo bp_get_member_type_tax_name();
2557  }
2558  
2559      /**
2560       * Return the slug of the member type taxonomy.
2561       *
2562       * @since 2.7.0
2563       *
2564       * @return string The unique member taxonomy slug.
2565       */
2566  	function bp_get_member_type_tax_name() {
2567          /**
2568           * Filters the slug of the member type taxonomy.
2569           *
2570           * @since 2.7.0
2571           *
2572           * @param string $value Member type taxonomy slug.
2573           */
2574          return apply_filters( 'bp_get_member_type_tax_name', 'bp_member_type' );
2575      }
2576  
2577  /**
2578   * Register a member type.
2579   *
2580   * @since 2.2.0
2581   *
2582   * @param string $member_type Unique string identifier for the member type.
2583   * @param array  $args {
2584   *     Array of arguments describing the member type.
2585   *
2586   *     @type array       $labels {
2587   *         Array of labels to use in various parts of the interface.
2588   *
2589   *         @type string $name          Default name. Should typically be plural.
2590   *         @type string $singular_name Singular name.
2591   *     }
2592   *     @type bool|string $has_directory Whether the member type should have its own type-specific directory.
2593   *                                      Pass `true` to use the `$member_type` string as the type's slug.
2594   *                                      Pass a string to customize the slug. Pass `false` to disable.
2595   *                                      Default: true.
2596   * }
2597   * @return object|WP_Error Member type object on success, WP_Error object on failure.
2598   */
2599  function bp_register_member_type( $member_type, $args = array() ) {
2600      $bp = buddypress();
2601  
2602      if ( isset( $bp->members->types[ $member_type ] ) ) {
2603          return new WP_Error( 'bp_member_type_exists', __( 'Member type already exists.', 'buddypress' ), $member_type );
2604      }
2605  
2606      $r = bp_parse_args( $args, array(
2607          'labels'        => array(),
2608          'has_directory' => true,
2609      ), 'register_member_type' );
2610  
2611      $member_type = sanitize_key( $member_type );
2612  
2613      /**
2614       * Filters the list of illegal member type names.
2615       *
2616       * - 'any' is a special pseudo-type, representing items unassociated with any member type.
2617       * - 'null' is a special pseudo-type, representing users without any type.
2618       * - '_none' is used internally to denote an item that should not apply to any member types.
2619       *
2620       * @since 2.4.0
2621       *
2622       * @param array $illegal_names Array of illegal names.
2623       */
2624      $illegal_names = apply_filters( 'bp_member_type_illegal_names', array( 'any', 'null', '_none' ) );
2625      if ( in_array( $member_type, $illegal_names, true ) ) {
2626          return new WP_Error( 'bp_member_type_illegal_name', __( 'You may not register a member type with this name.', 'buddypress' ), $member_type );
2627      }
2628  
2629      // Store the post type name as data in the object (not just as the array key).
2630      $r['name'] = $member_type;
2631  
2632      // Make sure the relevant labels have been filled in.
2633      $default_name = isset( $r['labels']['name'] ) ? $r['labels']['name'] : ucfirst( $r['name'] );
2634      $r['labels'] = array_merge( array(
2635          'name'          => $default_name,
2636          'singular_name' => $default_name,
2637      ), $r['labels'] );
2638  
2639      // Directory slug.
2640      if ( $r['has_directory'] ) {
2641          // A string value is intepreted as the directory slug. Otherwise fall back on member type.
2642          if ( is_string( $r['has_directory'] ) ) {
2643              $directory_slug = $r['has_directory'];
2644          } else {
2645              $directory_slug = $member_type;
2646          }
2647  
2648          // Sanitize for use in URLs.
2649          $r['directory_slug'] = sanitize_title( $directory_slug );
2650          $r['has_directory']  = true;
2651      } else {
2652          $r['directory_slug'] = '';
2653          $r['has_directory']  = false;
2654      }
2655  
2656      $bp->members->types[ $member_type ] = $type = (object) $r;
2657  
2658      /**
2659       * Fires after a member type is registered.
2660       *
2661       * @since 2.2.0
2662       *
2663       * @param string $member_type Member type identifier.
2664       * @param object $type        Member type object.
2665       */
2666      do_action( 'bp_registered_member_type', $member_type, $type );
2667  
2668      return $type;
2669  }
2670  
2671  /**
2672   * Retrieve a member type object by name.
2673   *
2674   * @since 2.2.0
2675   *
2676   * @param string $member_type The name of the member type.
2677   * @return object A member type object.
2678   */
2679  function bp_get_member_type_object( $member_type ) {
2680      $types = bp_get_member_types( array(), 'objects' );
2681  
2682      if ( empty( $types[ $member_type ] ) ) {
2683          return null;
2684      }
2685  
2686      return $types[ $member_type ];
2687  }
2688  
2689  /**
2690   * Get a list of all registered member type objects.
2691   *
2692   * @since 2.2.0
2693   *
2694   * @see bp_register_member_type() for accepted arguments.
2695   *
2696   * @param array|string $args     Optional. An array of key => value arguments to match against
2697   *                               the member type objects. Default empty array.
2698   * @param string       $output   Optional. The type of output to return. Accepts 'names'
2699   *                               or 'objects'. Default 'names'.
2700   * @param string       $operator Optional. The logical operation to perform. 'or' means only one
2701   *                               element from the array needs to match; 'and' means all elements
2702   *                               must match. Accepts 'or' or 'and'. Default 'and'.
2703   * @return array A list of member type names or objects.
2704   */
2705  function bp_get_member_types( $args = array(), $output = 'names', $operator = 'and' ) {
2706      $types = buddypress()->members->types;
2707  
2708      $types = wp_filter_object_list( $types, $args, $operator );
2709  
2710      /**
2711       * Filters the array of member type objects.
2712       *
2713       * This filter is run before the $output filter has been applied, so that
2714       * filtering functions have access to the entire member type objects.
2715       *
2716       * @since 2.2.0
2717       *
2718       * @param array  $types     Member type objects, keyed by name.
2719       * @param array  $args      Array of key=>value arguments for filtering.
2720       * @param string $operator  'or' to match any of $args, 'and' to require all.
2721       */
2722      $types = apply_filters( 'bp_get_member_types', $types, $args, $operator );
2723  
2724      if ( 'names' === $output ) {
2725          $types = wp_list_pluck( $types, 'name' );
2726      }
2727  
2728      return $types;
2729  }
2730  
2731  /**
2732   * Set type for a member.
2733   *
2734   * @since 2.2.0
2735   *
2736   * @param int    $user_id     ID of the user.
2737   * @param string $member_type Member type.
2738   * @param bool   $append      Optional. True to append this to existing types for user,
2739   *                            false to replace. Default: false.
2740   * @return false|array $retval See {@see bp_set_object_terms()}.
2741   */
2742  function bp_set_member_type( $user_id, $member_type, $append = false ) {
2743      // Pass an empty $member_type to remove a user's type.
2744      if ( ! empty( $member_type ) && ! bp_get_member_type_object( $member_type ) ) {
2745          return false;
2746      }
2747  
2748      $retval = bp_set_object_terms( $user_id, $member_type, bp_get_member_type_tax_name(), $append );
2749  
2750      // Bust the cache if the type has been updated.
2751      if ( ! is_wp_error( $retval ) ) {
2752          wp_cache_delete( $user_id, 'bp_member_member_type' );
2753  
2754          /**
2755           * Fires just after a user's member type has been changed.
2756           *
2757           * @since 2.2.0
2758           *
2759           * @param int    $user_id     ID of the user whose member type has been updated.
2760           * @param string $member_type Member type.
2761           * @param bool   $append      Whether the type is being appended to existing types.
2762           */
2763          do_action( 'bp_set_member_type', $user_id, $member_type, $append );
2764      }
2765  
2766      return $retval;
2767  }
2768  
2769  /**
2770   * Remove type for a member.
2771   *
2772   * @since 2.3.0
2773   *
2774   * @param int    $user_id     ID of the user.
2775   * @param string $member_type Member Type.
2776   * @return bool|WP_Error
2777   */
2778  function bp_remove_member_type( $user_id, $member_type ) {
2779      // Bail if no valid member type was passed.
2780      if ( empty( $member_type ) || ! bp_get_member_type_object( $member_type ) ) {
2781          return false;
2782      }
2783  
2784      // No need to continue if the member doesn't have the type.
2785      $existing_types = bp_get_member_type( $user_id, false );
2786      if ( ! in_array( $member_type, $existing_types, true ) ) {
2787          return false;
2788      }
2789  
2790      $deleted = bp_remove_object_terms( $user_id, $member_type, bp_get_member_type_tax_name() );
2791  
2792      // Bust the cache if the type has been removed.
2793      if ( ! is_wp_error( $deleted ) ) {
2794          wp_cache_delete( $user_id, 'bp_member_member_type' );
2795  
2796          /**
2797           * Fires just after a user's member type has been removed.
2798           *
2799           * @since 2.3.0
2800           *
2801           * @param int    $user_id     ID of the user whose member type has been updated.
2802           * @param string $member_type Member type.
2803           */
2804          do_action( 'bp_remove_member_type', $user_id, $member_type );
2805      }
2806  
2807      return $deleted;
2808  }
2809  
2810  /**
2811   * Get type for a member.
2812   *
2813   * @since 2.2.0
2814   *
2815   * @param int  $user_id ID of the user.
2816   * @param bool $single  Optional. Whether to return a single type string. If multiple types are found
2817   *                      for the user, the oldest one will be returned. Default: true.
2818   * @return string|array|bool On success, returns a single member type (if $single is true) or an array of member
2819   *                           types (if $single is false). Returns false on failure.
2820   */
2821  function bp_get_member_type( $user_id, $single = true ) {
2822      $types = wp_cache_get( $user_id, 'bp_member_member_type' );
2823  
2824      if ( false === $types ) {
2825          $raw_types = bp_get_object_terms( $user_id, bp_get_member_type_tax_name() );
2826  
2827          if ( ! is_wp_error( $raw_types ) ) {
2828              $types =  array();
2829  
2830              // Only include currently registered group types.
2831              foreach ( $raw_types as $mtype ) {
2832                  if ( bp_get_member_type_object( $mtype->name ) ) {
2833                      $types[] = $mtype->name;
2834                  }
2835              }
2836  
2837              wp_cache_set( $user_id, $types, 'bp_member_member_type' );
2838          }
2839      }
2840  
2841      $type = false;
2842      if ( ! empty( $types ) ) {
2843          if ( $single ) {
2844              $type = array_pop( $types );
2845          } else {
2846              $type = $types;
2847          }
2848      }
2849  
2850      /**
2851       * Filters a user's member type(s).
2852       *
2853       * @since 2.2.0
2854       *
2855       * @param string $type    Member type.
2856       * @param int    $user_id ID of the user.
2857       * @param bool   $single  Whether to return a single type string, or an array.
2858       */
2859      return apply_filters( 'bp_get_member_type', $type, $user_id, $single );
2860  }
2861  
2862  /**
2863   * Check whether the given user has a certain member type.
2864   *
2865   * @since 2.3.0
2866   *
2867   * @param int    $user_id     $user_id ID of the user.
2868   * @param string $member_type Member Type.
2869   * @return bool Whether the user has the given member type.
2870   */
2871  function bp_has_member_type( $user_id, $member_type ) {
2872      // Bail if no valid member type was passed.
2873      if ( empty( $member_type ) || ! bp_get_member_type_object( $member_type ) ) {
2874          return false;
2875      }
2876  
2877      // Get all user's member types.
2878      $types = bp_get_member_type( $user_id, false );
2879  
2880      if ( ! is_array( $types ) ) {
2881          return false;
2882      }
2883  
2884      return in_array( $member_type, $types );
2885  }
2886  
2887  /**
2888   * Delete a user's member type when the user when the user is deleted.
2889   *
2890   * @since 2.2.0
2891   *
2892   * @param int $user_id ID of the user.
2893   * @return false|array $value See {@see bp_set_member_type()}.
2894   */
2895  function bp_remove_member_type_on_user_delete( $user_id ) {
2896      return bp_set_member_type( $user_id, '' );
2897  }
2898  add_action( 'wpmu_delete_user', 'bp_remove_member_type_on_user_delete' );
2899  
2900  /**
2901   * Deletes user member type on the 'delete_user' hook.
2902   *
2903   * @since 6.0.0
2904   *
2905   * @param int $user_id The ID of the deleted user.
2906   */
2907  function bp_remove_member_type_on_delete_user( $user_id ) {
2908      if ( ! bp_remove_user_data_on_delete_user_hook( 'member_type', $user_id ) ) {
2909          return;
2910      }
2911  
2912      bp_remove_member_type_on_user_delete( $user_id );
2913  }
2914  add_action( 'delete_user', 'bp_remove_member_type_on_delete_user' );
2915  
2916  /**
2917   * Get the "current" member type, if one is provided, in member directories.
2918   *
2919   * @since 2.3.0
2920   *
2921   * @return string
2922   */
2923  function bp_get_current_member_type() {
2924  
2925      /**
2926       * Filters the "current" member type, if one is provided, in member directories.
2927       *
2928       * @since 2.3.0
2929       *
2930       * @param string $value "Current" member type.
2931       */
2932      return apply_filters( 'bp_get_current_member_type', buddypress()->current_member_type );
2933  }
2934  
2935  /**
2936   * Setup the avatar upload directory for a user.
2937   *
2938   * @since 6.0.0
2939   *
2940   * @param string $directory The root directory name. Optional.
2941   * @param int    $user_id   The user ID. Optional.
2942   * @return array Array containing the path, URL, and other helpful settings.
2943   */
2944  function bp_members_avatar_upload_dir( $directory = 'avatars', $user_id = 0 ) {
2945  
2946      // Use displayed user if no user ID was passed.
2947      if ( empty( $user_id ) ) {
2948          $user_id = bp_displayed_user_id();
2949      }
2950  
2951      // Failsafe against accidentally nooped $directory parameter.
2952      if ( empty( $directory ) ) {
2953          $directory = 'avatars';
2954      }
2955  
2956      $path      = bp_core_avatar_upload_path() . '/' . $directory. '/' . $user_id;
2957      $newbdir   = $path;
2958      $newurl    = bp_core_avatar_url() . '/' . $directory. '/' . $user_id;
2959      $newburl   = $newurl;
2960      $newsubdir = '/' . $directory. '/' . $user_id;
2961  
2962      /**
2963       * Filters the avatar upload directory for a user.
2964       *
2965       * @since 6.0.0
2966       *
2967       * @param array $value Array containing the path, URL, and other helpful settings.
2968       */
2969      return apply_filters( 'bp_members_avatar_upload_dir', array(
2970          'path'    => $path,
2971          'url'     => $newurl,
2972          'subdir'  => $newsubdir,
2973          'basedir' => $newbdir,
2974          'baseurl' => $newburl,
2975          'error'   => false
2976      ) );
2977  }


Generated: Sun May 31 01:01:27 2020 Cross-referenced by PHPXref 0.7.1