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


Generated: Wed Aug 12 01:01:32 2020 Cross-referenced by PHPXref 0.7.1