[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

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

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


Generated: Tue Nov 19 01:01:36 2019 Cross-referenced by PHPXref 0.7.1